-- 本地面板与快捷键共用同一组动作。所有游戏回调均在游戏线程执行。 local Bridge = require("panel_bridge") local KeyRouter=require('key_router') local FunctionKeys=require('function_keybinds') local SummonQueue=require("summon_queue") local PoolKeys=require("monster_pool_keys") local Runtime = {} Runtime.__index = Runtime local ACTIONS = FunctionKeys.actions local GLOBAL_KEYS={stop=true,exit_camera=true,refresh_catalog=true,cycle_team=true} local function read(path,limit) local file=io.open(path,'r');if not file then return nil end local text=file:read(limit);file:close();return text end function Runtime.new(options) local self=setmetatable({options=options,alive=true,pumpReady=false},Runtime) self.log=options.log or function() end self.summonQueue=SummonQueue.new({log=self.log,path=options.path, session=function()return options.session and options.session:status() end, state=function()return options.arena:status()end, begin=function()return options.arena:start()end, pending=function(enabled,blue,red,epoch)if options.arena.setRelayPending then options.arena:setRelayPending(enabled,blue,red,epoch)end end, spawn=function(path,team,count,profile) if profile then return self:requestHun(team,count,nil,nil,profile) end return self:summon(path,team,count) end}) -- Monster pool keys while the summon queue above is off: every press is kept here instead of being dropped as a -- held key would be (queueSummon). It is always on, and takes turns with the other summon shortcuts. self.poolQueue=SummonQueue.new({log=function(line)self.log((line:gsub('^%[SummonQueue%]','[PoolQueue]')))end, session=function()return options.session and options.session:status() end, spawn=function(path,team,count,profile)return self:summon(path,team,count,profile)end}) self.poolQueue.enabled=true if options.arena.companionSquad and options.session then self.squad=require('companion_squad').new({ path=options.path,log=self.log, session=function()return self.catalogSession or self:sessionStatus()end, members=function()return options.arena:companionSquad()end, busy=function() local teleport=options.support and options.support.teleport return self.summonPending or #self.poolQueue.jobs>0 or #self.summonQueue.jobs>0 or (teleport and teleport:relocating()) or (options.camera and options.camera:status().active) or (options.support and options.support.gamePaused and options.support.gamePaused()) end, spawn=function(path,dual) if path==require('hun_body').path then return self:requestHun('companion',1) end if dual then return options.support.companionManager:spawn() end return options.arena:spawn(path,'companion',1,true) end}) end self.router=options.router or KeyRouter.new({log=self.log}) local function unitOwner(vk,mask) local unit=options.unitKeys and options.unitKeys:owner(vk,mask) return unit and ((unit:match('%.([^%.]+)$') or unit):gsub('_C$','')) end local function sessionStatus()return self:sessionStatus() end self.functionKeys=FunctionKeys.new({path=options.path,router=self.router,log=self.log, unitOwner=function(vk,mask)return unitOwner(vk,mask) or (self.teleportKeys and self.teleportKeys:owner(vk,mask))end, poolOwner=function(vk,mask)return self.poolKeys:owner(vk,mask)end, queueSpawn=function(callback)self:queueSummon(callback)end, queue=function(callback,action)self:queueAction(callback,action)end, dispatch=function(action)self:dispatch(action,{})end}) self.poolKeys=PoolKeys.new({path=options.path,router=self.router,log=self.log,session=sessionStatus, conflict=function(vk,mask) local _,label=self.functionKeys:owner(vk,mask) if label then return '功能「'..label..'」' end local unit=unitOwner(vk,mask) if unit then return '单位「'..unit..'」' end local place=self.teleportKeys and self.teleportKeys:owner(vk,mask) if place then return '「'..place..'」' end end, -- How many of this unit one summon may hold; 0 when it cannot be summoned. capacity=function(path) local policy=options.spawnPolicy if not policy or not policy.check(path) then return 0 end local limit=policy.limits(path) return limit and limit.max_count or 100 end, queue=function(path,team,count)return self:queuePoolSummon(path,team,count)end}) self.router.dispatch=function(vk,mask) if not self.alive or self.functionKeys:press(vk,mask) then return end if options.unitKeys and options.unitKeys:dispatch(vk,mask) then return end if self.teleportKeys and self.teleportKeys:dispatch(vk,mask) then return end self.poolKeys:dispatch(vk,mask) end local function readyError() if not options.session then return "未配置游戏会话校验" end local status=options.session:status() if status.game_ready~=true then return status.game_ready_reason or "游戏尚未就绪" end end local function selfieActive() local module=options.support and options.support.selfie return module~=nil and module:status().on end -- nil once the free camera is running; otherwise why it could not be opened. local function openCamera() if selfieActive() then return {ok=false,message='selfie.exitFirst'} end if not options.camera then return {ok=false,message='自由观战模块未加载',spawned_count=0} end if options.camera:status().active then return nil end local why=readyError();if why then return {ok=false,message=why,spawned_count=0} end local entered=options.camera:toggle() if not entered or entered.ok~=true then return entered or {ok=false,message='自由观战没有打开',spawned_count=0} end end -- A Hun summon key: the same entry as the app's summon buttons, with the saved count. local function hunKey(team) return function() local why=readyError();if why then return {ok=false,message=why,spawned_count=0}end local queue=self.summonQueue.enabled and self.summonQueue return self:requestHun(team,nil,queue,queue and queue:epoch()) end end self.handlers={ hun_blue=hunKey('blue'),hun_red=hunKey('red'),hun_companion=hunKey('companion'),hun_neutral=hunKey('neutral'), hun_body_probe=function(command) local why=readyError();if why then return {ok=false,message=why,spawned_count=0}end local body=options.support and options.support.hunBody if not body then return {ok=false,message='魂本体验证模块未加载',spawned_count=0}end if command.unit_id~=''then return {ok=false,message='魂召唤不接受自定义类路径',spawned_count=0}end local epoch=command.key_start if epoch and epoch~='' then if not self.summonQueue.enabled or epoch~=self.summonQueue:epoch() then return {ok=false,message='该请求属于已取消的召唤队列',spawned_count=0} end local f=io.open(options.path..'/hun-queued-loadout.tsv','rb') local text=f and f:read(262145+96) if f then f:close() end local id,savedEpoch,data if type(text)=='string' then id,savedEpoch,data=text:match('^(%d+)\t(SQ_%d+)\n(.*)$') end local profile=id==tostring(command.id) and savedEpoch==epoch and require('hun_loadout').parse(data) if not profile or tostring(profile.revision)~=command.key_spawn then return {ok=false,message='此批魂的方案快照未读回',spawned_count=0} end return self:requestHun(command.team,command.count,self.summonQueue,epoch,profile) end if self.summonQueue.enabled then return {ok=false,message='排队状态已变更,请重新召唤魂',spawned_count=0} end return body:spawn(options.arena,command.team,command.count,command.key_spawn) end, spawn=function(command) local why=readyError(); if why then return {ok=false,message=why,spawned_count=0} end if self.summonQueue.enabled then return {ok=false,message='排队模式已开启,请重新提交召唤',spawned_count=0} end return self:summon(command.unit_id,command.team,command.count) end, queue_spawn=function(command) self.summonQueue:sync(options.session and options.session:status()) return self:enqueueUnit(self.summonQueue,command.unit_id,command.team,command.count,command.key_spawn) end, set_summon_queue=function(command) if command.key_start~='ON' and command.key_start~='OFF' then return {ok=false,message='无效的排队召唤设置'} end return self:setSummonQueue(command.key_start=='ON') end, configure_summon_queue=function(command) return self.summonQueue:configure(command.key_spawn,tonumber(command.key_start),tonumber(command.key_stop),tonumber(command.key_refresh_catalog)) end, cancel_summon_queue=function() local cancelled=self.summonQueue:cancel('清空召唤队列') return {ok=true,message='已取消 '..cancelled..' 条游戏内待执行召唤'} end, select_unit=function(command) return options.arena:select(command.unit_id,command.team,command.count) end, cycle_team=function() return options.arena:cycleTeam() end, toggle_selfie=function() local m=options.support and options.support.selfie if not m then return {ok=false,message='selfie.unavailable'} end local why=not m:status().on and readyError() if why then return {ok=false,message=why} end return m:toggle() end, toggle_photo=function() local m=options.support and options.support.selfie if not m or not m.studioSupported then return {ok=false,message='selfie.unavailable'} end local why=not m:status().on and readyError() if why then return {ok=false,message=why} end return m:standard() end, photo_panel=function() local m=options.support and options.support.selfie return m and m.studioSupported and m:panel() or {ok=false,message='selfie.unavailable'} end, selfie_pose=function() local m=options.support and options.support.selfie return m and m:pose() or {ok=false,message='selfie.unavailable'} end, selfie_shot=function() local m=options.support and options.support.selfie return m and m:shot() or {ok=false,message='selfie.unavailable'} end, selfie_next=function() local m=options.support and options.support.selfie return m and m:next() or {ok=false,message='selfie.unavailable'} end, toggle_camera=function() if not options.camera then return {ok=false,message='自由观战模块未加载',spawned_count=0}end local status=options.camera:status() if status.active or status.pending then return options.camera:exit()end local why=readyError();if why then return {ok=false,message=why,spawned_count=0}end return options.camera:toggle() end, exit_camera=function() if not options.camera then return {ok=false,message='自由观战模块未加载',spawned_count=0}end return options.camera:exit() end, -- 时停 (the app's switch and the function key of the same name): in the free camera on or off; outside it the -- camera opens first, frozen, for a screenshot. Leaving the camera ends it. toggle_time_stop=function() if selfieActive() then return {ok=false,message='selfie.exitFirst'} end if not options.camera or not options.camera.freeze then return {ok=false,message='自由观战模块未加载',spawned_count=0}end local status=options.camera:status() if status.active then return options.camera:freeze(not status.frozen) end local why=readyError();if why then return {ok=false,message=why,spawned_count=0} end local entered=options.camera:toggle() if not entered or entered.ok~=true then return entered or {ok=false,message='自由观战没有打开,未时停',spawned_count=0} end local frozen=options.camera:freeze(true) return {ok=frozen.ok==true,message='已进入自由观战;'..tostring(frozen.message),spawned_count=0} end, -- 镜头跟踪 (camera_track.lua). Outside the free camera it opens first, like 时停; leaving the camera ends it. toggle_track=function() if not options.track then return {ok=false,message='镜头跟踪模块未加载',spawned_count=0} end if options.track:status().on then return options.track:finish() end local failed=openCamera();if failed then return failed end return options.track:start() end, toggle_cinema=function() local track=options.track if not track or not track.startCinema or not track.stopCinema or not options.camera then return {ok=false,message='电影运镜模块未加载'} end if track:status().cinema_active then return track:stopCinema() end local cameraStatus=options.camera:status() if cameraStatus.frozen then return {ok=false,message='请先关闭时停,再开启电影运镜'} end local failed=openCamera();if failed then return failed end local ok,result=pcall(track.startCinema,track) if (not ok or not result or result.ok~=true) and not cameraStatus.active then options.camera:exit() end return ok and result or {ok=false,message='电影运镜未找到可用对局'} end, cycle_battle_hud=function() local why=readyError();if why then return {ok=false,message=why} end local support=options.support if not support or not support.cycleBattleHUD then return {ok=false,message='战斗血条控制未加载'} end return support:cycleBattleHUD() end, track_pick=function() if not options.track then return {ok=false,message='镜头跟踪模块未加载',spawned_count=0} end local failed=openCamera();if failed then return failed end return options.track:pick() end, track_next=function() if not options.track then return {ok=false,message='镜头跟踪模块未加载',spawned_count=0} end local failed=openCamera();if failed then return failed end return options.track:next() end, -- Framing upper case in key_spawn, the seconds before automatic comes back in key_start, the unit's address in unit_id. set_camera_track=function(command) if not options.track then return {ok=false,message='镜头跟踪模块未加载',spawned_count=0} end return options.track:set((command.key_spawn or ''):lower(),command.key_start,command.unit_id) end, -- Speed, turn and smoothing as whole numbers in the key_spawn, key_start and key_stop columns. set_free_camera=function(command) if not options.camera or not options.camera.configure then return {ok=false,message='自由观战模块未加载',spawned_count=0}end return options.camera:configure(tonumber(command.key_spawn),tonumber(command.key_start),tonumber(command.key_stop)) end, toggle_stat_match=function() if not options.statMatch then return {ok=false,message='数值统一模块未加载',spawned_count=0} end return options.statMatch:toggle() end, -- GAME, MATCH or CUSTOM in key_spawn; for CUSTOM the revision of Runtime/stat-custom-request.tsv in key_start. set_stat_mode=function(command) if not options.statMatch then return {ok=false,message='数值设定模块未加载',spawned_count=0} end return options.statMatch:setMode(command.key_spawn,command.key_start) end, -- The companions' own set: GAME or CUSTOM in key_spawn; for CUSTOM the revision of Runtime/companion-stats-request.tsv in key_start. set_companion_stats=function(command) if not options.companionStats then return {ok=false,message='随从数值模块未加载',spawned_count=0} end return options.companionStats:setMode(command.key_spawn,command.key_start) end, -- The revision of Runtime/ai-params-request.tsv in key_spawn. set_ai_params=function(command) if not options.aiParams then return {ok=false,message='AI 参数模块未加载',spawned_count=0} end return options.aiParams:setRequest(command.key_spawn) end, set_boss_combos=function(command) if not options.bossCombos then return {ok=false,message='连携技模块未加载',spawned_count=0} end return options.bossCombos:set(command.key_spawn=='ON') end, set_offcombat_regen=function(command) local feature=options.support and options.support.offCombatRegen if not feature then return {ok=false,message='脱战回血模块未加载'} end return feature:set(command.key_start) end, set_battle_music=function(command) local feature=options.support and options.support.battleMusic if not feature then return {ok=false,message='战斗音乐模块未加载'} end return feature:set(command.key_spawn,command.key_start) end, -- The difficulty token travels in the key_spawn column (FOLLOW, EASY, NORMAL, HARD, NIGHTMARE). set_spawn_difficulty=function(command) if not options.spawnDifficulty then return {ok=false,message='召唤难度模块未加载',spawned_count=0} end return options.spawnDifficulty:set(command.key_spawn) end, -- Feature token (SHACHI, DEFLECT, DODGE) in key_spawn, ON or OFF in key_start. set_fun_feature=function(command) if not options.funFeatures then return {ok=false,message='趣味功能模块未加载',spawned_count=0} end return options.funFeatures:set(command.key_spawn,command.key_start) end, -- Team (blue, red, companion) in the team column, ON or OFF in key_start (immortal_teams.lua). set_team_immortal=function(command) if not options.immortal then return {ok=false,message='不倒下模块未加载',spawned_count=0} end return options.immortal:set(command.team,command.key_start) end, -- HOME, HERE, CUSTOM, UNIT or CYCLE in key_spawn. CYCLE takes 0–7 in key_start. set_spawn_level=function(command) if not options.homeLevels then return {ok=false,message='召唤等级模块未加载',spawned_count=0} end return options.homeLevels:configure(command.unit_id,command.key_spawn,command.key_start) end, -- ON or OFF in key_start (battle_clock_hud.lua). set_clock_hud=function(command) if not options.clockHUD then return {ok=false,message='画面计时模块未加载',spawned_count=0} end return options.clockHUD:set(command.key_start) end, -- RED or BLUE in key_spawn, ON or OFF in key_start (attack_flash.lua). set_attack_flash=function(command) local module=options.support and options.support.attackFlash if not module then return {ok=false,message='招式预警模块未加载'} end return module:set(command.key_spawn:lower(),command.key_start) end, -- ON or OFF in key_start (execution_camera.lua). set_execution_camera=function(command) if not options.executionCamera then return {ok=false,message='处决镜头模块未加载',spawned_count=0} end return options.executionCamera:set(command.key_start) end, set_execution_appearance=function(command) local appearance=options.support and options.support.executionAppearance if not appearance then return {ok=false,message='处决外观设置不可用'} end return appearance:set(command.key_start) end, -- The unit in unit_id, the rule in key_spawn and its value in key_start, upper case on the wire (unit_rules.lua). set_unit_rule=function(command) if not options.unitRules then return {ok=false,message='单位规则模块未加载',spawned_count=0} end return options.unitRules:set(command.unit_id,command.key_spawn:lower(),command.key_start:lower()) end, -- ON or OFF in key_start (companion_executions.lua). -- 玩家可以穿过随从 (companion_passage.lua): ON or OFF in the key_start column. set_companion_passage=function(command) local module=options.support and options.support.companionPassage if not module then return {ok=false,message='穿过随从模块未加载',spawned_count=0} end return module:set(command.key_start) end, set_companion_minion_executions=function(command) if not options.companionExecutions or not options.companionExecutions.setMinions then return {ok=false,message='随从处决模块未加载',spawned_count=0} end return options.companionExecutions:setMinions(command.key_start) end, set_companion_executions=function(command) if not options.companionExecutions then return {ok=false,message='随从处决模块未加载',spawned_count=0} end return options.companionExecutions:set(command.key_start) end, start=function() local why=readyError(); if why then return {ok=false,message=why,spawned_count=0} end if self.summonQueue.enabled and self.summonQueue:isRelay() then return self.summonQueue:startRelay() end return options.arena:start() end, stop=function() self.hunInputGeneration=(self.hunInputGeneration or 0)+1 if options.support and options.support.hunBody then options.support.hunBody:cancel()end local pending=self.summonPending~=nil self.summonPending=nil;self.summonSkipped=0 if pending then self.log('[SummonKey] 停止并清理:旧召唤回调已失效;待执行槽读回=空') end if self.summonQueue.enabled then self.summonQueue:cancel('停止并清理') end if #self.poolQueue.jobs>0 then self.poolQueue:cancel('停止并清理') end if options.support then options.support:discover() end local result=options.arena:stop() local music=options.support and options.support.battleMusic if music then local stopped=music:stop() if not stopped.ok then result.ok=false;result.message=(result.message or '')..';'..stopped.message end end return result end, remove_arena_unit=function(command) local why=readyError() if not self.arenaRoster then return {ok=false,message='阵容管理模块未加载'} end local session,id=(command.unit_id or ''):match('^([%w_-]+)|(A[1-9]%d*)$') if why or not session or session~=sessionStatus().game_session then return {ok=false,message=why or '阵容已变更,请重新打开名单'} end if self.summonQueue.relayStarted then return {ok=false,message='接力交战中,暂时无法移除单位'} end if options.support then options.support:discover() end local result=options.arena:removeRosterUnit(id) self.arenaRoster:refresh() return result end, clear_neutral=function() if options.support then options.support:discover() end return options.arena:clearNeutral() end, dismiss_companions=function() if options.support then options.support:discover() end local saved=not self.squad or self.squad:dismiss() local result=options.arena:clearCompanions() if not saved then result.ok=false;result.message=result.message..';队伍记录清空待确认' end return result end, -- The app's 修复存档 (save_repair.lua): arms the repairs of what earlier versions did to saves, and reports. repair_save=function() local why=readyError(); if why then return {ok=false,message=why,spawned_count=0} end local repair=options.support and options.support.saveRepair if not repair then return {ok=false,message='存档修复模块未加载',spawned_count=0} end local result=repair:run() return {ok=result.ok==true,message=result.message,spawned_count=0} end, -- The app's 召回到身边 and the function key of the same name. manage_companion=function(c) local m=options.support and options.support.companionManager if not m then return {ok=false,message='随从管理未加载'} end return m:command(c.unit_id) end, summon_mu_companion=function() local why=readyError() local m=options.support and options.support.companionManager if why or not m then return {ok=false,message=why or '随从管理未加载'} end return m:spawn() end, recall_companions=function() if not options.companions then return {ok=false,message='随从模块未加载',spawned_count=0} end return options.companions:recall() end, toggle_spectator=function() local why=readyError(); if why then return {ok=false,message=why,spawned_count=0} end if not options.spectator then return {ok=false,message="无仇恨模块未加载",spawned_count=0} end local result=options.spectator:toggle() return {ok=result.ok==true,message=result.message or "观战模式已请求切换",spawned_count=0} end, refresh_catalog=function() if options.references then options.references:silence('重新核对目录');self.referencesStarted=false end if self.requestCatalogRefresh then self:requestCatalogRefresh() end if options.exporter:status().active then return {ok=true,message="正在读取单位目录,请等待进度更新",spawned_count=0} end local ok,status=options.exporter:start() if ok then self.catalogStarted=true end return {ok=ok,message=ok and "已开始读取游戏资源目录" or tostring(status.message or status.error or status.reason or "目录扫描未启动"),spawned_count=0} end, configure_keys=function(command) local proposal={} for _,name in ipairs(ACTIONS)do proposal[name]=command['key_'..name] or self.functionKeys.entries[name] end return self:configure(proposal) end, configure_unit_key=function(command) if not options.unitKeys then return {ok=false,message='单位快捷键模块未加载',spawned_count=0} end self.poolKeys:refresh(self.poolKeys.session) local key=command.key_spawn=='UNBOUND' and 0 or tonumber((command.key_spawn or ''):match('^VK_(%d+)$')) local mask=tonumber((command.key_start or ''):match('^MOD_(%d+)$')) -- FIXED in the key_stop column: the row's team and count belong to this unit's key. if command.key_stop=='FIXED' then return options.unitKeys:configure(command.unit_id,key,mask,command.team,command.count) end return options.unitKeys:configure(command.unit_id,key,mask) end, } local function weather(id) local why=readyError();if why then return {ok=false,message=why} end local module=options.support and options.support.weather if not module then return {ok=false,message='weather.unavailable'} end return module:set(id) end local function eyes(who) local why=readyError();if why then return {ok=false,message=why} end if not options.track or not options.track.firstPerson or not options.camera then return {ok=false,message='eyes.noCamera'} end local wasActive=options.camera:status().active local failed=openCamera();if failed then return failed end local ok,result=pcall(options.track.firstPerson,options.track,who) if (not ok or not result or not result.ok) and not wasActive then options.camera:exit() end return ok and result or {ok=false,message='eyes.noTarget'} end self.handlers.eyes_player=function()return eyes('player')end self.handlers.eyes_npc=function()return eyes('npc')end self.handlers.set_weather=function(cmd)return weather((cmd.key_spawn or ''):lower())end -- Teleport (experimental). The app sends a place code; the coordinates come from this mod's own table -- (teleport_places.lua), never from the command. nil = back to where the player stood before the last teleport. local function teleport(code) local why=readyError();if why then return {ok=false,message=why,spawned_count=0} end local module=options.support and options.support.teleport if not module then return {ok=false,message='传送模块未加载',spawned_count=0} end local result if code==nil then result=module:goBack() else local loaded,places=pcall(require,'teleport_places') local place=loaded and type(places)=='table' and places[code] or nil if not place then return {ok=false,message='这个地点不在本版模组的地点表里,请先更新游戏内的模组',spawned_count=0} end result=module:go(place) end return {ok=result.ok==true,message=tostring(result.message or ''),spawned_count=0} end self.handlers.teleport=function(cmd)return teleport(cmd.key_spawn or '')end self.handlers.teleport_back=function()return teleport(nil)end -- Teleport keys (teleport_keys.lua): one per place and one for the return; a press teleports at once. if options.support and options.support.teleport then local TeleportKeys=require('teleport_keys') self.teleportKeys=TeleportKeys.new({path=options.path,router=self.router,log=self.log, valid=function(target) local loaded,places=pcall(require,'teleport_places') local place=loaded and type(places)=='table' and places[target] return place and place.name or nil end, go=function(target) if target==TeleportKeys.BACK then return teleport(nil) end return teleport(target) end, ready=function()local why=readyError();return why==nil,why end, reserved=function(vk,mask) local _,label=self.functionKeys:owner(vk,mask) if label then return '功能「'..label..'」' end local unit=unitOwner(vk,mask) if unit then return '单位「'..unit..'」' end local pool=self.poolKeys:owner(vk,mask) if pool then return '怪物池「'..pool..'」' end end, queue=function(callback)self:queueAction(callback,'teleport')end}) end -- key_spawn: the place code or BACK; key_start: VK_ or UNBOUND; key_stop: MOD_. self.handlers.configure_teleport_key=function(cmd) if not self.teleportKeys then return {ok=false,message='传送模块未加载',spawned_count=0} end self.poolKeys:refresh(self.poolKeys.session) local key=cmd.key_start=='UNBOUND' and 0 or tonumber((cmd.key_start or ''):match('^VK_(%d+)$')) local mask=tonumber((cmd.key_stop or ''):match('^MOD_(%d+)$')) return self.teleportKeys:configure(cmd.key_spawn,key,mask) end for _,id in ipairs(require('map_weather').commands)do self.handlers['weather_'..id]=function()return weather(id)end end if options.arena.removeRosterUnit then self.arenaRoster=require('arena_roster').new({path=options.path,write=options.rosterWrite,clock=options.rosterClock}) end self.bridge=Bridge.new({path=options.path,log=self.log,handlers=self.handlers, session=function() return options.session and options.session:status() or {} end,status=function() local rosterDue=self.arenaRoster and self.arenaRoster:due() local arena=options.arena:status(rosterDue) local catalog=options.exporter:status() local spectator=options.spectator and options.spectator:status() or {} local out={build=options.build,blue_count=arena.blue_count,red_count=arena.red_count, neutral_count=arena.neutral_count,total=arena.total,current_unit=arena.current_unit, current_team=arena.current_team,current_count=arena.current_count, arena_state=arena.state,arena_message=arena.message, catalog_state=catalog.active and "scanning" or (catalog.complete and "complete" or catalog.reason), catalog_message=string.format("%s / %s 路径 · %s 个候选 · %s",tostring(catalog.paths_done),tostring(catalog.paths_total),tostring(catalog.candidates),tostring(catalog.reason)),catalog_paths_done=catalog.paths_done, catalog_paths_total=catalog.paths_total,catalog_truncated=catalog.truncated, catalog_started_at=catalog.started_at, catalog_coverage=catalog.coverage,catalog_candidates=catalog.candidates} local session=sessionStatus() self.catalogSession=session self.poolKeys:refresh(session.game_session) out.monster_pool_keys_schema=1 if self.squad then out.companion_squad_revision=self.squad.preferenceRevision or '0' out.companion_squad_enabled=self.squad.enabled out.companion_squad_total=self.squad.total out.companion_squad_state=self.squad.state end local queue=self.summonQueue if queue.enabled then queue:sync(session) end self.poolQueue:sync(session) out.summon_queue_enabled=queue.enabled out.summon_queue_epoch=queue:epoch() out.summon_queue_waiting=#queue.jobs out.summon_queue_running=queue.running==true out.summon_queue_completed=queue.completed out.summon_queue_message=queue.message out.summon_queue_settings_schema=1 out.summon_queue_mode=queue.mode;out.summon_queue_interval_ms=queue.intervalMs out.summon_queue_blue_slots=queue.blueSlots;out.summon_queue_red_slots=queue.redSlots out.summon_queue_relay_started=queue.relayStarted==true;out.summon_queue_generated=queue.generated local reserves=queue:reserves();out.summon_queue_blue_reserve=reserves.blue;out.summon_queue_red_reserve=reserves.red out.arena_battle_active=arena.battle_active==true if arena.winner then out.arena_winner=arena.winner end if self.arenaRoster then if rosterDue and session.game_ready==true and arena.roster then self.arenaRoster:publish(session.game_session,arena.roster_editable and not queue.relayStarted,arena.roster) end out.arena_roster_revision=self.arenaRoster.revision end out.monster_pool_queue_waiting=#self.poolQueue.jobs local policy=options.spawnPolicy and options.spawnPolicy.status() or {} out.spawn_trial_policy=policy.version or '' out.spawn_trial_count=policy.count or 0 out.spawn_mode=policy.mode or 'validated' out.arena_owned_records=arena.owned_records out.arena_dead_count=arena.dead_count out.arena_unreadable_count=arena.unreadable_count out.arena_max_units=arena.max_units out.neutral_owned_records=arena.neutral_owned out.companion_count=arena.companion_count or 0 out.companion_owned_records=arena.companion_owned or 0 local companion=options.companions and options.companions:status() or {} out.companion_supported=not not options.companions out.companion_follow=companion.follow or 0 out.companion_friendly=companion.friendly or 0 out.companion_failures=companion.failures or 0 out.companion_stuck_teleports=companion.stuck or 0 out.companion_recalls=companion.recalls or 0 out.companion_message=companion.message or '' out.arena_team_revision=arena.team_revision or 0 out.arena_summon_count=arena.summon_count or 0 out.battle_clock=arena.battle_clock or '' out.battle_seconds=string.format('%.1f',arena.battle_seconds or 0) local immortal=options.immortal and options.immortal:status() or {} out.immortal_supported=not not options.immortal out.immortal_blue=immortal.blue==true out.immortal_red=immortal.red==true out.immortal_companion=immortal.companion==true out.immortal_locked=immortal.locked or 0 out.immortal_failures=immortal.failures or 0 out.immortal_breaches=immortal.breaches or 0 out.immortal_message=immortal.message or '' local clockHUD=options.clockHUD and options.clockHUD:status() or {} out.clock_hud_supported=not not options.clockHUD out.clock_hud=clockHUD.on==true out.clock_hud_state=clockHUD.state or 'off' out.clock_hud_failures=clockHUD.failures or 0 local attackFlash=options.support and options.support.attackFlash if attackFlash then local state=attackFlash:status() out.attack_flash_supported=true out.attack_flash_red=state.red out.attack_flash_blue=state.blue end local executionCamera=options.executionCamera and options.executionCamera:status() or {} local appearance=options.support and options.support.executionAppearance if appearance then out.execution_appearance_legacy=appearance.on==true end out.execution_camera_supported=not not options.executionCamera out.execution_camera=executionCamera.on==true out.execution_camera_state=executionCamera.state or 'off' out.execution_camera_failures=executionCamera.failures or 0 if options.support and options.support.companionPassage then out.companion_passage_supported=true out.companion_passage=options.support.companionPassage:status().on==true end out.companion_executions_supported=not not options.companionExecutions if options.companionExecutions and options.companionExecutions.setMinions then out.companion_minion_executions_supported=true out.companion_minion_executions=options.companionExecutions:status().minions==true end out.companion_executions=options.companionExecutions and options.companionExecutions:status().on==true or false local track=options.track and options.track:status() or nil out.track_supported=track~=nil out.cinema_supported=(options.track~=nil and type(options.track.startCinema)=='function' and type(options.track.stopCinema)=='function') or nil if out.cinema_supported and track then out.cinema_active=track.cinema_active==true out.cinema_shot=track.cinema_shot or '' end if track then out.track_on=track.on==true;out.track_framing=track.framing;out.track_resume=track.resume out.track_target=track.target;out.track_target_class=track.target_class;out.track_other_class=track.other_class out.track_targets=options.camera and options.camera:status().active and options.track:targets() or '' end out.unit_rules_supported=not not options.unitRules out.unit_rules=options.unitRules and options.unitRules:status().text or '' out.clock_hud_message=clockHUD.message or '' -- The level a summon gets: the highest map enemy near the player at the last look (spawn_level.lua). local level=options.spawnLevel and options.spawnLevel:status() or {} out.spawn_level=level.last_level and string.format('%.0f',level.last_level) or '' out.spawn_level_unit=level.last_unit or '' local home=options.homeLevels and options.homeLevels:status() or {} out.spawn_level_mode=home.mode or '' out.spawn_level_custom=home.custom or '' out.spawn_cycle=home.cycle or '' local support=options.support and options.support:status() or {} out.boss_hud_registered=support.registered or 0 out.boss_hud_visible=support.visible or 0 out.boss_hud_pending=support.pending or 0 out.battle_hud_supported=(options.support~=nil and type(options.support.cycleBattleHUD)=='function') or nil if out.battle_hud_supported then out.battle_hud_mode=support.battle_hud_mode or 'full' end out.boss_hud_health_verified=support.health_verified or 0 out.boss_hud_names_verified=support.names_verified or 0 out.boss_hud_numbers_verified=support.numbers_verified or 0 out.arena_full_update_count=support.full_update_count or 0 out.arena_bone_refresh_count=support.bone_refresh_count or 0 out.npc_grab_events=support.grab_events or 0 out.npc_grab_pairs=support.grab_pairs or 0 out.npc_grab_restore_pending=support.grab_restore_pending==true out.arena_free_camera=support.free_camera==true -- 时停 and the free camera's speed, turn and smoothing (free_camera.lua). local camera=options.camera and options.camera.status and options.camera:status() or {} out.free_camera_frozen=camera.frozen==true if camera.settings then out.free_camera_settings_supported=true out.free_camera_speed=camera.settings.speed;out.free_camera_turn=camera.settings.turn;out.free_camera_smooth=camera.settings.smooth end out.observer_health_verified=support.observer_health_verified==true out.observer_message=support.observer_message or '' local matching=options.statMatch and options.statMatch:status() or {} out.stat_match_supported=not not options.statMatch out.stat_match_enabled=matching.enabled out.stat_match_baseline_unit=matching.baseline_unit or '' out.stat_match_health=matching.health out.stat_match_shachi=matching.shachi out.stat_match_attack=matching.attack out.stat_match_shachi_attack=matching.shachi_attack out.stat_match_count=matching.matched or 0 out.stat_match_failures=matching.failures or 0 out.stat_match_message=matching.message or '' out.stat_match_fields=matching.field_count or 0 out.stat_match_mode=matching.mode or 'game' out.stat_match_customized=matching.customized or 0 out.stat_custom_count=matching.custom_count or 0 local custom=matching.custom or {} out.stat_custom_health=custom.Health_Max or '' out.stat_custom_shachi=custom.Shachi_Max or '' out.stat_custom_attack=custom.Attack or '' out.stat_custom_shachi_attack=custom.ShachiAttack or '' -- The fields the game did not take on the last custom unit; the app names the first few. local rejected=matching.rejected or {} out.stat_custom_rejected=#rejected out.stat_custom_rejected_fields=table.concat(rejected,',',1,math.min(#rejected,12)) if options.support and options.support.companionManager then out.companion_manager_revision=options.support.companionManager.revision end local companionStats=options.companionStats and options.companionStats:status() or {} local companionRejected=companionStats.rejected or {} out.companion_stats_supported=not not options.companionStats out.companion_stats_mode=companionStats.mode or 'game' out.companion_stats_count=companionStats.custom_count or 0 out.companion_stats_customized=companionStats.customized or 0 out.companion_stats_failures=companionStats.failures or 0 out.companion_stats_message=companionStats.message or '' out.companion_stats_rejected=#companionRejected out.companion_stats_rejected_fields=table.concat(companionRejected,',',1,math.min(#companionRejected,12)) local difficulty=options.spawnDifficulty and options.spawnDifficulty:status() or {} out.spawn_difficulty_supported=not not options.spawnDifficulty out.spawn_difficulty=difficulty.level or '' out.spawn_difficulty_game=difficulty.game or '' out.spawn_difficulty_applied=difficulty.applied or 0 out.spawn_difficulty_skipped=difficulty.skipped or 0 out.spawn_difficulty_failures=difficulty.failures or 0 out.spawn_difficulty_message=difficulty.message or '' -- ai_difficulty.lua: whether the summoned units' AI checks answered their own level on readback. local ai=options.aiDifficulty and options.aiDifficulty:status() or {} out.spawn_difficulty_ai=ai.state or '' out.spawn_difficulty_ai_verified=ai.verified or 0 out.spawn_difficulty_ai_failed=ai.failed or 0 local fun=options.funFeatures and options.funFeatures:status() or {} out.boss_combos_supported=not not options.bossCombos out.boss_combos=options.bossCombos and options.bossCombos:status().enabled==true or false local regen=options.support and options.support.offCombatRegen and options.support.offCombatRegen:status() or {} out.offcombat_regen_supported=regen.supported==true out.offcombat_regen_disabled=regen.on==true out.offcombat_regen_state=regen.state or 'off' out.offcombat_regen_blocked=regen.blocked or 0 out.offcombat_regen_cleared=regen.cleared or 0 out.offcombat_regen_failures=regen.failures or 0 out.offcombat_regen_hooks=regen.hooks or 0 local music=options.support and options.support.battleMusic and options.support.battleMusic:status() or {} out.battle_music_supported=music.supported==true out.battle_music_mode=music.mode or 'NATIVE' out.battle_music_track=music.track or 'MOYUAN_P1' out.battle_music_state=music.state or 'native' out.battle_music_message=music.message or '' out.battle_music_playing_id=music.playing or 0 out.battle_music_pending=music.pending==true out.battle_local_token=music.local_token or '' out.battle_local_unit=music.local_unit or '' out.battle_local_client=music.local_client or '' out.battle_local_ready=music.local_ready==true out.battle_local_supported=true out.execution_minions_rule_supported=true out.entourage_rule_supported=true local body=options.support and options.support.hunBody out.hun_body_probe_supported=body~=nil out.fun_supported=not not options.funFeatures out.fun_shachi=fun.shachi==true out.fun_deflect=fun.deflect==true out.fun_dodge=fun.dodge==true out.fun_shachi_state=fun.shachi_state or 'off' out.fun_shachi_failures=fun.shachi_failures or 0 out.fun_guard_state=fun.guard_state or 'off' out.fun_guard_message=fun.guard_message or '' out.fun_deflect_pressed=fun.deflect_pressed or 0 out.fun_deflect_received=fun.deflect_received or 0 out.fun_dodge_pressed=fun.dodge_pressed or 0 out.fun_perfect_dodges=fun.perfect_dodges or 0 local unitKeys=options.unitKeys and options.unitKeys:status() or {} out.unit_keys_epoch=unitKeys.epoch or '' local remoteReflect=options.support and options.support.remoteReflect and options.support.remoteReflect:status() or {} out.remote_reflect_supported=remoteReflect.supported==true out.remote_reflect_hooks=remoteReflect.hooks or 0 out.remote_reflect_blocked=remoteReflect.blocked or 0 out.remote_reflect_unknown=remoteReflect.unknown or 0 local xianzhe=options.support and options.support.xianzhePhantom and options.support.xianzhePhantom:status() or {} out.longzhu_protection_supported=options.support~=nil and options.support.phantom~=nil out.xianzhe_phantom_supported=xianzhe.supported==true out.xianzhe_phantom_state=xianzhe.state or 'off' out.xianzhe_phantom_blocked=xianzhe.blocked or 0 out.xianzhe_phantom_failures=xianzhe.failures or 0 local phase=options.support and options.support.menghuaPhase and options.support.menghuaPhase:status() or {} out.menghua_phase_supported=phase.supported==true out.menghua_stage_rule_supported=phase.skip_supported==true out.menghua_phase_state=phase.state or 'off' out.menghua_phase_helpers=phase.helpers or 0 out.menghua_phase_busy=phase.busy or 0 out.menghua_phase_failures=phase.failures or 0 out.menghua_phase_completed=phase.completed or 0 out.menghua_phase_anchors=phase.anchors or 0 out.unit_keys_revision=unitKeys.revision or 0 out.unit_keys_event=unitKeys.event or 0 out.unit_keys_last_unit=unitKeys.unit or '' out.unit_keys_message=unitKeys.message or '' out.game_session=session.game_session out.game_ready=session.game_ready out.game_ready_reason=session.game_ready_reason out.spectator_enabled=spectator.enabled_requested out.spectator_flag_readback=spectator.player_can_be_hatred_readback out.spectator_pending_relations=spectator.pending_relations out.spectator_pending_flags=spectator.pending_flags out.spectator_message=spectator.message out.spectator_read_failures=spectator.readFailures local functions=self.functionKeys:status() -- Schema 7 extends the previous eighteen keys with preset, cycle and restore bindings. out.weather_supported=options.support~=nil and options.support.weather~=nil out.weather_choice=out.weather_supported and options.support.weather:status() or 'map' out.teleport_supported=options.support~=nil and options.support.teleport~=nil if out.teleport_supported then local state=options.support.teleport:status() out.teleport_pending=state.pending==true out.teleport_can_return=state.can_return==true out.teleport_message=state.last and ((state.last.place~='' and state.last.place..':' or '')..tostring(state.last.message)) or '' out.teleport_keys_revision=self.teleportKeys and self.teleportKeys:status().revision or 0 end out.first_person_supported=options.track~=nil and type(options.track.firstPerson)=='function' out.xbox_keys_supported=self.router.xboxSupported==true local selfie=options.support and options.support.selfie local studio=selfie and selfie.studioSupported==true if selfie then local s=selfie:status() out.selfie_supported=true out.selfie_on=s.on;out.selfie_ready=s.ready;out.selfie_target=s.target if studio then out.photo_studio=true;out.photo_mode=s.mode end out.selfie_posed=s.posed;out.selfie_style=s.style;out.selfie_next=s.next;out.selfie_message=s.message end local cinemaKeys=out.cinema_supported and out.battle_hud_supported out.function_keys_schema=cinemaKeys and 11 or studio and 10 or selfie and 9 or 8;out.function_keys_epoch=functions.epoch;out.function_keys_revision=functions.revision for _,action in ipairs(ACTIONS)do local studioKey=action=='toggle_photo' or action=='photo_panel' local selfieKey=action=='toggle_selfie' or action:sub(1,7)=='selfie_' local cinemaKey=action=='toggle_cinema' or action=='cycle_battle_hud' if (not studioKey or studio) and (not selfieKey or selfie) and (not cinemaKey or cinemaKeys) then out['key_'..action]=self.functionKeys:token(action) end end return out end}) return self end function Runtime:unitKeyReserved(vk,mask) local _,label=self.functionKeys:owner(vk,mask) local pool=self.poolKeys:owner(vk,mask) return label or (pool and ('怪物池:'..pool)) or (self.teleportKeys and self.teleportKeys:owner(vk,mask)) end function Runtime:unitKeyShared(vk) return self.router.installed[vk..':0']~=nil end function Runtime:configure(proposal) self.poolKeys:refresh(self.poolKeys.session) local result=self.functionKeys:configure(proposal) if result.ok and self.options.unitKeys then self.options.unitKeys:refresh()end if result.ok and self.teleportKeys then self.teleportKeys:refresh()end return result end function Runtime:setSummonQueue(enabled) local queue=self.summonQueue if enabled==queue.enabled then return {ok=true,message=enabled and '排队召唤已开启' or '排队召唤已关闭'} end if enabled then queue:sync(self.options.session and self.options.session:status()) if not queue.session then return {ok=false,message='进入地图后才能开启排队召唤'} end if type(LoopInGameThreadWithDelay)~='function' or type(CancelDelayedAction)~='function' then return {ok=false,message='排队召唤需要游戏线程定时器'} end local token={} local ok,handle=pcall(LoopInGameThreadWithDelay,25,function() if self.alive and self.summonLoopToken==token then queue:tick() end end) if not ok or handle==nil or handle==false then return {ok=false,message='召唤队列定时器注册未确认'} end self.summonLoopToken,self.summonLoop=token,handle self.summonPending=nil queue.enabled=true if #self.poolQueue.jobs>0 then self.poolQueue:cancel('排队召唤已开启') end queue.completed=0;queue.generated=0 queue:cancel('排队召唤已开启') if self.nextSummonAt then queue.nextAt=self.nextSummonAt end return {ok=true,message='排队召唤已开启'} end queue.enabled=false queue:cancel('排队召唤已关闭') local handle=self.summonLoop self.summonLoopToken,self.summonLoop=nil,nil if handle~=nil then local ok,result=pcall(CancelDelayedAction,handle) if not ok or result==false then self.log('[SummonQueue] 定时器取消未读回;回调已失效') end end return {ok=true,message='排队召唤已关闭'} end function Runtime:requestHun(team,count,queue,epoch,profile) local body=self.options.support and self.options.support.hunBody if not body then return {ok=false,message='魂本体模块未加载',spawned_count=0} end profile=profile or (self.options.hunLoadout and self.options.hunLoadout()) if not profile or not profile.kit then return {ok=false,message='魂方案未读回,请打开本版助手',spawned_count=0} end count=count or profile.count if not queue then return body:spawn(self.options.arena,team,count,tostring(profile.revision),profile) end if queue==self.summonQueue then queue:sync(self.options.session and self.options.session:status()) end local result=queue:enqueue(require('hun_body').path,team,count,epoch,profile) if queue==self.summonQueue and result.ok then local role='等待按间隔生成' if queue:isRelay() then role=(team=='blue' or team=='red') and '蓝红接力候补' or '随从及挑战按队列间隔生成,不占接力席位' end result.message='魂已入队 '..count..' 只,方案版本 '..profile.revision..';'..role end return result end function Runtime:enqueueUnit(queue,path,team,count,epoch) if path==require('hun_body').path then return self:requestHun(team,count,queue,epoch) end return queue:enqueue(path,team,count,epoch) end function Runtime:summon(path,team,count,profile) local arena=self.options.arena local selected,defaultTeam,defaultCount if (not path or not team or not count) and arena.selection then selected,defaultTeam,defaultCount=arena:selection() end local result if (path or selected)==require('hun_body').path then result=self:requestHun(team or defaultTeam,count or defaultCount,nil,nil,profile) else result=arena:spawn(path,team,count) end self.nextSummonAt=os.clock()+0.25 return result end function Runtime:sessionStatus() local ok,state=pcall(function()return self.options.session and self.options.session:status()end) if not ok or type(state)~='table' then state={} end self.hotkeySession=type(state.game_session)=='string' and state.game_session~='' and state.game_session or nil self.hotkeyReady=state.game_ready==true and self.hotkeySession~=nil return state end function Runtime:inputContext() -- Native game state is read only when this input already runs on the game thread. local readyAtInput if type(IsInGameThread)=='function' and IsInGameThread() then self:sessionStatus() readyAtInput=self.hotkeyReady end return {session=self.hotkeySession,ready=readyAtInput} end function Runtime:inputCurrent(request) self:sessionStatus() return request.ready~=false and self.hotkeyReady and (not request.session or request.session==self.hotkeySession) end function Runtime:existingModeInput(action,request) if action=='toggle_selfie' or action=='toggle_photo' or action=='photo_panel' then local selfie=self.options.support and self.options.support.selfie return selfie~=nil and selfie:status().on end if action=='toggle_cinema' then return self.options.track~=nil and self.options.track:status().cinema_active==true end if action~='toggle_camera' and action~='toggle_track' and action~='toggle_time_stop' then return false end local mode=action=='toggle_track' and self.options.track or self.options.camera if not mode then return false end local ok,status=pcall(function()return mode:status()end) if not ok or type(status)~='table' then return false end if action=='toggle_camera' then return status.active==true or status.pending==true end if action=='toggle_track' then return status.on==true end if action=='toggle_time_stop' and status.active==true then return status.frozen==true or not request.session or request.session==self.hotkeySession end return false end function Runtime:queueAction(callback,action) if not self.alive then return end local request=not GLOBAL_KEYS[action] and self:inputContext() or nil local hun=type(action)=='string' and action:match('^hun_') local epoch=hun and self.summonQueue:epoch() local generation=hun and (self.hunInputGeneration or 0) local queued,err=pcall(ExecuteInGameThread,function() if not self.alive then return end if hun and (epoch~=self.summonQueue:epoch() or generation~=(self.hunInputGeneration or 0)) then return end if request and not self:inputCurrent(request) and not self:existingModeInput(action,request) then self.log('[InputKey] 取消旧会话或未就绪的待执行操作 action='..tostring(action) ..' 原会话='..tostring(request.session)..' 当前会话='..tostring(self.hotkeySession)) return end callback() end) if not queued then self.log('[InputKey] 无法排入游戏线程:'..tostring(err)) end end -- A held or rapidly repeated summon key must not fill the engine's callback queue. -- Both summon shortcuts share one pending request and leave a gap after it runs. function Runtime:queueSummon(callback,path,team,count) if not self.alive then return end if self.summonQueue.enabled then local selected,defaultTeam,defaultCount=self.options.arena:selection() return self:enqueueUnit(self.summonQueue,path or selected,team or defaultTeam,count or defaultCount) end if self.summonPending or (self.nextSummonAt and os.clock()=task.retryAt then local ok,result if task==tables and tableMethod=='step' then ok,result=pcall(task.module.step,task.module,session.game_session,generation) if ok and type(result)=='table' and result.pending==true then return true end else ok,result=pcall(task.module[task.method],task.module) end if ok and (result==true or type(result)=='table' and result.ok==true) then task.done=true;task.retryAt=nil;task.failures=nil if homes and (task==codex or task==areas) then homes.done=false;homes.retryAt=nil end else task.failures=math.min((task.failures or 0)+1,6) task.retryAt=now+math.min(60,2^task.failures) if task.failures<=2 then self.log(task.label..'读取未确认,稍后重试:'.. tostring(type(result)=='table' and result.message or result))end end return true end end end pending=waiting end if self.options.spawnLevel and (not self.spawnLevelAt or now>=self.spawnLevelAt) then self.spawnLevelAt=now+10 local ok,found=pcall(self.options.spawnLevel.refresh,self.options.spawnLevel) if ok and found then self.spawnLevelAt=now+60 end if not ok and self.lastLevelError~=tostring(found) then self.log('附近等级读取未确认:'..tostring(found)) end self.lastLevelError=not ok and tostring(found) or nil return true end end if self.options.autoScan and not self.initialScanChecked and (not self.options.fullInventory or session and session.game_ready==true) then self.initialScanChecked=true local inventoryStatus=self.options.fullInventory and read(self.options.path..'/asset-index-status.tsv',8192) or nil local needed=self.options.fullInventory and (not inventoryStatus or not inventoryStatus:find('\ncomplete\ttrue\n',1,true)) or (not self.options.fullInventory and not read(self.options.path..'/catalog.tsv',1)) if needed and not self.options.exporter:status().active then local started,state=self.options.exporter:start() self.log("首次目录自动读取="..tostring(started)..";读回状态="..tostring(state.reason)) return true end end end local lastWasCatalog=false local function catalogTick() if self.catalogStarted then self.catalogStarted=nil;lastWasCatalog=true;return end if not (lastWasCatalog and self.options.exporter:status().active) and maintainCatalog(self.catalogSession) then lastWasCatalog=true;return end lastWasCatalog=false self.options.exporter:tick() if self.options.references then local inventory=self.options.exporter:status() if not self.referencesStarted and not inventory.active and inventory.paths_total>0 and inventory.paths_done==inventory.paths_total and self.options.exporter.referencePackages then self.referencesStarted=true;self.options.references:start(self.options.exporter:referencePackages()) end self.options.references:tick() end end local function supportTick() if self.options.spectator then self.options.spectator:tick() end self:tickPoolQueue() self.healthTicks=(self.healthTicks or 0)+1 if self.healthTicks%4==0 and self.options.arena.sampleHealth then self.options.arena:sampleHealth() end if self.healthTicks%2==0 and self.options.support then self.options.support:tick() end end local function bridgeTick() self.bridge:tick() if self.squad then self.squad:tick() end end -- A whole pump slower than 15 ms is logged (at most 60 times per Lua lifetime) to find stutter; every minute a summary -- of all pumps keeps coming after that (perf_meter.lua). Pumps run every 250 ms: a gap of 400 ms is a stalled game thread. local slowPumps=0 local pumpMeter=require('perf_meter').new({label='面板轮询',log=function(line)self.log(line)end,slow=15,hitch=400}) local phaseErrors,phaseTimes={},{} local function runPhase(label,fn) if not self.alive then phaseTimes[label]=0;return end local start=os.clock() local ok,err=xpcall(fn,debug.traceback) phaseTimes[label]=(os.clock()-start)*1000 if ok then phaseErrors[label]=nil elseif phaseErrors[label]~=tostring(err) then phaseErrors[label]=tostring(err);self.log("面板轮询失败 "..label..":"..tostring(err)) end end self.pumpCallback=function() if not self.alive or not self.pumpReady then return end local started=os.clock() self.catalogSession=nil runPhase('战斗',supportTick) runPhase('指令',bridgeTick) runPhase('目录',catalogTick) self.catalogSession=nil local spent=(os.clock()-started)*1000 if spent>=15 and slowPumps<60 then slowPumps=slowPumps+1 self.log(string.format('[Perf] 面板轮询耗时 %.1fms:战斗=%.1f 指令=%.1f 目录=%.1f', spent,phaseTimes['战斗'],phaseTimes['指令'],phaseTimes['目录'])) end pumpMeter:add(spent,started,phaseTimes) -- 此API忽略回调返回值;停止必须明确CancelDelayedAction(handle)。 end local ok,handle=pcall(LoopInGameThreadWithDelay,250,self.pumpCallback) if not ok or handle==nil or handle==false then self.log("面板轮询注册未确认:"..tostring(handle)..";未回退异步排队循环") return false end self.pumpHandle=handle self.pumpReady=true self.log("面板周期任务已注册;handle读回="..tostring(handle)..";实际心跳待tick验证;目录: "..self.options.path) return true end function Runtime:silence() self.alive=false if self.summonQueue.enabled then self:setSummonQueue(false) end self.poolQueue.enabled=false;self.poolQueue.jobs={} if self.teleportKeys then self.teleportKeys:silence() end self.functionKeys:silence();self.router:silence() if self.options.unitKeys then self.options.unitKeys:silence() end self.pumpReady=false if self.pumpHandle~=nil then local handle=self.pumpHandle local ok,result=pcall(CancelDelayedAction,handle) self.log("面板宿主任务取消调用="..tostring(ok)..";handle="..tostring(handle)..";返回="..tostring(result)..";未执行游戏对象恢复") if ok and result~=false then self.pumpHandle=nil end end self.options.exporter:silence("Mod卸载") if self.options.references then self.options.references:silence('Mod卸载') end if self.options.spectator then self.options.spectator:silence("Mod卸载") end end return Runtime