From b260d2899ee63b00b6d23090bcb8492ea8ca3752 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:15:47 +0800 Subject: [PATCH] chore(battle): snapshot the LocalMP rework baseline Records the uncommitted battle-session work exactly as it was left (local service matchmaking, settlement, chat, native LocalMP hooks, battle gui/exe patches) so the following review and rework commits show every correction as a diff against this state. This commit is not reviewed and is known to be incomplete: in-game testing reported wrong settlement rewards, single-country teams, missing random/fixed supplement slots, misattributed hit messages and other regressions. Do not merge this branch before the rework lands. --- .../allow-local-host-bot-spawns/locate.json | 12 + .../allow-local-host-bot-spawns/patch.json | 52 +++ .../locate.json | 12 + .../patch.json | 43 +++ .../append-extra-battle-slots/patch.json | 11 + .../force-extra-slot-weapons/patch.json | 11 + .../launch-local-battle-from-queue/patch.json | 11 + .../battle/lineup-br-for-submodes/patch.json | 30 ++ .../battle/local-host-spawn-score/patch.json | 11 + .../pass-spawn-modifications-blk/patch.json | 11 + .../patch.json | 11 + .../patch.json | 31 ++ .../quit-local-host-to-debriefing/patch.json | 31 ++ .../ready-local-host-respawn/patch.json | 31 ++ .../report-local-battle-settlement/patch.json | 11 + .../scoreboard-team-country-flags/patch.json | 30 ++ .../patch.json | 30 ++ native/wto-net/build.ps1 | 1 + native/wto-net/src/dll_main.c | 5 +- native/wto-net/src/hooks.h | 1 + native/wto-net/src/local_mp_actions.c | 206 ++++++++++++ native/wto-net/src/local_mp_core.c | 290 ++++++++++++++++ native/wto-net/src/local_mp_events.c | 284 ++++++++++++++++ native/wto-net/src/local_mp_internal.h | 103 ++++++ native/wto-net/src/local_mp_kills.c | 213 ++++++++++++ native/wto-net/src/local_mp_ledger.c | 295 +++++++++++++++++ native/wto-net/src/local_mp_loadout.c | 254 ++++++++++++++ native/wto-net/src/local_mp_offsets.h | 297 +++++++++++++++++ native/wto-net/src/local_mp_players.c | 232 +++++++++++++ .../src/battle/battle-coalitions.ts | 227 +++++++++++++ .../src/battle/battle-extra-slots.ts | 257 +++++++++++++++ .../src/battle/battle-matchmaker.ts | 293 +++++++++++++++++ .../local-service/src/battle/battle-ranks.ts | 177 ++++++++++ .../local-service/src/battle/battle-report.ts | 179 ++++++++++ .../src/battle/battle-result-log.ts | 280 ++++++++++++++++ .../src/battle/battle-rp-investment.ts | 266 +++++++++++++++ .../src/battle/battle-session-store.ts | 105 ++++++ .../src/battle/battle-settlement.ts | 117 +++++++ .../local-service/src/battle/battle-tuning.ts | 73 +++++ .../src/char/actions/action-table.ts | 11 +- .../src/char/actions/battle-actions.ts | 53 +++ .../src/char/actions/hangar-misc-actions.ts | 232 +++++++++++++ .../src/char/actions/payload-params.ts | 8 + .../src/char/actions/price-table.ts | 21 +- .../src/char/actions/research-actions.ts | 46 ++- .../local-service/src/chat/irc-protocol.ts | 88 +++++ packages/local-service/src/chat/irc-server.ts | 284 ++++++++++++++++ .../cloud-settings/cloud-settings-store.ts | 47 ++- .../src/crew/crew-skill-rules.ts | 38 ++- .../downloadable-content/content-indexes.ts | 100 +++++- .../downloadable-content-service.ts | 17 +- .../game-data/datasets/battle-spawn-rules.ts | 184 +++++++++++ .../src/game-data/datasets/crew-skills.ts | 26 +- .../src/game-data/datasets/decal-textures.ts | 198 +++++++++++ .../datasets/multiplayer-missions.ts | 6 +- .../game-data/datasets/vehicle-catalogue.ts | 18 +- .../src/game-modes/catalogue/catalogue.ts | 18 +- .../catalogue/game-mode-declaration.ts | 27 ++ .../src/game-modes/catalogue/mission-pools.ts | 15 + .../game-modes/catalogue/random-battles.ts | 13 +- .../game-modes/catalogue/sub-game-modes.ts | 119 +++++++ .../src/game-modes/game-modes.ts | 51 ++- .../src/game-modes/mode-definition.ts | 28 +- packages/local-service/src/local-service.ts | 32 +- .../src/matching/battle-queue-requests.ts | 180 ++++++++++ .../src/matching/game-settings.ts | 22 ++ .../src/matching/matching-requests.ts | 29 +- .../src/matching/matching-service.ts | 24 +- .../src/modifications/ammo-refill.ts | 70 ++-- .../modifications/module-research-target.ts | 62 +++- .../src/modifications/module-state.ts | 78 ++++- .../src/modifications/module-status.ts | 6 +- .../src/profile/profile-crew-skills.ts | 19 +- .../src/profile/profile-crews.ts | 32 ++ .../src/profile/profile-dest-rp.ts | 96 ++++++ .../src/profile/profile-research-points.ts | 6 + .../src/profile/profile-research-targets.ts | 21 +- .../src/profile/profile-trophies-log.ts | 6 +- .../src/profile/profile-vehicle-state.ts | 36 +- .../src/profile/profile-wishlist.ts | 98 ++++++ .../src/research/research-progress.ts | 70 ++-- .../src/research/research-rules.ts | 5 +- .../src/research/research-state.ts | 88 +++-- .../local-service/src/server/port-listener.ts | 27 +- .../local-service/src/store/store-web-api.ts | 3 +- .../local-service/src/store/web/gallery.js | 204 +++++++----- .../local-service/src/store/web/products.js | 18 +- .../local-service/src/tuning/limits-tuning.ts | 2 + packages/local-service/src/tuning/tuning.ts | 3 + .../src/web-ui/store-media-cache.ts | 105 ++---- packages/local-service/tuning/battle.jsonc | 41 +++ packages/local-service/tuning/limits.jsonc | 4 +- tools/src/wtotools/cli/__init__.py | 5 +- tools/src/wtotools/cli/exe_commands.py | 16 + tools/src/wtotools/cli/gui_commands.py | 39 +++ tools/src/wtotools/gui_check.py | 309 ++++++++++++++++++ tools/src/wtotools/offset_check.py | 134 ++++++++ 97 files changed, 7676 insertions(+), 396 deletions(-) create mode 100644 exe-patches/battle/allow-local-host-bot-spawns/locate.json create mode 100644 exe-patches/battle/allow-local-host-bot-spawns/patch.json create mode 100644 exe-patches/battle/allow-local-host-player-respawn/locate.json create mode 100644 exe-patches/battle/allow-local-host-player-respawn/patch.json create mode 100644 gui-patches/battle/append-extra-battle-slots/patch.json create mode 100644 gui-patches/battle/force-extra-slot-weapons/patch.json create mode 100644 gui-patches/battle/launch-local-battle-from-queue/patch.json create mode 100644 gui-patches/battle/lineup-br-for-submodes/patch.json create mode 100644 gui-patches/battle/local-host-spawn-score/patch.json create mode 100644 gui-patches/battle/pass-spawn-modifications-blk/patch.json create mode 100644 gui-patches/battle/populate-random-spawn-units-state/patch.json create mode 100644 gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.json create mode 100644 gui-patches/battle/quit-local-host-to-debriefing/patch.json create mode 100644 gui-patches/battle/ready-local-host-respawn/patch.json create mode 100644 gui-patches/battle/report-local-battle-settlement/patch.json create mode 100644 gui-patches/battle/scoreboard-team-country-flags/patch.json create mode 100644 gui-patches/battle/stabilize-respawn-countdown-button/patch.json create mode 100644 native/wto-net/src/local_mp_actions.c create mode 100644 native/wto-net/src/local_mp_core.c create mode 100644 native/wto-net/src/local_mp_events.c create mode 100644 native/wto-net/src/local_mp_internal.h create mode 100644 native/wto-net/src/local_mp_kills.c create mode 100644 native/wto-net/src/local_mp_ledger.c create mode 100644 native/wto-net/src/local_mp_loadout.c create mode 100644 native/wto-net/src/local_mp_offsets.h create mode 100644 native/wto-net/src/local_mp_players.c create mode 100644 packages/local-service/src/battle/battle-coalitions.ts create mode 100644 packages/local-service/src/battle/battle-extra-slots.ts create mode 100644 packages/local-service/src/battle/battle-matchmaker.ts create mode 100644 packages/local-service/src/battle/battle-ranks.ts create mode 100644 packages/local-service/src/battle/battle-report.ts create mode 100644 packages/local-service/src/battle/battle-result-log.ts create mode 100644 packages/local-service/src/battle/battle-rp-investment.ts create mode 100644 packages/local-service/src/battle/battle-session-store.ts create mode 100644 packages/local-service/src/battle/battle-settlement.ts create mode 100644 packages/local-service/src/battle/battle-tuning.ts create mode 100644 packages/local-service/src/char/actions/battle-actions.ts create mode 100644 packages/local-service/src/char/actions/hangar-misc-actions.ts create mode 100644 packages/local-service/src/chat/irc-protocol.ts create mode 100644 packages/local-service/src/chat/irc-server.ts create mode 100644 packages/local-service/src/game-data/datasets/battle-spawn-rules.ts create mode 100644 packages/local-service/src/game-data/datasets/decal-textures.ts create mode 100644 packages/local-service/src/game-modes/catalogue/sub-game-modes.ts create mode 100644 packages/local-service/src/matching/battle-queue-requests.ts create mode 100644 packages/local-service/src/matching/game-settings.ts create mode 100644 packages/local-service/src/profile/profile-dest-rp.ts create mode 100644 packages/local-service/src/profile/profile-wishlist.ts create mode 100644 packages/local-service/tuning/battle.jsonc create mode 100644 tools/src/wtotools/cli/gui_commands.py create mode 100644 tools/src/wtotools/gui_check.py create mode 100644 tools/src/wtotools/offset_check.py diff --git a/exe-patches/battle/allow-local-host-bot-spawns/locate.json b/exe-patches/battle/allow-local-host-bot-spawns/locate.json new file mode 100644 index 0000000..54dadc3 --- /dev/null +++ b/exe-patches/battle/allow-local-host-bot-spawns/locate.json @@ -0,0 +1,12 @@ +{ + "method": "signature", + "section": ".text", + + "how": [ + "取 BotSystem::changeUnit 内出生点检查(call 0x111a010)至 g_multiplayer 空指针拦截处共 0x3c 字节的掩码特征(authoring.py 生成)。", + "包含结构体偏移 +0x3e0 与栈槽偏移 [rsp+0x20],rip 相对位移和跳转目标已全部通配。", + "在 2.61.0.37 原版 aces.exe 的 .text 段唯一命中 0x11b2c14,目标修改点位于 +38(0x11b2c3a)。" + ], + + "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20" +} diff --git a/exe-patches/battle/allow-local-host-bot-spawns/patch.json b/exe-patches/battle/allow-local-host-bot-spawns/patch.json new file mode 100644 index 0000000..738e60f --- /dev/null +++ b/exe-patches/battle/allow-local-host-bot-spawns/patch.json @@ -0,0 +1,52 @@ +{ + "id": "battle/allow-local-host-bot-spawns", + "title": "允许本地多人主机模式下 BotSystem 为双方 AI 槽位刷出载具", + + "program_behaviour": { + "stock": "BotSystem::changeUnit 在选好 AI 载具并找到可用出生点(0x111a010)后,在 0x11b2c3a 检查全局多人对象 [0x7b83cb0] 是否为空:仅单机模式(g_multiplayer == nullptr)跳至 0x11b314e 执行 Unit::changeAircraft;多人模式下因客户端裁掉了服务端脚本校验分支,直接落入错误日志 \"BotSystem::changeUnit spawn denied by scripts\" 并放弃刷车。", + "patched": "将 0x11b2c3a 处的空指针比较与条件跳转改为无条件跳至 0x11b314e,使 LocalMP 本地权威主机通过出生点检查后直接执行 Unit::changeAircraft 为双方 AI 刷出坦克/飞机/舰艇(远程 Peer 模式已在函数入口 0x11b2259 因 isHost == 0 提前返回,不受影响)。" + }, + + "derivation": { + "requirement": "功能清单 L「AI 出车」。玩家排队进入本地多人对局后,双方 AI 必须按 customBots 载具池在各自出生点正常刷出参战。", + "cause": "2.61.0.37 客户端 exe 在编译时移除了专用服务端在 BotSystem::changeUnit 中调用的服务端脚本出生许可钩子,只保留了 g_multiplayer == nullptr 的单机跳转,导致 LocalMP 主机(g_multiplayer != nullptr 且 isHost == 1)每次刷 AI 都报 spawn denied by scripts。", + "lighter_options_ruled_out": [ + "原生配置或任务参数:0x11b2c3a 只判断 [0x7b83cb0] 是否为 0,不读任何 MissionSettings 或 DataBlock 开关。", + "本地服务或界面脚本:该判断位于客户端物理主机每帧原生 BotSystem::update 内部,不发网络请求也不调客户端 Quirrel 脚本。" + ], + "conclusion": "只能改 exe,在出生点检查通过后跳入原有的 0x11b314e 刷车构造分支。", + "if_not_applied": "进入 LocalMP 对局后双方 AI 槽位虽然加入房间,但因每次 changeUnit 都被拦截,战局内一辆 AI 载具都不会刷出。" + }, + + "why_this_site": [ + "0x11b2c32 刚完成出生点可用性检查(test al, al; je 0x11b2d15),紧接着的 14 字节(0x11b2c3a-0x11b2c48)就是唯一的 g_multiplayer == 0 拦截。", + "函数开头 0x11b224d-0x11b225d 已经拦住了所有非主机多人会话(isHost == 0 直接返回 0),所以能走到 0x11b2c3a 的多人会话一定是本地主机。", + "原地用 5 字节近跳转加 9 字节 nop 覆盖 14 字节原指令,不改栈帧大小,不引入新调用,异常展开信息保持不变。" + ], + + "features": ["L-AI出车"], + "requires": [], + "evidence": [ + "2.61.0.37 原版 aces.exe:BotSystem::changeUnit 0x11b2200,主机检查 0x11b224d-0x11b225d,出生点选择 0x11b2c2d(call 0x111a010),拦截点 0x11b2c3a-0x11b2c48,错误日志 0x11b2cfe,刷车构造入口 0x11b314e -> 0xff1020(Unit::changeAircraft)。", + "2.61.0.37 实测战斗日志:未打补丁时连续输出 \"BotSystem::changeUnit spawn denied by scripts for fm ... unit ...\"。" + ], + "verified_on": ["2.61.0.37"], + + "edit": { + "offset": 38, + "asm": [ + "jmp 0x514", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop" + ], + "bytes": "e90f050000909090909090909090", + "expect_original": "48833d6e109d06000f8406050000" + } +} diff --git a/exe-patches/battle/allow-local-host-player-respawn/locate.json b/exe-patches/battle/allow-local-host-player-respawn/locate.json new file mode 100644 index 0000000..27a42ab --- /dev/null +++ b/exe-patches/battle/allow-local-host-player-respawn/locate.json @@ -0,0 +1,12 @@ +{ + "method": "signature", + "section": ".text", + + "how": [ + "取 Unit::onEvent(0x103fbc0)中 0xf02f(UnitRespawnRequest)分支自人类玩家判定(call 0xfd34a0)至出生逻辑入口前(xor edx, edx)共 0x68 字节的掩码特征(authoring.py 生成)。", + "包含 MPlayer 指针偏移 [r13+0xf98]、出生目标偏移 [rdx+0xbf8]/[rdx+0xbf4] 与 GUI_STATE_CA_SELECT 常量 6,rip 相对位移与相对调用/跳转目标均已通配。", + "在 2.61.0.37 原版 aces.exe 的 .text 段唯一命中 0x1044e9b,目标修改点位于 +49(0x1044ecc)。" + ], + + "pattern": "48 89 d9 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 8b 05 ?? ?? ?? ?? 83 c0 fd 49 8b 95 98 0f 00 00 83 f8 02 72 ?? 0f b6 4a 08 83 ba f8 0b 00 00 00 79 ?? 83 ba f4 0b 00 00 00 0f 88 ?? ?? ?? ?? ba 06 00 00 00 e8 ?? ?? ?? ?? 4c 89 e9 b2 01 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 31 d2" +} diff --git a/exe-patches/battle/allow-local-host-player-respawn/patch.json b/exe-patches/battle/allow-local-host-player-respawn/patch.json new file mode 100644 index 0000000..3f2900c --- /dev/null +++ b/exe-patches/battle/allow-local-host-player-respawn/patch.json @@ -0,0 +1,43 @@ +{ + "id": "battle/allow-local-host-player-respawn", + "title": "允许本地多人主机模式下人类玩家在对战模式(GM_DOMINATION 等)中正常刷出载具参战", + + "program_behaviour": { + "stock": "Unit::onEvent(0x103fbc0)收到 0xf02f(UnitRespawnRequest)时,在 0x1044e9b-0x1044ecc 判断若为人类玩家载具且 g_multiplayer 非空,则仅允许 g_game_mode(0x7bb5060)为 3(GM_SINGLE_MISSION)或 4(GM_DYNAMIC)时跳至 0x1044f03 执行完整的出生位计算与 0xf030(UnitRespawn)派发;客户端二进制因编译期移除了专用对战服授权分支,在其它多人模式(如随机匹配的 GM_DOMINATION = 2)下无论出生点校验是否通过都会汇入 0x1044ee8,调用 setPlayerGuiState(playerId, GUI_STATE_CA_SELECT = 6) 并将载具重新置为延迟隐藏,导致玩家点击「加入战斗!」倒计时结束后无报错直接退回选车界面。", + "patched": "将 0x1044ecc 处的 2 字节条件短跳转(jb 0x1044f03)改为无条件短跳转(jmp 0x1044f03),使本地权威主机(isHost == 1;远程客户端的 0xf02f 发往远端服务端,不会在本地触发此分支)在所有对战模式下都能进入 0x1044f03 原生出生流程,按 MPlayer 记录的出生点 ID 刷出玩家载具并切入操控视角。" + }, + + "derivation": { + "requirement": "功能清单 K「战局任务加载与玩家出击」。玩家在重生界面选择乘员组载具与出生点并点击「加入战斗!」后,必须在所选出生点正常刷出载具进入战斗。", + "cause": "2.61.0.37 客户端 aces.exe 在 Unit::onEvent 的 0xf02f 分支中保留了完整的 0x1044f03 -> 0xfec9c0 -> 0xf030 人类玩家出生实现(供单机与联机合作单人任务/动态战役主机使用),但用 #ifdef DEDICATED_SERVER 裁掉了多人对战模式(GM_DOMINATION 等)放行路径,令 0x1044ed2 与 0x1046b61 所有分支最终均落入 0x1044ee8 退回 GUI_STATE_CA_SELECT(状态 6)。", + "lighter_options_ruled_out": [ + "原生配置或任务参数:0x1044eb9 硬编码判断全局 g_game_mode 枚举是否属于 {3, 4},把对局改成 GM_SINGLE_MISSION 会破坏占点统治规则、重生点机制与计分板。", + "本地服务或界面脚本:0xf02f 由 AcesApp::tryRespawn 在本地进程内通过 MPI 回环投递至 Unit::onEvent,纯属 C++ 战局权威状态机,不经过网络服务或 Quirrel 脚本。" + ], + "conclusion": "在 0x1044ecc 处将 1 字节条件跳转操作码 0x72(jb)改为 0xeb(jmp),复用紧随其后的完整 0x1044f03 人类玩家出生流程(rdx 已在 0x1044ec2 加载为 MPlayer*)。", + "if_not_applied": "玩家在 LocalMP 对局重生界面选车点击「加入战斗!」并等完倒计时后,每次都会被静默重置回 GUI_STATE_CA_SELECT,按钮恢复为「加入战斗!」,永远无法刷出载具参战。" + }, + + "why_this_site": [ + "0x1044dfa-0x1044e8a 已在前方完成了 GUI_STATE_CA_READY(8)与开局倒计时检查,0x1044ec2 也已将 MPlayer* 装入 rdx(0x1044f03 入口所需寄存器状态已就绪)。", + "远程联机客户端在 AcesApp::tryRespawn(0xc6c3da)中将 0xf02f 发往远端主机而非本地执行,只有本地作为权威主机时才会走到 0x1044ecc。", + "仅修改 1 个字节(72 35 -> eb 35),指令长度完全不变(2 字节),不改任何寄存器、栈帧或异常展开表。" + ], + + "features": ["K-战局任务加载"], + "requires": [], + "evidence": [ + "2.61.0.37 原版 aces.exe:AcesApp::tryRespawn 0xc6c279-0xc6c4af(投递 0xf02f),Unit::onEvent 0x103fbc0 中 0xf02f 入口 0x1042cff,模式拦截 0x1044eb9-0x1044efc,区域校验汇合点 0x1046b61-0x1046c33,完整人类出生路径 0x1044f03-0x104502c -> 0x1045c4c -> 0x1046a24(0xfec9c0 派发 0xf030)。", + "2.61.0.37 实测战斗日志(2026_11_27_07_21_47__51360.clog 154.23s):输出 \"unit respawn request received uid:44 name:tankModels/ussr_t_72b3_arena\" 后紧接着输出 \"[GUISTATE] set GUI_STATE_CA_SELECT to player 0\",未输出 \"sending unit respawn\"。" + ], + "verified_on": ["2.61.0.37"], + + "edit": { + "offset": 49, + "asm": [ + "jmp 0x37" + ], + "bytes": "eb35", + "expect_original": "7235" + } +} diff --git a/gui-patches/battle/append-extra-battle-slots/patch.json b/gui-patches/battle/append-extra-battle-slots/patch.json new file mode 100644 index 0000000..485ab59 --- /dev/null +++ b/gui-patches/battle/append-extra-battle-slots/patch.json @@ -0,0 +1,11 @@ +{ + "id": "battle/append-extra-battle-slots", + "title": "Append session killstreak aircraft and random-spawn vehicles to in-battle crew list", + "file": "scripts/slotbar/crewslist.nut", + "reason": "Dedicated servers append nuclear bombers, strike UCAVs, and RandomSpawnUnits filler slots to the battle crew list; appending activeBattle.extraBattleSlots when isInBattle is true exposes those slots to the respawn screen and slotbar.", + "features": ["J-本地对局", "K-战局任务加载"], + "edit": { + "find": " let res = crewInfo.filter(@(v) v.country == curCountry)\r\n if (res.len() == 1)\r\n return res.map(\r\n @(countryInfo) countryInfo.__merge({\r\n crews = countryInfo.crews.map(@(crew) crew.__merge({idCountry = 0}))\r\n })\r\n )", + "replace": " let appendWtoExtraBattleCrews = function(baseCrews) {\r\n let { ndbTryRead } = require(\"nestdb\")\r\n let wtoBattle = ndbTryRead([\"wto\", \"activeBattle\"])\r\n let extraSlots = wtoBattle?.extraBattleSlots\r\n if (extraSlots == null || extraSlots.len() == 0)\r\n return baseCrews\r\n if ((wtoBattle?.country ?? \"\") != \"\" && wtoBattle.country != curCountry)\r\n return baseCrews\r\n let merged = [].extend(baseCrews)\r\n foreach (idx, slot in extraSlots) {\r\n if (merged.len() >= 32)\r\n break\r\n let unitName = slot?.unitName ?? \"\"\r\n if (unitName == \"\")\r\n continue\r\n merged.append({\r\n id = -1 - idx\r\n idCountry = 0\r\n idInCountry = merged.len()\r\n country = curCountry\r\n aircraft = unitName\r\n isEmpty = 0\r\n trainedSpec = { [unitName] = 2 }\r\n trained = [unitName]\r\n skillPoints = 0\r\n lockedTillSec = 0\r\n isLocked = 0\r\n })\r\n }\r\n return merged\r\n }\r\n let res = crewInfo.filter(@(v) v.country == curCountry)\r\n if (res.len() == 1)\r\n return res.map(\r\n @(countryInfo) countryInfo.__merge({\r\n crews = appendWtoExtraBattleCrews(\r\n countryInfo.crews.map(@(crew) crew.__merge({idCountry = 0}))\r\n )\r\n })\r\n )" + } +} diff --git a/gui-patches/battle/force-extra-slot-weapons/patch.json b/gui-patches/battle/force-extra-slot-weapons/patch.json new file mode 100644 index 0000000..f4549aa --- /dev/null +++ b/gui-patches/battle/force-extra-slot-weapons/patch.json @@ -0,0 +1,11 @@ +{ + "id": "battle/force-extra-slot-weapons", + "title": "Lock nuclear, strike-UCAV, and RandomSpawnUnits forced weapon presets in LocalMP", + "file": "scripts/miscustomrules/rulebase.nut", + "reason": "Extra battle slots require fixed nuclear bomb or strike-UCAV missile presets and fallback RandomSpawnUnits event lookup when session room event metadata is local.", + "features": ["D-改装件与挂载", "J-本地对局"], + "edit": { + "find": " function getForcedUnitWeapon(unit) {\r\n let groupName = this.getRandomUnitsGroupName(unit.name)\r\n if (groupName == null)\r\n return this.missionParams?.editSlotbar[unit.shopCountry][unit.name][\"forceWeapon\"]\r\n\r\n return getRandomUnitsForceWeapon(getEventEconomicName(getRoomEvent()), unit.name)\r\n }", + "replace": " function getForcedUnitWeapon(unit) {\r\n let { ndbTryRead } = require(\"nestdb\")\r\n let wtoBattle = ndbTryRead([\"wto\", \"activeBattle\"])\r\n foreach (wtoSlot in (wtoBattle?.extraBattleSlots ?? [])) {\r\n if (wtoSlot?.unitName == unit.name && (wtoSlot?.forceWeapon ?? \"\") != \"\")\r\n return wtoSlot.forceWeapon\r\n }\r\n let groupName = this.getRandomUnitsGroupName(unit.name)\r\n if (groupName == null)\r\n return this.missionParams?.editSlotbar[unit.shopCountry][unit.name][\"forceWeapon\"]\r\n\r\n let wtoRoomEcon = getEventEconomicName(getRoomEvent())\r\n let wtoEconName = wtoRoomEcon != \"\" ? wtoRoomEcon : (wtoBattle?.randomUnitsEventName ?? \"\")\r\n return getRandomUnitsForceWeapon(wtoEconName, unit.name)\r\n }" + } +} diff --git a/gui-patches/battle/launch-local-battle-from-queue/patch.json b/gui-patches/battle/launch-local-battle-from-queue/patch.json new file mode 100644 index 0000000..972d407 --- /dev/null +++ b/gui-patches/battle/launch-local-battle-from-queue/patch.json @@ -0,0 +1,11 @@ +{ + "id": "battle/launch-local-battle-from-queue", + "title": "Launch local authoritative multiplayer battle on queue notification", + "file": "scripts/matching/servicenotifications/match.nut", + "reason": "Start an authoritative LocalMP host session from matching notifications with multi-nation coalition room state, per-difficulty mission ticket overrides, persistent killstreak spawn costs, and extra battle slot metadata.", + "features": ["battle-matchmaking", "mission-launch", "ai-bots"], + "edit": { + "find": " matchingApiFunc(\"match.enqueue\", cb, params)\r\n}\r\n\r\nmatchingRpcSubscribe(\"match.notify_clusters_changed\", onClustersChanged)", + "replace": " matchingApiFunc(\"match.enqueue\", cb, params)\r\n}\r\n\r\nfunction fillWtoBotEntries(parentBlk, blockName, entries) {\r\n if (entries == null)\r\n return\r\n foreach (entry in entries) {\r\n let b = parentBlk.addNewBlock(blockName)\r\n b.name = entry.name\r\n b.weight = (entry?.weight ?? 1.0).tofloat()\r\n b.country = entry.country\r\n }\r\n}\r\n\r\nfunction copyWtoMissionMetadata(misBlk, missionFile, difficulty) {\r\n if (missionFile == null || missionFile == \"\")\r\n return\r\n let { blkOptFromPath } = require(\"%sqstd/datablock.nut\")\r\n let rawMis = blkOptFromPath(missionFile)?.mission_settings?.mission\r\n if (rawMis == null)\r\n return\r\n let ruleKeys = [\r\n \"scoreLimit\", \"timeLimit\", \"killLimit\", \"deathPenaltyMul\",\r\n \"ctaCaptureZoneEqualPenaltyMul\", \"ctaCaptureZonePenaltyMul\",\r\n \"captureZonePenaltyMul\", \"scorePerSec\",\r\n \"ctaInstantDecreaseTicketsWhenNoRespawn\",\r\n \"randomSpawnTeams\", \"remapAiTankModels\", \"useAlternativeMapCoord\"\r\n ]\r\n foreach (key in [\r\n \"locName\", \"locDesc\", \"locNameTeamA\", \"locNameTeamB\",\r\n \"locDescTeamA\", \"locDescTeamB\", \"loc_name\", \"postfix\", \"restoreType\"\r\n ].extend(ruleKeys)) {\r\n let val = rawMis?[key]\r\n if (val != null)\r\n misBlk[key] = val\r\n }\r\n let targetDiff = (difficulty == \"simulator\" || difficulty == \"fullreal\") ? \"hardcore\"\r\n : (difficulty == \"historical\" ? \"realistic\" : difficulty)\r\n foreach (sub in (rawMis % \"mission\")) {\r\n let subDiff = sub?.difficulty\r\n if (subDiff != difficulty && subDiff != targetDiff)\r\n continue\r\n foreach (dKey in ruleKeys) {\r\n let dVal = sub?[dKey]\r\n if (dVal != null)\r\n misBlk[dKey] = dVal\r\n }\r\n }\r\n}\r\n\r\nfunction toWtoPrefixedCountries(list, fallback) {\r\n let src = (list != null && list.len() > 0) ? list : [fallback]\r\n return src.map(@(c) c.indexof(\"country_\") == 0 ? c : $\"country_{c}\")\r\n}\r\n\r\nfunction buildWtoMissionBlk(ev, gmConsts, guiMis) {\r\n let DataBlock = require(\"DataBlock\")\r\n let misBlk = DataBlock()\r\n let baseBlk = guiMis.get_meta_mission_info_by_gm_and_name(gmConsts.GM_SKIRMISH, ev.missionName)\r\n ?? guiMis.get_meta_mission_info_by_name(ev.missionName)\r\n copyWtoMissionMetadata(misBlk, ev?.missionFile, ev.difficulty)\r\n let levelVal = ev?.level ?? baseBlk?.level ?? misBlk?.level\r\n let envVal = ev?.environment ?? baseBlk?.environment ?? misBlk?.environment\r\n let weatherVal = ev?.weather ?? baseBlk?.weather ?? misBlk?.weather\r\n if (levelVal != null)\r\n misBlk.level = levelVal\r\n if (envVal != null)\r\n misBlk.environment = envVal\r\n if (weatherVal != null)\r\n misBlk.weather = weatherVal\r\n\r\n misBlk.localMP = true\r\n misBlk._gameMode = gmConsts.GM_DOMINATION\r\n misBlk.name = ev.missionName\r\n misBlk.economicName = ev.economicName\r\n misBlk.mis_file = ev.missionFile\r\n misBlk.chapter = \"skirmish\"\r\n misBlk.type = ev.missionType\r\n misBlk.difficulty = ev.difficulty\r\n misBlk.country_allies = ev.countryAllies\r\n misBlk.country_axis = ev.countryAxis\r\n misBlk.arcadeCountry = true\r\n misBlk.symmetricTeams = ev?.symmetricTeams ?? false\r\n misBlk.gt_versus = true\r\n misBlk.gt_mp_tickets = true\r\n misBlk.gt_mp_capture = true\r\n misBlk.gt_mp_solo = false\r\n misBlk.gt_use_wp = true\r\n misBlk.gt_use_xp = true\r\n misBlk.gt_use_stats = true\r\n misBlk.gt_use_unlocks = true\r\n misBlk.useSpawnScore = ev?.useSpawnScore ?? false\r\n misBlk.allowSpare = true\r\n misBlk.isLimitedAmmo = true\r\n misBlk.allowUseArtillerySupport = true\r\n misBlk.isBotsAllowed = true\r\n misBlk.useTankBots = ev?.useTankBots ?? false\r\n misBlk.useShipBots = ev?.useShipBots ?? false\r\n misBlk.autoBalance = true\r\n misBlk.maxPlayers = ev.maxPlayers\r\n misBlk.maxBots = ev.maxBots\r\n\r\n let extraSlots = ev?.extraBattleSlots ?? []\r\n local persistentBlk = null\r\n foreach (slot in extraSlots) {\r\n let cost = slot?.persistentCost ?? 0\r\n let uName = slot?.unitName ?? \"\"\r\n if (cost > 0 && uName != \"\") {\r\n if (persistentBlk == null)\r\n persistentBlk = misBlk.addNewBlock(\"customSpawnScore\").addNewBlock(\"persistent_costs\")\r\n persistentBlk[uName] = cost.tointeger()\r\n }\r\n }\r\n\r\n foreach (tag in [\"ranks\", \"forcedRanks\"]) {\r\n let rBlk = misBlk.addNewBlock(tag)\r\n rBlk.min = ev.minMrank\r\n rBlk.max = ev.maxMrank\r\n }\r\n let alliesBare = ev?.countriesAllies ?? [ev.countryAllies]\r\n let axisBare = ev?.countriesAxis ?? [ev.countryAxis]\r\n let botsBlk = misBlk.addNewBlock(\"customBots\")\r\n botsBlk.wtoPlayerTeam = $\"{ev?.playerTeam ?? 1}\"\r\n botsBlk.wtoTeamACountries = \";\".join(alliesBare)\r\n botsBlk.wtoTeamBCountries = \";\".join(axisBare)\r\n botsBlk.numBotRespawnsInMultiSlot = ev.airBotRespawns\r\n botsBlk.numTankBotRespawnsInMultiSlot = ev.tankBotRespawns\r\n botsBlk.numBotRespawnsInVersus = ev.airBotRespawns\r\n botsBlk.numTankBotRespawnsInVersus = ev.tankBotRespawns\r\n fillWtoBotEntries(botsBlk.addNewBlock(\"allowedTanks\"), \"tank\", ev?.customBots?.tanks)\r\n fillWtoBotEntries(botsBlk.addNewBlock(\"allowedAircrafts\"), \"aircraft\", ev?.customBots?.aircrafts)\r\n fillWtoBotEntries(botsBlk.addNewBlock(\"allowedShips\"), \"ship\", ev?.customBots?.ships)\r\n return misBlk\r\n}\r\n\r\nfunction enterWtoSessionRoom(ev, gmConsts) {\r\n let lobbyStates = require(\"%scripts/matchingRooms/lobbyStates.nut\")\r\n let { setSessionLobbySettings, switchSessionLobbyStatus } = require(\"%scripts/matchingRooms/sessionLobbyManager.nut\")\r\n let alliesCountries = toWtoPrefixedCountries(ev?.countriesAllies, ev.countryAllies)\r\n let axisCountries = toWtoPrefixedCountries(ev?.countriesAxis, ev.countryAxis)\r\n setSessionLobbySettings({\r\n game_mode_id = ev.modeId\r\n game_mode_name = ev.modeName\r\n economicName = ev.economicName\r\n symmetricTeams = ev?.symmetricTeams ?? false\r\n country_allies = alliesCountries\r\n country_axis = axisCountries\r\n mission = {\r\n name = ev.missionName\r\n _gameMode = gmConsts.GM_DOMINATION\r\n difficulty = ev.difficulty\r\n }\r\n }, true, false)\r\n switchSessionLobbyStatus(lobbyStates.IN_SESSION)\r\n}\r\n\r\nfunction onWtoBattleNotify(ev) {\r\n if (ev?.func != \"launch\" || isInFlight())\r\n return\r\n let { ndbWrite } = require(\"nestdb\")\r\n let guiMis = require(\"guiMission\")\r\n let missionMod = require(\"mission\")\r\n let gmConsts = require(\"%globalScripts/gameModeNativeConsts.nut\")\r\n let { reset_cur_mission_mode } = require(\"%appGlobals/ranks_common_shared.nut\")\r\n let { notifyQueueLeave } = require(\"%scripts/queue/queueManager.nut\")\r\n let destroySessionScripted = require(\"%scripts/matchingRooms/destroySessionScripted.nut\")\r\n let { invalidateCrewsList } = require(\"%scripts/slotbar/crewsList.nut\")\r\n let { guiStartFlight } = require(\"%scripts/missions/startMissionsList.nut\")\r\n let { currentCampaignMission } = require(\"%scripts/missions/missionsStates.nut\")\r\n\r\n notifyQueueLeave({})\r\n destroySessionScripted(\"on start wto local battle\")\r\n ndbWrite([\"wto\", \"activeBattle\"], {\r\n sessionId = ev.sessionId\r\n modeName = ev.modeName\r\n economicName = ev.economicName\r\n country = ev.country\r\n missionName = ev.missionName\r\n extraBattleSlots = ev?.extraBattleSlots ?? []\r\n randomUnits = ev?.randomUnits ?? {}\r\n randomUnitsEventName = ev?.randomUnitsEventName ?? \"\"\r\n })\r\n invalidateCrewsList(true)\r\n let misBlk = buildWtoMissionBlk(ev, gmConsts, guiMis)\r\n currentCampaignMission.set(ev.missionName)\r\n missionMod.set_game_mode(gmConsts.GM_DOMINATION)\r\n enterWtoSessionRoom(ev, gmConsts)\r\n reset_cur_mission_mode()\r\n guiMis.select_training_mission(misBlk)\r\n reset_cur_mission_mode()\r\n guiStartFlight()\r\n}\r\n\r\nrequire(\"%sqStdLibs/helpers/subscriptions.nut\").addListenersWithoutEnv({\r\n SessionDestroyed = function(_p) {\r\n if (!isInFlight()) {\r\n let { ndbExists, ndbDelete } = require(\"nestdb\")\r\n if (ndbExists([\"wto\", \"activeBattle\"])) {\r\n ndbDelete([\"wto\", \"activeBattle\"])\r\n require(\"%scripts/slotbar/crewsList.nut\").invalidateCrewsList(true)\r\n }\r\n }\r\n }\r\n})\r\n\r\nrequire(\"%scripts/matching/serviceNotifications/mrpc.nut\").mnSubscribe(\"wto_battle\", onWtoBattleNotify)\r\n\r\nmatchingRpcSubscribe(\"match.notify_clusters_changed\", onClustersChanged)" + } +} diff --git a/gui-patches/battle/lineup-br-for-submodes/patch.json b/gui-patches/battle/lineup-br-for-submodes/patch.json new file mode 100644 index 0000000..d034703 --- /dev/null +++ b/gui-patches/battle/lineup-br-for-submodes/patch.json @@ -0,0 +1,30 @@ +{ + "id": "battle/lineup-br-for-submodes", + "title": "多槽位预设模式下按整套可用出击阵容最高权重判定夜间战斗等附加子模式可用性", + "file": "scripts/events/secondgamemodesutils.nut", + + "program_behaviour": { + "stock": "secondgamemodesutils.nut 的 getCurRank(event) 在单人未组队状态下只读取机库当前鼠标高亮的单辆载具 getPlayerCurUnit(),导致在陆战历史性能等多槽位(multiSlot)模式中,即使预设编队内拥有 10.0+ 载具(面板标题已显示 12.0 权重),只要当前高亮槽位载具低于 10.0(如 9.7 的 BMD-4M),夜间战斗就会被误判为「不可用(仅限 10.0 及以上权重)」。", + "patched": "当处于单人且当前赛事启用了多槽位出击(events.isEventMultiSlotEnabled(event))时,遍历玩家当前国家的可用预设乘员组载具(getOwnCraftNames() 中允许参加该赛事的载具),取最高有效匹配分房等级(mrank)用于判定子模式可用性;单槽位模式(如空战历史性能的小规模战斗)仍保持只检查当前选中载具。" + }, + + "derivation": { + "requirement": "Evaluate Night Battles and other multi-slot sub-mode BR requirements against the highest-BR eligible vehicle in the player's active preset lineup rather than only the currently highlighted crew slot.", + "cause": "getCurRank(event) 在组队时调用 getRecentSquadMrank()(来自 wtmm_static.calc_ranks 的整套预设最高分房),但单人分支直接退化为读取 getPlayerCurUnit(),忽略了多槽位赛事中同预设其它槽位的高权重载具。", + "lighter_options_ruled_out": [ + "仅靠本地服务:本地服务 wtmm_static.calc_ranks 已正确返回 12.0 权重(recentBR 已显示 12.0),但客户端 isNightModeAvalible(event) 不读取 recentBR,而是直接调用本地脚本函数 getCurRank(event) 禁用开关控件。" + ], + "conclusion": "在 secondgamemodesutils.nut 的 getCurRank(event) 中对多槽位模式汇总预设内赛事允许载具的最大有效 mrank。", + "if_not_applied": "多槽位编队同时携带低权重与 10.0+ 高权重载具时,一旦机库高亮停留在低于 10.0 的槽位上,夜间战斗开关即被锁死并提示不可用,与顶栏显示的整套编队权重自相矛盾。" + }, + + "features": ["J-对局模式目录与队列"], + "evidence": [ + "2.61.0.37 gui.vromfs.bin:scripts/events/secondgamemodesutils.nut 第 123-157、426-460 行,scripts/mainmenu/secondgamemodespanel.nut 第 70-103 行,scripts/events/eventsmanager.nut 第 902、1043、1248 行。" + ], + + "edit": { + "find": "function getCurRank(event) {\r\n if (isInSquad())\r\n return getRecentSquadMrank()\r\n\r\n let unit = getPlayerCurUnit()\r\n return unit == null ? null : getEffectiveMrank(unit, events.getEDiffByEvent(event))\r\n}", + "replace": "function getCurRank(event) {\r\n if (isInSquad())\r\n return getRecentSquadMrank()\r\n\r\n let ediff = events.getEDiffByEvent(event)\r\n if (events.isEventMultiSlotEnabled(event)) {\r\n let ownCraftNames = getOwnCraftNames()\r\n let mrankDeltaByUnit = getMrankDeltaByUnit(ownCraftNames)\r\n local maxMrank = null\r\n foreach (unitName in ownCraftNames) {\r\n let unit = getAircraftByName(unitName)\r\n if (unit != null && events.isUnitAllowedForEvent(event, unit)) {\r\n let mrank = getEffectiveMrank(unit, ediff, mrankDeltaByUnit?[unitName] ?? 0)\r\n maxMrank = maxMrank == null ? mrank : max(maxMrank, mrank)\r\n }\r\n }\r\n if (maxMrank != null)\r\n return maxMrank\r\n }\r\n\r\n let unit = getPlayerCurUnit()\r\n return unit == null ? null : getEffectiveMrank(unit, ediff)\r\n}" + } +} diff --git a/gui-patches/battle/local-host-spawn-score/patch.json b/gui-patches/battle/local-host-spawn-score/patch.json new file mode 100644 index 0000000..46336ef --- /dev/null +++ b/gui-patches/battle/local-host-spawn-score/patch.json @@ -0,0 +1,11 @@ +{ + "id": "battle/local-host-spawn-score", + "title": "Register missing LocalMP host spawn-point callbacks and preserve persistent costs", + "file": "scripts/respawn/respawnstate.nut", + "reason": "Client script packs omit server-only get_max_spawn_score and get_unit_spawn_score callbacks, and get_unit_spawn_score_weapon_mul otherwise scales persistent killstreak costs by bomb/missile mass.", + "features": ["K-战局任务加载"], + "edit": { + "find": "registerRespondent(\"get_spawn_score_type_mul\", get_spawn_score_type_mul)\r\nregisterRespondent(\"get_unit_spawn_score_weapon_mul\", get_unit_spawn_score_weapon_mul)", + "replace": "function calcWtoMaxSpawnScore(_userId, _maxRank) {\r\n let ranksShared = require(\"%appGlobals/ranks_common_shared.nut\")\r\n let mathMod = require(\"math\")\r\n let baseCoef = ranksShared.get_spawn_score_param(\"base_respawn_points_coef\", 450)\r\n let maxMul = ranksShared.get_spawn_score_param(\"maxRespawnPointsMul\", 1.0)\r\n return mathMod.max(0, mathMod.round(baseCoef * maxMul).tointeger())\r\n}\r\n\r\nfunction calcWtoUnitSpawnScore(_userId, unitName, _unitRankArg) {\r\n if (unitName == null || unitName == \"\")\r\n return 0\r\n let ranksShared = require(\"%appGlobals/ranks_common_shared.nut\")\r\n let { get_current_mission_info_cached, get_wpcost_blk } = require(\"blkGetters\")\r\n let { round_by_value } = require(\"%sqstd/math.nut\")\r\n let mathMod = require(\"math\")\r\n let misBlk = get_current_mission_info_cached()\r\n let persistentCost = misBlk?.customSpawnScore?.persistent_costs?[unitName] ?? 0\r\n if (persistentCost > 0)\r\n return persistentCost.tointeger()\r\n let unitClass = ranksShared.getWpcostUnitClass(unitName)\r\n let costMul = ranksShared.get_spawn_score_param(unitName, null)\r\n ?? ranksShared.get_spawn_score_param(unitClass, 0.0)\r\n if (costMul <= 0.0)\r\n return 0\r\n let baseCoef = ranksShared.get_spawn_score_param(\"base_respawn_points_coef\", 450)\r\n let unitType = ranksShared.get_unit_type_by_unit_name(unitName)\r\n let brDiffMul = ranksShared.get_spawn_score_param($\"br_diff_mul_{unitType}\", 0.0)\r\n let maxBrDiff = ranksShared.get_spawn_score_param(\"max_br_diff\", 1.0)\r\n let sessionMaxRank = misBlk?.ranks?.max ?? 0\r\n let unitBlk = get_wpcost_blk()?[unitName]\r\n let ediff = ranksShared.get_mission_mode()\r\n let unitRank = ranksShared.get_unit_blk_economic_rank_by_mode(unitBlk, ediff, sessionMaxRank)\r\n local brFactor = 1.0\r\n if (maxBrDiff > 0.0 && brDiffMul != 0.0) {\r\n let sessionBr = ranksShared.calcBattleRatingFromRank(sessionMaxRank)\r\n let unitBr = ranksShared.calcBattleRatingFromRank(unitRank)\r\n let brDiff = mathMod.clamp(sessionBr - unitBr, 0.0, maxBrDiff)\r\n brFactor = 1.0 - brDiffMul * (brDiff / maxBrDiff)\r\n }\r\n let rawScore = baseCoef * costMul * brFactor\r\n return mathMod.max(1, round_by_value(rawScore, 10).tointeger())\r\n}\r\n\r\nfunction calcWtoUnitSpawnScoreWeaponMul(unitname, weapon, bulletArray, presetTbl = {}) {\r\n let { get_current_mission_info_cached } = require(\"blkGetters\")\r\n let persistentCost = get_current_mission_info_cached()?.customSpawnScore?.persistent_costs?[unitname] ?? 0\r\n if (persistentCost > 0)\r\n return 1.0\r\n return get_unit_spawn_score_weapon_mul(unitname, weapon, bulletArray, presetTbl)\r\n}\r\n\r\nregisterRespondent(\"get_max_spawn_score\", calcWtoMaxSpawnScore)\r\nregisterRespondent(\"get_unit_spawn_score\", calcWtoUnitSpawnScore)\r\nregisterRespondent(\"get_spawn_score_type_mul\", get_spawn_score_type_mul)\r\nregisterRespondent(\"get_unit_spawn_score_weapon_mul\", calcWtoUnitSpawnScoreWeaponMul)" + } +} diff --git a/gui-patches/battle/pass-spawn-modifications-blk/patch.json b/gui-patches/battle/pass-spawn-modifications-blk/patch.json new file mode 100644 index 0000000..a7cf0bd --- /dev/null +++ b/gui-patches/battle/pass-spawn-modifications-blk/patch.json @@ -0,0 +1,11 @@ +{ + "id": "battle/pass-spawn-modifications-blk", + "title": "Pass enabled modifications, spaded extra-slot loadout, and unit reward rates on LocalMP spawn", + "file": "scripts/respawn/respawn.nut", + "reason": "Forward enabled/disabled modifications, forced presets for extra battle slots, class-scaled warpoints/wpcost rates, and silent-preview state through requestAircraftAndWeaponWithSlots for LocalMP.", + "features": ["modifications-loadout", "local-battle"], + "edit": { + "find": " function requestAircraftAndWeapon(requestData) {\r\n if (this.requestInProgress)\r\n return\r\n\r\n set_aircraft_accepted_cb(this, this.aircraftAcceptedCb);\r\n let _taskId = requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry,\r\n requestData.respBaseId, requestData.spareUid)\r\n if (_taskId < 0)\r\n set_aircraft_accepted_cb(null, null);\r\n else {\r\n this.requestInProgress = true\r\n this.showTaskProgressBox(loc(\"charServer/purchase0\"), function() { this.requestInProgress = false })\r\n\r\n this.lastRequestData = requestData\r\n }\r\n }\r\n\r\n function requestChangeUnitSilent() {\r\n let unit = this.getCurSlotUnit()\r\n if (!unit?.isHuman() || !this.canChangeAircraft || this.isApplyPressed) {\r\n this.isSilentRequestPending = false\r\n return\r\n }\r\n this.isSilentRequestPending = this.requestInProgress || !canRequestAircraftNow()\r\n if (this.isSilentRequestPending)\r\n return\r\n\r\n let requestData = this.getSelectedRequestData(true)\r\n if (!requestData)\r\n return\r\n\r\n set_aircraft_accepted_cb(this, this.silentAircraftAcceptedCb);\r\n let _taskId = requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry,\r\n requestData.respBaseId, requestData.spareUid)\r\n if (_taskId < 0)\r\n set_aircraft_accepted_cb(null, null);\r\n else {\r\n this.requestInProgress = true\r\n this.lastRequestData = requestData\r\n }\r\n }", + "replace": " function sendWtoAircraftAndWeaponRequest(requestData, isSilent = false) {\r\n let wtoNdb = require(\"nestdb\")\r\n if (!wtoNdb.ndbExists([\"wto\", \"activeBattle\"]))\r\n return requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry,\r\n requestData.respBaseId, requestData.spareUid)\r\n let wtoBattle = wtoNdb.ndbTryRead([\"wto\", \"activeBattle\"])\r\n let wtoGuiRespawn = require(\"guiRespawn\")\r\n let wtoChardRes = require(\"chardResearch\")\r\n let wtoBlkGetters = require(\"blkGetters\")\r\n let wtoUnitName = requestData?.name ?? \"\"\r\n local wtoExtraSlot = null\r\n foreach (slot in (wtoBattle?.extraBattleSlots ?? [])) {\r\n if (slot?.unitName == wtoUnitName) {\r\n wtoExtraSlot = slot\r\n break\r\n }\r\n }\r\n if ((wtoExtraSlot?.forceWeapon ?? \"\") != \"\")\r\n requestData.weapon = wtoExtraSlot.forceWeapon\r\n let wtoIsSpaded = wtoExtraSlot?.spaded == true\r\n let wtoUnit = getAircraftByName(wtoUnitName) ?? this.getCurSlotUnit()\r\n let wtoEnabledMods = []\r\n let wtoDisabledMods = []\r\n foreach (wtoMod in (wtoUnit?.getModifications() ?? [])) {\r\n let wtoModName = wtoMod?.name ?? \"\"\r\n if (wtoModName == \"\")\r\n continue\r\n if (wtoIsSpaded || wtoChardRes.shopIsModificationEnabled(wtoUnitName, wtoModName))\r\n wtoEnabledMods.append(wtoModName)\r\n else if (wtoChardRes.shopIsModificationPurchased(wtoUnitName, wtoModName))\r\n wtoDisabledMods.append(wtoModName)\r\n }\r\n let wtoEdiff = this.getCurrentEdiff()\r\n let wtoDiffRem = wtoEdiff >= 0 ? (wtoEdiff % 3) : 1\r\n let wtoDiffSuffix = wtoDiffRem == 0 ? \"Arcade\" : wtoDiffRem == 1 ? \"Historical\" : \"Simulation\"\r\n let wtoUnitCost = get_wpcost_blk()?[wtoUnitName]\r\n let wtoWarBlk = wtoBlkGetters.get_warpoints_blk()\r\n let wtoBlk = DataBlock()\r\n wtoBlk.enabledMods = \";\".join(wtoEnabledMods)\r\n wtoBlk.disabledMods = \";\".join(wtoDisabledMods)\r\n wtoBlk.isSilentPreview = isSilent ? \"1\" : \"0\"\r\n if (wtoUnitCost != null && wtoWarBlk != null) {\r\n let wtoClassKillMul = wtoWarBlk.units[wtoUnitCost.unitClass].tofloat()\r\n let wtoRewardMul = wtoUnitCost[$\"rewardMul{wtoDiffSuffix}\"].tofloat()\r\n wtoBlk.wpPerKill = (wtoWarBlk.aKill.tofloat() * wtoClassKillMul * wtoWarBlk.wpMultiplier.tofloat() * wtoRewardMul).tofloat()\r\n wtoBlk.expMul = wtoUnitCost.expMul.tofloat()\r\n wtoBlk.battleTimeAward = wtoUnitCost[$\"battleTimeAward{wtoDiffSuffix}\"].tofloat()\r\n wtoBlk.aiKillK = wtoWarBlk.aiKillK.tofloat()\r\n wtoBlk.winK = wtoWarBlk.winK.tofloat()\r\n }\r\n if (!isSilent && (requestData?.spareUid ?? \"\") != \"\" && wtoUnitName != \"\") {\r\n let prevSpares = wtoBattle?.usedSpares ?? {}\r\n prevSpares[wtoUnitName] <- (prevSpares?[wtoUnitName] ?? 0) + 1\r\n wtoBattle.usedSpares <- prevSpares\r\n wtoNdb.ndbWrite([\"wto\", \"activeBattle\"], wtoBattle)\r\n }\r\n return wtoGuiRespawn.requestAircraftAndWeaponWithSlots(requestData, requestData.idInCountry,\r\n requestData.respBaseId, requestData.spareUid, wtoBlk, DataBlock())\r\n }\r\n\r\n function requestAircraftAndWeapon(requestData) {\r\n if (this.requestInProgress)\r\n return\r\n\r\n set_aircraft_accepted_cb(this, this.aircraftAcceptedCb);\r\n let _taskId = this.sendWtoAircraftAndWeaponRequest(requestData, false)\r\n if (_taskId < 0)\r\n set_aircraft_accepted_cb(null, null);\r\n else {\r\n this.requestInProgress = true\r\n this.showTaskProgressBox(loc(\"charServer/purchase0\"), function() { this.requestInProgress = false })\r\n\r\n this.lastRequestData = requestData\r\n }\r\n }\r\n\r\n function requestChangeUnitSilent() {\r\n let unit = this.getCurSlotUnit()\r\n if (!unit?.isHuman() || !this.canChangeAircraft || this.isApplyPressed) {\r\n this.isSilentRequestPending = false\r\n return\r\n }\r\n this.isSilentRequestPending = this.requestInProgress || !canRequestAircraftNow()\r\n if (this.isSilentRequestPending)\r\n return\r\n\r\n let requestData = this.getSelectedRequestData(true)\r\n if (!requestData)\r\n return\r\n\r\n set_aircraft_accepted_cb(this, this.silentAircraftAcceptedCb);\r\n let _taskId = this.sendWtoAircraftAndWeaponRequest(requestData, true)\r\n if (_taskId < 0)\r\n set_aircraft_accepted_cb(null, null);\r\n else {\r\n this.requestInProgress = true\r\n this.lastRequestData = requestData\r\n }\r\n }" + } +} diff --git a/gui-patches/battle/populate-random-spawn-units-state/patch.json b/gui-patches/battle/populate-random-spawn-units-state/patch.json new file mode 100644 index 0000000..0e20cb8 --- /dev/null +++ b/gui-patches/battle/populate-random-spawn-units-state/patch.json @@ -0,0 +1,11 @@ +{ + "id": "battle/populate-random-spawn-units-state", + "title": "Populate local player's random_units state block in LocalMP sessions", + "file": "scripts/miscustomrules/rulebase.nut", + "reason": "Online servers replicate random_units candidate lists into MPlayer custom state; populating get_user_custom_state from activeBattle.randomUnits enables native dice icons, group titles, BR ranges, and hover candidate tooltips on slotbarview.", + "features": ["J-本地对局", "K-战局任务加载"], + "edit": { + "find": " function getMyStateBlk() {\r\n return get_user_custom_state(userIdInt64.get(), false)\r\n }", + "replace": " function getMyStateBlk() {\r\n let wtoUid = userIdInt64.get()\r\n local wtoStateBlk = get_user_custom_state(wtoUid, false)\r\n let { ndbTryRead } = require(\"nestdb\")\r\n let wtoRandom = ndbTryRead([\"wto\", \"activeBattle\"])?.randomUnits\r\n if (wtoRandom == null || wtoRandom.len() == 0)\r\n return wtoStateBlk\r\n if (wtoStateBlk == null)\r\n wtoStateBlk = get_user_custom_state(wtoUid, true) ?? DataBlock()\r\n if (wtoStateBlk?.random_units == null) {\r\n let wtoRuBlk = wtoStateBlk.addNewBlock(\"random_units\")\r\n foreach (wtoGroupName, wtoUnits in wtoRandom) {\r\n if (wtoUnits == null || wtoUnits.len() == 0)\r\n continue\r\n let wtoGroupBlk = wtoRuBlk.addNewBlock(wtoGroupName)\r\n foreach (wtoUnitName in wtoUnits)\r\n wtoGroupBlk[wtoUnitName] = true\r\n }\r\n }\r\n return wtoStateBlk\r\n }" + } +} diff --git a/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.json b/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.json new file mode 100644 index 0000000..fe3c44b --- /dev/null +++ b/gui-patches/battle/quit-local-host-spectator-to-debriefing/patch.json @@ -0,0 +1,31 @@ +{ + "id": "battle/quit-local-host-spectator-to-debriefing", + "title": "重生与观战界面在本地多人主机模式下退出任务时直接进入战后结算", + "file": "scripts/hud/starthud.nut", + + "program_behaviour": { + "stock": "quitMission() 在重生或观战界面只要判断 is_multiplayer() 为真就调用 leave_mp_session() 并提前返回;在 LocalMP 主机模式下 leave_mp_session() 为空操作,无法退到结算界面。", + "patched": "仅在 is_multiplayer() && !is_mplayer_host() 时调用 leave_mp_session(),本地主机继续执行下方的 quit_to_debriefing() 与 interrupt_multiplayer(true)。" + }, + + "derivation": { + "requirement": "Allow leaving a LocalMP battle from the respawn or spectator screen (e.g. when out of spawn points or crews) and proceeding to debriefing.", + "cause": "与 flightmenu.nut 相同,原生 leave_mp_session(aces.exe 0x17909a0)在主机模式下直接空返回。", + "lighter_options_ruled_out": [ + "仅修 flightmenu.nut:当玩家载具全部阵亡或重生点不足停留在重生/观战界面点「返回基地」时,调用的是 scripts/hud/starthud.nut 的 quitMission()(respawn.nut 第 2671 行等引用)。" + ], + "conclusion": "在 starthud.nut 的 quitMission() 中同样排除 is_mplayer_host(),使本地主机走 quit_to_debriefing()。", + "if_not_applied": "载具耗尽或重生点不足时在重生/观战界面点「返回基地」无法退出战局。" + }, + + "features": ["K-战局任务加载", "M-战后结算"], + "evidence": [ + "2.61.0.37 aces.exe:0x17909a0-0x17909be(leave_mp_session 主机空返回)。", + "2.61.0.37 gui.vromfs.bin:scripts/hud/starthud.nut 第 33-44 行。" + ], + + "edit": { + "find": " if (is_multiplayer())\r\n return leave_mp_session()", + "replace": " if (is_multiplayer() && !require(\"multiplayer\").is_mplayer_host())\r\n return leave_mp_session()" + } +} diff --git a/gui-patches/battle/quit-local-host-to-debriefing/patch.json b/gui-patches/battle/quit-local-host-to-debriefing/patch.json new file mode 100644 index 0000000..d3eaf44 --- /dev/null +++ b/gui-patches/battle/quit-local-host-to-debriefing/patch.json @@ -0,0 +1,31 @@ +{ + "id": "battle/quit-local-host-to-debriefing", + "title": "局内菜单在本地多人主机模式下显示常规随机战退局提示并直接进入战后结算", + "file": "scripts/flightmenu/flightmenu.nut", + + "program_behaviour": { + "stock": "FlightMenu.onQuitMission 对 is_mplayer_host() 一律显示自定义房主专用提示(\"其他玩家将无法完成该任务\"),且 sendDisconnectMessage 只要判断 is_multiplayer() 为真就调用主机下为空操作的 leave_mp_session()。", + "patched": "随机战(GM_DOMINATION)下跳过自定义房主提示,照常列出剩余可出击载具与随机战中途退出提示;确认退出时仅对非主机调用 leave_mp_session(),本地主机走 this.quitToDebriefing() 进入战后结算。" + }, + + "derivation": { + "requirement": "Show the standard random-battle quit confirmation (remaining crews and early-leave notice) and proceed cleanly to debriefing when pressing Esc -> Return to Hangar in a LocalMP battle.", + "cause": "flightmenu.nut 第 255 行把 is_mplayer_host() 放在 get_game_mode() == GM_DOMINATION 之前,误将 LocalMP 随机战当成联机合作自定义房主;且原生 leave_mp_session(aces.exe 0x17909a0)在 is_mplayer_host() 为真时直接 ret。", + "lighter_options_ruled_out": [ + "仅靠本地服务:按 Esc 弹窗与退局确认均为纯客户端本地界面逻辑,期间不发网络请求。" + ], + "conclusion": "在 onQuitMission 中把房主提示限定为 get_game_mode() != GM_DOMINATION,并在 sendDisconnectMessage 中将 Peer 退房条件收紧为 is_multiplayer() && !is_mplayer_host()。", + "if_not_applied": "按 Esc 点返回基地会弹出「其他玩家将无法完成该任务」的联机房主提示,甚至因 leave_mp_session 空返回而无法退出。" + }, + + "features": ["K-战局任务加载", "M-战后结算"], + "evidence": [ + "2.61.0.37 aces.exe:0x17909a0-0x17909be(leave_mp_session 在 [0x7b83cb0 + 0x60] != 0 时直接跳至返回)、0x17897c0(quit_to_debriefing)。", + "2.61.0.37 gui.vromfs.bin:scripts/flightmenu/flightmenu.nut 第 26-34、228-277 行。" + ], + + "edit": { + "find": " function sendDisconnectMessage() {\r\n broadcastEvent(\"PlayerQuitMission\")\r\n if (is_multiplayer()) {\r\n leave_mp_session()\r\n this.onResumeRaw()\r\n }\r\n else\r\n this.quitToDebriefing()\r\n }\r\n\r\n function quitToDebriefing() {\r\n disableOrders()\r\n quit_to_debriefing()\r\n interrupt_multiplayer(true)\r\n HudBattleLog.reset()\r\n this.onResumeRaw()\r\n }\r\n\r\n function onQuitMission(_obj) {\r\n if (is_offline_version() && !ludeo?.is_running())\r\n return restart_mission()\r\n\r\n if (is_replay_playing()) {\r\n this.quitToDebriefing()\r\n }\r\n else if (get_mission_status() == MISSION_STATUS_RUNNING) {\r\n local text = \"\"\r\n if (is_mplayer_host())\r\n text = loc(\"flightmenu/questionQuitMissionHost\")", + "replace": " function sendDisconnectMessage() {\r\n broadcastEvent(\"PlayerQuitMission\")\r\n if (is_multiplayer() && !is_mplayer_host()) {\r\n leave_mp_session()\r\n this.onResumeRaw()\r\n }\r\n else\r\n this.quitToDebriefing()\r\n }\r\n\r\n function quitToDebriefing() {\r\n disableOrders()\r\n quit_to_debriefing()\r\n interrupt_multiplayer(true)\r\n HudBattleLog.reset()\r\n this.onResumeRaw()\r\n }\r\n\r\n function onQuitMission(_obj) {\r\n if (is_offline_version() && !ludeo?.is_running())\r\n return restart_mission()\r\n\r\n if (is_replay_playing()) {\r\n this.quitToDebriefing()\r\n }\r\n else if (get_mission_status() == MISSION_STATUS_RUNNING) {\r\n local text = \"\"\r\n if (is_mplayer_host() && get_game_mode() != GM_DOMINATION)\r\n text = loc(\"flightmenu/questionQuitMissionHost\")" + } +} diff --git a/gui-patches/battle/ready-local-host-respawn/patch.json b/gui-patches/battle/ready-local-host-respawn/patch.json new file mode 100644 index 0000000..5ddeb21 --- /dev/null +++ b/gui-patches/battle/ready-local-host-respawn/patch.json @@ -0,0 +1,31 @@ +{ + "id": "battle/ready-local-host-respawn", + "title": "本地多人主机模式下自动置位战局经济与出生点就绪状态以打开乘员组重生面板", + "file": "scripts/respawn/misloadingstate.nut", + + "program_behaviour": { + "stock": "misloadingstate.nut 一直等待远程专用对战服发来 0xb0b7 数据包触发 on_update_es_from_host 事件后才置位 MIS_LOAD.ECONOMIC_STATE 并检查出生点;在 LocalMP 本地主机下没有远程包下发,导致 isReadyToShowRespawn() 恒为 false,界面一直卡在「等待服务器返回数据...」与「等待乘员组的相关数据...」。", + "patched": "当处于局内本地多人主机(isInFlight() && is_mplayer_host())时,立即置位 MIS_LOAD.ECONOMIC_STATE(本地档案与 wasReadySlots 掩码已在内存中就绪),并在出生点激活后置位 MIS_LOAD.RESPAWN_BASES、触发 ChangedMissionRespawnBasesStatus 刷新重生界面。" + }, + + "derivation": { + "requirement": "Display the crew slotbar, tactical map, spawn points, and spawn button immediately upon entering a LocalMP battle.", + "cause": "on_update_es_from_host 仅在客户端收到远程对战服网络同步包(0x5c7146 / 0xb0b7)时广播;LocalMP 主机(is_mplayer_host() == true)自身即为权威端,不会给自己发 Peer 同步包,且对称遭遇战(CTA)出生点在任务加载后约 1 秒激活。", + "lighter_options_ruled_out": [ + "仅靠本地服务:战局内重生界面状态机纯属客户端内存状态,对局加载期间不请求 HTTP/TCP 本地服务。" + ], + "conclusion": "在 misloadingstate.nut 中为本地多人主机补齐 ECONOMIC_STATE 置位与出生点就绪复核。", + "if_not_applied": "进入对局后卡在观战镜头顶栏「等待服务器返回数据...」,打开重生面板一直显示「等待乘员组的相关数据...」,无法选车出击。" + }, + + "features": ["K-战局任务加载"], + "evidence": [ + "2.61.0.37 aces.exe:0x5acce6(MPlayer.wasReadySlots 默认初始化为 0xffffffff)、0x5c7146(远程同步路径触发 on_update_es_from_host)。", + "2.61.0.37 gui.vromfs.bin:scripts/respawn/misloadingstate.nut 第 12-90 行,scripts/respawn/respawn.nut 第 701-705、836-844、996-1006 行。" + ], + + "edit": { + "find": "g_mis_loading_state.isReadyToShowRespawn <- function isReadyToShowRespawn() {\r\n return (getCurState() & MIS_LOAD.RESPAWN_DATA_LOADED) == MIS_LOAD.RESPAWN_DATA_LOADED\r\n}\r\n\r\ng_mis_loading_state.isCrewsListReceived <- function isCrewsListReceived() {\r\n return (getCurState() & MIS_LOAD.ECONOMIC_STATE) != 0\r\n}\r\n\r\ng_mis_loading_state.onEventUpdateEsFromHost <- function onEventUpdateEsFromHost(_p) {\r\n if (getCurState() & MIS_LOAD.ECONOMIC_STATE)\r\n return\r\n\r\n log(\"misLoadState: received initial economicState\")\r\n setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE)\r\n this.checkRespawnBases()\r\n}\r\n\r\ng_mis_loading_state.onEventLoadingStateChange <- function onEventLoadingStateChange(_p) {\r\n if (!isInFlight()) {\r\n if (getCurState() != 0)\r\n log(\"misLoadState: reset mision loading state\")\r\n setCurState(0)\r\n }\r\n}", + "replace": "function syncWtoLocalHostLoadingState() {\r\n if (!isInFlight() || !require(\"multiplayer\").is_mplayer_host())\r\n return\r\n if (!(getCurState() & MIS_LOAD.ECONOMIC_STATE))\r\n setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE)\r\n if (!(getCurState() & MIS_LOAD.RESPAWN_BASES)) {\r\n g_mis_loading_state.checkRespawnBases()\r\n if (getCurState() & MIS_LOAD.RESPAWN_BASES)\r\n require(\"dagor.workcycle\").defer(@() broadcastEvent(\"ChangedMissionRespawnBasesStatus\"))\r\n }\r\n}\r\n\r\ng_mis_loading_state.isReadyToShowRespawn <- function isReadyToShowRespawn() {\r\n syncWtoLocalHostLoadingState()\r\n return (getCurState() & MIS_LOAD.RESPAWN_DATA_LOADED) == MIS_LOAD.RESPAWN_DATA_LOADED\r\n}\r\n\r\ng_mis_loading_state.isCrewsListReceived <- function isCrewsListReceived() {\r\n syncWtoLocalHostLoadingState()\r\n return (getCurState() & MIS_LOAD.ECONOMIC_STATE) != 0\r\n}\r\n\r\ng_mis_loading_state.onEventUpdateEsFromHost <- function onEventUpdateEsFromHost(_p) {\r\n if (getCurState() & MIS_LOAD.ECONOMIC_STATE)\r\n return\r\n\r\n log(\"misLoadState: received initial economicState\")\r\n setCurState(getCurState() | MIS_LOAD.ECONOMIC_STATE)\r\n this.checkRespawnBases()\r\n}\r\n\r\ng_mis_loading_state.onEventLoadingStateChange <- function onEventLoadingStateChange(_p) {\r\n if (!isInFlight()) {\r\n if (getCurState() != 0)\r\n log(\"misLoadState: reset mision loading state\")\r\n setCurState(0)\r\n }\r\n else\r\n syncWtoLocalHostLoadingState()\r\n}" + } +} diff --git a/gui-patches/battle/report-local-battle-settlement/patch.json b/gui-patches/battle/report-local-battle-settlement/patch.json new file mode 100644 index 0000000..9519c66 --- /dev/null +++ b/gui-patches/battle/report-local-battle-settlement/patch.json @@ -0,0 +1,11 @@ +{ + "id": "battle/report-local-battle-settlement", + "title": "Report LocalMP debriefing statistics to local-service before opening DebriefingModal", + "file": "scripts/debriefing/debriefingmodal.nut", + "reason": "Hydrate and scale only explicit additive stat_get_exp reward categories (never expBefore, expAfter, or *F float duplicates), forward full per-unit reward breakdowns to cln_wto_finish_battle, and attach the resulting EULT_SESSION_RESULT userlog to DebriefingModal.", + "features": ["battle-rewards", "post-battle-settlement"], + "edit": { + "find": "function guiStartDebriefingFull(params = {}) {\r\n loadHandler(get_gui_handler(\"DebriefingModal\"), params)\r\n}", + "replace": "let WTO_ADDITIVE_REWARD_CATS = [\r\n \"AirKills\", \"GroundKills\", \"HumanKills\", \"NavalKills\",\r\n \"Landings\", \"Takeoffs\", \"Captures\", \"Destruction\", \"Damage\",\r\n \"Critical\", \"Hit\", \"Assist\", \"BattleTime\", \"Mission\",\r\n \"MissionObjective\", \"Race\", \"Scout\", \"ScoutCriticalHit\",\r\n \"ScoutKill\", \"ScoutKillUnknown\", \"Unlocks\", \"AwardDamage\",\r\n \"TimedAward\", \"AirSevereDamage\", \"ShipSevereDamage\",\r\n \"MissileEvade\", \"ShellInterception\", \"SectorCapture\",\r\n \"SuppliesDelivery\", \"SuppliesReturn\", \"SuppliesDestroy\", \"SuppliesEscort\"\r\n]\r\n\r\nlet WTO_MAIL_REWARD_CATS = [\r\n \"AirKills\", \"GroundKills\", \"NavalKills\", \"HumanKills\",\r\n \"Assist\", \"AirSevereDamage\", \"ShipSevereDamage\", \"Critical\",\r\n \"Hit\", \"Captures\", \"SectorCapture\", \"Destruction\", \"Damage\",\r\n \"Scout\", \"ScoutCriticalHit\", \"ScoutKill\", \"ScoutKillUnknown\",\r\n \"Takeoffs\", \"Landings\", \"MissileEvade\", \"ShellInterception\",\r\n \"TimedAward\", \"Unlocks\", \"BattleTime\",\r\n \"SuppliesDelivery\", \"SuppliesReturn\", \"SuppliesDestroy\", \"SuppliesEscort\"\r\n]\r\n\r\nlet WTO_SCALABLE_EXTRA_EXP_KEYS = [\r\n \"expTotal\", \"expFree\", \"expScouting\", \"expSkillBonus\", \"expSkillBonusTotal\",\r\n \"expModsTotal\", \"expUnitTotal\", \"expInvestModule\", \"expInvestModuleTotal\",\r\n \"expInvestUnit\", \"expInvestUnitTotal\"\r\n]\r\n\r\nfunction hydrateWtoContainerTotals(tbl, isUnitTbl) {\r\n if (!u.isTable(tbl))\r\n return\r\n local wpSum = 0\r\n local expSum = 0\r\n foreach (cat in WTO_ADDITIVE_REWARD_CATS) {\r\n if (!isUnitTbl && cat == \"Race\")\r\n continue\r\n let wpVal = tbl?[$\"wp{cat}\"]\r\n if (is_numeric(wpVal) && wpVal > 0)\r\n wpSum += wpVal.tointeger()\r\n let expVal = tbl?[$\"exp{cat}\"]\r\n if (is_numeric(expVal) && expVal > 0)\r\n expSum += expVal.tointeger()\r\n }\r\n let tblTotal = tbl?.tblTotal\r\n if ((tbl?.wpTotal ?? 0) <= 0) {\r\n let fallbackWp = (tblTotal?.noBonusWp ?? 0).tointeger()\r\n tbl.wpTotal <- wpSum > fallbackWp ? wpSum : fallbackWp\r\n }\r\n if ((tbl?.expTotal ?? 0) <= 0) {\r\n let fallbackExp = (tblTotal?.noBonusExp ?? 0).tointeger()\r\n tbl.expTotal <- expSum > fallbackExp ? expSum : fallbackExp\r\n }\r\n}\r\n\r\nfunction ensureWtoDebriefingTotals(cur) {\r\n if (!u.isTable(cur?.exp))\r\n return\r\n hydrateWtoContainerTotals(cur.exp, false)\r\n foreach (_u, airData in (cur.exp?.aircrafts ?? {}))\r\n hydrateWtoContainerTotals(airData, true)\r\n}\r\n\r\nfunction writeWtoRewardCategories(dstBlk, srcTbl) {\r\n if (!u.isTable(srcTbl))\r\n return\r\n local catsBlk = null\r\n foreach (cat in WTO_MAIL_REWARD_CATS) {\r\n let tblRow = srcTbl?[$\"tbl{cat}\"]\r\n let countVal = (srcTbl?[$\"num{cat}\"] ?? tblRow?.count ?? 0).tointeger()\r\n let wpVal = (srcTbl?[$\"wp{cat}\"] ?? tblRow?.noBonusWp ?? 0).tointeger()\r\n let expVal = (srcTbl?[$\"exp{cat}\"] ?? tblRow?.noBonusExp ?? 0).tointeger()\r\n if (countVal <= 0 && wpVal <= 0 && expVal <= 0)\r\n continue\r\n if (catsBlk == null)\r\n catsBlk = dstBlk.addNewBlock(\"rewards\")\r\n let cBlk = catsBlk.addNewBlock(cat)\r\n cBlk.count = countVal\r\n cBlk.wp = wpVal\r\n cBlk.exp = expVal\r\n }\r\n}\r\n\r\nfunction buildWtoFinishBattleBlk(wtoBattle, res) {\r\n ensureWtoDebriefingTotals(res)\r\n let guiMis = require(\"guiMission\")\r\n let exp = res?.exp ?? {}\r\n let mStatus = guiMis.get_mission_status()\r\n let expRes = exp?.result\r\n let outcome = (mStatus == guiMis.MISSION_STATUS_SUCCESS || expRes == STATS_RESULT_SUCCESS || res?.isSucceed == true) ? \"win\"\r\n : (mStatus == guiMis.MISSION_STATUS_FAIL || expRes == STATS_RESULT_FAIL || res?.state == guiMis.MISSION_STATUS_FAIL) ? \"lose\"\r\n : \"running\"\r\n local teamAKills = 0\r\n local teamBKills = 0\r\n foreach (p in (res?.mplayers_list ?? [])) {\r\n let k = (p?.kills ?? 0) + (p?.groundKills ?? 0) + (p?.navalKills ?? 0)\r\n if (p?.team == 2)\r\n teamBKills += k\r\n else if (p?.team == 1)\r\n teamAKills += k\r\n }\r\n let blk = DataBlock()\r\n blk.sessionId = wtoBattle.sessionId\r\n blk.country = (wtoBattle?.country ?? \"\") != \"\" ? wtoBattle.country : (res?.country ?? \"\")\r\n blk.outcome = outcome\r\n blk.localTeam = (res?.localTeam ?? 1).tointeger()\r\n blk.teamAScore = (res?.mpTblTeams?[0]?.score ?? 0).tointeger()\r\n blk.teamBScore = (res?.mpTblTeams?[1]?.score ?? 0).tointeger()\r\n blk.teamAKills = teamAKills.tointeger()\r\n blk.teamBKills = teamBKills.tointeger()\r\n blk.wpTotal = (exp?.wpTotal ?? 0).tointeger()\r\n blk.expTotal = (exp?.expTotal ?? 0).tointeger()\r\n blk.expFree = (exp?.expFree ?? 0).tointeger()\r\n blk.wpMission = (exp?.wpMission ?? 0).tointeger()\r\n blk.wpTeamKills = (exp?.wpTeamKills ?? exp?.wpFriendlyKills ?? 0).tointeger()\r\n blk.expSkillBonusTotal = (exp?.expSkillBonusTotal ?? 0).tointeger()\r\n blk.expSkillBonusLevel = (exp?.expSkillBonusLevel ?? 0).tointeger()\r\n blk.activity = (exp?.activity ?? 0.0).tofloat()\r\n blk.sessionTime = (exp?.sessionTime ?? 0.0).tofloat()\r\n blk.battleTime = (exp?.battleTime ?? 0.0).tofloat()\r\n writeWtoRewardCategories(blk, exp)\r\n let usedSpares = wtoBattle?.usedSpares\r\n if (u.isTable(usedSpares) && usedSpares.len() > 0) {\r\n let spBlk = blk.addNewBlock(\"spares\")\r\n foreach (spUnit, spCnt in usedSpares)\r\n if (spUnit != \"\" && is_numeric(spCnt) && spCnt > 0)\r\n spBlk[spUnit] = spCnt.tointeger()\r\n }\r\n let vehiclesBlk = blk.addNewBlock(\"vehicles\")\r\n foreach (unitName, airData in (exp?.aircrafts ?? {})) {\r\n let uBlk = vehiclesBlk.addNewBlock(unitName)\r\n uBlk.wpTotal = (airData?.wpTotal ?? 0).tointeger()\r\n uBlk.expTotal = (airData?.expTotal ?? 0).tointeger()\r\n uBlk.expModsTotal = (airData?.expInvestModuleTotal ?? 0).tointeger()\r\n uBlk.expUnitTotal = (airData?.expInvestUnitTotal ?? 0).tointeger()\r\n uBlk.wpMission = (airData?.wpMission ?? 0).tointeger()\r\n uBlk.expSkillBonusTotal = (airData?.expSkillBonusTotal ?? 0).tointeger()\r\n uBlk.expSkillBonusLevel = (airData?.expSkillBonusLevel ?? 0).tointeger()\r\n uBlk.sessionTime = (airData?.sessionTime ?? 0.0).tofloat()\r\n uBlk.battleTime = (airData?.battleTime ?? 0.0).tofloat()\r\n writeWtoRewardCategories(uBlk, airData)\r\n }\r\n return blk\r\n}\r\n\r\nfunction scaleWtoPositiveField(tbl, key, mul) {\r\n if ((key in tbl) && is_numeric(tbl[key]) && tbl[key] > 0)\r\n tbl[key] = (tbl[key] * mul + 0.5).tointeger()\r\n}\r\n\r\nfunction scaleWtoStatContainer(tbl, slMul, rpMul) {\r\n if (!u.isTable(tbl))\r\n return\r\n if (slMul != 1.0) {\r\n foreach (cat in WTO_ADDITIVE_REWARD_CATS)\r\n scaleWtoPositiveField(tbl, $\"wp{cat}\", slMul)\r\n scaleWtoPositiveField(tbl, \"wpScouting\", slMul)\r\n scaleWtoPositiveField(tbl, \"wpTotal\", slMul)\r\n }\r\n if (rpMul != 1.0) {\r\n foreach (cat in WTO_ADDITIVE_REWARD_CATS)\r\n scaleWtoPositiveField(tbl, $\"exp{cat}\", rpMul)\r\n foreach (eKey in WTO_SCALABLE_EXTRA_EXP_KEYS)\r\n scaleWtoPositiveField(tbl, eKey, rpMul)\r\n foreach (k, _v in tbl)\r\n if (k.len() > 13 && k.slice(0, 13) == \"expInvestUnit\" && !k.endswith(\"Name\"))\r\n scaleWtoPositiveField(tbl, k, rpMul)\r\n }\r\n foreach (k, val in tbl) {\r\n if (k.len() >= 4 && k.slice(0, 3) == \"tbl\" && !k.endswith(\"F\") && u.isTable(val)) {\r\n foreach (subKey, _sv in val) {\r\n if (slMul != 1.0 && subKey.endswith(\"Wp\"))\r\n scaleWtoPositiveField(val, subKey, slMul)\r\n else if (rpMul != 1.0 && subKey.endswith(\"Exp\"))\r\n scaleWtoPositiveField(val, subKey, rpMul)\r\n }\r\n }\r\n }\r\n}\r\n\r\nfunction scaleWtoDebriefingMultipliers(cur, slMul, rpMul) {\r\n if (slMul == 1.0 && rpMul == 1.0)\r\n return\r\n scaleWtoStatContainer(cur.exp, slMul, rpMul)\r\n foreach (_u, airData in (cur.exp?.aircrafts ?? {}))\r\n scaleWtoStatContainer(airData, slMul, rpMul)\r\n}\r\n\r\nfunction applyWtoSettledDebriefing(wtoBattle) {\r\n let debrFull = require(\"%scripts/debriefing/debriefingFull.nut\")\r\n let cur = getDebriefingResult()\r\n if (cur == null)\r\n return\r\n ensureWtoDebriefingTotals(cur)\r\n let evObj = events.getEvent(wtoBattle?.modeName ?? \"\")\r\n if (evObj != null && cur.roomEvent == null)\r\n cur.roomEvent = {\r\n name = evObj?.name\r\n economicName = evObj?.economicName\r\n difficulty = evObj?.difficulty\r\n chapter = evObj?.chapter\r\n gameModeId = evObj?.gameModeId\r\n }\r\n let sessionLogs = getUserLogsList({ show = [EULT_SESSION_RESULT], disableVisible = true })\r\n let matched = sessionLogs.findvalue(@(l) l?.wtoSessionId == wtoBattle.sessionId)\r\n if (matched == null)\r\n return\r\n let others = (cur?.roomUserlogs ?? []).filter(@(l) l?.type != EULT_SESSION_RESULT)\r\n cur.roomUserlogs = [matched].extend(others)\r\n let isWin = matched?.win ?? false\r\n cur.isSucceed = isWin\r\n if ((cur.exp?.result ?? STATS_RESULT_IN_PROGRESS) == STATS_RESULT_IN_PROGRESS)\r\n cur.exp.result <- isWin ? STATS_RESULT_SUCCESS : STATS_RESULT_FAIL\r\n scaleWtoDebriefingMultipliers(cur, (matched?.wtoSlMul ?? 1.0).tofloat(), (matched?.wtoRpMul ?? 1.0).tofloat())\r\n debrFull.recountDebriefingResult()\r\n}\r\n\r\nfunction settleWtoBattleAndOpen(wtoBattle, params) {\r\n let { charSendBlk } = require(\"chard\")\r\n let { addTask } = require(\"%scripts/tasker.nut\")\r\n if (getDebriefingResult() == null)\r\n gatherDebriefingResult()\r\n let blk = buildWtoFinishBattleBlk(wtoBattle, getDebriefingResult())\r\n let openModal = function() {\r\n updateGamercards()\r\n loadHandler(get_gui_handler(\"DebriefingModal\"), params)\r\n }\r\n let onSuccess = function() {\r\n try {\r\n applyWtoSettledDebriefing(wtoBattle)\r\n } catch (e) {\r\n log($\"[WTO] applyWtoSettledDebriefing error: {e}\")\r\n }\r\n openModal()\r\n }\r\n let taskId = charSendBlk(\"cln_wto_finish_battle\", blk)\r\n if (taskId < 0 || !addTask(taskId, { showProgressBox = true }, onSuccess, @(_) openModal()))\r\n openModal()\r\n}\r\n\r\nfunction guiStartDebriefingFull(params = {}) {\r\n let { ndbTryRead, ndbDelete } = require(\"nestdb\")\r\n let wtoBattle = ndbTryRead([\"wto\", \"activeBattle\"])\r\n if (wtoBattle != null) {\r\n ndbDelete([\"wto\", \"activeBattle\"])\r\n if (getDebriefingResult() == null)\r\n gatherDebriefingResult()\r\n let curMis = getDebriefingResult()?.missionName ?? \"\"\r\n let expectedMis = wtoBattle?.missionName ?? \"\"\r\n if (get_game_mode() == GM_DOMINATION && (expectedMis == \"\" || curMis == expectedMis)) {\r\n settleWtoBattleAndOpen(wtoBattle, params)\r\n return\r\n }\r\n }\r\n loadHandler(get_gui_handler(\"DebriefingModal\"), params)\r\n}" + } +} diff --git a/gui-patches/battle/scoreboard-team-country-flags/patch.json b/gui-patches/battle/scoreboard-team-country-flags/patch.json new file mode 100644 index 0000000..6efa3f9 --- /dev/null +++ b/gui-patches/battle/scoreboard-team-country-flags/patch.json @@ -0,0 +1,30 @@ +{ + "id": "battle/scoreboard-team-country-flags", + "title": "开局倒计时载具尚未生成前从房间国家配置回退渲染计分板双方参战国旗", + "file": "scripts/statistics/mpstatistics.nut", + + "program_behaviour": { + "stock": "MPStatistics.getCountriesByTeam(team) 只遍历本队已生成载具(ownedUnitName / aircraftName 非空)的成员来汇总参战国旗;开局首秒全体成员尚处于待出击伞兵状态时返回空数组,导致顶栏国旗区空白直至首批载具落地且 3 秒刷新周期到达。", + "patched": "当已出击成员汇总列表为空时,回退读取当前房间会话配置的 country_allies / country_axis 列表并经 getCountryFlagSubstitute 转换,使重生界面与计分板从第 0 帧起即稳定显示双方参战国家国旗;载具出击后仍按原版实时载具所属国汇总。" + }, + + "derivation": { + "requirement": "Display participating nation flags on the scoreboard and respawn header immediately upon entering a battle, before AI bots or the player spawn their first vehicles.", + "cause": "mpstatistics.nut 第 972-988 行 getCountriesByTeam(team) 仅从 getMplayersList(team) 成员的已生成载具反查国籍;在 isTeamsWithCountryFlags 为真时 teamIco 已被置为 null,若此时无人完成首次出击则国旗区完全为空。", + "lighter_options_ruled_out": [ + "仅靠本地服务:getCountriesByTeam 为纯客户端统计面板方法,在无人出击时不读取房间 country_allies / country_axis 字段。" + ], + "conclusion": "在 getCountriesByTeam 末尾当 countries 为空时回退读取 getSessionLobbyPublicParam 内的队伍国家数组。", + "if_not_applied": "开局选车阶段打开计分板或查看顶栏时,在首批载具生成前的数秒内阵营国旗位显示空白。" + }, + + "features": ["K-战局任务加载"], + "evidence": [ + "2.61.0.37 gui.vromfs.bin:scripts/statistics/mpstatistics.nut 第 288-291、930-989 行,scripts/matchingRooms/sessionLobbyState.nut 第 222-226 行(getSessionLobbyPublicParam)。" + ], + + "edit": { + "find": " let country = useOperatorFlagsInBattle ? unit.getOperatorCountry() : getCountryOverride(getUnitCountry(unit))\r\n u.appendOnce(getCountryFlagSubstitute(country), countries, true)\r\n }\r\n return countries\r\n }", + "replace": " let country = useOperatorFlagsInBattle ? unit.getOperatorCountry() : getCountryOverride(getUnitCountry(unit))\r\n u.appendOnce(getCountryFlagSubstitute(country), countries, true)\r\n }\r\n if (countries.len() == 0) {\r\n let roomKey = team == Team.B ? \"country_axis\" : \"country_allies\"\r\n foreach (country in getSessionLobbyPublicParam(roomKey, []))\r\n u.appendOnce(getCountryFlagSubstitute(getCountryOverride(country)), countries, true)\r\n }\r\n return countries\r\n }" + } +} diff --git a/gui-patches/battle/stabilize-respawn-countdown-button/patch.json b/gui-patches/battle/stabilize-respawn-countdown-button/patch.json new file mode 100644 index 0000000..e35d8c4 --- /dev/null +++ b/gui-patches/battle/stabilize-respawn-countdown-button/patch.json @@ -0,0 +1,30 @@ +{ + "id": "battle/stabilize-respawn-countdown-button", + "title": "开局倒计时期间保持重生主按钮同步显示剩余秒数避免与「取消」来回闪烁", + "file": "scripts/respawn/respawn.nut", + + "program_behaviour": { + "stock": "开局 15 秒准备倒计时内,玩家点击「加入战斗!」进入等待出击状态(isApplyPressed == true && readyForRespawn == true)后,onUpdate 每帧调用 updateCountdown(countdown) 将主按钮设为「取消 (15秒)」,而任务自定义状态事件 MissionCustomStateChanged 高频触发 checkUpdateCustomStateRespawns() -> updateApplyText() 又把同一按钮重置为不带秒数的「取消」,导致右下角按钮在「取消」与「取消 (15秒)」之间高频闪烁。", + "patched": "在 updateApplyText() 刷新底部主按钮(mainButtonsId)时,若处于等待倒计时出击状态且 get_mp_respawn_countdown() > 0,同样拼接「(N秒)」后缀(同时保持 this.applyText 与乘员槽小按钮文案不变),与 updateCountdown() 输出完全一致。" + }, + + "derivation": { + "requirement": "Keep the respawn screen bottom-right cancel button text stable during the match-start countdown without flickering between '取消' and '取消 (15秒)'.", + "cause": "respawn.nut 中 updateApplyText() 直接向 mainButtonsId 写入不带倒计时后缀的 this.applyText(\"取消\"),而 updateCountdown() 向同一组按钮写入拼接了倒计时秒数的 btnText(\"取消 (15秒)\");战局内 MissionCustomStateChanged 每秒触发十余次 updateApplyText(),与 onUpdate 交替覆盖按钮文本。", + "lighter_options_ruled_out": [ + "仅靠本地服务:战局内 UI 刷新完全在客户端重生界面脚本内闭环运行,不经过本地服务。" + ], + "conclusion": "在 respawn.nut 的 updateApplyText() 中对底部主按钮同步附带当前开局倒计时秒数。", + "if_not_applied": "开局 15 秒倒计时等待出击期间,右下角主按钮在「取消」与「取消 (15秒)」之间持续高频跳变。" + }, + + "features": ["K-战局任务加载"], + "evidence": [ + "2.61.0.37 gui.vromfs.bin:scripts/respawn/respawn.nut 第 104、2366-2367、2457-2467、2639-2640、2972-2977、3439-3445 行。" + ], + + "edit": { + "find": " foreach (btnId in this.mainButtonsId) {\r\n let buttonSelectObj = setColoredDoubleTextToButton(this.scene.findObject(\"nav-help\"), btnId, this.applyText)", + "replace": " local mainBtnText = this.applyText\r\n if (!this.stayOnRespScreen && this.readyForRespawn && this.isApplyPressed) {\r\n let countdown = get_mp_respawn_countdown()\r\n if (countdown > 0)\r\n mainBtnText = \"\".concat(mainBtnText, loc(\"ui/parentheses/space\", { text = \"\".concat(countdown, loc(\"mainmenu/seconds\")) }))\r\n }\r\n\r\n foreach (btnId in this.mainButtonsId) {\r\n let buttonSelectObj = setColoredDoubleTextToButton(this.scene.findObject(\"nav-help\"), btnId, mainBtnText)" + } +} diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index 7a534e7..f51d0ce 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -22,6 +22,7 @@ New-Item -ItemType Directory -Force $obj | Out-Null $sources = @( "$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c", + "$src\local_mp_core.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_ledger.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" ) | ForEach-Object { '"' + (Resolve-Path $_) + '"' } diff --git a/native/wto-net/src/dll_main.c b/native/wto-net/src/dll_main.c index e019b4a..aaf91e8 100644 --- a/native/wto-net/src/dll_main.c +++ b/native/wto-net/src/dll_main.c @@ -37,7 +37,10 @@ static int install(void) g_ws2 = GetModuleHandleW(L"ws2_32.dll"); if (g_ws2 == NULL || MH_Initialize() != MH_OK) return 0; - return install_resolver_hooks() && install_connection_hooks(); + if (!install_resolver_hooks() || !install_connection_hooks()) + return 0; + install_local_mp_hooks(); + return 1; } BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) diff --git a/native/wto-net/src/hooks.h b/native/wto-net/src/hooks.h index 384a4ea..885d04a 100644 --- a/native/wto-net/src/hooks.h +++ b/native/wto-net/src/hooks.h @@ -9,3 +9,4 @@ int hook_export(const char *name, void *replacement, void **original); int install_resolver_hooks(void); int install_connection_hooks(void); +void install_local_mp_hooks(void); diff --git a/native/wto-net/src/local_mp_actions.c b/native/wto-net/src/local_mp_actions.c new file mode 100644 index 0000000..e4c49d7 --- /dev/null +++ b/native/wto-net/src/local_mp_actions.c @@ -0,0 +1,206 @@ +/* + * LocalMP multi-nation team country lists (`team1_countries` / `team2_countries`), + * MPChat / MPChatHost initialization, UCAV recon drone bridge, and active-player count + * bridge for CTA ticket bleed rules. + */ +#include "hooks.h" +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include "MinHook.h" + +#include + +#define MAX_TEAM_COUNTRIES 16u + +typedef uint8_t (__fastcall *MpConstructLocalFn)(uint8_t *mp, void *mis, void *chat_settings); +typedef void (__fastcall *MpInitChatFn)(uint8_t *mp, void *chat_settings); +typedef void *(__fastcall *DagmemAllocFn)(size_t size); +typedef int64_t (__fastcall *UcavLaunchFn)(void *a1, void *a2, void *a3, void *a4); +typedef int32_t (__fastcall *CountActivePlayersFn)(int32_t team, uint8_t include_connecting); + +static MpConstructLocalFn orig_mp_construct_local; +static MpInitChatFn fn_mp_init_chat; +static DagmemAllocFn fn_dagmem_alloc; +static UcavLaunchFn orig_ucav_launch; +static CountActivePlayersFn orig_count_active_players; + +static void clear_team_country_tab(uint8_t *tab) +{ + char **data = *(char ***)(tab + LMP_TAB_OFF_DATA); + uint32_t count = *(uint32_t *)(tab + LMP_TAB_OFF_COUNT); + uint32_t i; + + if (data != NULL) { + for (i = 0; i < count; i++) + local_mp_mem_free(data[i]); + local_mp_mem_free(data); + } + *(char ***)(tab + LMP_TAB_OFF_DATA) = NULL; + *(void **)(tab + LMP_TAB_OFF_ALLOC) = g_local_mp_stdmem ? *g_local_mp_stdmem : NULL; + *(uint32_t *)(tab + LMP_TAB_OFF_COUNT) = 0; + *(uint32_t *)(tab + LMP_TAB_OFF_CAPACITY) = 0; +} + +static void populate_team_country_tab(uint8_t *tab, const char *csv) +{ + char tokens[MAX_TEAM_COUNTRIES][32]; + uint32_t count = 0; + const char *p = csv; + char **arr; + uint32_t i; + + clear_team_country_tab(tab); + if (p == NULL || *p == '\0' || g_local_mp_stdmem == NULL || *g_local_mp_stdmem == NULL) + return; + + while (*p != '\0' && count < MAX_TEAM_COUNTRIES) { + const char *sep = strchr(p, ';'); + size_t len = sep ? (size_t)(sep - p) : strlen(p); + if (len > 0 && len < sizeof(tokens[0])) { + memcpy(tokens[count], p, len); + tokens[count][len] = '\0'; + count++; + } + if (sep == NULL) + break; + p = sep + 1; + } + if (count == 0) + return; + + arr = (char **)local_mp_mem_alloc((size_t)count * sizeof(char *)); + if (arr == NULL) + return; + for (i = 0; i < count; i++) + arr[i] = local_mp_strdup(tokens[i]); + + *(char ***)(tab + LMP_TAB_OFF_DATA) = arr; + *(void **)(tab + LMP_TAB_OFF_ALLOC) = *g_local_mp_stdmem; + *(uint32_t *)(tab + LMP_TAB_OFF_COUNT) = count; + *(uint32_t *)(tab + LMP_TAB_OFF_CAPACITY) = count; +} + +static void apply_custom_bot_team_countries(uint8_t *mp) +{ + const void *bots_blk; + const char *team_a; + const char *team_b; + + if (g_local_mp_mission_settings == NULL || g_lmp_datablock_get_str == NULL) + return; + bots_blk = g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS; + team_a = g_lmp_datablock_get_str(bots_blk, "wtoTeamACountries", ""); + team_b = g_lmp_datablock_get_str(bots_blk, "wtoTeamBCountries", ""); + if (team_a != NULL && team_a[0] != '\0') + populate_team_country_tab(mp + LMP_MP_MGR_OFF_TEAM1_COUNTRIES, team_a); + if (team_b != NULL && team_b[0] != '\0') + populate_team_country_tab(mp + LMP_MP_MGR_OFF_TEAM2_COUNTRIES, team_b); +} + +static uint8_t __fastcall hook_mp_construct_local(uint8_t *mp, void *mis, void *chat_settings) +{ + uint8_t ok = orig_mp_construct_local(mp, mis, chat_settings); + if (!ok || mp == NULL) + return ok; + apply_custom_bot_team_countries(mp); + if (chat_settings != NULL && fn_mp_init_chat != NULL && + *(void **)(mp + LMP_MP_MGR_OFF_MP_CHAT) == NULL) { + fn_mp_init_chat(mp, chat_settings); + } + if (fn_dagmem_alloc != NULL && *(void **)(mp + LMP_MP_MGR_OFF_CHAT_HOST) == NULL) { + void **chat_host = (void **)fn_dagmem_alloc(2u * sizeof(void *)); + if (chat_host != NULL) { + chat_host[0] = mp; + chat_host[1] = NULL; + *(void **)(mp + LMP_MP_MGR_OFF_CHAT_HOST) = chat_host; + } + } + log_line("local_mp: initialized multi-nation bot teams and MPChat for LocalMP"); + return ok; +} + +static int64_t __fastcall hook_ucav_launch(void *a1, void *a2, void *a3, void *a4) +{ + int64_t res; + + if (!local_mp_is_host()) + return orig_ucav_launch(a1, a2, a3, a4); + + (*g_local_mp_multiplayer)[LMP_MP_MGR_OFF_IS_HOST] = 0; + res = orig_ucav_launch(a1, a2, a3, a4); + if (*g_local_mp_multiplayer != NULL) + (*g_local_mp_multiplayer)[LMP_MP_MGR_OFF_IS_HOST] = 1; + return res; +} + +static int is_unit_alive_for_tickets(uint32_t eid) +{ + uint8_t *unit; + + if (eid == 0 || g_lmp_get_unit_by_eid == NULL) + return 0; + unit = (uint8_t *)g_lmp_get_unit_by_eid(eid); + if (unit == NULL || *(uint16_t *)(unit + LMP_UNIT_OFF_BAIL_STATE) != 0) + return 0; + if (*(uint32_t *)(unit + LMP_UNIT_OFF_ALIVE_STATE) == 0 && + *(uint16_t *)(unit + LMP_UNIT_OFF_TYPE) != LMP_UNIT_TYPE_HELICOPTER) + return 0; + return (*(uint32_t *)(unit + LMP_UNIT_OFF_DEAD_FLAGS) & LMP_UNIT_DEAD_FLAGS_MASK) == 0; +} + +static int32_t __fastcall hook_count_active_players(int32_t team, uint8_t include_connecting) +{ + uint8_t **table; + uint32_t count; + uint32_t i; + int32_t alive = 0; + + if (!local_mp_is_host()) + return orig_count_active_players(team, include_connecting); + + table = g_local_mp_player_table ? *g_local_mp_player_table : NULL; + count = g_local_mp_player_count ? *g_local_mp_player_count : 0; + if (table == NULL || count == 0) + return orig_count_active_players(team, include_connecting); + + for (i = 0; i < count; i++) { + uint8_t *mp = table[i]; + if (mp == NULL) + continue; + if ((*(uint32_t *)(mp + LMP_MP_OFF_FLAGS) & LMP_MP_FLAG_SPECTATOR_MASK) != 0) + continue; + if (team > 0 && mp[LMP_MP_OFF_TEAM] != (uint8_t)team) + continue; + if (is_unit_alive_for_tickets(*(uint32_t *)(mp + LMP_MP_OFF_UNIT_EID)) || + is_unit_alive_for_tickets(*(uint32_t *)(mp + LMP_MP_OFF_SUPPORT_UNIT_EID))) + alive++; + } + return alive; +} + +int install_local_mp_action_hooks(const uint8_t *text, size_t text_size) +{ + uint8_t *p_construct = local_mp_scan_unique(text, text_size, "Multiplayer::constructLocalMP", LMP_SIG_MP_CONSTRUCT_LOCAL); + uint8_t *p_init_chat = local_mp_scan_unique(text, text_size, "Multiplayer::initMPChat", LMP_SIG_MP_INIT_CHAT); + uint8_t *p_set_from = local_mp_scan_unique(text, text_size, "DataBlock::setFrom", LMP_SIG_DATABLOCK_SET_FROM); + uint8_t *p_ucav = local_mp_scan_unique(text, text_size, "ucavLaunch", LMP_SIG_UCAV_LAUNCH); + uint8_t *p_count_active = local_mp_scan_unique(text, text_size, "countActivePlayers", LMP_SIG_COUNT_ACTIVE_PLAYERS); + + if (!p_construct || !p_init_chat || !p_set_from || !p_ucav || !p_count_active) + return 0; + fn_mp_init_chat = (MpInitChatFn)p_init_chat; + fn_dagmem_alloc = (DagmemAllocFn)local_mp_resolve_rip(p_set_from + 0x25, 1, 5); + + if (MH_CreateHook(p_construct, (void *)&hook_mp_construct_local, (void **)&orig_mp_construct_local) != MH_OK || + MH_EnableHook(p_construct) != MH_OK || + MH_CreateHook(p_ucav, (void *)&hook_ucav_launch, (void **)&orig_ucav_launch) != MH_OK || + MH_EnableHook(p_ucav) != MH_OK || + MH_CreateHook(p_count_active, (void *)&hook_count_active_players, (void **)&orig_count_active_players) != MH_OK || + MH_EnableHook(p_count_active) != MH_OK) { + log_line("local_mp: failed to install action or active-player hooks"); + return 0; + } + return 1; +} diff --git a/native/wto-net/src/local_mp_core.c b/native/wto-net/src/local_mp_core.c new file mode 100644 index 0000000..ebddb2b --- /dev/null +++ b/native/wto-net/src/local_mp_core.c @@ -0,0 +1,290 @@ +/* + * Core signature scanner, RIP-relative address resolver, Dagor allocator helpers, + * and engine global discovery for the LocalMP in-process host bridge. + */ +#include "hooks.h" +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include + +typedef void *(__fastcall *DagorMemAllocFn)(void *alloc_self, size_t size); +typedef void (__fastcall *DagorMemFreeFn)(void *alloc_self, void *ptr); + +uint8_t **g_local_mp_multiplayer; +uint8_t **g_local_mp_app; +uint8_t **g_local_mp_mplayer; +uint8_t **g_local_mp_hero; +uint8_t *g_local_mp_mission_settings; +void ***g_local_mp_stdmem; +uint8_t ***g_local_mp_player_table; +uint32_t *g_local_mp_player_count; + +LmpGetPlayerCountryFn g_lmp_get_player_country; +LmpSetPlayerGuiStateFn g_lmp_set_player_gui_state; +LmpAircraftChangeResultFn g_lmp_aircraft_change_result; +LmpGetUnitByEidFn g_lmp_get_unit_by_eid; +LmpSetOwningMPlayerFn g_lmp_set_owning_mplayer; +LmpDataBlockGetStrFn g_lmp_datablock_get_str; + +static int hex_nibble(char c) +{ + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +static size_t parse_pattern(const char *spec, uint8_t *bytes, uint8_t *mask, size_t cap) +{ + size_t n = 0; + const char *p = spec; + while (*p != '\0') { + while (*p == ' ') p++; + if (*p == '\0') break; + if (n >= cap) return 0; + if (p[0] == '?' && p[1] == '?') { + bytes[n] = 0; + mask[n] = 0; + p += 2; + } else { + int hi = hex_nibble(p[0]); + int lo = hex_nibble(p[1]); + if (hi < 0 || lo < 0) return 0; + bytes[n] = (uint8_t)((hi << 4) | lo); + mask[n] = 1; + p += 2; + } + n++; + } + return n; +} + +uint8_t *local_mp_scan_unique(const uint8_t *base, size_t size, const char *name, const char *spec) +{ + uint8_t pat[192]; + uint8_t mask[192]; + size_t len = parse_pattern(spec, pat, mask, sizeof(pat)); + uint8_t *hit = NULL; + size_t i, j; + + if (len == 0 || size < len) { + log_line("local_mp: invalid pattern for %s", name); + return NULL; + } + for (i = 0; i <= size - len; i++) { + for (j = 0; j < len; j++) { + if (mask[j] && base[i + j] != pat[j]) + break; + } + if (j == len) { + if (hit != NULL) { + log_line("local_mp: ambiguous signature for %s", name); + return NULL; + } + hit = (uint8_t *)(base + i); + } + } + if (hit == NULL) + log_line("local_mp: signature not found for %s", name); + return hit; +} + +void *local_mp_resolve_rip(const uint8_t *insn, size_t disp_off, size_t insn_len) +{ + int32_t disp = 0; + memcpy(&disp, insn + disp_off, sizeof(disp)); + return (void *)(insn + insn_len + (intptr_t)disp); +} + +int local_mp_is_host(void) +{ + uint8_t *mp = g_local_mp_multiplayer ? *g_local_mp_multiplayer : NULL; + return mp != NULL && + mp[LMP_MP_MGR_OFF_IS_HOST] == 1 && + mp[LMP_MP_MGR_OFF_IS_LOCAL_MP] == 1; +} + +int local_mp_is_local_mplayer(const uint8_t *mp) +{ + uint8_t *local_mp = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL; + if (mp == NULL) + return 0; + return mp == local_mp || mp[LMP_MP_OFF_PID] == 0; +} + +uint8_t *local_mp_econ_state(void) +{ + uint8_t *app = g_local_mp_app ? *g_local_mp_app : NULL; + uint8_t *holder = app ? *(uint8_t **)(app + LMP_APP_OFF_ECON_HOLDER) : NULL; + return holder ? *(uint8_t **)(holder + LMP_ECON_HOLDER_OFF_STATE) : NULL; +} + +uint8_t *local_mp_find_mplayer(int64_t user_id, uint8_t pid) +{ + uint8_t **table = g_local_mp_player_table ? *g_local_mp_player_table : NULL; + uint32_t count = g_local_mp_player_count ? *g_local_mp_player_count : 0; + uint32_t i; + + if (table == NULL || count == 0) + return NULL; + if (user_id != -1 && user_id != 0) { + for (i = 0; i < count; i++) { + uint8_t *mp = table[i]; + if (mp != NULL && *(int64_t *)(mp + LMP_MP_OFF_USER_ID) == user_id) + return mp; + } + } + if (pid != 0xffu) { + uint32_t slot = (pid == 0xfau) ? 0u : (uint32_t)pid; + if (slot < count && table[slot] != NULL) + return table[slot]; + } + return NULL; +} + +void *local_mp_mem_alloc(size_t size) +{ + void **mem = g_local_mp_stdmem ? *g_local_mp_stdmem : NULL; + void **vtable; + + if (size == 0 || mem == NULL || *mem == NULL) + return NULL; + vtable = (void **)(*mem); + return ((DagorMemAllocFn)vtable[3])(mem, size); +} + +void local_mp_mem_free(void *ptr) +{ + void **mem = g_local_mp_stdmem ? *g_local_mp_stdmem : NULL; + void **vtable; + + if (ptr == NULL || mem == NULL || *mem == NULL) + return; + vtable = (void **)(*mem); + ((DagorMemFreeFn)vtable[8])(mem, ptr); +} + +char *local_mp_strdup(const char *s) +{ + size_t len; + char *copy; + + if (s == NULL || s[0] == '\0') + return NULL; + len = strlen(s) + 1; + copy = (char *)local_mp_mem_alloc(len); + if (copy != NULL) + memcpy(copy, s, len); + return copy; +} + +const char *local_mp_unit_name(const uint8_t *unit) +{ + const uint8_t *uinfo; + const char *name; + + if (unit == NULL) + return NULL; + uinfo = *(const uint8_t *const *)(unit + LMP_UNIT_OFF_INFO); + if (uinfo == NULL) + return NULL; + name = *(const char *const *)(uinfo + LMP_UNIT_INFO_OFF_NAME); + return (name != NULL && name[0] != '\0') ? name : NULL; +} + +static int find_exe_text_section(const uint8_t **out_base, size_t *out_size) +{ + const uint8_t *mod = (const uint8_t *)GetModuleHandleW(NULL); + const IMAGE_DOS_HEADER *dos; + const IMAGE_NT_HEADERS64 *nt; + const IMAGE_SECTION_HEADER *sec; + WORD i; + + if (mod == NULL) return 0; + dos = (const IMAGE_DOS_HEADER *)mod; + if (dos->e_magic != IMAGE_DOS_SIGNATURE) return 0; + nt = (const IMAGE_NT_HEADERS64 *)(mod + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE) return 0; + sec = IMAGE_FIRST_SECTION(nt); + for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++) { + if (memcmp(sec->Name, ".text\0\0\0", 8) == 0) { + *out_base = mod + sec->VirtualAddress; + *out_size = sec->Misc.VirtualSize; + return 1; + } + } + return 0; +} + +static int verify_core_rip_opcodes( + const uint8_t *p_refl_dtor, + const uint8_t *p_sq_country, + const uint8_t *p_get_country +) +{ + return p_refl_dtor[0x8b] == 0x48 && p_refl_dtor[0x8c] == 0x8b && p_refl_dtor[0x8d] == 0x0d && + p_sq_country[0x1c] == 0x48 && p_sq_country[0x1d] == 0x8d && p_sq_country[0x1e] == 0x0d && + p_get_country[0x2e] == 0x44 && p_get_country[0x2f] == 0x3b && p_get_country[0x30] == 0x15 && + p_get_country[0x37] == 0x4c && p_get_country[0x38] == 0x8b && p_get_country[0x39] == 0x1d; +} + +void install_local_mp_hooks(void) +{ + const uint8_t *text = NULL; + size_t text_size = 0; + uint8_t *p_disabled_mask, *p_do_respawn, *p_get_country, *p_sq_country, *p_blk_str; + uint8_t *p_refl_dtor, *p_change_res, *p_set_gui, *p_unit_eid, *p_set_owner, *p_ground_dead; + + if (!find_exe_text_section(&text, &text_size)) { + log_line("local_mp: executable .text section not found, skipping"); + return; + } + + p_disabled_mask = local_mp_scan_unique(text, text_size, "getDisabledSlotsMask", LMP_SIG_DISABLED_SLOTS_MASK); + p_do_respawn = local_mp_scan_unique(text, text_size, "doRespawnPlayer", LMP_SIG_DO_RESPAWN_PLAYER); + p_get_country = local_mp_scan_unique(text, text_size, "MissionSettings::getPlayerCountry", LMP_SIG_GET_PLAYER_COUNTRY); + p_sq_country = local_mp_scan_unique(text, text_size, "sq_get_local_player_country", LMP_SIG_SQ_LOCAL_COUNTRY); + p_refl_dtor = local_mp_scan_unique(text, text_size, "ChangeUnitReflection::dtor", LMP_SIG_REFL_DTOR); + p_change_res = local_mp_scan_unique(text, text_size, "aircraftChangeResultFromHost", LMP_SIG_AIRCRAFT_CHANGE_RESULT); + p_set_gui = local_mp_scan_unique(text, text_size, "setPlayerGuiState", LMP_SIG_SET_PLAYER_GUI_STATE); + p_unit_eid = local_mp_scan_unique(text, text_size, "getUnitByEid", LMP_SIG_GET_UNIT_BY_EID); + p_set_owner = local_mp_scan_unique(text, text_size, "Unit::setOwningMPlayer", LMP_SIG_SET_OWNING_MPLAYER); + p_ground_dead = local_mp_scan_unique(text, text_size, "IGroundModel::onBecameDead", LMP_SIG_IGROUND_ON_DEAD); + p_blk_str = local_mp_scan_unique(text, text_size, "DataBlock::getStr", LMP_SIG_DATABLOCK_GET_STR); + + if (!p_disabled_mask || !p_do_respawn || !p_get_country || !p_sq_country || !p_refl_dtor || + !p_change_res || !p_set_gui || !p_unit_eid || !p_set_owner || !p_ground_dead || !p_blk_str || + !verify_core_rip_opcodes(p_refl_dtor, p_sq_country, p_get_country)) { + log_line("local_mp: core signatures or RIP layout unavailable, LocalMP bridge disabled"); + return; + } + + g_local_mp_multiplayer = (uint8_t **)local_mp_resolve_rip(p_disabled_mask + 0x02, 3, 8); + g_local_mp_app = (uint8_t **)local_mp_resolve_rip(p_disabled_mask + 0x0c, 3, 7); + g_local_mp_mplayer = (uint8_t **)local_mp_resolve_rip(p_disabled_mask + 0x1f, 3, 7); + g_local_mp_hero = (uint8_t **)local_mp_resolve_rip(p_do_respawn + 0x7d, 3, 7); + g_local_mp_mission_settings = (uint8_t *)local_mp_resolve_rip(p_sq_country + 0x1c, 3, 7); + g_local_mp_stdmem = (void ***)local_mp_resolve_rip(p_refl_dtor + 0x8b, 3, 7); + g_local_mp_player_count = (uint32_t *)local_mp_resolve_rip(p_get_country + 0x2e, 3, 7); + g_local_mp_player_table = (uint8_t ***)local_mp_resolve_rip(p_get_country + 0x37, 3, 7); + + g_lmp_get_player_country = (LmpGetPlayerCountryFn)p_get_country; + g_lmp_set_player_gui_state = (LmpSetPlayerGuiStateFn)p_set_gui; + g_lmp_aircraft_change_result = (LmpAircraftChangeResultFn)p_change_res; + g_lmp_get_unit_by_eid = (LmpGetUnitByEidFn)p_unit_eid; + g_lmp_set_owning_mplayer = (LmpSetOwningMPlayerFn)p_set_owner; + g_lmp_datablock_get_str = (LmpDataBlockGetStrFn)p_blk_str; + + if (!install_local_mp_player_hooks(text, text_size, p_do_respawn) || + !install_local_mp_loadout_hooks(text, text_size) || + !install_local_mp_action_hooks(text, text_size) || + !install_local_mp_ledger_hooks(text, text_size, p_ground_dead) || + !install_local_mp_kill_hooks(text, text_size, p_ground_dead) || + !install_local_mp_event_hooks(text, text_size)) { + log_line("local_mp: one or more LocalMP subsystem hooks failed to initialize"); + return; + } + log_line("local_mp: all LocalMP host subsystems installed"); +} diff --git a/native/wto-net/src/local_mp_events.c b/native/wto-net/src/local_mp_events.c new file mode 100644 index 0000000..595a14b --- /dev/null +++ b/native/wto-net/src/local_mp_events.c @@ -0,0 +1,284 @@ +/* + * LocalMP non-fatal combat event dispatchers: deduplicated assists across air/ground/naval, + * zone captures, hits/criticals, severe damage, and naval damage awards. + * + * `IGroundModel::onBecameDead` calls both `IGroundModel::awardAssists` (`0x465540`) and + * `Unit::awardAssists` (`0xe5b200` -> `dispatchAssist` `0x35beb0`); deduplicating `(victim, mp)` + * per unit death ensures every assist across air, ground, and naval is credited strictly once. + */ +#include "hooks.h" +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include "MinHook.h" + +#include + +#define SCORE_SEVERE_DAMAGE 160.0f +#define SCORE_PVP_ASSIST 100.0f +#define SCORE_AI_UNIT_ASSIST 30.0f +#define SCORE_CAPTURE_ZONE 300.0f +#define SCORE_CRITICAL_HIT 50.0f +#define SCORE_HIT 10.0f +#define SCORE_NAVAL_DMG_FACTOR 0.08f +#define MAX_OFFENDER_SNAP 64u +#define MAX_ASSIST_DEDUP 64u + +#define HUD_MSG_HIT_FEED 3u +#define HUD_MSG_CENTER_BANNER 4u + +typedef struct AssistDedupRecord { + const uint8_t *victim; + const uint8_t *offender_mp; +} AssistDedupRecord; + +typedef void (__fastcall *IGroundAwardAssistsFn)(uint8_t *victim); +typedef void (__fastcall *DispatchAssistFn)(int64_t uid, uint8_t *victim, uint8_t *offender, float share, int32_t extra); +typedef void (__fastcall *DispatchCaptureZoneFn)(int64_t uid, uint8_t *capturer_unit); +typedef void (__fastcall *DispatchHitCritFn)(int64_t uid, uint8_t *victim, uint8_t *offender, float dmg, uint8_t is_kill, uint8_t is_crit, uint8_t extra); +typedef void (__fastcall *DispatchSevereDamageFn)(int64_t uid, uint8_t *victim, uint8_t *offender); +typedef void (__fastcall *DispatchNavalDamageFn)(int64_t uid, uint8_t *victim, uint8_t *offender, float award_dmg); + +static IGroundAwardAssistsFn orig_iground_award_assists; +static DispatchAssistFn orig_dispatch_assist; +static DispatchCaptureZoneFn orig_dispatch_capture_zone; +static DispatchHitCritFn orig_dispatch_hit_crit; +static DispatchSevereDamageFn orig_dispatch_severe_damage; +static DispatchNavalDamageFn orig_dispatch_naval_damage; + +static AssistDedupRecord g_assist_dedup[MAX_ASSIST_DEDUP]; +static size_t g_assist_dedup_cursor = 0; + +void local_mp_events_reset(void) +{ + memset(g_assist_dedup, 0, sizeof(g_assist_dedup)); + g_assist_dedup_cursor = 0; +} + +void local_mp_events_begin_death(const uint8_t *victim) +{ + size_t i; + if (victim == NULL) + return; + for (i = 0; i < MAX_ASSIST_DEDUP; i++) { + if (g_assist_dedup[i].victim == victim) { + g_assist_dedup[i].victim = NULL; + g_assist_dedup[i].offender_mp = NULL; + } + } +} + +static int mark_assist_credited_once(const uint8_t *victim, const uint8_t *mp) +{ + size_t i; + for (i = 0; i < MAX_ASSIST_DEDUP; i++) { + if (g_assist_dedup[i].victim == victim && g_assist_dedup[i].offender_mp == mp) + return 0; + } + g_assist_dedup[g_assist_dedup_cursor].victim = victim; + g_assist_dedup[g_assist_dedup_cursor].offender_mp = mp; + g_assist_dedup_cursor = (g_assist_dedup_cursor + 1u) % MAX_ASSIST_DEDUP; + return 1; +} + +static void credit_assist_to_mplayer(uint8_t *mp, uint8_t *victim) +{ + uint8_t *victim_mp = *(uint8_t **)(victim + LMP_UNIT_OFF_MPLAYER); + float pts; + + if (mp == NULL || mp == victim_mp || !mark_assist_credited_once(victim, mp)) + return; + pts = victim_mp ? SCORE_PVP_ASSIST : SCORE_AI_UNIT_ASSIST; + local_mp_inc_mplayer_stat(mp, LMP_MP_OFF_ASSISTS); + local_mp_add_mplayer_score(mp, pts, LMP_EXP_EVENT_ASSIST); + local_mp_mark_mplayer_dirty(mp); + if (local_mp_is_local_mplayer(mp)) { + const char *uname = local_mp_active_player_unit_name(); + const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname); + float mul = victim_mp ? 0.45f : (0.45f * rates->ai_kill_k); + int32_t wp = (int32_t)(rates->wp_per_kill * mul + 0.5f); + int32_t rp = (int32_t)(180.0f * rates->exp_mul * mul + 0.5f); + local_mp_ledger_record_event(uname, LMP_STAT_BKT_ASSIST, 1, wp, rp, pts); + local_mp_ledger_banner(LMP_EXP_EVENT_ASSIST, HUD_MSG_CENTER_BANNER, rp, wp, victim); + } +} + +static void __fastcall hook_iground_award_assists(uint8_t *victim) +{ + uint8_t prev_sent[MAX_OFFENDER_SNAP]; + uint32_t count = 0; + uint8_t *arr = NULL; + uint32_t i; + + if (local_mp_is_host() && victim != NULL) { + arr = *(uint8_t **)(victim + LMP_IGM_OFF_OFFENDERS_PTR); + count = *(uint32_t *)(victim + LMP_IGM_OFF_OFFENDERS_CNT); + if (count > MAX_OFFENDER_SNAP) + count = MAX_OFFENDER_SNAP; + for (i = 0; arr != NULL && i < count; i++) + prev_sent[i] = arr[i * LMP_OFFENDER_STRIDE + LMP_OFFENDER_OFF_ASSIST_SENT]; + } + + orig_iground_award_assists(victim); + + if (local_mp_is_host() && victim != NULL && arr != NULL && count > 0) { + arr = *(uint8_t **)(victim + LMP_IGM_OFF_OFFENDERS_PTR); + for (i = 0; arr != NULL && i < count; i++) { + uint8_t *off = arr + i * LMP_OFFENDER_STRIDE; + if (prev_sent[i] == 0 && off[LMP_OFFENDER_OFF_ASSIST_SENT] != 0) { + uint8_t *mp = local_mp_find_mplayer( + *(int64_t *)(off + LMP_OFFENDER_OFF_UID), off[LMP_OFFENDER_OFF_PID]); + credit_assist_to_mplayer(mp, victim); + } + } + } +} + +static void __fastcall hook_dispatch_assist(int64_t uid, uint8_t *victim, uint8_t *offender, float share, int32_t extra) +{ + if (local_mp_is_host() && victim != NULL) { + uint8_t *mp = local_mp_find_mplayer(uid, offender ? offender[LMP_OFFENDER_OFF_PID] : 0xffu); + credit_assist_to_mplayer(mp, victim); + } + orig_dispatch_assist(uid, victim, offender, share, extra); +} + +static void __fastcall hook_dispatch_capture_zone(int64_t uid, uint8_t *capturer_unit) +{ + if (local_mp_is_host()) { + uint8_t *mp = local_mp_find_mplayer(uid, 0xffu); + if (mp == NULL && capturer_unit != NULL) + mp = *(uint8_t **)(capturer_unit + LMP_UNIT_OFF_MPLAYER); + if (mp != NULL) { + local_mp_inc_mplayer_stat(mp, LMP_MP_OFF_CAPTURE_ZONE); + local_mp_add_mplayer_score(mp, SCORE_CAPTURE_ZONE, LMP_EXP_EVENT_CAPTURE_ZONE); + local_mp_mark_mplayer_dirty(mp); + if (local_mp_is_local_mplayer(mp)) { + const char *uname = capturer_unit ? local_mp_unit_name(capturer_unit) : NULL; + const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname); + int32_t wp = (int32_t)(rates->wp_per_kill + 0.5f); + int32_t rp = (int32_t)(200.0f * rates->exp_mul + 0.5f); + local_mp_ledger_record_event(uname, LMP_STAT_BKT_CAPTURES, 1, wp, rp, SCORE_CAPTURE_ZONE); + local_mp_ledger_banner(LMP_EXP_EVENT_CAPTURE_ZONE, HUD_MSG_CENTER_BANNER, rp, wp, capturer_unit); + } + } + } + orig_dispatch_capture_zone(uid, capturer_unit); +} + +static void __fastcall hook_dispatch_hit_crit( + int64_t uid, uint8_t *victim, uint8_t *offender, float dmg, uint8_t is_kill, uint8_t is_crit, uint8_t extra +) +{ + if (local_mp_is_host() && !is_kill && victim != NULL) { + uint8_t *mp = local_mp_find_mplayer(uid, offender ? offender[LMP_OFFENDER_OFF_PID] : 0xffu); + if (mp != NULL && mp != *(uint8_t **)(victim + LMP_UNIT_OFF_MPLAYER)) { + float pts = is_crit ? SCORE_CRITICAL_HIT : SCORE_HIT; + uint32_t ev = is_crit ? LMP_EXP_EVENT_CRITICAL_HIT : LMP_EXP_EVENT_HIT; + local_mp_add_mplayer_score(mp, pts, ev); + local_mp_mark_mplayer_dirty(mp); + if (local_mp_is_local_mplayer(mp)) { + const char *uname = local_mp_active_player_unit_name(); + const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname); + float mul = is_crit ? 0.20f : 0.06f; + int32_t wp = (int32_t)(rates->wp_per_kill * mul + 0.5f); + int32_t rp = (int32_t)(180.0f * rates->exp_mul * mul + 0.5f); + local_mp_ledger_record_event(uname, is_crit ? LMP_STAT_BKT_CRITICAL : LMP_STAT_BKT_HIT, 1, wp, rp, pts); + local_mp_ledger_banner(ev, HUD_MSG_HIT_FEED, rp, wp, victim); + } + } + } + orig_dispatch_hit_crit(uid, victim, offender, dmg, is_kill, is_crit, extra); +} + +static void __fastcall hook_dispatch_severe_damage(int64_t uid, uint8_t *victim, uint8_t *offender) +{ + if (local_mp_is_host() && victim != NULL && offender != NULL) { + uint8_t victim_army = victim[LMP_UNIT_OFF_ARMY]; + if (victim_army == 0 || *(int32_t *)(offender + LMP_OFFENDER_OFF_ARMY) != (int32_t)victim_army) { + uint8_t *mp = local_mp_find_mplayer(uid, offender[LMP_OFFENDER_OFF_PID]); + uint8_t *victim_mp = *(uint8_t **)(victim + LMP_UNIT_OFF_MPLAYER); + if (mp != NULL && mp != victim_mp && victim_mp != NULL) { + uint16_t utype = *(uint16_t *)(victim + LMP_UNIT_OFF_TYPE); + int is_air = (utype == 0u || utype == 0xdu); + if (is_air) local_mp_inc_mplayer_stat(mp, LMP_MP_OFF_AIR_SEVERE_DMG); + else if (utype == 5u) local_mp_inc_mplayer_stat(mp, LMP_MP_OFF_SHIP_SEVERE_DMG); + local_mp_add_mplayer_score(mp, SCORE_SEVERE_DAMAGE, LMP_EXP_EVENT_SEVERE_DAMAGE); + local_mp_mark_mplayer_dirty(mp); + if (local_mp_is_local_mplayer(mp)) { + const char *uname = local_mp_active_player_unit_name(); + const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname); + int32_t wp = (int32_t)(rates->wp_per_kill * 0.8f + 0.5f); + int32_t rp = (int32_t)(144.0f * rates->exp_mul + 0.5f); + local_mp_ledger_record_event(uname, is_air ? LMP_STAT_BKT_AIR_SEVERE : LMP_STAT_BKT_SHIP_SEVERE, 1, wp, rp, SCORE_SEVERE_DAMAGE); + local_mp_ledger_banner(LMP_EXP_EVENT_SEVERE_DAMAGE, HUD_MSG_CENTER_BANNER, rp, wp, victim); + } + } + } + } + orig_dispatch_severe_damage(uid, victim, offender); +} + +static void __fastcall hook_dispatch_naval_damage(int64_t uid, uint8_t *victim, uint8_t *offender, float award_dmg) +{ + if (local_mp_is_host() && victim != NULL && offender != NULL && award_dmg > 0.0f) { + uint8_t victim_army = victim[LMP_UNIT_OFF_ARMY]; + if (victim_army == 0 || *(int32_t *)(offender + LMP_OFFENDER_OFF_ARMY) != (int32_t)victim_army) { + uint8_t *mp = local_mp_find_mplayer(uid, offender[LMP_OFFENDER_OFF_PID]); + if (mp != NULL) { + int32_t add_dmg = (int32_t)(award_dmg + 0.5f); + float pts = award_dmg * SCORE_NAVAL_DMG_FACTOR; + if (add_dmg > 0) *(int32_t *)(mp + LMP_MP_OFF_AWARD_DAMAGE) += add_dmg; + if (pts >= 1.0f) local_mp_add_mplayer_score(mp, pts, LMP_EXP_EVENT_UNIT_DAMAGE); + local_mp_mark_mplayer_dirty(mp); + if (local_mp_is_local_mplayer(mp) && add_dmg > 0) { + const char *uname = local_mp_active_player_unit_name(); + const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname); + int32_t wp = (int32_t)(rates->wp_per_kill * (award_dmg / 1500.0f) + 0.5f); + int32_t rp = (int32_t)(rates->exp_mul * (award_dmg * 0.10f) + 0.5f); + local_mp_ledger_record_event(uname, LMP_STAT_BKT_AWARD_DAMAGE, add_dmg, wp, rp, pts >= 1.0f ? pts : 0.0f); + } + } + } + } + orig_dispatch_naval_damage(uid, victim, offender, award_dmg); +} + +int install_local_mp_event_hooks(const uint8_t *text, size_t text_size) +{ + uint8_t *p_igm_ass = local_mp_scan_unique(text, text_size, "IGroundModel::awardAssists", LMP_SIG_IGROUND_AWARD_ASSISTS); + uint8_t *p_assist = local_mp_scan_unique(text, text_size, "dispatchAssist", LMP_SIG_DISPATCH_ASSIST); + uint8_t *p_cap_c = local_mp_scan_unique(text, text_size, "caller_captureZone", LMP_SIG_CALLER_CAPTURE_ZONE); + uint8_t *p_hit_c = local_mp_scan_unique(text, text_size, "caller_hitCrit", LMP_SIG_CALLER_HIT_CRIT); + uint8_t *p_sev_c = local_mp_scan_unique(text, text_size, "caller_severeDmg", LMP_SIG_CALLER_SEVERE_DMG); + uint8_t *p_nav_c = local_mp_scan_unique(text, text_size, "caller_navalDmg", LMP_SIG_CALLER_NAVAL_DMG); + uint8_t *p_cap, *p_hit, *p_sev, *p_nav; + + if (!p_igm_ass || !p_assist || !p_cap_c || !p_hit_c || !p_sev_c || !p_nav_c) + return 0; + if (p_cap_c[0x6b] != 0xe8 || p_hit_c[0x59] != 0xe8 || p_sev_c[0x2f] != 0xe8 || p_nav_c[0x67] != 0xe8) + return 0; + + p_cap = (uint8_t *)local_mp_resolve_rip(p_cap_c + 0x6b, 1, 5); + p_hit = (uint8_t *)local_mp_resolve_rip(p_hit_c + 0x59, 1, 5); + p_sev = (uint8_t *)local_mp_resolve_rip(p_sev_c + 0x2f, 1, 5); + p_nav = (uint8_t *)local_mp_resolve_rip(p_nav_c + 0x67, 1, 5); + + if (MH_CreateHook(p_igm_ass, (void *)&hook_iground_award_assists, (void **)&orig_iground_award_assists) != MH_OK || + MH_EnableHook(p_igm_ass) != MH_OK || + MH_CreateHook(p_assist, (void *)&hook_dispatch_assist, (void **)&orig_dispatch_assist) != MH_OK || + MH_EnableHook(p_assist) != MH_OK || + MH_CreateHook(p_cap, (void *)&hook_dispatch_capture_zone, (void **)&orig_dispatch_capture_zone) != MH_OK || + MH_EnableHook(p_cap) != MH_OK || + MH_CreateHook(p_hit, (void *)&hook_dispatch_hit_crit, (void **)&orig_dispatch_hit_crit) != MH_OK || + MH_EnableHook(p_hit) != MH_OK || + MH_CreateHook(p_sev, (void *)&hook_dispatch_severe_damage, (void **)&orig_dispatch_severe_damage) != MH_OK || + MH_EnableHook(p_sev) != MH_OK || + MH_CreateHook(p_nav, (void *)&hook_dispatch_naval_damage, (void **)&orig_dispatch_naval_damage) != MH_OK || + MH_EnableHook(p_nav) != MH_OK) { + log_line("local_mp: failed to install combat event hooks"); + return 0; + } + return 1; +} diff --git a/native/wto-net/src/local_mp_internal.h b/native/wto-net/src/local_mp_internal.h new file mode 100644 index 0000000..fa42088 --- /dev/null +++ b/native/wto-net/src/local_mp_internal.h @@ -0,0 +1,103 @@ +/* + * Shared internal state, resolved engine pointers, and subsystem interfaces + * for the LocalMP in-process host bridge. + * + * All addresses are resolved dynamically from masked .text signatures in + * local_mp_offsets.h and every detour is gated on local_mp_is_host(). + */ +#pragma once + +#include +#include + +#define LMP_MAX_UNIT_RATES 32u + +typedef char *(__fastcall *LmpGetPlayerCountryFn)(uint8_t *mis, int32_t pid, char *buf, int32_t buf_size); +typedef void (__fastcall *LmpSetPlayerGuiStateFn)(int32_t player_id, int32_t state); +typedef void (__fastcall *LmpAircraftChangeResultFn)(void *econ_state, int32_t err_code); +typedef void *(__fastcall *LmpGetUnitByEidFn)(uint32_t eid); +typedef void (__fastcall *LmpSetOwningMPlayerFn)(void *unit, void *mplayer, uint8_t f1, uint8_t set_pid); +typedef const char *(__fastcall *LmpDataBlockGetStrFn)(const void *blk, const char *name, const char *def); + +typedef struct LocalMpUnitRates { + char unit_name[64]; + float wp_per_kill; + float exp_mul; + float battle_time_award; + float ai_kill_k; + float win_k; +} LocalMpUnitRates; + +typedef struct LocalMpUnitRateEntry { + LocalMpUnitRates rates; + uint8_t spawned; +} LocalMpUnitRateEntry; + +extern uint8_t **g_local_mp_multiplayer; +extern uint8_t **g_local_mp_app; +extern uint8_t **g_local_mp_mplayer; +extern uint8_t **g_local_mp_hero; +extern uint8_t *g_local_mp_mission_settings; +extern void ***g_local_mp_stdmem; +extern uint8_t ***g_local_mp_player_table; +extern uint32_t *g_local_mp_player_count; + +extern LmpGetPlayerCountryFn g_lmp_get_player_country; +extern LmpSetPlayerGuiStateFn g_lmp_set_player_gui_state; +extern LmpAircraftChangeResultFn g_lmp_aircraft_change_result; +extern LmpGetUnitByEidFn g_lmp_get_unit_by_eid; +extern LmpSetOwningMPlayerFn g_lmp_set_owning_mplayer; +extern LmpDataBlockGetStrFn g_lmp_datablock_get_str; + +uint8_t *local_mp_scan_unique(const uint8_t *base, size_t size, const char *name, const char *spec); +void *local_mp_resolve_rip(const uint8_t *insn, size_t disp_off, size_t insn_len); +int local_mp_is_host(void); +int local_mp_is_local_mplayer(const uint8_t *mp); +uint8_t *local_mp_econ_state(void); +uint8_t *local_mp_find_mplayer(int64_t user_id, uint8_t pid); +void *local_mp_mem_alloc(size_t size); +void local_mp_mem_free(void *ptr); +char *local_mp_strdup(const char *s); +const char *local_mp_unit_name(const uint8_t *unit); +const char *local_mp_active_player_unit_name(void); + +/* Player state & slot tracking notifications shared with loadout module. */ +void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int is_silent); + +/* SessionStatsNet ledger & HUD center-screen reward banner API. */ +void local_mp_ledger_reset(void); +void local_mp_ledger_store_rates(const LocalMpUnitRates *rates); +void local_mp_ledger_activate_unit(const char *unit_name); +const LocalMpUnitRates *local_mp_ledger_rates_for_unit(const char *unit_name); +void local_mp_ledger_record_event( + const char *unit_name, + size_t bucket_off, + int32_t count_inc, + int32_t wp, + int32_t exp, + float score_delta +); +void local_mp_ledger_banner( + uint32_t event_id, + uint32_t msg_type, + int32_t xp, + int32_t wp, + void *target_unit +); + +/* Assist deduplication lifecycle shared between kill and event hooks. */ +void local_mp_events_reset(void); +void local_mp_events_begin_death(const uint8_t *victim); + +/* Shared MPlayer scoreboard helpers exposed by local_mp_kills.c. */ +void local_mp_add_mplayer_score(uint8_t *mp, float delta, uint32_t event_id); +void local_mp_mark_mplayer_dirty(uint8_t *mp); +void local_mp_inc_mplayer_stat(uint8_t *mp, size_t off); + +/* Subsystem hook installers invoked once from install_local_mp_hooks(). */ +int install_local_mp_player_hooks(const uint8_t *text, size_t text_size, uint8_t *p_do_respawn); +int install_local_mp_loadout_hooks(const uint8_t *text, size_t text_size); +int install_local_mp_action_hooks(const uint8_t *text, size_t text_size); +int install_local_mp_ledger_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead); +int install_local_mp_kill_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead); +int install_local_mp_event_hooks(const uint8_t *text, size_t text_size); diff --git a/native/wto-net/src/local_mp_kills.c b/native/wto-net/src/local_mp_kills.c new file mode 100644 index 0000000..33b763c --- /dev/null +++ b/native/wto-net/src/local_mp_kills.c @@ -0,0 +1,213 @@ +/* + * LocalMP authoritative unit-death and kill-attribution hooks across all vehicle branches. + * + * Hooks BOTH `IGroundModel::onBecameDead` (tanks, IFVs, SPAA, boats, ships, infantry) + * and `onUnitDeadOnce` (aircraft & helicopters). All 31 bound MPlayer bots receive 1:1 + * PvP kill/death counters and battle score alongside the local player. + */ +#include "hooks.h" +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include "MinHook.h" + +#include + +#define SCORE_PVP_KILL 200.0f +#define SCORE_SEVERE_FINISH 40.0f +#define SCORE_AI_UNIT_KILL 60.0f +#define SCORE_DEATH 30.0f +#define HUD_MSG_CENTER_BANNER 4u + +typedef void (__fastcall *MPlayerAddScoreFn)(uint8_t *mp, float delta, uint32_t event_id, uint8_t add_team); +typedef void (__fastcall *NetMarkDirtyFn)(void *dirty_field, void *owner_obj, void *payload_ptr); +typedef void (__fastcall *ChooseOffenderVfn)(uint8_t *victim, uint8_t *out_offender, uint8_t clear_flag); +typedef void (__fastcall *IGroundOnDeadFn)(uint8_t *victim, int32_t p2); +typedef void (__fastcall *OnUnitDeadOnceFn)(uint8_t *victim); + +static MPlayerAddScoreFn fn_mplayer_add_score; +static NetMarkDirtyFn fn_net_mark_dirty; +static IGroundOnDeadFn orig_iground_on_dead; +static OnUnitDeadOnceFn orig_on_unit_dead_once; + +void local_mp_mark_mplayer_dirty(uint8_t *mp) +{ + if (mp != NULL && fn_net_mark_dirty != NULL) + fn_net_mark_dirty(mp + LMP_MP_OFF_STAT_DIRTY, mp, mp + LMP_MP_OFF_STAT_PAYLOAD); +} + +void local_mp_inc_mplayer_stat(uint8_t *mp, size_t off) +{ + int16_t v = *(int16_t *)(mp + off); + if (v < 32767) + *(int16_t *)(mp + off) = (int16_t)(v + 1); +} + +static void dec_mplayer_stat_pos(uint8_t *mp, size_t off) +{ + int16_t v = *(int16_t *)(mp + off); + if (v > 0) + *(int16_t *)(mp + off) = (int16_t)(v - 1); +} + +void local_mp_add_mplayer_score(uint8_t *mp, float delta, uint32_t event_id) +{ + uint8_t *app = g_local_mp_app ? *g_local_mp_app : NULL; + int32_t total; + if (mp == NULL || delta <= 0.0f || event_id >= LMP_EXP_EVENT_COUNT || !fn_mplayer_add_score) + return; + if (app == NULL || *(void **)(app + LMP_APP_OFF_SCORE_RULES) == NULL) + return; + fn_mplayer_add_score(mp, delta, event_id, 1); + total = *(int32_t *)(mp + LMP_MP_OFF_SCORE); + *(int16_t *)(mp + LMP_MP_OFF_FALLBACK_SCORE) = (total > 32767) ? (int16_t)32767 : (int16_t)total; +} + +static int is_same_severe_offender(const uint8_t *victim, const uint8_t *killer_mp) +{ + if (victim == NULL || killer_mp == NULL || *(const int16_t *)(victim + LMP_UNIT_OFF_SEVERE_IDX) == -1) + return 0; + return local_mp_find_mplayer(*(const int64_t *)(victim + LMP_UNIT_OFF_SEVERE_UID), + victim[LMP_UNIT_OFF_SEVERE_PID]) == killer_mp; +} + +static void record_enemy_kill(uint8_t *killer_mp, uint8_t *victim, int is_pvp) +{ + uint16_t utype = *(uint16_t *)(victim + LMP_UNIT_OFF_TYPE); + int is_air = (utype == 0u || utype == 0xdu); + int is_ship = (utype == 5u); + int is_human = (utype == 0xeu); + int own_sev = is_pvp && (is_air || is_ship) && is_same_severe_offender(victim, killer_mp); + uint32_t ev = is_air ? LMP_EXP_EVENT_KILL : (is_human ? LMP_EXP_EVENT_KILL_HUMAN : LMP_EXP_EVENT_KILL_GROUND); + size_t bkt = is_air ? LMP_STAT_BKT_AIR_KILLS : (is_ship ? LMP_STAT_BKT_NAVAL_KILLS : + (is_human ? LMP_STAT_BKT_HUMAN_KILLS : LMP_STAT_BKT_GROUND_KILLS)); + float pts = is_pvp ? (own_sev ? SCORE_SEVERE_FINISH : SCORE_PVP_KILL) : SCORE_AI_UNIT_KILL; + + if (is_pvp) { + local_mp_inc_mplayer_stat(killer_mp, is_air ? LMP_MP_OFF_KILLS : (is_ship ? LMP_MP_OFF_NAVAL_KILLS : + (is_human ? LMP_MP_OFF_HUMAN_KILLS : LMP_MP_OFF_GROUND_KILLS))); + if (own_sev) + dec_mplayer_stat_pos(killer_mp, is_air ? LMP_MP_OFF_AIR_SEVERE_DMG : LMP_MP_OFF_SHIP_SEVERE_DMG); + } else { + local_mp_inc_mplayer_stat(killer_mp, is_air ? LMP_MP_OFF_AI_KILLS : + (is_ship ? LMP_MP_OFF_AI_NAVAL_KILLS : LMP_MP_OFF_AI_GROUND_KILLS)); + } + local_mp_add_mplayer_score(killer_mp, pts, ev); + local_mp_mark_mplayer_dirty(killer_mp); + + if (local_mp_is_local_mplayer(killer_mp)) { + const char *uname = local_mp_active_player_unit_name(); + const LocalMpUnitRates *rates = local_mp_ledger_rates_for_unit(uname); + float mul = is_pvp ? (own_sev ? 0.2f : 1.0f) : rates->ai_kill_k; + int32_t wp = (int32_t)(rates->wp_per_kill * mul + 0.5f); + int32_t rp = (int32_t)(180.0f * rates->exp_mul * mul + 0.5f); + local_mp_ledger_record_event(uname, bkt, 1, wp, rp, pts); + local_mp_ledger_banner(ev, HUD_MSG_CENTER_BANNER, rp, wp, victim); + } +} + +static void process_unit_death(uint8_t *victim, uint8_t *killer_mp, int32_t killer_army, int allow_kill_credit) +{ + uint8_t *victim_mp = *(uint8_t **)(victim + LMP_UNIT_OFF_MPLAYER); + uint8_t victim_army = victim[LMP_UNIT_OFF_ARMY]; + + if (victim_mp != NULL) { + local_mp_inc_mplayer_stat(victim_mp, LMP_MP_OFF_DEATHS); + local_mp_add_mplayer_score(victim_mp, SCORE_DEATH, LMP_EXP_EVENT_DEATH); + local_mp_mark_mplayer_dirty(victim_mp); + } + if (!allow_kill_credit || killer_mp == NULL || killer_mp == victim_mp) + return; + if (killer_army <= 0) + killer_army = (int32_t)killer_mp[LMP_MP_OFF_TEAM]; + if (victim_army != 0 && killer_army == (int32_t)victim_army) { + local_mp_inc_mplayer_stat(killer_mp, LMP_MP_OFF_TEAM_KILLS); + local_mp_mark_mplayer_dirty(killer_mp); + } else { + record_enemy_kill(killer_mp, victim, victim_mp != NULL); + } +} + +static uint8_t *resolve_offender_killer(uint8_t *victim, int32_t *out_army) +{ + __declspec(align(16)) uint8_t offender[0x180]; + uintptr_t vtbl = victim ? *(uintptr_t *)victim : 0; + ChooseOffenderVfn choose_fn; + + if (vtbl == 0) + return NULL; + memset(offender, 0, sizeof(offender)); + *(int16_t *)offender = -1; + offender[LMP_OFFENDER_OFF_PID] = 0xffu; + *(int64_t *)(offender + LMP_OFFENDER_OFF_UID) = -1; + choose_fn = *(ChooseOffenderVfn *)(vtbl + LMP_UNIT_VTF_CHOOSE_OFFENDER); + if (choose_fn != NULL) + choose_fn(victim, offender, 0); + if (*(int16_t *)offender == -1) + return NULL; + *out_army = *(int32_t *)(offender + LMP_OFFENDER_OFF_ARMY); + return local_mp_find_mplayer(*(int64_t *)(offender + LMP_OFFENDER_OFF_UID), offender[LMP_OFFENDER_OFF_PID]); +} + +static void __fastcall hook_iground_on_became_dead(uint8_t *victim, int32_t p2) +{ + int is_host = local_mp_is_host(); + if (is_host && victim != NULL && + victim[LMP_IGM_OFF_ALREADY_DEAD] == 0 && + victim[LMP_IGM_OFF_DEAD_SILENT] == 0) { + int allow_kill = (victim[LMP_IGM_OFF_BAILOUT_DEAD] == 0); + int32_t killer_army = *(int32_t *)(victim + LMP_IGM_OFF_KILLER_ARMY); + uint8_t *killer_mp = allow_kill ? local_mp_find_mplayer( + *(int64_t *)(victim + LMP_IGM_OFF_KILLER_UID), victim[LMP_IGM_OFF_KILLER_PID]) : NULL; + local_mp_events_begin_death(victim); + if (allow_kill && killer_mp == NULL) + killer_mp = resolve_offender_killer(victim, &killer_army); + if (allow_kill && killer_mp != NULL && victim[LMP_IGM_OFF_KILLER_PID] == 0xffu) { + victim[LMP_IGM_OFF_KILLER_PID] = killer_mp[LMP_MP_OFF_PID]; + *(int64_t *)(victim + LMP_IGM_OFF_KILLER_UID) = *(int64_t *)(killer_mp + LMP_MP_OFF_USER_ID); + } + process_unit_death(victim, killer_mp, killer_army, allow_kill); + } + if (is_host && *g_local_mp_multiplayer != NULL) { + (*g_local_mp_multiplayer)[LMP_MP_MGR_OFF_IS_LOCAL_MP] = 0; + orig_iground_on_dead(victim, p2); + if (*g_local_mp_multiplayer != NULL) + (*g_local_mp_multiplayer)[LMP_MP_MGR_OFF_IS_LOCAL_MP] = 1; + return; + } + orig_iground_on_dead(victim, p2); +} + +static void __fastcall hook_on_unit_dead_once(uint8_t *victim) +{ + if (local_mp_is_host() && victim != NULL && victim[LMP_UNIT_OFF_SKIP_KILL] == 0) { + int32_t killer_army = 0; + uint8_t *killer_mp = resolve_offender_killer(victim, &killer_army); + local_mp_events_begin_death(victim); + process_unit_death(victim, killer_mp, killer_army, 1); + } + orig_on_unit_dead_once(victim); +} + +int install_local_mp_kill_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead) +{ + uint8_t *p_add = local_mp_scan_unique(text, text_size, "MPlayer::addScore", LMP_SIG_MPLAYER_ADD_SCORE); + uint8_t *p_dirty = local_mp_scan_unique(text, text_size, "net_mark_dirty", LMP_SIG_NET_MARK_DIRTY); + uint8_t *p_dead = local_mp_scan_unique(text, text_size, "onUnitDeadOnce", LMP_SIG_ON_UNIT_DEAD_ONCE); + + if (!p_ground_dead || !p_add || !p_dirty || !p_dead) + return 0; + + fn_mplayer_add_score = (MPlayerAddScoreFn)p_add; + fn_net_mark_dirty = (NetMarkDirtyFn)p_dirty; + + if (MH_CreateHook(p_ground_dead, (void *)&hook_iground_on_became_dead, (void **)&orig_iground_on_dead) != MH_OK || + MH_EnableHook(p_ground_dead) != MH_OK || + MH_CreateHook(p_dead, (void *)&hook_on_unit_dead_once, (void **)&orig_on_unit_dead_once) != MH_OK || + MH_EnableHook(p_dead) != MH_OK) { + log_line("local_mp: failed to install unit-death scoring hooks"); + return 0; + } + return 1; +} diff --git a/native/wto-net/src/local_mp_ledger.c b/native/wto-net/src/local_mp_ledger.c new file mode 100644 index 0000000..c75bb00 --- /dev/null +++ b/native/wto-net/src/local_mp_ledger.c @@ -0,0 +1,295 @@ +/* + * LocalMP SessionStatsNet & UnitSessionStat ledger, per-unit rate table, + * and center-screen HUD reward banner. + */ +#include "hooks.h" +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include "MinHook.h" + +#include + +typedef struct DagorSimpleStr { + const char *ptr; + void *alloc; + uint64_t len_cap; +} DagorSimpleStr; + +typedef void (__fastcall *SessionStatsResetFn)(void *stats_net); +typedef uint8_t *(__fastcall *SessionStatsGetUnitFn)(void *stats_net, const char *unit_name); +typedef void (__fastcall *StartActualizeClientFn)(void *econ_state, int32_t p2, uint8_t p3); +typedef void (__fastcall *HudAddScoreMessageFn)( + void *hud, uint32_t event_id, uint32_t msg_type, int32_t xp, int32_t wp, + uint32_t delay, void *target_unit, const DagorSimpleStr *str, int64_t a9, int64_t a10 +); + +static void **g_hud_ptr; +static SessionStatsResetFn fn_stats_reset; +static SessionStatsGetUnitFn fn_stats_get_unit; +static HudAddScoreMessageFn fn_hud_add_score_msg; +static StartActualizeClientFn orig_start_actualize; + +static LocalMpUnitRateEntry g_unit_rates[LMP_MAX_UNIT_RATES]; +static size_t g_unit_rate_count = 0; +static char g_last_spawned_unit[64]; +static int g_finalized_this_match = 0; +static const LocalMpUnitRates k_empty_rates = { "", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + +static void sat_add_i32(int32_t *dst, int32_t delta) +{ + int64_t sum = (int64_t)(*dst) + (int64_t)delta; + if (sum > 0x7fffffffLL) sum = 0x7fffffffLL; + if (sum < 0) sum = 0; + *dst = (int32_t)sum; +} + +static void add_bucket_values(uint8_t *base, size_t bkt_off, int32_t count_inc, int32_t wp, int32_t exp) +{ + uint8_t *b = base + bkt_off; + sat_add_i32((int32_t *)(b + LMP_BKT_OFF_COUNT), count_inc); + sat_add_i32((int32_t *)(b + LMP_BKT_OFF_EXP), exp); + sat_add_i32((int32_t *)(b + LMP_BKT_OFF_WP), wp); + sat_add_i32((int32_t *)(b + LMP_BKT_OFF_RAW_EXP), exp); + sat_add_i32((int32_t *)(b + LMP_BKT_OFF_RAW_WP), wp); + sat_add_i32((int32_t *)(b + LMP_BKT_OFF_NO_BONUS_EXP), exp); + sat_add_i32((int32_t *)(b + LMP_BKT_OFF_NO_BONUS_WP), wp); +} + +static void record_on_unit( + uint8_t *sstat, const char *unit_name, size_t bkt_off, + int32_t count_inc, int32_t wp, int32_t exp, float score_delta +) +{ + int32_t total_inc = count_inc > 0 ? 1 : 0; + uint8_t *ustat; + + add_bucket_values(sstat, bkt_off, count_inc, wp, exp); + if (bkt_off != LMP_STAT_BKT_TOTAL) + add_bucket_values(sstat, LMP_STAT_BKT_TOTAL, total_inc, wp, exp); + sat_add_i32((int32_t *)(sstat + LMP_SSTAT_OFF_EXP_FREE), exp); + if (unit_name == NULL || unit_name[0] == '\0' || fn_stats_get_unit == NULL) + return; + ustat = fn_stats_get_unit(sstat, unit_name); + if (ustat == NULL) + return; + add_bucket_values(ustat, bkt_off, count_inc, wp, exp); + if (bkt_off != LMP_STAT_BKT_TOTAL) + add_bucket_values(ustat, LMP_STAT_BKT_TOTAL, total_inc, wp, exp); + *(float *)(ustat + LMP_USTAT_OFF_SCORE) += score_delta; + sat_add_i32((int32_t *)(ustat + LMP_USTAT_OFF_EXP_MOD), exp); + sat_add_i32((int32_t *)(ustat + LMP_USTAT_OFF_EXP_MOD_TOTAL), exp); + sat_add_i32((int32_t *)(ustat + LMP_USTAT_OFF_EXP_UNIT), exp); + sat_add_i32((int32_t *)(ustat + LMP_USTAT_OFF_EXP_UNIT_TOTAL), exp); +} + +void local_mp_ledger_reset(void) +{ + uint8_t *econ = local_mp_econ_state(); + g_unit_rate_count = 0; + g_finalized_this_match = 0; + memset(g_unit_rates, 0, sizeof(g_unit_rates)); + memset(g_last_spawned_unit, 0, sizeof(g_last_spawned_unit)); + local_mp_events_reset(); + if (econ != NULL && fn_stats_reset != NULL) + fn_stats_reset(econ + LMP_ECON_OFF_SESSION_STATS); +} + +void local_mp_ledger_store_rates(const LocalMpUnitRates *rates) +{ + size_t i; + if (rates == NULL || rates->unit_name[0] == '\0') + return; + for (i = 0; i < g_unit_rate_count; i++) { + if (strcmp(g_unit_rates[i].rates.unit_name, rates->unit_name) == 0) { + g_unit_rates[i].rates = *rates; + return; + } + } + if (g_unit_rate_count < LMP_MAX_UNIT_RATES) { + g_unit_rates[g_unit_rate_count].rates = *rates; + g_unit_rates[g_unit_rate_count].spawned = 0; + g_unit_rate_count++; + } +} + +void local_mp_ledger_activate_unit(const char *unit_name) +{ + uint8_t *econ = local_mp_econ_state(); + size_t i; + + if (unit_name == NULL || unit_name[0] == '\0') + return; + g_finalized_this_match = 0; + memset(g_last_spawned_unit, 0, sizeof(g_last_spawned_unit)); + strncpy(g_last_spawned_unit, unit_name, sizeof(g_last_spawned_unit) - 1); + if (econ != NULL && fn_stats_get_unit != NULL) + fn_stats_get_unit(econ + LMP_ECON_OFF_SESSION_STATS, unit_name); + + for (i = 0; i < g_unit_rate_count; i++) { + if (strcmp(g_unit_rates[i].rates.unit_name, unit_name) == 0) { + g_unit_rates[i].spawned = 1; + return; + } + } + if (g_unit_rate_count < LMP_MAX_UNIT_RATES) { + memset(&g_unit_rates[g_unit_rate_count], 0, sizeof(g_unit_rates[0])); + strncpy(g_unit_rates[g_unit_rate_count].rates.unit_name, unit_name, + sizeof(g_unit_rates[0].rates.unit_name) - 1); + g_unit_rates[g_unit_rate_count].spawned = 1; + g_unit_rate_count++; + } +} + +const char *local_mp_active_player_unit_name(void) +{ + uint8_t *mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL; + const char *hero_name = (g_local_mp_hero && *g_local_mp_hero) ? local_mp_unit_name(*g_local_mp_hero) : NULL; + + if (hero_name != NULL && mplayer != NULL && mplayer[LMP_MP_OFF_GUI_STATE] == LMP_GUI_STATE_PILOT_CONTROL) { + local_mp_ledger_activate_unit(hero_name); + return hero_name; + } + return g_last_spawned_unit[0] != '\0' ? g_last_spawned_unit : hero_name; +} + +const LocalMpUnitRates *local_mp_ledger_rates_for_unit(const char *unit_name) +{ + const char *target = (unit_name && unit_name[0] != '\0') ? unit_name : local_mp_active_player_unit_name(); + size_t i; + + if (target != NULL && target[0] != '\0') { + for (i = 0; i < g_unit_rate_count; i++) { + if (strcmp(g_unit_rates[i].rates.unit_name, target) == 0) + return &g_unit_rates[i].rates; + } + } + return &k_empty_rates; +} + +void local_mp_ledger_record_event( + const char *unit_name, size_t bucket_off, int32_t count_inc, int32_t wp, int32_t exp, float score_delta +) +{ + uint8_t *econ = local_mp_econ_state(); + const char *active_name = (unit_name && unit_name[0] != '\0') ? unit_name : local_mp_active_player_unit_name(); + + if (econ == NULL) + return; + if (active_name != NULL && active_name[0] != '\0') + local_mp_ledger_activate_unit(active_name); + record_on_unit(econ + LMP_ECON_OFF_SESSION_STATS, active_name, + bucket_off, count_inc, wp > 0 ? wp : 0, exp > 0 ? exp : 0, score_delta); +} + +void local_mp_ledger_banner(uint32_t event_id, uint32_t msg_type, int32_t xp, int32_t wp, void *target_unit) +{ + void *hud = g_hud_ptr ? *g_hud_ptr : NULL; + DagorSimpleStr empty_str = { NULL, g_local_mp_stdmem ? *g_local_mp_stdmem : NULL, 0 }; + + if (hud != NULL && fn_hud_add_score_msg != NULL) + fn_hud_add_score_msg(hud, event_id, msg_type, xp, wp, 0, target_unit, &empty_str, 0, 0); +} + +static size_t count_spawned_units(void) +{ + size_t i, spawned = 0; + for (i = 0; i < g_unit_rate_count; i++) { + if (g_unit_rates[i].spawned && g_unit_rates[i].rates.wp_per_kill > 0.0f) + spawned++; + } + return spawned; +} + +static void finalize_session_stats_before_exit(uint8_t *econ) +{ + uint8_t *sstat = econ + LMP_ECON_OFF_SESSION_STATS; + uint8_t *app = g_local_mp_app ? *g_local_mp_app : NULL; + uint8_t *rules = app ? *(uint8_t **)(app + LMP_APP_OFF_SCORE_RULES) : NULL; + int32_t mstat = rules ? *(int32_t *)(rules + LMP_SCORE_RULES_OFF_MSTATUS) : 0; + uint8_t *local_mp = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL; + float score = local_mp ? (float)(*(int32_t *)(local_mp + LMP_MP_OFF_SCORE)) : 0.0f; + float total_bt = *(float *)(sstat + LMP_STAT_OFF_BATTLE_TIME); + float total_st = *(float *)(sstat + LMP_STAT_OFF_SESSION_TIME); + float active_sec = total_bt > 1.0f ? total_bt : (total_st * 0.65f); + float activity = 0.0f; + size_t spawned_count, i; + + if (g_finalized_this_match) + return; + g_finalized_this_match = 1; + *(int32_t *)(sstat + LMP_SSTAT_OFF_RESULT) = (mstat == LMP_MISSION_STATUS_SUCCESS) ? LMP_STATS_RESULT_SUCCESS : + ((mstat == LMP_MISSION_STATUS_FAIL) ? LMP_STATS_RESULT_FAIL : LMP_STATS_RESULT_IN_PROGRESS); + + if (score > 0.0f || active_sec > 3.0f) { + activity = (score / 1200.0f) * 0.65f + (active_sec / 480.0f) * 0.35f; + if (activity < 0.15f) activity = 0.15f; + if (activity > 1.0f) activity = 1.0f; + } + *(float *)(sstat + LMP_SSTAT_OFF_ACTIVITY) = activity; + if (total_bt < 1.0f && active_sec > 0.0f) + *(float *)(sstat + LMP_STAT_OFF_BATTLE_TIME) = active_sec; + + spawned_count = count_spawned_units(); + if (spawned_count == 0) + return; + + for (i = 0; i < g_unit_rate_count; i++) { + const LocalMpUnitRates *r = &g_unit_rates[i].rates; + uint8_t *ustat; + float u_bt, u_st, share_st, eff_sec; + if (!g_unit_rates[i].spawned || r->wp_per_kill <= 0.0f) + continue; + ustat = fn_stats_get_unit ? fn_stats_get_unit(sstat, r->unit_name) : NULL; + u_bt = ustat ? *(float *)(ustat + LMP_STAT_OFF_BATTLE_TIME) : 0.0f; + u_st = ustat ? *(float *)(ustat + LMP_STAT_OFF_SESSION_TIME) : 0.0f; + share_st = total_st > 1.0f ? (total_st / (float)spawned_count) : active_sec; + eff_sec = u_bt > 1.0f ? u_bt : (u_st > 1.0f ? u_st * 0.65f : (active_sec / (float)spawned_count)); + if (ustat != NULL && u_st < 1.0f && share_st > 0.5f) + *(float *)(ustat + LMP_STAT_OFF_SESSION_TIME) = share_st; + if (eff_sec > 2.0f && activity > 0.0f) { + int32_t bt_wp = (int32_t)((eff_sec / 60.0f) * r->battle_time_award * activity + 0.5f); + int32_t bt_rp = (int32_t)((eff_sec * 1.4f) * r->exp_mul * activity + 0.5f); + if (ustat != NULL && u_bt < 1.0f) + *(float *)(ustat + LMP_STAT_OFF_BATTLE_TIME) = eff_sec; + record_on_unit(sstat, r->unit_name, LMP_STAT_BKT_BATTLE_TIME, 1, bt_wp, bt_rp, 0.0f); + if (*(int32_t *)(sstat + LMP_SSTAT_OFF_RESULT) == LMP_STATS_RESULT_SUCCESS) { + record_on_unit(sstat, r->unit_name, LMP_STAT_BKT_MISSION, 1, + (int32_t)((float)bt_wp * r->win_k + 0.5f), (int32_t)((float)bt_rp * r->win_k + 0.5f), 0.0f); + } + } + } +} + +static void __fastcall hook_start_actualize_client(void *econ_state, int32_t p2, uint8_t p3) +{ + if (local_mp_is_host() && econ_state != NULL) + finalize_session_stats_before_exit((uint8_t *)econ_state); + orig_start_actualize(econ_state, p2, p3); +} + +int install_local_mp_ledger_hooks(const uint8_t *text, size_t text_size, uint8_t *p_ground_dead) +{ + uint8_t *p_hud_msg = local_mp_scan_unique(text, text_size, "Hud::addScoreMessage", LMP_SIG_HUD_ADD_SCORE_MSG); + uint8_t *p_reset = local_mp_scan_unique(text, text_size, "SessionStatsNet::reset", LMP_SIG_SESSION_STATS_RESET); + uint8_t *p_get_u = local_mp_scan_unique(text, text_size, "SessionStatsNet::getOrCreateUnitStat", LMP_SIG_SESSION_STATS_GET_UNIT); + uint8_t *p_actualize = local_mp_scan_unique(text, text_size, "GameSaveData::startActualizeClient", LMP_SIG_START_ACTUALIZE_CLIENT); + + if (!p_ground_dead || !p_hud_msg || !p_reset || !p_get_u || !p_actualize) + return 0; + if (p_ground_dead[0xa19] != 0x48 || p_ground_dead[0xa1a] != 0x8b || p_ground_dead[0xa1b] != 0x0d) + return 0; + + g_hud_ptr = (void **)local_mp_resolve_rip(p_ground_dead + 0xa19, 3, 7); + fn_hud_add_score_msg = (HudAddScoreMessageFn)p_hud_msg; + fn_stats_reset = (SessionStatsResetFn)p_reset; + fn_stats_get_unit = (SessionStatsGetUnitFn)p_get_u; + + if (MH_CreateHook(p_actualize, (void *)&hook_start_actualize_client, (void **)&orig_start_actualize) != MH_OK || + MH_EnableHook(p_actualize) != MH_OK) { + log_line("local_mp: failed to install startActualizeClient hook"); + return 0; + } + return 1; +} diff --git a/native/wto-net/src/local_mp_loadout.c b/native/wto-net/src/local_mp_loadout.c new file mode 100644 index 0000000..7f64393 --- /dev/null +++ b/native/wto-net/src/local_mp_loadout.c @@ -0,0 +1,254 @@ +/* + * LocalMP vehicle loadout, modification map, decals, 3D attachables, and crew-skill bridge. + * + * Stores per-unit economic multipliers in `LocalMpUnitRateEntry[32]` without touching + * `SessionStatsNet` during respawn-screen previews (`requestChangeUnitSilent`). + */ +#include "hooks.h" +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include "MinHook.h" + +#include + +typedef void (__fastcall *SemChangeAircraftSendFn)( + void *self, const char *unit_name, const char *weapon_name, const void *modifications_blk, + const char *skin_name, const void *custom_preset_blk, uint8_t flags_byte, + const void *serialized_bullets, int32_t crew_id, int32_t resp_base_id, float fuel, + float gun_targeting_dist, uint8_t vertical_targeting, float bomb_activation_time, + uint16_t extra_u16, uint8_t extra_b1, uint8_t extra_b2, const char *extra_str, + const char *custom_skin, int32_t slot_id, const void *spare_data, int32_t spare_type +); +typedef void *(__fastcall *ReflCtorFn)(void *refl); +typedef void (__fastcall *ReflDtorFn)(void *refl); +typedef uint8_t (__fastcall *UnitChangeAircraftFn)(void *unit, void *refl, uint8_t async); +typedef void *(__fastcall *DataBlockSetFromFn)(void *dst_blk, const void *src_blk, const char *src_fname); +typedef void (__fastcall *DataBlockDtorFn)(void *blk); +typedef float (__fastcall *DataBlockGetRealFn)(const void *blk, const char *name, float def); +typedef void (__fastcall *BulletSetVecAssignFn)(void *dst_vec, const void *first, const void *last); +typedef void *(__fastcall *GetDecalsBlkFn)( + void *econ, void *out_blk, const char *unit, const char *skin, const char *def_key, const char *cskin +); +typedef const void *(__fastcall *GetAttachablesBlkFn)( + void *econ, const char *unit, const char *skin, const char *cskin +); +typedef uint64_t (__fastcall *StrHashFnv1Fn)(const char *str, size_t len); +typedef int32_t (__fastcall *NameMapAddNameIdFn)(void *map, const char *str, size_t len, uint64_t hash); +typedef void (__fastcall *CrewSkillsInitFn)(void *crew_skills, void *econ_state, const char *unit_name, float mult); + +static SemChangeAircraftSendFn orig_sem_send; +static ReflCtorFn fn_refl_ctor; +static ReflDtorFn fn_refl_dtor; +static UnitChangeAircraftFn fn_unit_change_aircraft; +static DataBlockSetFromFn fn_datablock_set_from; +static DataBlockDtorFn fn_datablock_dtor; +static DataBlockGetRealFn fn_datablock_get_real; +static BulletSetVecAssignFn fn_bullet_vec_assign; +static GetDecalsBlkFn fn_get_decals_blk; +static GetAttachablesBlkFn fn_get_attachables_blk; +static StrHashFnv1Fn fn_str_hash; +static NameMapAddNameIdFn fn_namemap_add; +static CrewSkillsInitFn fn_crew_skills_init; + +static void populate_namemap_csv(void *map, const char *csv) +{ + const char *p = csv; + char tok[96]; + + if (map == NULL || p == NULL || *p == '\0') + return; + while (*p != '\0') { + const char *sep = strchr(p, ';'); + size_t len = sep ? (size_t)(sep - p) : strlen(p); + if (len > 0 && len < sizeof(tok)) { + memcpy(tok, p, len); + tok[len] = '\0'; + fn_namemap_add(map, tok, len, fn_str_hash(tok, len)); + } + if (sep == NULL) + break; + p = sep + 1; + } +} + +static int parse_spawn_metadata_blk(const char *unit_name, const void *mods_blk, uint8_t *refl) +{ + LocalMpUnitRates rates; + const char *enabled_csv = ""; + const char *disabled_csv = ""; + const char *silent_str = "0"; + + memset(&rates, 0, sizeof(rates)); + if (unit_name != NULL) + strncpy(rates.unit_name, unit_name, sizeof(rates.unit_name) - 1); + + if (mods_blk != NULL && g_lmp_datablock_get_str != NULL) { + enabled_csv = g_lmp_datablock_get_str(mods_blk, "enabledMods", ""); + disabled_csv = g_lmp_datablock_get_str(mods_blk, "disabledMods", ""); + silent_str = g_lmp_datablock_get_str(mods_blk, "isSilentPreview", "0"); + rates.wp_per_kill = fn_datablock_get_real(mods_blk, "wpPerKill", 0.0f); + rates.exp_mul = fn_datablock_get_real(mods_blk, "expMul", 0.0f); + rates.battle_time_award = fn_datablock_get_real(mods_blk, "battleTimeAward", 0.0f); + rates.ai_kill_k = fn_datablock_get_real(mods_blk, "aiKillK", 0.0f); + rates.win_k = fn_datablock_get_real(mods_blk, "winK", 0.0f); + } + + if (refl != NULL) { + populate_namemap_csv(refl + LMP_REFL_OFF_ENABLED_MODS, enabled_csv); + populate_namemap_csv(refl + LMP_REFL_OFF_DISABLED_MODS, disabled_csv); + } + if (rates.unit_name[0] != '\0' && rates.wp_per_kill > 0.0f) + local_mp_ledger_store_rates(&rates); + return silent_str != NULL && strcmp(silent_str, "1") == 0; +} + +static void populate_cosmetics( + uint8_t *refl, uint8_t *econ_state, const char *unit_name, const char *skin_name, const char *custom_skin +) +{ + __declspec(align(16)) uint8_t decals_tmp[64]; + const char *u = unit_name ? unit_name : ""; + const char *s = skin_name ? skin_name : ""; + const char *c = custom_skin ? custom_skin : ""; + const void *att_blk; + + memset(decals_tmp, 0, sizeof(decals_tmp)); + if (fn_get_decals_blk(econ_state, decals_tmp, u, s, "defaultDecals", c) != NULL) { + fn_datablock_set_from(refl + LMP_REFL_OFF_DECALS_BLK, decals_tmp, NULL); + fn_datablock_dtor(decals_tmp); + } + att_blk = fn_get_attachables_blk(econ_state, u, s, c); + if (att_blk != NULL) + fn_datablock_set_from(refl + LMP_REFL_OFF_ATTACHABLES_BLK, att_blk, NULL); +} + +static void apply_mplayer_spawn_base(uint8_t *mplayer, int32_t req_base_id) +{ + *(int32_t *)(mplayer + LMP_MP_OFF_RESP_BASE_ID) = req_base_id; + *(int32_t *)(mplayer + LMP_MP_OFF_SPAWN_DELAY_A) = -1; + *(int32_t *)(mplayer + LMP_MP_OFF_SPAWN_DELAY_B) = -1; + *(float *)(mplayer + LMP_MP_OFF_SPAWN_POS_X) = 0.0f; + *(float *)(mplayer + LMP_MP_OFF_SPAWN_POS_Y) = 0.0f; + *(float *)(mplayer + LMP_MP_OFF_SPAWN_POS_Z) = 0.0f; +} + +static void __fastcall hook_sem_change_aircraft_send( + void *self, const char *unit_name, const char *weapon_name, const void *modifications_blk, + const char *skin_name, const void *custom_preset_blk, uint8_t flags_byte, + const void *serialized_bullets, int32_t crew_id, int32_t resp_base_id, float fuel, + float gun_targeting_dist, uint8_t vertical_targeting, float bomb_activation_time, + uint16_t extra_u16, uint8_t extra_b1, uint8_t extra_b2, const char *extra_str, + const char *custom_skin, int32_t slot_id, const void *spare_data, int32_t spare_type +) +{ + uint8_t *hero, *mplayer, *econ_state, *req; + const void *bullets_begin, *bullets_end; + void *crew_skills; + int32_t req_slot_id, req_base_id, req_spare_type; + int is_silent; + __declspec(align(16)) uint8_t refl[LMP_REFL_SIZE]; + + if (!local_mp_is_host()) { + orig_sem_send(self, unit_name, weapon_name, modifications_blk, skin_name, custom_preset_blk, + flags_byte, serialized_bullets, crew_id, resp_base_id, fuel, gun_targeting_dist, + vertical_targeting, bomb_activation_time, extra_u16, extra_b1, extra_b2, + extra_str, custom_skin, slot_id, spare_data, spare_type); + return; + } + + hero = g_local_mp_hero ? *g_local_mp_hero : NULL; + mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : (hero ? *(uint8_t **)(hero + LMP_UNIT_OFF_MPLAYER) : NULL); + econ_state = local_mp_econ_state(); + if (hero == NULL || mplayer == NULL || econ_state == NULL) + return; + + if (mplayer[LMP_MP_OFF_GUI_STATE] == LMP_GUI_STATE_PILOT_CONTROL && + parse_spawn_metadata_blk(unit_name, modifications_blk, NULL)) { + g_lmp_aircraft_change_result(econ_state, 0); + return; + } + + req = econ_state + LMP_ECON_OFF_CHANGE_REQ; + bullets_begin = *(const void **)(req + LMP_REQ_OFF_BULLETS_BEGIN); + bullets_end = *(const void **)(req + LMP_REQ_OFF_BULLETS_END); + req_slot_id = *(int32_t *)(req + LMP_REQ_OFF_SLOT_ID); + req_base_id = *(int32_t *)(req + LMP_REQ_OFF_RESP_BASE_ID); + req_spare_type = *(int32_t *)(req + LMP_REQ_OFF_SPARE_TYPE); + apply_mplayer_spawn_base(mplayer, req_base_id); + + memset(refl, 0, sizeof(refl)); + fn_refl_ctor(refl); + *(char **)(refl + LMP_REFL_OFF_UNIT_NAME) = local_mp_strdup(unit_name); + *(char **)(refl + LMP_REFL_OFF_WEAPON_NAME) = local_mp_strdup(weapon_name); + *(char **)(refl + LMP_REFL_OFF_SKIN_NAME) = local_mp_strdup(skin_name); + *(char **)(refl + LMP_REFL_OFF_CUSTOM_SKIN) = local_mp_strdup(custom_skin); + populate_cosmetics(refl, econ_state, unit_name, skin_name, custom_skin); + is_silent = parse_spawn_metadata_blk(unit_name, modifications_blk, refl); + if (custom_preset_blk != NULL) + fn_datablock_set_from(refl + LMP_REFL_OFF_CUSTOM_PRESET_BLK, custom_preset_blk, NULL); + if (bullets_begin != NULL && bullets_end != NULL && bullets_end > bullets_begin) + fn_bullet_vec_assign(refl + LMP_REFL_OFF_BULLETS_VEC, bullets_begin, bullets_end); + + *(uint32_t *)(refl + LMP_REFL_OFF_FLAGS) |= 0x50u; + *(float *)(refl + LMP_REFL_OFF_FUEL) = fuel; + *(float *)(refl + LMP_REFL_OFF_GUN_CONVERGENCE) = gun_targeting_dist; + refl[LMP_REFL_OFF_VERT_TARGETING] = vertical_targeting ? 1u : 0u; + *(float *)(refl + LMP_REFL_OFF_BOMB_FUSE) = bomb_activation_time; + + fn_unit_change_aircraft(hero, refl, 1); + fn_refl_dtor(refl); + + crew_skills = *(void **)(hero + LMP_UNIT_OFF_CREW_SKILLS); + if (crew_skills != NULL && unit_name != NULL && unit_name[0] != '\0') + fn_crew_skills_init(crew_skills, econ_state, unit_name, 1.0f); + if (mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_PILOT_CONTROL && + mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_CA_READY) + g_lmp_set_player_gui_state((int32_t)mplayer[LMP_MP_OFF_PID], LMP_GUI_STATE_CA_READY); + + local_mp_players_queue_spawn(req_slot_id, req_spare_type, is_silent); + log_line("local_mp: configured unit='%s' weapon='%s' slot=%d silent=%d", + unit_name ? unit_name : "", weapon_name ? weapon_name : "", (int)req_slot_id, is_silent); +} + +int install_local_mp_loadout_hooks(const uint8_t *text, size_t text_size) +{ + uint8_t *p_sem_send = local_mp_scan_unique(text, text_size, "SemChangeAircraftRequest::send", LMP_SIG_SEM_CHANGE_AIRCRAFT_SEND); + uint8_t *p_refl_ctor = local_mp_scan_unique(text, text_size, "ChangeUnitReflection::ctor", LMP_SIG_REFL_CTOR); + uint8_t *p_refl_dtor = local_mp_scan_unique(text, text_size, "ChangeUnitReflection::dtor", LMP_SIG_REFL_DTOR); + uint8_t *p_change_air = local_mp_scan_unique(text, text_size, "Unit::changeAircraft", LMP_SIG_UNIT_CHANGE_AIRCRAFT); + uint8_t *p_blk_set = local_mp_scan_unique(text, text_size, "DataBlock::setFrom", LMP_SIG_DATABLOCK_SET_FROM); + uint8_t *p_blk_dtor = local_mp_scan_unique(text, text_size, "DataBlock::~DataBlock", LMP_SIG_DATABLOCK_DTOR); + uint8_t *p_blk_real = local_mp_scan_unique(text, text_size, "DataBlock::getReal", LMP_SIG_DATABLOCK_GET_REAL); + uint8_t *p_bullets = local_mp_scan_unique(text, text_size, "BulletSetVec::assign", LMP_SIG_BULLET_VEC_ASSIGN); + uint8_t *p_decals = local_mp_scan_unique(text, text_size, "GameSaveData::getDecalsBlk", LMP_SIG_GET_DECALS_BLK); + uint8_t *p_attach = local_mp_scan_unique(text, text_size, "GameSaveData::getAttachablesBlk", LMP_SIG_GET_ATTACHABLES_BLK); + uint8_t *p_hash = local_mp_scan_unique(text, text_size, "str_hash_fnv1", LMP_SIG_STR_HASH_FNV1); + uint8_t *p_nm_add = local_mp_scan_unique(text, text_size, "OAHashNameMap::addNameId", LMP_SIG_NAMEMAP_ADD_NAME_ID); + uint8_t *p_crew = local_mp_scan_unique(text, text_size, "UnitCrewSkills::initFromSave", LMP_SIG_CREW_SKILLS_INIT); + + if (!p_sem_send || !p_refl_ctor || !p_refl_dtor || !p_change_air || !p_blk_set || !p_blk_dtor || + !p_blk_real || !p_bullets || !p_decals || !p_attach || !p_hash || !p_nm_add || !p_crew) + return 0; + + fn_refl_ctor = (ReflCtorFn)p_refl_ctor; + fn_refl_dtor = (ReflDtorFn)p_refl_dtor; + fn_unit_change_aircraft = (UnitChangeAircraftFn)p_change_air; + fn_datablock_set_from = (DataBlockSetFromFn)p_blk_set; + fn_datablock_dtor = (DataBlockDtorFn)p_blk_dtor; + fn_datablock_get_real = (DataBlockGetRealFn)p_blk_real; + fn_bullet_vec_assign = (BulletSetVecAssignFn)p_bullets; + fn_get_decals_blk = (GetDecalsBlkFn)p_decals; + fn_get_attachables_blk = (GetAttachablesBlkFn)p_attach; + fn_str_hash = (StrHashFnv1Fn)p_hash; + fn_namemap_add = (NameMapAddNameIdFn)p_nm_add; + fn_crew_skills_init = (CrewSkillsInitFn)p_crew; + + if (MH_CreateHook(p_sem_send, (void *)&hook_sem_change_aircraft_send, (void **)&orig_sem_send) != MH_OK || + MH_EnableHook(p_sem_send) != MH_OK) { + log_line("local_mp: failed to install SemChangeAircraftRequest::send hook"); + return 0; + } + return 1; +} diff --git a/native/wto-net/src/local_mp_offsets.h b/native/wto-net/src/local_mp_offsets.h new file mode 100644 index 0000000..e11f6dd --- /dev/null +++ b/native/wto-net/src/local_mp_offsets.h @@ -0,0 +1,297 @@ +/* + * Centralized struct offsets, RIP-relative displacements, and .text signatures + * for the War Thunder 2.61.0.37 LocalMP in-process host bridge. + */ +#pragma once + +#define LMP_GUI_STATE_PILOT_CONTROL 2 +#define LMP_GUI_STATE_CA_SELECT 6 +#define LMP_GUI_STATE_CA_READY 8 + +#define LMP_MISSION_STATUS_RUNNING 1 +#define LMP_MISSION_STATUS_SUCCESS 2 +#define LMP_MISSION_STATUS_FAIL 3 +#define LMP_STATS_RESULT_IN_PROGRESS 0 +#define LMP_STATS_RESULT_SUCCESS 1 +#define LMP_STATS_RESULT_FAIL 2 + +#define LMP_EXP_EVENT_CAPTURE_ZONE 2u +#define LMP_EXP_EVENT_KILL 5u +#define LMP_EXP_EVENT_KILL_GROUND 6u +#define LMP_EXP_EVENT_ASSIST 9u +#define LMP_EXP_EVENT_CRITICAL_HIT 10u +#define LMP_EXP_EVENT_HIT 13u +#define LMP_EXP_EVENT_UNIT_DAMAGE 24u +#define LMP_EXP_EVENT_DEATH 30u +#define LMP_EXP_EVENT_SEVERE_DAMAGE 35u +#define LMP_EXP_EVENT_KILL_HUMAN 39u +#define LMP_EXP_EVENT_COUNT 45u + +/* + * @anchor "localMP" + * @anchor "get_local_player_country" + * @anchor "mpDom1" + * @anchor "mpHadAlivePlayers" + * @anchor "guiscriptutils::is_crew_slot_was_ready_at_host" + * @anchor "customBots" + * @anchor "botDeviationLimits" + * @anchor "Reflection: invalid object 0x%p" + */ +#define LMP_MP_MGR_OFF_IS_HOST 0x0060u +#define LMP_MP_MGR_OFF_IS_LOCAL_MP 0x0061u +#define LMP_MP_MGR_OFF_TEAM1_COUNTRIES 0x0150u +#define LMP_MP_MGR_OFF_TEAM2_COUNTRIES 0x0170u +#define LMP_MP_MGR_OFF_MP_CHAT 0x01f0u +#define LMP_MP_MGR_OFF_CHAT_HOST 0x01f8u +#define LMP_TAB_OFF_DATA 0x0000u +#define LMP_TAB_OFF_ALLOC 0x0008u +#define LMP_TAB_OFF_COUNT 0x0010u +#define LMP_TAB_OFF_CAPACITY 0x0014u +#define LMP_APP_OFF_SCORE_RULES 0x03e0u +#define LMP_SCORE_RULES_OFF_MSTATUS 0x00f0u +#define LMP_APP_OFF_ECON_HOLDER 0x03f0u +#define LMP_ECON_HOLDER_OFF_STATE 0x09a8u +#define LMP_MIS_OFF_AXIS_COUNTRY 0x00c8u +#define LMP_MIS_OFF_ALLIES_COUNTRY 0x00d0u +#define LMP_MIS_OFF_ARCADE_COUNTRY 0x01d0u +#define LMP_MIS_OFF_CUSTOM_BOTS 0x0718u +#define LMP_MATCH_INFO_OFF_TEAM 0x0004u + +/* + * @anchor "set_aircraft_accepted_cb" + * @anchor "warpoints::stat_get_exp current exp %d" + * @anchor "GameSaveData::startActualizeClient" + */ +#define LMP_ECON_OFF_CHANGE_REQ 0xf578u +#define LMP_ECON_OFF_SESSION_STATS 0xf678u +#define LMP_REQ_OFF_BULLETS_BEGIN 0x0090u +#define LMP_REQ_OFF_BULLETS_END 0x0098u +#define LMP_REQ_OFF_RESP_BASE_ID 0x00b8u +#define LMP_REQ_OFF_SPARE_TYPE 0x00c0u +#define LMP_REQ_OFF_SLOT_ID 0x00e4u + +/* + * @anchor "get_mplayers_list" + * @anchor "kills" + * @anchor "teamKills" + * @anchor "deaths" + * @anchor "groundKills" + * @anchor "humanKills" + * @anchor "navalKills" + * @anchor "aiKills" + * @anchor "aiGroundKills" + * @anchor "aiNavalKills" + * @anchor "assists" + * @anchor "captureZone" + * @anchor "awardDamage" + * @anchor "airSevereDamage" + * @anchor "shipSevereDamage" + */ +#define LMP_MP_OFF_PID 0x0008u +#define LMP_MP_OFF_USER_ID 0x00b8u +#define LMP_MP_OFF_FLAGS 0x01d8u +#define LMP_MP_OFF_TEAM 0x0228u +#define LMP_MP_OFF_FALLBACK_SCORE 0x02d8u +#define LMP_MP_OFF_BROKEN_SLOTS_MASK 0x04d0u +#define LMP_MP_OFF_USED_SPARES_MASK 0x0520u +#define LMP_MP_OFF_GUI_STATE 0x0640u +#define LMP_MP_OFF_UNIT_EID 0x0850u +#define LMP_MP_OFF_SUPPORT_UNIT_EID 0x0880u +#define LMP_MP_FLAG_SPECTATOR_MASK 0x00020020u +#define LMP_MP_OFF_SCORE 0x08f8u +#define LMP_MP_OFF_KILLS 0x09d8u +#define LMP_MP_OFF_TEAM_KILLS 0x09dau +#define LMP_MP_OFF_DEATHS 0x09dcu +#define LMP_MP_OFF_GROUND_KILLS 0x09deu +#define LMP_MP_OFF_HUMAN_KILLS 0x09e0u +#define LMP_MP_OFF_NAVAL_KILLS 0x09e2u +#define LMP_MP_OFF_AI_KILLS 0x09e4u +#define LMP_MP_OFF_AI_GROUND_KILLS 0x09e6u +#define LMP_MP_OFF_AI_NAVAL_KILLS 0x09e8u +#define LMP_MP_OFF_ASSISTS 0x09ecu +#define LMP_MP_OFF_CAPTURE_ZONE 0x09eeu +#define LMP_MP_OFF_AWARD_DAMAGE 0x0a00u +#define LMP_MP_OFF_AIR_SEVERE_DMG 0x0a06u +#define LMP_MP_OFF_SHIP_SEVERE_DMG 0x0a08u +#define LMP_MP_OFF_STAT_DIRTY 0x0a10u +#define LMP_MP_OFF_STAT_PAYLOAD 0x0a30u +#define LMP_MP_OFF_RESP_BASE_ID 0x0bd8u +#define LMP_MP_OFF_SPAWN_DELAY_A 0x0bf4u +#define LMP_MP_OFF_SPAWN_DELAY_B 0x0bf8u +#define LMP_MP_OFF_SPAWN_POS_X 0x0bfcu +#define LMP_MP_OFF_SPAWN_POS_Y 0x0c00u +#define LMP_MP_OFF_SPAWN_POS_Z 0x0c04u + +/* + * @anchor "unit__playerId" + * @anchor "setMyPlayer uid:%i eid:%08x ptr:%p pid:%d (saved pid:%d)" + * @anchor "IGroundModel__onBecameDead" + */ +#define LMP_UNIT_OFF_ALIVE_STATE 0x0088u +#define LMP_UNIT_OFF_TYPE 0x008cu +#define LMP_UNIT_OFF_DEAD_FLAGS 0x0090u +#define LMP_UNIT_OFF_SEVERE_IDX 0x06b0u +#define LMP_UNIT_OFF_SEVERE_PID 0x06d0u +#define LMP_UNIT_OFF_SEVERE_UID 0x0708u +#define LMP_UNIT_OFF_BAIL_STATE 0x0f90u +#define LMP_UNIT_OFF_MPLAYER 0x0f98u +#define LMP_UNIT_DEAD_FLAGS_MASK 0x01000014u +#define LMP_UNIT_TYPE_HELICOPTER 0x000du +#define LMP_UNIT_OFF_ARMY 0x1010u +#define LMP_UNIT_OFF_PID 0x1018u +#define LMP_UNIT_OFF_INFO 0x1020u +#define LMP_UNIT_INFO_OFF_NAME 0x0010u +#define LMP_UNIT_OFF_CREW_SKILLS 0x10a8u +#define LMP_UNIT_VTF_CHOOSE_OFFENDER 0x0498u +#define LMP_UNIT_OFF_SKIP_KILL 0x3058u +#define LMP_IGM_OFF_OFFENDERS_PTR 0x17c0u +#define LMP_IGM_OFF_OFFENDERS_CNT 0x17d0u +#define LMP_IGM_OFF_KILLER_PID 0x1a08u +#define LMP_IGM_OFF_KILLER_ARMY 0x1a04u +#define LMP_IGM_OFF_KILLER_UID 0x1a40u +#define LMP_IGM_OFF_DEAD_SILENT 0x1c19u +#define LMP_IGM_OFF_ALREADY_DEAD 0x2101u +#define LMP_IGM_OFF_BAILOUT_DEAD 0x3888u +#define LMP_OFFENDER_STRIDE 0x0160u +#define LMP_OFFENDER_OFF_ARMY 0x001cu +#define LMP_OFFENDER_OFF_PID 0x0020u +#define LMP_OFFENDER_OFF_UID 0x0058u +#define LMP_OFFENDER_OFF_ASSIST_SENT 0x0148u + +/* + * @anchor "defaultDecals" + * @anchor "slaveAttachables" + * @anchor "bulletsWeapon%i" + */ +#define LMP_REFL_SIZE 0x0200u +#define LMP_REFL_OFF_UNIT_NAME 0x0050u +#define LMP_REFL_OFF_WEAPON_NAME 0x0058u +#define LMP_REFL_OFF_SKIN_NAME 0x0060u +#define LMP_REFL_OFF_CUSTOM_SKIN 0x0068u +#define LMP_REFL_OFF_DECALS_BLK 0x0070u +#define LMP_REFL_OFF_ATTACHABLES_BLK 0x0090u +#define LMP_REFL_OFF_CUSTOM_PRESET_BLK 0x00b0u +#define LMP_REFL_OFF_FLAGS 0x00d0u +#define LMP_REFL_OFF_FUEL 0x00d8u +#define LMP_REFL_OFF_GUN_CONVERGENCE 0x00dcu +#define LMP_REFL_OFF_VERT_TARGETING 0x00e0u +#define LMP_REFL_OFF_BOMB_FUSE 0x00e4u +#define LMP_REFL_OFF_ENABLED_MODS 0x00f0u +#define LMP_REFL_OFF_DISABLED_MODS 0x0140u +#define LMP_REFL_OFF_BULLETS_VEC 0x0190u + +/* + * @anchor "GameSaveData::addScoreMessage - bad messageType received %d" + * @anchor "numAirKills" + * @anchor "numGroundKills" + * @anchor "numHumanKills" + * @anchor "numNavalKills" + * @anchor "numCaptures" + * @anchor "numDamage" + * @anchor "numCritical" + * @anchor "numHit" + * @anchor "numAssist" + * @anchor "numBattleTime" + * @anchor "numMission" + * @anchor "numTotal" + * @anchor "numAwardDamage" + * @anchor "numAirSevereDamage" + * @anchor "numShipSevereDamage" + * @anchor "noBonusWp" + * @anchor "expInvestModuleTotal" + * @anchor "expInvestUnitTotal" + * @anchor "ucavLaunch" + * @anchor "prepareSupportPlane" + */ +#define LMP_STAT_OFF_SESSION_TIME 0x0000u +#define LMP_STAT_OFF_BATTLE_TIME 0x0008u +#define LMP_STAT_BKT_AIR_KILLS 0x0110u +#define LMP_STAT_BKT_GROUND_KILLS 0x0150u +#define LMP_STAT_BKT_HUMAN_KILLS 0x01d0u +#define LMP_STAT_BKT_NAVAL_KILLS 0x0250u +#define LMP_STAT_BKT_CAPTURES 0x0350u +#define LMP_STAT_BKT_DAMAGE 0x03d0u +#define LMP_STAT_BKT_CRITICAL 0x0410u +#define LMP_STAT_BKT_HIT 0x0450u +#define LMP_STAT_BKT_ASSIST 0x0490u +#define LMP_STAT_BKT_BATTLE_TIME 0x04d0u +#define LMP_STAT_BKT_MISSION 0x0550u +#define LMP_STAT_BKT_TOTAL 0x0650u +#define LMP_STAT_BKT_AWARD_DAMAGE 0x0790u +#define LMP_STAT_BKT_AIR_SEVERE 0x0810u +#define LMP_STAT_BKT_SHIP_SEVERE 0x0850u +#define LMP_USTAT_OFF_SCORE 0x0a5cu +#define LMP_USTAT_OFF_EXP_MOD 0x0a78u +#define LMP_USTAT_OFF_EXP_MOD_TOTAL 0x0a7cu +#define LMP_USTAT_OFF_EXP_UNIT 0x0a80u +#define LMP_USTAT_OFF_EXP_UNIT_TOTAL 0x0a84u +#define LMP_SSTAT_OFF_ACTIVITY 0x0aa4u +#define LMP_SSTAT_OFF_EXP_FREE 0x0ae0u +#define LMP_SSTAT_OFF_RESULT 0x0ae4u + +#define LMP_BKT_OFF_COUNT 0x00u +#define LMP_BKT_OFF_EXP 0x04u +#define LMP_BKT_OFF_WP 0x08u +#define LMP_BKT_OFF_RAW_EXP 0x0cu +#define LMP_BKT_OFF_RAW_WP 0x10u +#define LMP_BKT_OFF_NO_BONUS_EXP 0x14u +#define LMP_BKT_OFF_NO_BONUS_WP 0x18u + +/* @rip_check LMP_SIG_DISABLED_SLOTS_MASK + 0x02 : 48 83 3d */ +/* @rip_check LMP_SIG_DISABLED_SLOTS_MASK + 0x0c : 48 8b 0d */ +/* @rip_check LMP_SIG_DISABLED_SLOTS_MASK + 0x1f : 48 8b 0d */ +/* @rip_check LMP_SIG_DO_RESPAWN_PLAYER + 0x7d : 48 8b 15 */ +/* @rip_check LMP_SIG_SQ_LOCAL_COUNTRY + 0x1c : 48 8d 0d */ +/* @rip_check LMP_SIG_REFL_DTOR + 0x8b : 48 8b 0d */ +/* @rip_check LMP_SIG_GET_PLAYER_COUNTRY + 0x2e : 44 3b 15 */ +/* @rip_check LMP_SIG_GET_PLAYER_COUNTRY + 0x37 : 4c 8b 1d */ +/* @rip_check LMP_SIG_IGROUND_ON_DEAD + 0xa19 : 48 8b 0d */ +/* @rip_check LMP_SIG_DATABLOCK_SET_FROM + 0x25 : e8 */ +/* @rip_check LMP_SIG_CALLER_CAPTURE_ZONE + 0x6b : e8 */ +/* @rip_check LMP_SIG_CALLER_HIT_CRIT + 0x59 : e8 */ +/* @rip_check LMP_SIG_CALLER_SEVERE_DMG + 0x2f : e8 */ +/* @rip_check LMP_SIG_CALLER_NAVAL_DMG + 0x67 : e8 */ + +#define LMP_SIG_DISABLED_SLOTS_MASK "31 c0 48 83 3d ?? ?? ?? ?? 00 74 ?? 48 8b 0d ?? ?? ?? ?? 0f b6 89 f3 00 00 00 f6 c1 01 74 ?? 48 8b 0d ?? ?? ?? ?? 48 85 c9 74 ?? 8b 81 a0 04 00 00 0b 81 d0 04 00 00 c3" +#define LMP_SIG_DO_RESPAWN_PLAYER "56 57 53 48 81 ec 40 01 00 00 44 0f 29 84 24 30 01 00 00 0f 29 bc 24 20 01 00 00 0f 29 b4 24 10 01 00 00 48 8b 91 e0 03 00 00 48 c7 c0 ff ff ff ff 48 85 d2 0f 84 ?? ?? ?? ?? 8b 92 f0 00 00 00 83 fa 01 0f 85 ?? ?? ?? ?? f3 0f 10 81 e4 06 00 00 0f 57 c9 0f 2e c1 0f 83 ?? ?? ?? ?? 4c 8b 05 ?? ?? ?? ?? 40 b6 01 4d 85 c0 0f 84 ?? ?? ?? ?? f6 05 ?? ?? ?? ?? 04 0f 84 ?? ?? ?? ?? 48 8b 15 ?? ?? ?? ?? 48 85 d2 0f 84 ?? ?? ?? ??" +#define LMP_SIG_SEM_CHANGE_AIRCRAFT_SEND "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec f8 01 00 00 44 0f 29 84 24 e0 01 00 00 0f 29 bc 24 d0 01 00 00 0f 29 b4 24 c0 01 00 00 4c 89 cf 4c 89 c3 49 89 d7 48 89 ce 8b 05 ?? ?? ?? ?? 65 48 8b 0c 25 58 00 00 00" +#define LMP_SIG_GUI_STATE_UPDATE "56 57 48 83 ec 48 48 89 ce f3 0f 10 41 08 f3 0f 58 c1 f3 0f 11 41 08 f3 0f 10 51 10 0f 57 c0 0f 2e c2 73 ?? f3 0f 5c d1 f3 0f 11 56 10 48 8b 0d ?? ?? ?? ?? b0 01 0f 2e 81 e4 06 00 00 76 ??" +#define LMP_SIG_MPLAYER_INIT_MATCHING "41 56 56 57 55 53 48 81 ec e0 00 00 00 48 89 d7 48 89 ce 48 89 91 90 0c 00 00 48 8d 8c 24 88 00 00 00 0f 57 c0 0f 11 84 24 b8 00 00 00 0f 11 84 24 a8 00 00 00 0f 11 84 24 98 00 00 00" +#define LMP_SIG_GET_PLAYER_COUNTRY "56 48 83 ec 40 4c 89 c0 4c 8b 05 ?? ?? ?? ?? 4d 85 c0 0f 84 ?? ?? ?? ?? 45 31 d2 41 80 78 61 00 44 0f 44 d2 81 fa fa 00 00 00 44 0f 45 d2 44 3b 15 ?? ?? ?? ?? 73 ?? 4c 8b 1d ?? ?? ?? ??" +#define LMP_SIG_SQ_LOCAL_COUNTRY "41 56 56 57 53 48 83 ec 68 48 89 ce 48 8b 05 ?? ?? ?? ?? 48 85 c0 74 ?? 0f b6 50 08 48 8d 0d ?? ?? ?? ?? 4c 8d 44 24 20 41 b9 40 00 00 00 e8 ?? ?? ?? ?? 48 89 c7" +#define LMP_SIG_REFL_CTOR "56 48 83 ec 50 0f 29 74 24 40 48 89 ce 66 c7 41 08 ff ff c7 41 0c ff ff ff ff 0f 57 f6 0f 11 71 10 c7 41 20 44 4e 45 54 0f 11 71 28 0f 11 71 38" +#define LMP_SIG_REFL_DTOR "56 57 53 48 83 ec 40 48 89 ce 48 8d 05 ?? ?? ?? ?? 48 89 01 48 8b 89 b0 01 00 00 48 85 c9 74 ?? e8 ?? ?? ?? ?? 48 8b be 90 01 00 00 48 8b 9e 98 01 00 00 48 39 df" +#define LMP_SIG_UNIT_CHANGE_AIRCRAFT "41 57 41 56 56 57 55 53 48 81 ec 88 00 00 00 48 89 ce 8b 81 90 00 00 00 a8 10 75 ?? 80 be 1a 0f 00 00 00 75 ?? 48 8b 05 ?? ?? ?? ?? 0f b6 80 f3 00 00 00 0f b6 0d ?? ?? ?? ?? 08 c8 a8 01 74 ??" +#define LMP_SIG_AIRCRAFT_CHANGE_RESULT "41 57 41 56 56 57 53 48 83 ec 50 41 89 d0 48 89 ce 48 81 c1 78 f5 00 00 48 89 f2 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 8b 9e 78 f5 00 00 48 85 db 48 8d 3d ?? ?? ?? ?? 48 0f 44 df" +#define LMP_SIG_DATABLOCK_SET_FROM "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 48 48 89 d7 48 89 ce 66 2e 0f 1f 84 00 00 00 00 00 b9 90 00 00 00 e8 ?? ?? ?? ?? 48 85 c0 75 ?? 48 8b 05 ?? ?? ?? ??" +#define LMP_SIG_DATABLOCK_DTOR "41 57 41 56 41 54 56 57 53 48 83 ec 38 0f 29 74 24 20 48 8b 41 18" +#define LMP_SIG_DATABLOCK_GET_STR "48 83 ec 28 4c 89 44 24 20 4c 8d 44 24 20 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc cc 41 57" +#define LMP_SIG_DATABLOCK_GET_REAL "48 83 ec 28 f3 0f 11 54 24 24 4c 8d 44 24 24 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc 56 57 53 48 83 ec 30 48 89 d7 48 89 ce 48 8d 15" +#define LMP_SIG_MP_CONSTRUCT_LOCAL "56 57 53 48 83 ec 60 48 89 ce 48 81 c1 f8 00 00 00 e8 ?? ?? ?? ?? 66 c7 46 60 01 01" +#define LMP_SIG_MP_INIT_CHAT "41 57 41 56 41 54 56 57 53 48 83 ec 48 48 89 d7 48 89 ce 48 8b 05 ?? ?? ?? ?? 48 85 c0 74 ?? c6 00 01 48 8b 9e 00 02 00 00" +#define LMP_SIG_IGROUND_AWARD_ASSISTS "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec a8 01 00 00 44 0f 29 94 24 90 01 00 00 44 0f 29 8c 24 80 01 00 00 44 0f 29 84 24 70 01 00 00 0f 29 bc 24 60 01 00 00 0f 29 b4 24 50 01 00 00 48 89 ce 48 8b 01 48 8d 54 24 28 41 b0 01 ff 90 98 04 00 00" +#define LMP_SIG_BULLET_VEC_ASSIGN "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 58 4c 89 c5 49 89 d7 48 89 ce 4c 89 c3 48 29 d3 4c 8b 01 48 8b 41 10 4c 29 c0 48 39 c3 0f 86 ?? ?? ?? ?? 48 89 d9" +#define LMP_SIG_SET_PLAYER_GUI_STATE "41 57 41 56 41 54 56 57 55 53 48 83 ec 40 89 d6 48 8b 15 ?? ?? ?? ?? 48 85 d2 74 ?? 80 7a 60 00 0f 84 ?? ?? ?? ?? 85 c9 78 ?? 31 c0 80 7a 61 00 0f 44 c1 81 f9 fa 00 00 00 0f 45 c1 eb ?? 89 c8" +#define LMP_SIG_GET_UNIT_BY_EID "39 0d ?? ?? ?? ?? 74 2f 89 ca c1 ea 0a 3b 15 ?? ?? ?? ??" +#define LMP_SIG_SET_OWNING_MPLAYER "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 98 00 00 00 44 89 c3 48 89 d7 48 89 ce 48 85 d2" +#define LMP_SIG_GET_DECALS_BLK "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 88 00 00 00 44 0f 29 44 24 70 0f 29 7c 24 60 0f 29 74 24 50 4d 89 cf" +#define LMP_SIG_GET_ATTACHABLES_BLK "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 38 48 89 d7 4d 85 c0" +#define LMP_SIG_STR_HASH_FNV1 "41 56 56 57 53 49 89 d0 49 ba db 28 b4 a0 d1 7e 03 e7 48 83 fa 10 77 76" +#define LMP_SIG_NAMEMAP_ADD_NAME_ID "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 38 44 89 cf 48 89 ce 80 79 4b 00" +#define LMP_SIG_CREW_SKILLS_INIT "41 56 56 57 55 53 48 81 ec 90 00 00 00 0f 29 b4 24 80 00 00 00 0f 28 f3" +#define LMP_SIG_UCAV_LAUNCH "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 18 02 00 00 0f 29 bc 24 00 02 00 00 0f 29 b4 24 f0 01 00 00 48 8b 05 ?? ?? ?? ??" +#define LMP_SIG_IGROUND_ON_DEAD "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec a8 01 00 00 44 0f 29 8c 24 90 01 00 00 44 0f 29 84 24 80 01 00 00 0f 29 bc 24 70 01 00 00 0f 29 b4 24 60 01 00 00 89 d3" +#define LMP_SIG_ON_UNIT_DEAD_ONCE "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 98 01 00 00 44 0f 29 84 24 80 01 00 00 0f 29 bc 24 70 01 00 00 0f 29 b4 24 60 01 00 00 80 b9 58 30 00 00 00 0f 85 ?? ?? ?? ?? 48 89 ce 48 8d 54 24 38 e8 ?? ?? ?? ?? 66 83 7c 24 38 ff" +#define LMP_SIG_MPLAYER_ADD_SCORE "41 57 41 56 56 57 55 53 48 81 ec 88 00 00 00 0f 29 7c 24 70 0f 29 74 24 60 48 89 ce 44 89 c0 f3 0f 2a 84 81 fc 08 00 00 0f 28 f9 f3 0f 58 c1 f3 0f 2c c8 89 8c 86 fc 08 00 00" +#define LMP_SIG_NET_MARK_DIRTY "56 57 53 48 83 ec 40 81 7a 20 44 4e 45 54 0f 85 ?? ?? ?? ?? 48 89 ce 0f b7 41 02 a8 02 75 ?? f6 42 48 02 75 ?? a8 01 75 ?? 4c 89 c7 83 c8 01 66 89 46 02" +#define LMP_SIG_HUD_ADD_SCORE_MSG "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 38 01 00 00 45 89 c5 41 8d 45 fd" +#define LMP_SIG_SESSION_STATS_RESET "41 56 56 57 53 48 83 ec 48 0f 29 74 24 30 48 89 ce 48 8d 05 ?? ?? ?? ?? 48 89 44 24 28" +#define LMP_SIG_SESSION_STATS_GET_UNIT "56 57 53 48 83 ec 40 48 89 d6 48 89 cf 48 89 54 24 30" +#define LMP_SIG_START_ACTUALIZE_CLIENT "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 38 01 00 00 0f 29 b4 24 20 01 00 00 83 b9 80 02 01 00 ff" +#define LMP_SIG_DISPATCH_ASSIST "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 78 0f 29 7c 24 60 0f 29 74 24 50 0f 28 f3 4c 89 c6 48 89 d7 48 89 cb 48 8b 05 ?? ?? ?? ?? 48 85 c9 7e ?? 48 85 c0" +#define LMP_SIG_CALLER_CAPTURE_ZONE "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 38 44 0f b7 72 02 44 8b 7a 04 4c 8b 62 08 4c 8b 6a 18 49 8d 85 88 06 00 00 48 89 44 24 30 49 8d 85 50 06 00 00 48 89 44 24 28 eb ?? 48 8b 90 08 0e 00 00 89 d1 83 e1 01 0b 0d ?? ?? ?? ?? 3b 88 14 0e 00 00 0f 85 ?? ?? ?? ?? 48 83 e2 fe 48 8b 82 98 0f 00 00 48 8b 88 b8 00 00 00 e8 ?? ?? ?? ??" +#define LMP_SIG_CALLER_HIT_CRIT "8b 0d ?? ?? ?? ?? f7 c1 00 00 08 00 75 ?? f7 c1 00 00 00 01 75 ?? 0f b6 8f 10 10 00 00 39 4e 1c 74 ?? 41 20 c0 0f b6 86 49 01 00 00 0f 57 db f3 0f 5f 9e 30 01 00 00 48 8b 4e 58 85 ed f3 0f 5d 1d ?? ?? ?? ?? 88 44 24 30 0f 9f 44 24 28 44 88 44 24 20 48 89 fa 49 89 f0 e8 ?? ?? ?? ??" +#define LMP_SIG_CALLER_SEVERE_DMG "66 83 be b0 06 00 00 ff 0f 85 ?? ?? ?? ?? 48 89 f1 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 8d 9e b0 06 00 00 48 8b 4f 58 48 89 f2 49 89 f8 e8 ?? ?? ?? ?? 48 89 f1 48 89 fa e8 ?? ?? ?? ?? 0f b6 ae d4 06 00 00" +#define LMP_SIG_CALLER_NAVAL_DMG "66 83 b9 90 0f 00 00 01 77 ?? 66 83 ff ff 74 ?? 0f b7 c7 0f 57 d2 f3 0f 2a d0 f3 0f 59 15 ?? ?? ?? ?? eb ?? f3 0f 10 15 ?? ?? ?? ?? 48 8b 94 24 c0 03 00 00 0f b6 7c 24 5b 41 89 f9 e8 ?? ?? ?? ?? 0f 57 c0 0f 2e f0 0f 96 c0 40 08 f8 a8 01 75 ?? 48 8b 96 e8 0a 00 00 4c 8b 84 24 c0 03 00 00 49 8b 48 58 0f 28 de e8 ?? ?? ?? ??" +#define LMP_SIG_COUNT_ACTIVE_PLAYERS "41 57 41 56 41 54 56 57 53 48 83 ec 38 89 cf 80 f2 01 0f b6 c2 c1 e0 0a 83 c8 3a" +#define LMP_SIG_IS_SLOT_READY_AT_HOST "41 56 56 57 55 53 48 81 ec a0 00 00 00 0f 29 b4 24 90 00 00 00 44 89 c3 48 89 d6 48 83 3d" diff --git a/native/wto-net/src/local_mp_players.c b/native/wto-net/src/local_mp_players.c new file mode 100644 index 0000000..980703f --- /dev/null +++ b/native/wto-net/src/local_mp_players.c @@ -0,0 +1,232 @@ +/* + * LocalMP player team alignment, AI MPlayer <-> Unit ownership binding, + * asynchronous aircraftChangeResultFromHost handshake, and spawn-only ledger activation. + */ +#include "hooks.h" +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include "MinHook.h" + +#include + +typedef void (__fastcall *GuiStateUpdateFn)(uint8_t *gui_state_obj, float dt); +typedef void (__fastcall *MPlayerInitFromMatchingFn)(uint8_t *mplayer, uint8_t *info, uint64_t uid); +typedef int64_t (__fastcall *DoRespawnPlayerFn)(void *app); +typedef uint8_t (__fastcall *IsSlotReadyAtHostFn)(int32_t slot_id, const char *unit_name, uint8_t debug); + +static GuiStateUpdateFn orig_gui_state_update; +static MPlayerInitFromMatchingFn orig_mplayer_init_matching; +static DoRespawnPlayerFn orig_do_respawn; +static IsSlotReadyAtHostFn orig_is_slot_ready_at_host; + +static int g_accept_pending = 0; +static int g_respawn_dispatched = 0; +static int32_t g_pending_slot_id = -1; +static int32_t g_pending_spare_type = -1; + +void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int is_silent) +{ + if (!is_silent || g_pending_slot_id < 0) { + g_pending_slot_id = slot_id; + g_pending_spare_type = spare_type; + } + if (!is_silent) + g_respawn_dispatched = 0; + g_accept_pending = 1; +} + +static void bind_ai_mplayer_units(void) +{ + uint8_t **table = g_local_mp_player_table ? *g_local_mp_player_table : NULL; + uint32_t count = g_local_mp_player_count ? *g_local_mp_player_count : 0; + uint32_t i; + + if (table == NULL || count <= 1 || !g_lmp_get_unit_by_eid || !g_lmp_set_owning_mplayer) + return; + + for (i = 1; i < count; i++) { + uint8_t *mp = table[i]; + uint32_t eid; + uint8_t *unit; + + if (mp == NULL) + continue; + eid = *(uint32_t *)(mp + LMP_MP_OFF_UNIT_EID); + if (eid == 0) + continue; + unit = (uint8_t *)g_lmp_get_unit_by_eid(eid); + if (unit != NULL && *(uint8_t **)(unit + LMP_UNIT_OFF_MPLAYER) != mp) + g_lmp_set_owning_mplayer(unit, mp, 1, 1); + } +} + +static int32_t resolve_configured_player_team(void) +{ + const char *team_str; + char country_buf[64]; + uint8_t saved_arcade; + const char *short_country; + const char *axis_country; + const char *allies_country; + + if (g_lmp_datablock_get_str != NULL) { + team_str = g_lmp_datablock_get_str( + g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS, "wtoPlayerTeam", ""); + if (team_str != NULL && strcmp(team_str, "1") == 0) + return 1; + if (team_str != NULL && strcmp(team_str, "2") == 0) + return 2; + } + + memset(country_buf, 0, sizeof(country_buf)); + saved_arcade = g_local_mp_mission_settings[LMP_MIS_OFF_ARCADE_COUNTRY]; + g_local_mp_mission_settings[LMP_MIS_OFF_ARCADE_COUNTRY] = 1; + g_lmp_get_player_country(g_local_mp_mission_settings, 0, country_buf, (int32_t)sizeof(country_buf)); + g_local_mp_mission_settings[LMP_MIS_OFF_ARCADE_COUNTRY] = saved_arcade; + + short_country = strncmp(country_buf, "country_", 8) == 0 ? country_buf + 8 : country_buf; + axis_country = *(const char **)(g_local_mp_mission_settings + LMP_MIS_OFF_AXIS_COUNTRY); + allies_country = *(const char **)(g_local_mp_mission_settings + LMP_MIS_OFF_ALLIES_COUNTRY); + if (short_country[0] != '\0') { + if (axis_country != NULL && strcmp(short_country, axis_country) == 0) + return 2; + if (allies_country != NULL && strcmp(short_country, allies_country) == 0) + return 1; + } + return 0; +} + +static void __fastcall hook_mplayer_init_from_matching(uint8_t *mplayer, uint8_t *info, uint64_t uid) +{ + if (local_mp_is_host() && mplayer != NULL && info != NULL && + g_local_mp_mission_settings != NULL && g_lmp_get_player_country != NULL && + local_mp_is_local_mplayer(mplayer)) { + int32_t desired_team = resolve_configured_player_team(); + if (desired_team == 1 || desired_team == 2) + *(int32_t *)(info + LMP_MATCH_INFO_OFF_TEAM) = desired_team; + local_mp_ledger_reset(); + log_line("local_mp: initialized local player team=%d", + (int)(*(int32_t *)(info + LMP_MATCH_INFO_OFF_TEAM))); + } + orig_mplayer_init_matching(mplayer, info, uid); +} + +static void consume_pending_slot_if_spawned(uint8_t *mplayer) +{ + const char *hero_name; + + if (!g_respawn_dispatched || mplayer == NULL) + return; + if (mplayer[LMP_MP_OFF_GUI_STATE] == LMP_GUI_STATE_CA_SELECT) { + g_respawn_dispatched = 0; + return; + } + if (mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_PILOT_CONTROL) + return; + + g_respawn_dispatched = 0; + hero_name = g_local_mp_hero ? local_mp_unit_name(*g_local_mp_hero) : NULL; + if (hero_name != NULL) + local_mp_ledger_activate_unit(hero_name); + + if (g_pending_slot_id >= 0 && g_pending_slot_id < 32) { + uint32_t bit = 1u << (uint32_t)g_pending_slot_id; + if (g_pending_spare_type < 0) + *(uint32_t *)(mplayer + LMP_MP_OFF_BROKEN_SLOTS_MASK) |= bit; + else + *(uint32_t *)(mplayer + LMP_MP_OFF_USED_SPARES_MASK) |= bit; + log_line("local_mp: spawned unit='%s' slot=%d spare=%d brokenMask=0x%x spareMask=0x%x", + hero_name ? hero_name : "", (int)g_pending_slot_id, (int)g_pending_spare_type, + *(uint32_t *)(mplayer + LMP_MP_OFF_BROKEN_SLOTS_MASK), + *(uint32_t *)(mplayer + LMP_MP_OFF_USED_SPARES_MASK)); + g_pending_slot_id = -1; + } +} + +static void __fastcall hook_gui_state_update(uint8_t *gui_state_obj, float dt) +{ + uint8_t *mplayer; + + orig_gui_state_update(gui_state_obj, dt); + + if (!local_mp_is_host()) { + g_accept_pending = 0; + g_respawn_dispatched = 0; + g_pending_slot_id = -1; + return; + } + + bind_ai_mplayer_units(); + mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL; + consume_pending_slot_if_spawned(mplayer); + + if (g_accept_pending && gui_state_obj != NULL) { + uint8_t *econ_state = local_mp_econ_state(); + if (mplayer != NULL && econ_state != NULL && + mplayer[LMP_MP_OFF_GUI_STATE] == LMP_GUI_STATE_CA_READY && + *(int32_t *)gui_state_obj == LMP_GUI_STATE_CA_READY) { + g_accept_pending = 0; + *(float *)(gui_state_obj + 0x10) = 0.0f; + g_lmp_aircraft_change_result(econ_state, 0); + } + } +} + +static int64_t __fastcall hook_do_respawn_player(void *app) +{ + uint8_t *mplayer; + int64_t result; + + if (!local_mp_is_host()) + return orig_do_respawn(app); + + mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL; + if (mplayer != NULL && mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_PILOT_CONTROL) + g_respawn_dispatched = 1; + + result = orig_do_respawn(app); + consume_pending_slot_if_spawned(mplayer); + bind_ai_mplayer_units(); + return result; +} + +static uint8_t __fastcall hook_is_slot_ready_at_host(int32_t slot_id, const char *unit_name, uint8_t debug) +{ + uint8_t *mplayer; + + if (!local_mp_is_host()) + return orig_is_slot_ready_at_host(slot_id, unit_name, debug); + if (orig_is_slot_ready_at_host(slot_id, unit_name, debug)) + return 1; + if (slot_id < 0 || slot_id >= 32 || unit_name == NULL || unit_name[0] == '\0') + return 0; + mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL; + if (mplayer == NULL) + return 1; + return (*(uint32_t *)(mplayer + LMP_MP_OFF_BROKEN_SLOTS_MASK) & (1u << (uint32_t)slot_id)) == 0 ? 1 : 0; +} + +int install_local_mp_player_hooks(const uint8_t *text, size_t text_size, uint8_t *p_do_respawn) +{ + uint8_t *p_gui_update = local_mp_scan_unique(text, text_size, "GuiState::update", LMP_SIG_GUI_STATE_UPDATE); + uint8_t *p_mp_init = local_mp_scan_unique(text, text_size, "MPlayer::initFromMatching", LMP_SIG_MPLAYER_INIT_MATCHING); + uint8_t *p_slot_ready = local_mp_scan_unique(text, text_size, "is_crew_slot_was_ready_at_host", LMP_SIG_IS_SLOT_READY_AT_HOST); + + if (!p_gui_update || !p_mp_init || !p_do_respawn || !p_slot_ready) + return 0; + + if (MH_CreateHook(p_gui_update, (void *)&hook_gui_state_update, (void **)&orig_gui_state_update) != MH_OK || + MH_EnableHook(p_gui_update) != MH_OK || + MH_CreateHook(p_mp_init, (void *)&hook_mplayer_init_from_matching, (void **)&orig_mplayer_init_matching) != MH_OK || + MH_EnableHook(p_mp_init) != MH_OK || + MH_CreateHook(p_do_respawn, (void *)&hook_do_respawn_player, (void **)&orig_do_respawn) != MH_OK || + MH_EnableHook(p_do_respawn) != MH_OK || + MH_CreateHook(p_slot_ready, (void *)&hook_is_slot_ready_at_host, (void **)&orig_is_slot_ready_at_host) != MH_OK || + MH_EnableHook(p_slot_ready) != MH_OK) { + log_line("local_mp: failed to install player state hooks"); + return 0; + } + return 1; +} diff --git a/packages/local-service/src/battle/battle-coalitions.ts b/packages/local-service/src/battle/battle-coalitions.ts new file mode 100644 index 0000000..67821b6 --- /dev/null +++ b/packages/local-service/src/battle/battle-coalitions.ts @@ -0,0 +1,227 @@ +/** + * Authentic nation coalition pairing for Arcade, Realistic, and Simulator battles. + * + * Filters eligible countries by tech-tree vehicle availability in the match's BR window, + * assigns the player uniformly to Team 1 (`allies`) or Team 2 (`axis`), and builds + * per-team bare country lists (`"usa"`, `"germany"`, ...) with `playerCountry` at index 0 + * of the player's team array. + */ +import { randomInt } from 'node:crypto'; +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts'; +import { stripCountryPrefix, unitClassOfExpClass, vehicleMrank } from './battle-ranks.ts'; +import type { BattleTuning } from './battle-tuning.ts'; + +const SIM_WW2_ALLIES: readonly string[] = ['usa', 'ussr', 'britain', 'china', 'france', 'israel']; +const SIM_WW2_AXIS: readonly string[] = ['germany', 'japan', 'italy', 'sweden']; +const SIM_CW_WEST: readonly string[] = ['usa', 'germany', 'britain', 'japan', 'italy', 'france', 'sweden', 'israel']; +const SIM_CW_EAST: readonly string[] = ['ussr', 'china']; + +export interface CoalitionPairingInput { + readonly vehicles: readonly CatalogueVehicle[]; + readonly knownCountries: readonly string[]; + readonly playerCountry: string; + readonly difficulty: ModeDifficulty; + readonly requiredClass: UnitClass; + readonly playerMrank: number; + readonly minMrank: number; + readonly maxMrank: number; + readonly tuning: BattleTuning; +} + +export interface CoalitionPairing { + readonly playerTeam: 1 | 2; + readonly countryAllies: string; + readonly countryAxis: string; + readonly countriesAllies: readonly string[]; + readonly countriesAxis: readonly string[]; + readonly symmetricTeams: boolean; +} + +export function selectBattleCoalitions(input: CoalitionPairingInput): CoalitionPairing { + const playerCountry = stripCountryPrefix(input.playerCountry); + const eligible = eligibleCountriesForBracket(input, playerCountry); + const playerTeam: 1 | 2 = randomInt(2) === 0 ? 1 : 2; + const sides = input.difficulty === 'arcade' + ? buildArcadeSides(eligible, playerCountry) + : input.difficulty === 'simulator' + ? buildSimulatorSides(eligible, playerCountry, input.playerMrank, input.tuning.simColdWarMinMrank) + : buildRealisticSides(eligible, playerCountry, input.requiredClass, input.tuning); + + const countriesAllies = playerTeam === 1 ? sides.playerSide : sides.enemySide; + const countriesAxis = playerTeam === 2 ? sides.playerSide : sides.enemySide; + return { + playerTeam, + countryAllies: countriesAllies[0] ?? playerCountry, + countryAxis: countriesAxis[0] ?? playerCountry, + countriesAllies, + countriesAxis, + symmetricTeams: sides.symmetricTeams, + }; +} + +interface TeamSides { + readonly playerSide: readonly string[]; + readonly enemySide: readonly string[]; + readonly symmetricTeams: boolean; +} + +function eligibleCountriesForBracket(input: CoalitionPairingInput, playerCountry: string): string[] { + const knownBare = [...new Set(input.knownCountries.map(stripCountryPrefix).filter((c) => c.length > 0))]; + const knownSet = new Set(knownBare); + const inWindow = new Set(); + const inClass = new Set(); + + for (const vehicle of input.vehicles) { + if (!isStandardTreeVehicle(vehicle, input.requiredClass)) continue; + const bare = stripCountryPrefix(vehicle.country); + if (!knownSet.has(bare)) continue; + inClass.add(bare); + const mrank = vehicleMrank(vehicle, input.difficulty, input.requiredClass); + if (mrank >= input.minMrank && mrank <= input.maxMrank) inWindow.add(bare); + } + + inWindow.add(playerCountry); + if (inWindow.size >= 2) return knownBare.filter((c) => inWindow.has(c)); + inClass.add(playerCountry); + if (inClass.size >= 2) return knownBare.filter((c) => inClass.has(c)); + return knownBare.includes(playerCountry) ? knownBare : [playerCountry, ...knownBare]; +} + +function isStandardTreeVehicle(vehicle: CatalogueVehicle, requiredClass: UnitClass): boolean { + return vehicle.inTechTree + && !vehicle.onlyShownWhenOwned + && !vehicle.premiumPack + && !vehicle.gift + && !vehicle.event + && vehicle.researchType === undefined + && unitClassOfExpClass(vehicle.unitClass) === requiredClass; +} + +function buildArcadeSides(eligible: readonly string[], playerCountry: string): TeamSides { + const playerSide = placeFirst(shuffle(eligible), playerCountry); + const enemySide = shuffle(eligible); + return { playerSide, enemySide, symmetricTeams: true }; +} + +function buildSimulatorSides( + eligible: readonly string[], + playerCountry: string, + playerMrank: number, + coldWarMinMrank: number, +): TeamSides { + const eligibleSet = new Set(eligible); + const blocA = (playerMrank < coldWarMinMrank ? SIM_WW2_ALLIES : SIM_CW_WEST).filter((c) => eligibleSet.has(c)); + const blocB = (playerMrank < coldWarMinMrank ? SIM_WW2_AXIS : SIM_CW_EAST).filter((c) => eligibleSet.has(c)); + + const playerInB = blocB.includes(playerCountry); + const rawPlayerBloc = playerInB ? [...blocB] : [...blocA]; + const rawEnemyBloc = playerInB ? [...blocA] : [...blocB]; + if (!rawPlayerBloc.includes(playerCountry)) rawPlayerBloc.unshift(playerCountry); + + const playerOthers = shuffle(rawPlayerBloc.filter((c) => c !== playerCountry)); + let enemySide = shuffle(rawEnemyBloc.filter((c) => c !== playerCountry)); + if (enemySide.length === 0 && playerOthers.length > 0) { + enemySide = [playerOthers.pop()!]; + } + if (enemySide.length === 0) { + const fallback = eligible.find((c) => c !== playerCountry) ?? playerCountry; + enemySide = [fallback]; + } + return { + playerSide: [playerCountry, ...playerOthers], + enemySide, + symmetricTeams: false, + }; +} + +function buildRealisticSides( + eligible: readonly string[], + playerCountry: string, + requiredClass: UnitClass, + tuning: BattleTuning, +): TeamSides { + const mixedChance = requiredClass === 'tank' + ? tuning.rbGroundMixedChance + : requiredClass === 'ship' + ? tuning.rbNavalMixedChance + : tuning.rbAirMixedChance; + const roll = randomInt(1_000_000) / 1_000_000; + if (roll >= mixedChance && eligible.length >= 2) { + return buildDisjointRealisticSides(eligible, playerCountry, tuning); + } + return buildMixedRealisticSides(eligible, playerCountry, tuning); +} + +function buildDisjointRealisticSides( + eligible: readonly string[], + playerCountry: string, + tuning: BattleTuning, +): TeamSides { + const others = shuffle(eligible.filter((c) => c !== playerCountry)); + const total = eligible.length; + const minC = tuning.rbCoalitionMinCountries; + const maxC = tuning.rbCoalitionMaxCountries; + const playerMax = total >= minC * 2 ? Math.min(maxC, total - minC) : Math.min(maxC, total - 1); + const playerMin = total >= minC * 2 ? Math.min(minC, playerMax) : 1; + const playerCount = randomRangeInclusive(playerMin, playerMax); + const remaining = total - playerCount; + const enemyMax = Math.min(maxC, remaining); + const enemyMin = Math.min(minC, enemyMax); + const enemyCount = randomRangeInclusive(enemyMin, enemyMax); + return { + playerSide: [playerCountry, ...others.slice(0, playerCount - 1)], + enemySide: others.slice(playerCount - 1, playerCount - 1 + enemyCount), + symmetricTeams: false, + }; +} + +function buildMixedRealisticSides( + eligible: readonly string[], + playerCountry: string, + tuning: BattleTuning, +): TeamSides { + if (eligible.length < 2 || randomInt(2) === 0) { + return buildArcadeSides(eligible, playerCountry); + } + const total = eligible.length; + const minCount = Math.min(tuning.rbCoalitionMinCountries, total); + const maxCount = Math.min(tuning.rbCoalitionMaxCountries, total); + const playerCount = randomRangeInclusive(minCount, maxCount); + const enemyCount = randomRangeInclusive(minCount, maxCount); + const others = shuffle(eligible.filter((c) => c !== playerCountry)); + const playerSide = [playerCountry, ...others.slice(0, playerCount - 1)]; + const shared = playerSide[randomInt(playerSide.length)]!; + const enemyPool = shuffle(eligible.filter((c) => c !== shared)); + const enemySide = shuffle([shared, ...enemyPool.slice(0, enemyCount - 1)]); + return { + playerSide, + enemySide, + symmetricTeams: sameCountrySet(playerSide, enemySide), + }; +} + +function placeFirst(countries: readonly string[], first: string): string[] { + return [first, ...countries.filter((c) => c !== first)]; +} + +function sameCountrySet(a: readonly string[], b: readonly string[]): boolean { + if (a.length !== b.length) return false; + const setB = new Set(b); + return a.every((item) => setB.has(item)); +} + +function randomRangeInclusive(min: number, max: number): number { + return max <= min ? min : min + randomInt(max - min + 1); +} + +function shuffle(items: readonly T[]): T[] { + const copy = [...items]; + for (let i = copy.length - 1; i > 0; i--) { + const j = randomInt(i + 1); + const tmp = copy[i]!; + copy[i] = copy[j]!; + copy[j] = tmp; + } + return copy; +} diff --git a/packages/local-service/src/battle/battle-extra-slots.ts b/packages/local-service/src/battle/battle-extra-slots.ts new file mode 100644 index 0000000..7502eb2 --- /dev/null +++ b/packages/local-service/src/battle/battle-extra-slots.ts @@ -0,0 +1,257 @@ +/** + * Session-level extra crew slot selection for Ground RB killstreak aircraft + * (nuclear bombers from `gameplay.blk/missionSupportPlane`, strike UCAVs from `wpcost.blk`) + * and `gameplay.blk/RandomSpawnUnits` auto-supplemented lineup slots. + */ +import { randomInt } from 'node:crypto'; +import type { + BattleSpawnRulesData, + NuclearAircraftEntry, + NuclearPresetBracket, + RandomSpawnCandidate, + RandomSpawnGroupRule, +} from '../game-data/datasets/battle-spawn-rules.ts'; +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import type { GameModeDeclaration } from '../game-modes/catalogue/game-mode-declaration.ts'; +import { unitClassOfExpClass, vehicleMrank } from './battle-ranks.ts'; + +/** Ground RB persistent spawn-point cost for strike UCAVs (`ucav_*_killstreak`). */ +const STRIKE_UCAV_SPAWN_SCORE = 750; +/** Standard maximum rank spread below `economicRankHistorical` where strike UCAVs appear. */ +const STRIKE_UCAV_MAX_RANK_DIFF = 2; +/** Engine bitmask limit on crew slots (`LMP_MP_OFF_BROKEN_SLOTS_MASK` is `uint32_t`). */ +const MAX_BATTLE_CREW_SLOTS = 32; + +export interface ExtraBattleSlot { + readonly unitName: string; + readonly persistentCost: number; + readonly spaded: boolean; + readonly forceWeapon?: string; + readonly groupName?: string; +} + +export interface ExtraBattleSlotsInput { + readonly country: string; + readonly slotVehicles: readonly string[]; + readonly declaration: GameModeDeclaration; + readonly sessionMaxMrank: number; + readonly vehiclesByName: ReadonlyMap; + readonly rules?: BattleSpawnRulesData; +} + +export interface ExtraBattleSlotsPlan { + readonly extraBattleSlots: readonly ExtraBattleSlot[]; + readonly randomUnits: Readonly>; + readonly randomUnitsEventName?: string; +} + +export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): ExtraBattleSlotsPlan { + const { rules, declaration, slotVehicles } = input; + const maxExtra = Math.max(0, MAX_BATTLE_CREW_SLOTS - slotVehicles.length); + if (!rules || declaration.multiSlot === false || maxExtra === 0) { + return { extraBattleSlots: [], randomUnits: {} }; + } + + const slots: ExtraBattleSlot[] = []; + if (declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic') { + const nuclear = pickNuclearSlot(input.country, input.sessionMaxMrank, rules.nuclearBrackets); + if (nuclear) slots.push(nuclear); + const ucav = pickStrikeUcavSlot(input.country, input.sessionMaxMrank, rules); + if (ucav) slots.push(ucav); + } + + const randomPlan = pickRandomSpawnSlots(input, rules); + slots.push(...randomPlan.slots); + + return { + extraBattleSlots: slots.slice(0, maxExtra), + randomUnits: randomPlan.randomUnits, + ...(randomPlan.eventName ? { randomUnitsEventName: randomPlan.eventName } : {}), + }; +} + +function pickNuclearSlot( + country: string, + sessionMaxMrank: number, + brackets: readonly NuclearPresetBracket[], +): ExtraBattleSlot | undefined { + if (brackets.length === 0) return undefined; + const minNuclearRank = brackets[0]!.minMrank; + if (sessionMaxMrank < minNuclearRank) return undefined; + + const matchingBracket = brackets.find((b) => sessionMaxMrank >= b.minMrank && sessionMaxMrank <= b.maxMrank) + ?? (sessionMaxMrank > brackets[brackets.length - 1]!.maxMrank ? brackets[brackets.length - 1] : undefined); + if (!matchingBracket) return undefined; + + const countryEntries = matchingBracket.entries.filter((entry) => entry.country === country); + if (countryEntries.length === 0) return undefined; + + const chosen = chooseBestNuclearEntry(countryEntries, sessionMaxMrank); + return { + unitName: chosen.unitName, + persistentCost: matchingBracket.spawnScore, + spaded: true, + forceWeapon: chosen.weapon, + }; +} + +function chooseBestNuclearEntry( + entries: readonly NuclearAircraftEntry[], + sessionMaxMrank: number, +): NuclearAircraftEntry { + const withinRank = entries.filter((entry) => entry.tankRealisticMrank <= sessionMaxMrank); + if (withinRank.length > 0) { + const highestRank = withinRank.reduce((max, entry) => Math.max(max, entry.tankRealisticMrank), 0); + const tied = withinRank.filter((entry) => entry.tankRealisticMrank === highestRank); + return tied[randomInt(tied.length)]!; + } + const lowestRank = entries.reduce((min, entry) => Math.min(min, entry.tankRealisticMrank), Infinity); + const fallback = entries.filter((entry) => entry.tankRealisticMrank === lowestRank); + return fallback[randomInt(fallback.length)]!; +} + +function pickStrikeUcavSlot( + country: string, + sessionMaxMrank: number, + rules: BattleSpawnRulesData, +): ExtraBattleSlot | undefined { + const ucav = rules.strikeUcavs.find((entry) => entry.country === country); + if (!ucav) return undefined; + const minSessionRank = Math.max(0, ucav.historicalMrank - STRIKE_UCAV_MAX_RANK_DIFF); + if (sessionMaxMrank < minSessionRank) return undefined; + return { + unitName: ucav.unitName, + persistentCost: STRIKE_UCAV_SPAWN_SCORE, + spaded: true, + ...(ucav.weapon ? { forceWeapon: ucav.weapon } : {}), + }; +} + +function pickRandomSpawnSlots( + input: ExtraBattleSlotsInput, + rules: BattleSpawnRulesData, +): { + readonly eventName?: string; + readonly slots: readonly ExtraBattleSlot[]; + readonly randomUnits: Readonly>; +} { + const eventName = resolveRandomSpawnEventName(input.declaration); + if (!eventName) return { slots: [], randomUnits: {} }; + const eventRule = rules.randomSpawnEvents.find((entry) => entry.eventName === eventName); + const groups = eventRule?.countries[input.country]; + if (!groups || groups.length === 0) return { slots: [], randomUnits: {} }; + + const playerTopMrank = topAllowedLineupMrank(input.slotVehicles, input.declaration, input.vehiclesByName); + const equipped = new Set(input.slotVehicles); + const slots: ExtraBattleSlot[] = []; + const randomUnits: Record = {}; + + for (const group of groups) { + if (playerTopMrank < group.minPlayerMRank) continue; + if (input.sessionMaxMrank - playerTopMrank > group.maxDiffBetweenTopUnitAndSessionRank) continue; + const minWindowRank = Math.max(0, playerTopMrank - group.mRanksCount); + if (!lineupNeedsRandomGroup(group.groupName, input.slotVehicles, minWindowRank, input.declaration, input.vehiclesByName)) { + continue; + } + const candidates = filterGroupCandidates(group, minWindowRank, playerTopMrank, equipped, input.declaration, input.vehiclesByName); + if (candidates.length === 0) continue; + + const chosen = candidates[randomInt(candidates.length)]!; + randomUnits[group.groupName] = candidates.map((candidate) => candidate.unitName); + slots.push({ + unitName: chosen.unitName, + persistentCost: 0, + spaded: true, + groupName: group.groupName, + ...(chosen.forceWeapon ? { forceWeapon: chosen.forceWeapon } : {}), + }); + } + + if (slots.length === 0) return { slots: [], randomUnits: {} }; + return { eventName, slots, randomUnits }; +} + +function resolveRandomSpawnEventName(declaration: GameModeDeclaration): string | undefined { + if (declaration.requiredClass === 'tank') { + if (declaration.difficulty === 'realistic') return 'tank_random_battles_historical_base'; + if (declaration.difficulty === 'arcade') return 'tank_event_in_random_battles_arcade'; + } + if (declaration.requiredClass === 'ship') { + if (declaration.difficulty === 'realistic') return 'ship_event_in_random_battles_realistic'; + if (declaration.difficulty === 'arcade') return 'ship_event_in_random_battles_arcade'; + } + return undefined; +} + +function topAllowedLineupMrank( + slotVehicles: readonly string[], + declaration: GameModeDeclaration, + byName: ReadonlyMap, +): number { + const allowed = new Set(declaration.allowedClasses); + let top = 0; + for (const name of slotVehicles) { + const vehicle = byName.get(name); + const cls = vehicle && unitClassOfExpClass(vehicle.unitClass); + if (!vehicle || !cls || !allowed.has(cls)) continue; + top = Math.max(top, vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass)); + } + return top; +} + +function lineupNeedsRandomGroup( + groupName: string, + slotVehicles: readonly string[], + minWindowRank: number, + declaration: GameModeDeclaration, + byName: ReadonlyMap, +): boolean { + let matching = 0; + for (const name of slotVehicles) { + const vehicle = byName.get(name); + if (!vehicle) continue; + const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass); + if (groupName === 'spaa') { + if (vehicle.unitClass === 'exp_SPAA' && rank >= minWindowRank) matching++; + } else if (groupName === 'tank') { + if (unitClassOfExpClass(vehicle.unitClass) === 'tank' && vehicle.unitClass !== 'exp_SPAA' && rank >= minWindowRank) { + matching++; + } + } else if (groupName === 'bomber') { + if (vehicle.unitClass === 'exp_bomber' || vehicle.unitClass === 'exp_assault') matching++; + } else if (groupName === 'fighter') { + if (vehicle.unitClass === 'exp_fighter') matching++; + } + } + return groupName === 'tank' ? matching < 2 : matching < 1; +} + +function filterGroupCandidates( + group: RandomSpawnGroupRule, + minWindowRank: number, + maxWindowRank: number, + equipped: ReadonlySet, + declaration: GameModeDeclaration, + byName: ReadonlyMap, +): RandomSpawnCandidate[] { + const inWindow = group.units.filter((candidate) => { + if (equipped.has(candidate.unitName)) return false; + const vehicle = byName.get(candidate.unitName); + if (!vehicle) return false; + const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass); + return rank >= minWindowRank && rank <= maxWindowRank; + }); + if (inWindow.length > 0) return inWindow; + + const lowerCandidates = group.units + .flatMap((candidate) => { + if (equipped.has(candidate.unitName)) return []; + const vehicle = byName.get(candidate.unitName); + if (!vehicle) return []; + const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass); + return rank <= maxWindowRank ? [{ candidate, rank }] : []; + }); + if (lowerCandidates.length === 0) return []; + const bestRank = lowerCandidates.reduce((max, item) => Math.max(max, item.rank), 0); + return lowerCandidates.filter((item) => item.rank === bestRank).map((item) => item.candidate); +} diff --git a/packages/local-service/src/battle/battle-matchmaker.ts b/packages/local-service/src/battle/battle-matchmaker.ts new file mode 100644 index 0000000..445fbdf --- /dev/null +++ b/packages/local-service/src/battle/battle-matchmaker.ts @@ -0,0 +1,293 @@ +/** + * Pure local-battle matchmaking rules (`match.enqueue`): + * validates the chosen PvP mode and country, computes the player's lineup BR, selects a + * two-sided multiplayer mission honoring banned/disliked map preferences, pairs AB/RB/SB + * nation coalitions, builds the `customBots` pool and extra battle slots, and records a + * `BattleSession`. + */ +import { randomInt } from 'node:crypto'; +import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts'; +import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts'; +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts'; +import { MISSION_DIFFICULTY } from '../game-modes/mode-definition.ts'; +import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts'; +import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts'; +import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts'; +import { + lineupMrank, + selectCustomBots, + unitClassOfExpClass, + vehicleMrank, + type CustomBotsPool, +} from './battle-ranks.ts'; +import type { BattleSessionStore } from './battle-session-store.ts'; +import type { BattleTuning } from './battle-tuning.ts'; + +export interface EnqueueBattleInput { + readonly userId: string; + readonly mode: OfferedGameMode; + readonly modes?: readonly OfferedGameMode[]; + readonly country: string; + readonly slotVehicles: readonly string[]; + readonly selectedSlotVehicle?: string; + readonly bannedMissions: ReadonlySet; + readonly dislikedMissions: ReadonlySet; +} + +export interface BattleLaunchPlan { + readonly sessionId: string; + readonly modeId: number; + readonly modeName: string; + readonly economicName: string; + readonly missionName: string; + readonly missionFile: string; + readonly missionType: string; + readonly level?: string; + readonly environment?: string; + readonly weather?: string; + readonly difficulty: string; + readonly country: string; + readonly playerTeam: 1 | 2; + readonly countryAllies: string; + readonly countryAxis: string; + readonly countriesAllies: readonly string[]; + readonly countriesAxis: readonly string[]; + readonly symmetricTeams: boolean; + readonly minMrank: number; + readonly maxMrank: number; + readonly maxPlayers: number; + readonly maxBots: number; + readonly tankBotRespawns: number; + readonly airBotRespawns: number; + readonly useTankBots: boolean; + readonly useShipBots: boolean; + readonly useSpawnScore: boolean; + readonly customBots: CustomBotsPool; + readonly extraBattleSlots: readonly ExtraBattleSlot[]; + readonly randomUnits: Readonly>; + readonly randomUnitsEventName?: string; +} + +export type MatchmakeOutcome = + | { readonly ok: true; readonly launch: BattleLaunchPlan } + | { readonly ok: false; readonly error: string }; + +export class BattleMatchmaker { + readonly #gameModes: GameModes; + readonly #vehicles: readonly CatalogueVehicle[]; + readonly #vehiclesByName: ReadonlyMap; + readonly #sessions: BattleSessionStore; + readonly #tuning: BattleTuning; + readonly #spawnRules: BattleSpawnRulesData | undefined; + + constructor( + gameModes: GameModes, + vehicles: readonly CatalogueVehicle[], + sessions: BattleSessionStore, + tuning: BattleTuning, + spawnRules?: BattleSpawnRulesData, + ) { + this.#gameModes = gameModes; + this.#vehicles = vehicles; + this.#vehiclesByName = new Map(vehicles.map((vehicle) => [vehicle.name, vehicle])); + this.#sessions = sessions; + this.#tuning = tuning; + this.#spawnRules = spawnRules; + } + + enqueue(input: EnqueueBattleInput): MatchmakeOutcome { + const knownCountries = this.#gameModes.countries(); + if (!knownCountries.includes(input.country)) return { ok: false, error: 'BAD_PARAMS' }; + + const candidates = input.modes && input.modes.length > 0 ? input.modes : [input.mode]; + const chosenMode = this.#pickQueuedMode(candidates, input.slotVehicles, input.selectedSlotVehicle); + if (!chosenMode) return { ok: false, error: 'PVE_NOT_SUPPORTED' }; + + const { declaration } = chosenMode; + const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlotVehicle, this.#vehiclesByName); + const playerMrank = lineupMrank( + activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses, + ); + const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank); + const maxMrank = Math.max(minMrank, playerMrank + this.#tuning.brSpreadMrank); + const mission = pickMission(twoSidedMissionsOf(chosenMode), input.bannedMissions, input.dislikedMissions); + const coalitions = selectBattleCoalitions({ + vehicles: this.#vehicles, + knownCountries, + playerCountry: input.country, + difficulty: declaration.difficulty, + requiredClass: declaration.requiredClass, + playerMrank, + minMrank, + maxMrank, + tuning: this.#tuning, + }); + const customBots = selectCustomBots(this.#vehicles, { + difficulty: declaration.difficulty, + requiredClass: declaration.requiredClass, + allowedClasses: declaration.allowedClasses, + countries: [...coalitions.countriesAllies, ...coalitions.countriesAxis], + centerMrank: playerMrank, + minMrank, + maxMrank, + limitPerType: this.#tuning.botPoolLimitPerType, + }); + return { + ok: true, + launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, minMrank, maxMrank, customBots), + }; + } + + #pickQueuedMode( + candidates: readonly OfferedGameMode[], + slotVehicles: readonly string[], + selectedSlotVehicle: string | undefined, + ): OfferedGameMode | undefined { + const pvpModes = candidates.filter( + (mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0, + ); + if (pvpModes.length === 0) return undefined; + const eligible = pvpModes.filter((mode) => + isModeEligibleForLineup(mode.declaration, slotVehicles, selectedSlotVehicle, this.#vehiclesByName)); + const pool = eligible.length > 0 ? eligible : pvpModes.filter((mode) => !mode.declaration.tag); + if (pool.length === 0) return pvpModes[0]; + const classics = pool.filter((mode) => !mode.declaration.tag); + const subModes = pool.filter((mode) => Boolean(mode.declaration.tag)); + if (subModes.length > 0 && classics.length > 0) { + const useSubMode = randomInt(1_000_000) < Math.round(this.#tuning.subModeChance * 1_000_000); + const bucket = useSubMode ? subModes : classics; + return bucket[randomInt(bucket.length)]; + } + return pool[randomInt(pool.length)]; + } + + #buildLaunchPlan( + input: EnqueueBattleInput, + chosenMode: OfferedGameMode, + mission: MissionHeader, + coalitions: CoalitionPairing, + minMrank: number, + maxMrank: number, + customBots: CustomBotsPool, + ): BattleLaunchPlan { + const { declaration } = chosenMode; + const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers; + const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers)); + const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1)); + const missionLocName = resolveMissionLocName(mission); + const environment = declaration.environmentOverride ?? mission.environment; + const session = this.#sessions.create({ + userId: input.userId, + modeId: declaration.gameModeId, + modeName: declaration.name, + economicName: declaration.economicName, + difficulty: declaration.difficulty, + requiredClass: declaration.requiredClass, + missionName: mission.name, + missionPath: mission.path, + ...(missionLocName !== undefined ? { missionLocName } : {}), + country: input.country, + startedAtSec: serverTimeToUnixSeconds(serverTimeNow()), + }); + const allowedSet = new Set(declaration.allowedClasses); + const extraPlan = selectExtraBattleSlots({ + country: input.country, + slotVehicles: input.slotVehicles, + declaration, + sessionMaxMrank: maxMrank, + vehiclesByName: this.#vehiclesByName, + ...(this.#spawnRules ? { rules: this.#spawnRules } : {}), + }); + return { + sessionId: session.sessionId, + modeId: declaration.gameModeId, + modeName: declaration.name, + economicName: declaration.economicName, + missionName: mission.name, + missionFile: mission.path, + missionType: mission.type ?? 'domination', + ...(mission.level !== undefined ? { level: mission.level } : {}), + ...(environment !== undefined ? { environment } : {}), + ...(mission.weather !== undefined ? { weather: mission.weather } : {}), + difficulty: MISSION_DIFFICULTY[declaration.difficulty], + country: input.country, + playerTeam: coalitions.playerTeam, + countryAllies: coalitions.countryAllies, + countryAxis: coalitions.countryAxis, + countriesAllies: coalitions.countriesAllies, + countriesAxis: coalitions.countriesAxis, + symmetricTeams: coalitions.symmetricTeams, + minMrank, + maxMrank, + maxPlayers, + maxBots, + tankBotRespawns: this.#tuning.tankBotRespawns, + airBotRespawns: this.#tuning.airBotRespawns, + useTankBots: allowedSet.has('tank'), + useShipBots: allowedSet.has('ship'), + useSpawnScore: declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic', + customBots, + extraBattleSlots: extraPlan.extraBattleSlots, + randomUnits: extraPlan.randomUnits, + ...(extraPlan.randomUnitsEventName ? { randomUnitsEventName: extraPlan.randomUnitsEventName } : {}), + }; + } +} + +function twoSidedMissionsOf(mode: OfferedGameMode): MissionHeader[] { + return mode.missions.filter((m) => m.playerSlots.teamA > 0 && m.playerSlots.teamB > 0); +} + +function activeVehiclesForMode( + declaration: OfferedGameMode['declaration'], + slotVehicles: readonly string[], + selectedSlotVehicle: string | undefined, + byName: ReadonlyMap, +): readonly string[] { + if (declaration.multiSlot !== false || !selectedSlotVehicle) return slotVehicles; + const selected = byName.get(selectedSlotVehicle); + return selected && unitClassOfExpClass(selected.unitClass) === declaration.requiredClass + ? [selectedSlotVehicle] + : slotVehicles; +} + +function isModeEligibleForLineup( + declaration: OfferedGameMode['declaration'], + slotVehicles: readonly string[], + selectedSlotVehicle: string | undefined, + byName: ReadonlyMap, +): boolean { + if (!declaration.tag) return true; + const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName); + const minMrank = declaration.minQueueMrank ?? 0; + const minCrafts = declaration.minCraftsToPlay ?? 1; + const matchingCount = active.filter((name) => { + const vehicle = byName.get(name); + if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false; + return vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass) >= minMrank; + }).length; + return matchingCount >= minCrafts; +} + +function pickMission(missions: readonly MissionHeader[], banned: ReadonlySet, disliked: ReadonlySet): MissionHeader { + const unbanned = missions.filter((mission) => !banned.has(mission.name)); + const poolAfterBan = unbanned.length > 0 ? unbanned : missions; + const preferred = poolAfterBan.filter((mission) => !disliked.has(mission.name)); + const pool = preferred.length > 0 ? preferred : poolAfterBan; + return pool[randomInt(pool.length)]!; +} + +function maxSlotsForMission(mission: MissionHeader, desiredMaxPlayers: number): number { + const { teamA, teamB } = mission.playerSlots; + return Math.max(2, Math.min(desiredMaxPlayers, Math.min(teamA, teamB) * 2)); +} + +function resolveMissionLocName(mission: MissionHeader): string | undefined { + if (mission.locName && mission.locName.length > 0) return mission.locName; + if (mission.postfix && mission.postfix.length > 0 && mission.name.endsWith(mission.postfix)) { + const baseName = mission.name.slice(0, -mission.postfix.length); + if (baseName.length > 0) return `missions/${mission.postfix};missions/${baseName}`; + } + return undefined; +} diff --git a/packages/local-service/src/battle/battle-ranks.ts b/packages/local-service/src/battle/battle-ranks.ts new file mode 100644 index 0000000..1b9c11a --- /dev/null +++ b/packages/local-service/src/battle/battle-ranks.ts @@ -0,0 +1,177 @@ +/** + * Pure matchmaking rank (`mrank`) calculation and deterministic BR-matched `customBots` + * vehicle-pool selection (`scripts/slotbar/slotbarpresets/calcranks.nut`). + * + * `BotSystem` (`aces.exe` `0x11af3f0`) reads `MissionSettings.customBots` using bare country + * names (`"usa"`, `"germany"`, ...) and three sub-blocks: `allowedTanks` (`tank`), + * `allowedAircrafts` (`aircraft`), and `allowedShips` (`ship`). + */ +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts'; +import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts'; + +const COUNTRY_PREFIX = 'country_'; + +export interface CraftRankEntry { + readonly unitClass: UnitClass | undefined; + readonly mrank: number; +} + +export interface BotPoolEntry { + readonly name: string; + readonly country: string; + readonly weight: number; +} + +export interface CustomBotsPool { + readonly tanks: readonly BotPoolEntry[]; + readonly aircrafts: readonly BotPoolEntry[]; + readonly ships: readonly BotPoolEntry[]; +} + +export interface BotPoolQuery { + readonly difficulty: ModeDifficulty; + readonly requiredClass: UnitClass; + readonly allowedClasses: readonly UnitClass[]; + readonly countries: readonly string[]; + readonly centerMrank: number; + readonly minMrank: number; + readonly maxMrank: number; + readonly limitPerType: number; +} + +export function stripCountryPrefix(country: string): string { + return country.startsWith(COUNTRY_PREFIX) ? country.slice(COUNTRY_PREFIX.length) : country; +} + +export function unitClassOfExpClass(expClass: string): UnitClass | undefined { + return unitClassOfVehicleType(vehicleTypeOfClass(expClass)); +} + +export function unitClassOfTypeCode(unitTypeCode: number): UnitClass | undefined { + return unitClassOfVehicleType(vehicleTypeById(unitTypeCode)); +} + +export function vehicleMrank(vehicle: CatalogueVehicle, difficulty: ModeDifficulty, requiredClass: UnitClass): number { + if (difficulty === 'arcade') return vehicle.economicRankArcade; + if (difficulty === 'simulator') { + return requiredClass === 'tank' && vehicle.economicRankTankSimulation !== undefined + ? vehicle.economicRankTankSimulation + : vehicle.economicRankSimulation; + } + return requiredClass === 'tank' && vehicle.economicRankTankHistorical !== undefined + ? vehicle.economicRankTankHistorical + : vehicle.economicRankHistorical; +} + +/** + * Maximum `mrank` among crafts allowed in the mode (`calcranks.nut` `filterCrafts` + + * `specialShipsFilter`: in naval modes, aircraft above `maxShipMrank + 1` are ignored). + */ +export function maxModeMrank( + crafts: readonly CraftRankEntry[], + requiredClass: UnitClass, + allowedClasses: readonly UnitClass[], +): number { + const allowedSet = new Set(allowedClasses); + const matching = crafts.filter((craft) => craft.unitClass !== undefined && allowedSet.has(craft.unitClass)); + if (!matching.some((craft) => craft.unitClass === requiredClass)) return 0; + + let filtered = matching; + if (requiredClass === 'ship') { + const maxShip = matching + .filter((craft) => craft.unitClass === 'ship') + .reduce((max, craft) => Math.max(max, craft.mrank), 0); + filtered = matching.filter((craft) => craft.unitClass !== 'aircraft' || craft.mrank <= maxShip + 1); + } + return filtered.reduce((max, craft) => Math.max(max, Math.max(0, Math.trunc(craft.mrank))), 0); +} + +export function lineupMrank( + vehicleNames: readonly string[], + byName: ReadonlyMap, + difficulty: ModeDifficulty, + requiredClass: UnitClass, + allowedClasses: readonly UnitClass[], +): number { + const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => { + const vehicle = byName.get(name); + if (!vehicle) return []; + return [{ + unitClass: unitClassOfExpClass(vehicle.unitClass), + mrank: vehicleMrank(vehicle, difficulty, requiredClass), + }]; + }); + return maxModeMrank(crafts, requiredClass, allowedClasses); +} + +export function selectCustomBots(vehicles: readonly CatalogueVehicle[], query: BotPoolQuery): CustomBotsPool { + const allowed = new Set(query.allowedClasses); + const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))]; + return { + tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [], + aircrafts: allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [], + ships: allowed.has('ship') ? pickCategoryPool(vehicles, orderedCountries, 'ship', query) : [], + }; +} + +function pickCategoryPool( + vehicles: readonly CatalogueVehicle[], + orderedCountries: readonly string[], + category: 'tank' | 'aircraft' | 'ship', + query: BotPoolQuery, +): BotPoolEntry[] { + const countrySet = new Set(orderedCountries); + const eligible = vehicles.filter((vehicle) => + vehicle.inTechTree + && !vehicle.onlyShownWhenOwned + && !vehicle.premiumPack + && !vehicle.gift + && !vehicle.event + && vehicle.researchType === undefined + && countrySet.has(vehicle.country) + && unitClassOfExpClass(vehicle.unitClass) === category); + if (eligible.length === 0) return []; + + const sortedByCloseness = [...eligible].sort((a, b) => { + const distA = Math.abs(vehicleMrank(a, query.difficulty, query.requiredClass) - query.centerMrank); + const distB = Math.abs(vehicleMrank(b, query.difficulty, query.requiredClass) - query.centerMrank); + return distA !== distB ? distA - distB : a.name.localeCompare(b.name); + }); + const inWindow = sortedByCloseness.filter((vehicle) => { + const mrank = vehicleMrank(vehicle, query.difficulty, query.requiredClass); + return mrank >= query.minMrank && mrank <= query.maxMrank; + }); + const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType); + return roundRobinByCountry(source, orderedCountries, query.limitPerType); +} + +function roundRobinByCountry( + vehicles: readonly CatalogueVehicle[], + orderedCountries: readonly string[], + limit: number, +): BotPoolEntry[] { + const buckets = new Map(orderedCountries.map((country) => [country, []])); + for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle); + const out: BotPoolEntry[] = []; + for (let index = 0; out.length < limit; index++) { + let added = false; + for (const country of orderedCountries) { + const vehicle = buckets.get(country)?.[index]; + if (!vehicle) continue; + out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 }); + added = true; + if (out.length >= limit) break; + } + if (!added) break; + } + return out; +} + +function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined { + if (type === 'Tank') return 'tank'; + if (type === 'Aircraft') return 'aircraft'; + if (type === 'Helicopter') return 'helicopter'; + if (type === 'Ship' || type === 'Boat') return 'ship'; + return undefined; +} diff --git a/packages/local-service/src/battle/battle-report.ts b/packages/local-service/src/battle/battle-report.ts new file mode 100644 index 0000000..f2a0dac --- /dev/null +++ b/packages/local-service/src/battle/battle-report.ts @@ -0,0 +1,179 @@ +/** + * Battle debriefing report schema and DataBlock parser for `cln_wto_finish_battle`, + * including per-unit and top-level reward categories mapped to `EULT_SESSION_RESULT` + * `body/container` event blocks (`scripts/userlog/getuserlogbattlerewardstable.nut`). + */ +import { findBlock, type BlkBlock } from '@wto/blk'; + +export type BattleOutcomeKind = 'win' | 'lose' | 'running'; + +export interface RewardCategoryStat { + readonly count: number; + readonly wp: number; + readonly exp: number; +} + +export interface RewardCategorySpec { + readonly category: string; + readonly containerId: string; + readonly victimUnitFileName?: string; + readonly singleSummaryEvent?: boolean; +} + +export const REWARD_CATEGORY_SPECS: readonly RewardCategorySpec[] = [ + { category: 'AirKills', containerId: 'eventKill' }, + { category: 'GroundKills', containerId: 'eventKillGround' }, + { category: 'NavalKills', containerId: 'eventKillGround', victimUnitFileName: 'ships/' }, + { category: 'HumanKills', containerId: 'eventKillHuman' }, + { category: 'Assist', containerId: 'eventAssist' }, + { category: 'AirSevereDamage', containerId: 'eventSevereDamage' }, + { category: 'ShipSevereDamage', containerId: 'eventSevereDamage' }, + { category: 'Critical', containerId: 'eventCriticalHit' }, + { category: 'Hit', containerId: 'eventHit' }, + { category: 'Takeoffs', containerId: 'eventTakeoff' }, + { category: 'Landings', containerId: 'eventLanding' }, + { category: 'MissileEvade', containerId: 'eventMissileEvade' }, + { category: 'ShellInterception', containerId: 'eventShellInterception' }, + { category: 'Captures', containerId: 'eventCaptureZone' }, + { category: 'SectorCapture', containerId: 'eventSectorCapture' }, + { category: 'SuppliesDelivery', containerId: 'eventSuppliesDelivery' }, + { category: 'SuppliesReturn', containerId: 'eventSuppliesReturn' }, + { category: 'SuppliesDestroy', containerId: 'eventSuppliesDestroy' }, + { category: 'SuppliesEscort', containerId: 'eventSuppliesEscort' }, + { category: 'Destruction', containerId: 'eventDestroyZone' }, + { category: 'Damage', containerId: 'eventDamageZone' }, + { category: 'Scout', containerId: 'eventScout' }, + { category: 'ScoutCriticalHit', containerId: 'eventScoutCriticalHit' }, + { category: 'ScoutKill', containerId: 'eventScoutKill' }, + { category: 'ScoutKillUnknown', containerId: 'eventScoutKill' }, + { category: 'TimedAward', containerId: 'eventTimedAward' }, + { category: 'Unlocks', containerId: 'eventStreak' }, + { category: 'BattleTime', containerId: 'eventBattletime', singleSummaryEvent: true }, +]; + +export interface VehicleBattleStats { + readonly vehicle: string; + readonly wpTotal: number; + readonly expTotal: number; + readonly expModsTotal: number; + readonly expUnitTotal: number; + readonly wpMission: number; + readonly expSkillBonusTotal: number; + readonly expSkillBonusLevel: number; + readonly sessionTime: number; + readonly battleTime: number; + readonly rewards: Readonly>; +} + +export interface BattleReport { + readonly sessionId: string; + readonly country: string; + readonly outcome: BattleOutcomeKind; + readonly localTeam: number; + readonly teamAScore: number; + readonly teamBScore: number; + readonly teamAKills: number; + readonly teamBKills: number; + readonly wpTotal: number; + readonly expTotal: number; + readonly expFree: number; + readonly wpMission: number; + readonly wpTeamKills: number; + readonly expSkillBonusTotal: number; + readonly expSkillBonusLevel: number; + readonly activity: number; + readonly sessionTime: number; + readonly battleTime: number; + readonly rewards: Readonly>; + readonly usedSpares: Readonly>; + readonly vehicles: readonly VehicleBattleStats[]; +} + +export function parseBattleReport(payload: BlkBlock): BattleReport | undefined { + const sessionId = strOf(payload, 'sessionId'); + if (!sessionId || !/^[0-9a-f]{16}$/i.test(sessionId)) return undefined; + const rawOutcome = strOf(payload, 'outcome'); + const outcome: BattleOutcomeKind = rawOutcome === 'win' || rawOutcome === 'lose' ? rawOutcome : 'running'; + const vehiclesBlock = findBlock(payload, 'vehicles'); + const vehicles: VehicleBattleStats[] = (vehiclesBlock?.blocks ?? []) + .filter((block) => block.name.length > 0) + .map((block) => ({ + vehicle: block.name, + wpTotal: intOf(block, 'wpTotal'), + expTotal: intOf(block, 'expTotal'), + expModsTotal: intOf(block, 'expModsTotal'), + expUnitTotal: intOf(block, 'expUnitTotal'), + wpMission: intOf(block, 'wpMission'), + expSkillBonusTotal: intOf(block, 'expSkillBonusTotal'), + expSkillBonusLevel: intOf(block, 'expSkillBonusLevel'), + sessionTime: realOf(block, 'sessionTime'), + battleTime: realOf(block, 'battleTime'), + rewards: parseRewardMap(findBlock(block, 'rewards')), + })); + return { + sessionId: sessionId.toLowerCase(), + country: strOf(payload, 'country') ?? '', + outcome, + localTeam: intOf(payload, 'localTeam', 1), + teamAScore: intOf(payload, 'teamAScore'), + teamBScore: intOf(payload, 'teamBScore'), + teamAKills: intOf(payload, 'teamAKills'), + teamBKills: intOf(payload, 'teamBKills'), + wpTotal: intOf(payload, 'wpTotal'), + expTotal: intOf(payload, 'expTotal'), + expFree: intOf(payload, 'expFree'), + wpMission: intOf(payload, 'wpMission'), + wpTeamKills: intOf(payload, 'wpTeamKills'), + expSkillBonusTotal: intOf(payload, 'expSkillBonusTotal'), + expSkillBonusLevel: intOf(payload, 'expSkillBonusLevel'), + activity: realOf(payload, 'activity'), + sessionTime: realOf(payload, 'sessionTime'), + battleTime: realOf(payload, 'battleTime'), + rewards: parseRewardMap(findBlock(payload, 'rewards')), + usedSpares: parseSpareMap(findBlock(payload, 'spares')), + vehicles, + }; +} + +function parseRewardMap(rewardsBlk: BlkBlock | undefined): Record { + const out: Record = {}; + if (!rewardsBlk) return out; + for (const catBlk of rewardsBlk.blocks) { + if (!catBlk.name) continue; + const count = Math.max(0, intOf(catBlk, 'count')); + const wp = Math.max(0, intOf(catBlk, 'wp')); + const exp = Math.max(0, intOf(catBlk, 'exp')); + if (count > 0 || wp > 0 || exp > 0) out[catBlk.name] = { count, wp, exp }; + } + return out; +} + +function parseSpareMap(sparesBlk: BlkBlock | undefined): Record { + const out: Record = {}; + if (!sparesBlk) return out; + for (const param of sparesBlk.params) { + if (!param.name) continue; + const count = param.value.type === 'int' ? param.value.value : param.value.type === 'int64' ? Number(param.value.value) : 0; + if (count > 0) out[param.name] = count; + } + return out; +} + +function strOf(block: BlkBlock, name: string): string | undefined { + const value = block.params.find((p) => p.name === name)?.value; + return value?.type === 'string' ? value.value : undefined; +} + +function intOf(block: BlkBlock, name: string, fallback = 0): number { + const value = block.params.find((p) => p.name === name)?.value; + if (value?.type === 'int') return value.value; + if (value?.type === 'int64') return Number(value.value); + return fallback; +} + +function realOf(block: BlkBlock, name: string): number { + const value = block.params.find((p) => p.name === name)?.value; + if (value?.type === 'real') return value.value; + if (value?.type === 'int') return value.value; + return 0; +} diff --git a/packages/local-service/src/battle/battle-result-log.ts b/packages/local-service/src/battle/battle-result-log.ts new file mode 100644 index 0000000..6552afa --- /dev/null +++ b/packages/local-service/src/battle/battle-result-log.ts @@ -0,0 +1,280 @@ +/** + * Assemble and append full `EULT_SESSION_RESULT` (`type = 2`) battle mail entries into + * `profile.userlogs` matching `scripts/userlog/userlogviewdata.nut` and + * `scripts/userlog/getuserlogbattlerewardstable.nut`. + */ +import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; +import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts'; +import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts'; +import { REWARD_CATEGORY_SPECS, type BattleReport, type RewardCategorySpec } from './battle-report.ts'; +import type { BattleSession } from './battle-session-store.ts'; + +export interface EarnedRpItem { + readonly unit: string; + readonly modification?: string; + readonly rp: number; + readonly excessRp?: number; +} + +export interface BattleResultSummary { + readonly win: boolean; + readonly country: string; + readonly wpEarned: number; + readonly xpEarned: number; + readonly activity: number; + readonly slMul: number; + readonly rpMul: number; + readonly weaponRefillSl: number; + readonly friendlyFirePenalty: number; + readonly report: BattleReport; + readonly rpItems: readonly EarnedRpItem[]; +} + +export function mergeEarnedRpItems(items: readonly EarnedRpItem[]): EarnedRpItem[] { + const byKey = new Map(); + for (const item of items) { + if (item.rp <= 0 && (item.excessRp ?? 0) <= 0) continue; + const key = `${item.unit}\0${item.modification ?? ''}`; + const existing = byKey.get(key); + if (existing) { + const mergedExcess = (existing.excessRp ?? 0) + (item.excessRp ?? 0); + byKey.set(key, { + unit: existing.unit, + ...(existing.modification ? { modification: existing.modification } : {}), + rp: existing.rp + item.rp, + ...(mergedExcess > 0 ? { excessRp: mergedExcess } : {}), + }); + } else { + byKey.set(key, item); + } + } + return [...byKey.values()]; +} + +export function appendBattleResultLog( + profile: BlkBlock, + session: BattleSession, + summary: BattleResultSummary, +): void { + const bodyParams: BlkParam[] = [ + { name: 'win', value: { type: 'bool', value: summary.win } }, + { name: 'mission', value: { type: 'string', value: session.missionName } }, + ...(session.missionLocName ? [{ name: 'locName', value: { type: 'string' as const, value: session.missionLocName } }] : []), + { name: 'country', value: { type: 'string', value: summary.country } }, + { name: 'eventId', value: { type: 'string', value: session.modeName } }, + { name: 'wpEarned', value: { type: 'int', value: summary.wpEarned } }, + { name: 'xpEarned', value: { type: 'int', value: summary.xpEarned } }, + { name: 'activity', value: { type: 'real', value: summary.activity } }, + ...(summary.friendlyFirePenalty !== 0 + ? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: summary.friendlyFirePenalty } }] + : []), + { name: 'wtoSessionId', value: { type: 'string', value: session.sessionId } }, + { name: 'wtoSlMul', value: { type: 'real', value: summary.slMul } }, + { name: 'wtoRpMul', value: { type: 'real', value: summary.rpMul } }, + ]; + + const bodyBlocks: BlkBlock[] = [buildContainerBlock(summary)]; + const aircrafts = buildAircraftsBlock(summary.report); + if (aircrafts) bodyBlocks.push(aircrafts); + const spare = buildSpareBlock(summary.report); + if (spare) bodyBlocks.push(spare); + const rpEarned = buildRpEarnedBlock(summary.rpItems); + if (rpEarned) bodyBlocks.push(rpEarned); + + appendUserLog(profile, { + type: EULT_SESSION_RESULT, + timeSec: serverTimeToUnixSeconds(serverTimeNow()), + roomId: session.roomId, + bodyParams, + bodyBlocks, + }); +} + +function buildContainerBlock(summary: BattleResultSummary): BlkBlock { + const container = emptyBlock('container'); + const { report, slMul, rpMul } = summary; + if (summary.weaponRefillSl > 0) { + setParam(container, 'wpCostWeaponRefill', { type: 'int', value: summary.weaponRefillSl }); + } + const wpMission = scalePositive( + Math.max(report.wpMission, report.vehicles.reduce((s, v) => s + Math.max(0, v.wpMission), 0)), + slMul, + ); + if (wpMission > 0) { + setParam(container, 'wpMissionEndAward', { type: 'int', value: wpMission }); + } + + const eventLists = new Map(); + for (const spec of REWARD_CATEGORY_SPECS) { + appendCategoryEvents(eventLists, spec, report, slMul, rpMul); + } + for (const [containerId, events] of eventLists) { + if (events.length > 0) { + container.blocks.push({ name: containerId, params: [], blocks: events }); + } + } + + const sessionAward = buildUnitSessionAwardBlock(report); + if (sessionAward) container.blocks.push(sessionAward); + const skillBonus = buildSkillBonusBlock(report, rpMul); + if (skillBonus) container.blocks.push(skillBonus); + return container; +} + +function appendCategoryEvents( + eventLists: Map, + spec: RewardCategorySpec, + report: BattleReport, + slMul: number, + rpMul: number, +): void { + let unitWpSum = 0; + let unitExpSum = 0; + let hasUnitEntries = false; + for (const vehicle of report.vehicles) { + const stat = vehicle.rewards[spec.category]; + if (!stat) continue; + hasUnitEntries = true; + const wp = scalePositive(stat.wp, slMul); + const exp = scalePositive(stat.exp, rpMul); + unitWpSum += stat.wp; + unitExpSum += stat.exp; + pushSplitEvents(eventLists, spec, vehicle.vehicle, stat.count, wp, exp); + } + const rootStat = report.rewards[spec.category]; + if (!rootStat) return; + if (!hasUnitEntries) { + const fallbackUnit = report.vehicles[0]?.vehicle ?? ''; + pushSplitEvents( + eventLists, + spec, + fallbackUnit, + rootStat.count, + scalePositive(rootStat.wp, slMul), + scalePositive(rootStat.exp, rpMul), + ); + return; + } + const extraWp = scalePositive(rootStat.wp - unitWpSum, slMul); + const extraExp = scalePositive(rootStat.exp - unitExpSum, rpMul); + if (extraWp > 0 || extraExp > 0) { + pushSplitEvents(eventLists, spec, report.vehicles[0]?.vehicle ?? '', 1, extraWp, extraExp); + } +} + +function pushSplitEvents( + eventLists: Map, + spec: RewardCategorySpec, + offenderUnit: string, + rawCount: number, + totalWp: number, + totalExp: number, +): void { + if (rawCount <= 0 && totalWp <= 0 && totalExp <= 0) return; + const count = spec.singleSummaryEvent ? 1 : Math.min(64, Math.max(1, rawCount)); + let list = eventLists.get(spec.containerId); + if (!list) { + list = []; + eventLists.set(spec.containerId, list); + } + let prevWp = 0; + let prevExp = 0; + for (let i = 0; i < count; i++) { + const nextWp = Math.round((totalWp * (i + 1)) / count); + const nextExp = Math.round((totalExp * (i + 1)) / count); + const ev = emptyBlock('event'); + if (offenderUnit) setParam(ev, 'offenderUnit', { type: 'string', value: offenderUnit }); + if (spec.victimUnitFileName) setParam(ev, 'victimUnitFileName', { type: 'string', value: spec.victimUnitFileName }); + setParam(ev, 'wpNoBonus', { type: 'int', value: nextWp - prevWp }); + setParam(ev, 'expNoBonus', { type: 'int', value: nextExp - prevExp }); + list.push(ev); + prevWp = nextWp; + prevExp = nextExp; + } +} + +function buildUnitSessionAwardBlock(report: BattleReport): BlkBlock | undefined { + const events: BlkBlock[] = []; + for (const v of report.vehicles) { + const sec = Math.round(v.sessionTime > 0 ? v.sessionTime : v.battleTime); + if (sec <= 0) continue; + const ev = emptyBlock('event'); + setParam(ev, 'unit', { type: 'string', value: v.vehicle }); + setParam(ev, 'lifetime', { type: 'int', value: sec }); + setParam(ev, 'wpNoBonus', { type: 'int', value: 0 }); + setParam(ev, 'expNoBonus', { type: 'int', value: 0 }); + events.push(ev); + } + if (events.length === 0) { + const rootSec = Math.round(report.sessionTime > 0 ? report.sessionTime : report.battleTime); + if (rootSec <= 0) return undefined; + const ev = emptyBlock('event'); + setParam(ev, 'lifetime', { type: 'int', value: rootSec }); + setParam(ev, 'wpNoBonus', { type: 'int', value: 0 }); + setParam(ev, 'expNoBonus', { type: 'int', value: 0 }); + events.push(ev); + } + return { name: 'unitSessionAward', params: [], blocks: events }; +} + +function buildSkillBonusBlock(report: BattleReport, rpMul: number): BlkBlock | undefined { + const units: BlkBlock[] = []; + for (const v of report.vehicles) { + const exp = scalePositive(v.expSkillBonusTotal, rpMul); + if (exp <= 0) continue; + const uBlk = emptyBlock('unit'); + setParam(uBlk, 'unit', { type: 'string', value: v.vehicle }); + setParam(uBlk, 'bonusLevel', { type: 'int', value: Math.max(1, v.expSkillBonusLevel || report.expSkillBonusLevel) }); + setParam(uBlk, 'exp', { type: 'int', value: exp }); + units.push(uBlk); + } + if (units.length === 0 && report.expSkillBonusTotal > 0) { + const exp = scalePositive(report.expSkillBonusTotal, rpMul); + if (exp > 0) { + const uBlk = emptyBlock('unit'); + setParam(uBlk, 'unit', { type: 'string', value: report.vehicles[0]?.vehicle ?? '' }); + setParam(uBlk, 'bonusLevel', { type: 'int', value: Math.max(1, report.expSkillBonusLevel) }); + setParam(uBlk, 'exp', { type: 'int', value: exp }); + units.push(uBlk); + } + } + return units.length > 0 ? { name: 'expSkillBonus', params: [], blocks: units } : undefined; +} + +function buildAircraftsBlock(report: BattleReport): BlkBlock | undefined { + if (report.vehicles.length === 0) return undefined; + const blk = emptyBlock('aircrafts'); + for (const v of report.vehicles) { + setParam(blk, v.vehicle, { type: 'real', value: 1.0 }); + } + return blk; +} + +function buildSpareBlock(report: BattleReport): BlkBlock | undefined { + const entries = Object.entries(report.usedSpares).filter(([unit, cnt]) => unit.length > 0 && cnt > 0); + if (entries.length === 0) return undefined; + const blk = emptyBlock('spare'); + for (const [unit, count] of entries) { + setParam(blk, unit, { type: 'int', value: Math.trunc(count) }); + } + return blk; +} + +function buildRpEarnedBlock(items: readonly EarnedRpItem[]): BlkBlock | undefined { + if (items.length === 0) return undefined; + const rpEarned = emptyBlock('rpEarned'); + items.forEach((item, index) => { + setParam(rpEarned, `aname${index}`, { type: 'string', value: item.unit }); + if (item.modification) setParam(rpEarned, `mname${index}`, { type: 'string', value: item.modification }); + setParam(rpEarned, `mrp${index}`, { type: 'int', value: item.rp }); + if (item.excessRp && item.excessRp > 0) { + setParam(rpEarned, `merp${index}`, { type: 'int', value: item.excessRp }); + } + }); + return rpEarned; +} + +function scalePositive(base: number, mul: number): number { + if (!Number.isFinite(base) || base <= 0) return 0; + return Math.min(0x7fffffff, Math.max(0, Math.round(base * mul))); +} diff --git a/packages/local-service/src/battle/battle-rp-investment.ts b/packages/local-service/src/battle/battle-rp-investment.ts new file mode 100644 index 0000000..0965464 --- /dev/null +++ b/packages/local-service/src/battle/battle-rp-investment.ts @@ -0,0 +1,266 @@ +/** + * Post-battle Modification RP and Vehicle RP investment with overflow banking: + * - Modification RP completes at most the vehicle's active `investMode` modification, sets + * `investModePrev = `, clears `investMode = ""`, and banks remaining RP into + * `hangar//excessExp:i64` (unless all modifications on the vehicle are researched). + * - Vehicle RP aggregates per `(country, branchType)` before investing, completes at most the + * active `currUnit` once, sets `prevUnit = `, clears `currUnit = ""`, and + * banks remaining RP into `researchUnits..exp:i64`. + */ +import type { BlkBlock } from '@wto/blk'; +import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts'; +import type { UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts'; +import { isResearchable, type EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; +import { pickDefaultResearchableModule } from '../modifications/module-state.ts'; +import { isModuleResearched, ModuleStatus, vehicleModuleState } from '../modifications/module-status.ts'; +import { addExpertToAceRp, specializationOf } from '../profile/profile-crew-skills.ts'; +import { crewForVehicleInCountry } from '../profile/profile-crews.ts'; +import { readRedirectedResearchDomain, type VehicleDomain } from '../profile/profile-dest-rp.ts'; +import { ownedVehicles } from '../profile/profile-hangar.ts'; +import { moduleResearchPoints, setModuleResearchPoints } from '../profile/profile-module-research.ts'; +import { + branchExcessRp, + finishedResearch, + researchTarget, + setBranchExcessRp, + setFinishedResearch, + setResearchTarget, +} from '../profile/profile-research-targets.ts'; +import { researchPointsOf } from '../profile/profile-vehicle-research.ts'; +import { + finishedModuleResearch, + moduleResearchTarget, + setFinishedModuleResearch, + setModuleResearchTarget, + setVehicleExcessRp, + vehicleExcessRp, +} from '../profile/profile-vehicle-state.ts'; +import { addResearchPoints } from '../research/research-progress.ts'; +import type { ResearchRules } from '../research/research-rules.ts'; +import { currentStatus, refreshResearchState } from '../research/research-state.ts'; +import { VehicleStatus } from '../research/vehicle-status.ts'; +import type { BattleReport } from './battle-report.ts'; +import type { EarnedRpItem } from './battle-result-log.ts'; +import type { BattleSession } from './battle-session-store.ts'; + +export interface BattleRpDeps { + readonly research: ResearchRules; + readonly equipment: EquipmentCatalogue; + readonly crew: CrewSkillCatalogue; +} + +export function collectEarnedBattleRp( + profile: BlkBlock, + report: BattleReport, + session: BattleSession, + deps: BattleRpDeps, + rpMul: number, + earnedTotalRp: number, +): EarnedRpItem[] { + const rpItems: EarnedRpItem[] = []; + const owned = ownedVehicles(profile); + const branchTotals = new Map(); + + refreshResearchState(profile, deps.research); + for (const stat of report.vehicles) { + const modRp = scaleRp(stat.expModsTotal > 0 ? stat.expModsTotal : stat.expTotal, rpMul); + const unitRp = scaleRp(stat.expUnitTotal > 0 ? stat.expUnitTotal : stat.expTotal, rpMul); + if (modRp > 0 && owned.has(stat.vehicle)) { + const modItem = investModificationRp(profile, deps.equipment, stat.vehicle, modRp); + if (modItem) rpItems.push(modItem); + } + if (unitRp > 0) { + if (owned.has(stat.vehicle)) investAceCrewRp(profile, deps.crew, session.country, stat.vehicle, unitRp); + accumulateBranchRp(branchTotals, profile, deps.research, stat.vehicle, session, unitRp); + } + } + if (report.vehicles.length === 0 && earnedTotalRp > 0) { + const fallbackBranch = resolveFallbackBranch(profile, session.country, session.requiredClass); + if (fallbackBranch) addToBranchMap(branchTotals, session.country, fallbackBranch, earnedTotalRp); + } + for (const entry of branchTotals.values()) { + const item = investIntoBranch(profile, deps.research, entry.country, entry.branchType, entry.amount); + if (item) rpItems.push(item); + } + return rpItems; +} + +function accumulateBranchRp( + branchTotals: Map, + profile: BlkBlock, + research: ResearchRules, + playedVehicleName: string, + session: BattleSession, + amount: number, +): void { + const played = research.techTree.vehicle(playedVehicleName); + if (played) { + const targetBranch = readRedirectedResearchDomain(profile, played.country, played.type); + addToBranchMap(branchTotals, played.country, targetBranch, amount); + return; + } + const fallbackBranch = resolveFallbackBranch(profile, session.country, session.requiredClass); + if (fallbackBranch) { + const targetBranch = readRedirectedResearchDomain(profile, session.country, fallbackBranch); + addToBranchMap(branchTotals, session.country, targetBranch, amount); + } +} + +function addToBranchMap( + map: Map, + country: string, + branchType: string, + amount: number, +): void { + const key = `${country}\0${branchType}`; + const existing = map.get(key); + if (existing) existing.amount += amount; + else map.set(key, { country, branchType, amount }); +} + +function resolveFallbackBranch(profile: BlkBlock, country: string, requiredClass: UnitClass): VehicleDomain | undefined { + const preferred: Readonly> = { + tank: ['Tank', 'Aircraft', 'Helicopter', 'Boat', 'Ship'], + aircraft: ['Aircraft', 'Helicopter', 'Tank', 'Boat', 'Ship'], + helicopter: ['Helicopter', 'Aircraft', 'Tank', 'Boat', 'Ship'], + ship: ['Ship', 'Boat', 'Aircraft', 'Tank', 'Helicopter'], + }; + return preferred[requiredClass].find((branch) => Boolean(researchTarget(profile, country, branch))) + ?? preferred[requiredClass][0]; +} + +function investModificationRp( + profile: BlkBlock, + catalogue: EquipmentCatalogue, + vehicleName: string, + amount: number, +): EarnedRpItem | undefined { + const equipment = catalogue.vehicle(vehicleName); + if (!equipment || amount <= 0) return undefined; + const state = vehicleModuleState(profile, equipment); + let targetName = moduleResearchTarget(profile, vehicleName); + if (targetName && state.statuses.get(targetName) !== ModuleStatus.CAN_RESEARCH) { + targetName = ''; + setModuleResearchTarget(profile, vehicleName, ''); + } + if (!targetName && finishedModuleResearch(profile, vehicleName) === '' && vehicleExcessRp(profile, vehicleName) === 0) { + targetName = pickDefaultResearchableModule(equipment, state); + if (targetName) setModuleResearchTarget(profile, vehicleName, targetName); + } + if (!targetName) { + if (!hasUnresearchedModification(profile, vehicleName, equipment.modifications)) return undefined; + setVehicleExcessRp(profile, vehicleName, vehicleExcessRp(profile, vehicleName) + amount); + return { unit: vehicleName, rp: 0, excessRp: amount }; + } + + const modFacts = catalogue.modification(vehicleName, targetName); + if (!modFacts || modFacts.researchPoints <= 0) return undefined; + const before = moduleResearchPoints(profile, vehicleName, targetName); + const invested = Math.min(amount, Math.max(0, modFacts.researchPoints - before)); + const leftover = amount - invested; + if (invested > 0) setModuleResearchPoints(profile, vehicleName, targetName, before + invested); + + let bankedExcess = 0; + if (before + invested >= modFacts.researchPoints) { + setModuleResearchTarget(profile, vehicleName, ''); + setFinishedModuleResearch(profile, vehicleName, targetName); + if (hasUnresearchedModification(profile, vehicleName, equipment.modifications)) { + if (leftover > 0) { + setVehicleExcessRp(profile, vehicleName, vehicleExcessRp(profile, vehicleName) + leftover); + bankedExcess = leftover; + } + } else { + setVehicleExcessRp(profile, vehicleName, 0); + } + } + return { + unit: vehicleName, + modification: targetName, + rp: invested, + ...(bankedExcess > 0 ? { excessRp: bankedExcess } : {}), + }; +} + +function investIntoBranch( + profile: BlkBlock, + research: ResearchRules, + country: string, + branchType: string, + amount: number, +): EarnedRpItem | undefined { + if (amount <= 0) return undefined; + const targetName = researchTarget(profile, country, branchType); + const target = targetName ? research.techTree.vehicle(targetName) : undefined; + if (!target || target.researchPoints <= 0 || currentStatus(profile, research, target.name) !== VehicleStatus.CAN_RESEARCH) { + if (!hasUnresearchedBranchVehicle(profile, research, country, branchType)) return undefined; + setBranchExcessRp(profile, country, branchType, branchExcessRp(profile, country, branchType) + amount); + const labelUnit = finishedResearch(profile, country, branchType); + return labelUnit ? { unit: labelUnit, rp: 0, excessRp: amount } : undefined; + } + + const before = researchPointsOf(profile, target.name); + const invested = Math.min(amount, Math.max(0, target.researchPoints - before)); + const remaining = amount - invested; + if (invested > 0) addResearchPoints(profile, target, invested); + + let bankedExcess = 0; + if (before + invested >= target.researchPoints) { + setResearchTarget(profile, country, branchType, ''); + setFinishedResearch(profile, country, branchType, target.name); + if (hasUnresearchedBranchVehicle(profile, research, country, branchType)) { + if (remaining > 0) { + setBranchExcessRp(profile, country, branchType, branchExcessRp(profile, country, branchType) + remaining); + bankedExcess = remaining; + } + } else { + setBranchExcessRp(profile, country, branchType, 0); + } + } + return { + unit: target.name, + rp: invested, + ...(bankedExcess > 0 ? { excessRp: bankedExcess } : {}), + }; +} + +function hasUnresearchedModification( + profile: BlkBlock, + vehicle: string, + modifications: readonly Parameters[2][], +): boolean { + return modifications.some((mod) => isResearchable(mod) && !isModuleResearched(profile, vehicle, mod)); +} + +function hasUnresearchedBranchVehicle( + profile: BlkBlock, + research: ResearchRules, + country: string, + branchType: string, +): boolean { + const owned = ownedVehicles(profile); + for (const vehicle of research.techTree.all()) { + if (vehicle.kind !== 'research' || vehicle.country !== country || vehicle.type !== branchType) continue; + if (!owned.has(vehicle.name) && researchPointsOf(profile, vehicle.name) < vehicle.researchPoints) return true; + } + return false; +} + +function investAceCrewRp( + profile: BlkBlock, + catalogue: CrewSkillCatalogue, + country: string, + vehicleName: string, + amount: number, +): void { + const targetRp = catalogue.training(vehicleName)?.aceResearchPoints ?? 0; + if (targetRp <= 0) return; + const crew = crewForVehicleInCountry(profile, country, vehicleName); + if (crew && specializationOf(crew, vehicleName) === 1) { + addExpertToAceRp(crew, vehicleName, amount, targetRp); + } +} + +function scaleRp(base: number, multiplier: number): number { + if (!Number.isFinite(base) || base <= 0) return 0; + return Math.min(0x7fffffff, Math.max(0, Math.round(base * multiplier))); +} diff --git a/packages/local-service/src/battle/battle-session-store.ts b/packages/local-service/src/battle/battle-session-store.ts new file mode 100644 index 0000000..949e887 --- /dev/null +++ b/packages/local-service/src/battle/battle-session-store.ts @@ -0,0 +1,105 @@ +/** + * In-memory registry of battle sessions created by `match.enqueue` and settled once by + * `cln_wto_finish_battle`. + * + * Each session gets a non-zero positive 63-bit integer `roomId` formatted as a 16-character + * lowercase hexadecimal `sessionId`, matching `userlogs` `roomId:i64` (`aces.exe` `0x1799d30`). + */ +import { randomBytes } from 'node:crypto'; +import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts'; + +export interface BattleSession { + readonly sessionId: string; + readonly roomId: bigint; + readonly userId: string; + readonly modeId: number; + readonly modeName: string; + readonly economicName: string; + readonly difficulty: ModeDifficulty; + readonly requiredClass: UnitClass; + readonly missionName: string; + readonly missionPath: string; + readonly missionLocName?: string; + readonly country: string; + readonly startedAtSec: number; + settled: boolean; +} + +export interface NewBattleSession { + readonly userId: string; + readonly modeId: number; + readonly modeName: string; + readonly economicName: string; + readonly difficulty: ModeDifficulty; + readonly requiredClass: UnitClass; + readonly missionName: string; + readonly missionPath: string; + readonly missionLocName?: string; + readonly country: string; + readonly startedAtSec: number; +} + +export class BattleSessionStore { + readonly #sessions = new Map(); + readonly #pendingByUser = new Map(); + readonly #maxRetained: number; + + constructor(maxRetained: number) { + this.#maxRetained = Math.max(1, maxRetained); + } + + create(input: NewBattleSession): BattleSession { + const roomId = generateRoomId(this.#sessions); + const sessionId = roomId.toString(16).padStart(16, '0'); + const session: BattleSession = { ...input, sessionId, roomId, settled: false }; + this.#sessions.set(sessionId, session); + this.#pendingByUser.set(input.userId, sessionId); + this.#trim(); + return session; + } + + /** Cancel a queued session if the player leaves the queue before entering flight. */ + cancelPendingForUser(userId: string): void { + this.#pendingByUser.delete(userId); + } + + isPending(userId: string, sessionId: string): boolean { + return this.#pendingByUser.get(userId) === sessionId; + } + + clearPending(userId: string, sessionId: string): void { + if (this.#pendingByUser.get(userId) === sessionId) { + this.#pendingByUser.delete(userId); + } + } + + findForUser(sessionId: string, userId: string): BattleSession | undefined { + const session = this.#sessions.get(sessionId); + return session && session.userId === userId ? session : undefined; + } + + markSettled(sessionId: string): void { + const session = this.#sessions.get(sessionId); + if (session) { + session.settled = true; + this.clearPending(session.userId, sessionId); + } + } + + #trim(): void { + while (this.#sessions.size > this.#maxRetained) { + const oldestKey = this.#sessions.keys().next().value; + if (oldestKey === undefined) break; + this.#sessions.delete(oldestKey); + } + } +} + +function generateRoomId(existing: ReadonlyMap): bigint { + for (;;) { + const raw = randomBytes(8).readBigUInt64BE(0) & 0x7fffffffffffffffn; + const roomId = raw === 0n ? 1n : raw; + const hex = roomId.toString(16).padStart(16, '0'); + if (!existing.has(hex)) return roomId; + } +} diff --git a/packages/local-service/src/battle/battle-settlement.ts b/packages/local-service/src/battle/battle-settlement.ts new file mode 100644 index 0000000..78c2715 --- /dev/null +++ b/packages/local-service/src/battle/battle-settlement.ts @@ -0,0 +1,117 @@ +/** + * Post-battle settlement rules (`cln_wto_finish_battle`): + * - Resolves battle win/loss (direct outcome when finished, weighted ticket + kill ratio on + * early leave). + * - Applies offline multipliers (`tuning/battle.jsonc`) to Silver Lions, Free RP, Modification + * RP, and Vehicle RP, runs `autoRefillWeapons` equipment top-ups, and appends the full + * `EULT_SESSION_RESULT` battle mail log. + */ +import type { BlkBlock } from '@wto/blk'; +import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts'; +import { stockAndRefillEquipment } from '../modifications/ammo-refill.ts'; +import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; +import { isAutoRefillWeaponsEnabled } from '../profile/profile-client-settings.ts'; +import { addSilverLions, balanceOf, pay } from '../profile/profile-currency.ts'; +import { ownedVehicles } from '../profile/profile-hangar.ts'; +import { addFreeResearchPoints } from '../profile/profile-research-points.ts'; +import type { ResearchRules } from '../research/research-rules.ts'; +import type { BattleReport } from './battle-report.ts'; +import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts'; +import { collectEarnedBattleRp } from './battle-rp-investment.ts'; +import type { BattleSession } from './battle-session-store.ts'; +import type { BattleTuning } from './battle-tuning.ts'; + +export type { BattleOutcomeKind, BattleReport, VehicleBattleStats } from './battle-report.ts'; + +export interface BattleSettlementDeps { + readonly research: ResearchRules; + readonly equipment: EquipmentCatalogue; + readonly crew: CrewSkillCatalogue; + readonly tuning: BattleTuning; +} + +export function settleBattle( + profile: BlkBlock, + report: BattleReport, + session: BattleSession, + deps: BattleSettlementDeps, +): void { + const win = resolveWin(report, deps.tuning); + const slMul = deps.tuning.rewardMultiplierSilverLions; + const rpMul = deps.tuning.rewardMultiplierResearchPoints; + + const earnedSilverLions = scaleNonNegative(report.wpTotal, slMul); + const friendlyFirePenalty = report.wpTeamKills !== 0 + ? -scaleNonNegative(Math.abs(report.wpTeamKills), slMul) + : 0; + const baseTotalRp = Math.max( + report.expTotal, + report.vehicles.reduce((sum, vehicle) => sum + Math.max(0, vehicle.expTotal), 0), + ); + const earnedTotalRp = scaleNonNegative(baseTotalRp, rpMul); + const earnedFreeRp = scaleNonNegative(report.expFree > 0 ? report.expFree : baseTotalRp, rpMul); + + applyNetSilverLions(profile, earnedSilverLions + friendlyFirePenalty); + if (earnedFreeRp > 0) addFreeResearchPoints(profile, earnedFreeRp); + + const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment); + const rpItems = collectEarnedBattleRp(profile, report, session, deps, rpMul, earnedTotalRp); + const country = report.country.startsWith('country_') ? report.country : session.country; + appendBattleResultLog(profile, session, { + win, + country, + wpEarned: earnedSilverLions, + xpEarned: earnedTotalRp, + activity: clampActivity(report.activity), + slMul, + rpMul, + weaponRefillSl, + friendlyFirePenalty, + report, + rpItems: mergeEarnedRpItems(rpItems), + }); +} + +function applyNetSilverLions(profile: BlkBlock, netDelta: number): void { + if (netDelta > 0) { + addSilverLions(profile, netDelta); + } else if (netDelta < 0) { + const deduction = Math.min(balanceOf(profile).silverLions, -netDelta); + if (deduction > 0) pay(profile, { silverLions: deduction, goldenEagles: 0 }); + } +} + +function refillOwnedEquipment(profile: BlkBlock, catalogue: EquipmentCatalogue): number { + if (!isAutoRefillWeaponsEnabled(profile)) return 0; + const owned = [...ownedVehicles(profile)].sort((a, b) => a.localeCompare(b)); + let totalSpent = 0; + for (const vehicle of owned) { + const eq = catalogue.vehicle(vehicle); + if (eq) totalSpent += stockAndRefillEquipment(profile, eq, true).silverLionsSpent; + } + return totalSpent; +} + +function resolveWin(report: BattleReport, tuning: BattleTuning): boolean { + if (report.outcome === 'win') return true; + if (report.outcome === 'lose') return false; + const isTeamB = report.localTeam === 2; + const myTickets = Math.max(0, isTeamB ? report.teamBScore : report.teamAScore); + const enemyTickets = Math.max(0, isTeamB ? report.teamAScore : report.teamBScore); + const myKills = Math.max(0, isTeamB ? report.teamBKills : report.teamAKills); + const enemyKills = Math.max(0, isTeamB ? report.teamAKills : report.teamBKills); + const ticketShare = myTickets + enemyTickets > 0 ? myTickets / (myTickets + enemyTickets) : 0.5; + const killShare = myKills + enemyKills > 0 ? myKills / (myKills + enemyKills) : 0.5; + const totalWeight = tuning.earlyLeaveTicketWeight + tuning.earlyLeaveKillWeight; + return (ticketShare * tuning.earlyLeaveTicketWeight + killShare * tuning.earlyLeaveKillWeight) / totalWeight >= 0.5; +} + +function scaleNonNegative(base: number, multiplier: number): number { + if (!Number.isFinite(base) || base <= 0) return 0; + return Math.min(0x7fffffff, Math.max(0, Math.round(base * multiplier))); +} + +function clampActivity(activity: number): number { + if (!Number.isFinite(activity)) return 0; + return Math.min(1, Math.max(0, activity)); +} diff --git a/packages/local-service/src/battle/battle-tuning.ts b/packages/local-service/src/battle/battle-tuning.ts new file mode 100644 index 0000000..8ad658f --- /dev/null +++ b/packages/local-service/src/battle/battle-tuning.ts @@ -0,0 +1,73 @@ +/** + * Typed reader for `tuning/battle.jsonc`: offline Silver Lions and Research Points + * multipliers, LocalMP slot and bot counts, matchmaking BR window, coalition pairing + * rules, and early-leave win-inference weights. + */ +import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts'; + +export interface BattleTuning { + readonly rewardMultiplierSilverLions: number; + readonly rewardMultiplierResearchPoints: number; + readonly maxPlayers: number; + readonly maxBots: number; + readonly smallTeamsMaxPlayers: number; + readonly subModeChance: number; + readonly brSpreadMrank: number; + readonly botPoolLimitPerType: number; + readonly rbCoalitionMinCountries: number; + readonly rbCoalitionMaxCountries: number; + readonly rbGroundMixedChance: number; + readonly rbAirMixedChance: number; + readonly rbNavalMixedChance: number; + readonly simColdWarMinMrank: number; + readonly tankBotRespawns: number; + readonly airBotRespawns: number; + readonly earlyLeaveTicketWeight: number; + readonly earlyLeaveKillWeight: number; +} + +export function readBattleTuning(reader: TuningReader): BattleTuning { + const maxPlayers = reader.int('maxPlayers', { min: 2, max: 64 }); + const maxBots = reader.int('maxBots', { min: 1, max: 63 }); + if (maxBots >= maxPlayers) { + throw new TuningError(`tuning file battle.jsonc: maxBots (${maxBots}) must be less than maxPlayers (${maxPlayers})`); + } + const smallTeamsMaxPlayers = reader.int('smallTeamsMaxPlayers', { min: 2, max: 64 }); + if (smallTeamsMaxPlayers > maxPlayers) { + throw new TuningError( + `tuning file battle.jsonc: smallTeamsMaxPlayers (${smallTeamsMaxPlayers}) must not exceed maxPlayers (${maxPlayers})`, + ); + } + const rbCoalitionMinCountries = reader.int('rbCoalitionMinCountries', { min: 1, max: 10 }); + const rbCoalitionMaxCountries = reader.int('rbCoalitionMaxCountries', { min: 1, max: 10 }); + if (rbCoalitionMaxCountries < rbCoalitionMinCountries) { + throw new TuningError( + `tuning file battle.jsonc: rbCoalitionMaxCountries (${rbCoalitionMaxCountries}) must be at least rbCoalitionMinCountries (${rbCoalitionMinCountries})`, + ); + } + const earlyLeaveTicketWeight = reader.number('earlyLeaveTicketWeight', { min: 0, max: 1 }); + const earlyLeaveKillWeight = reader.number('earlyLeaveKillWeight', { min: 0, max: 1 }); + if (earlyLeaveTicketWeight + earlyLeaveKillWeight <= 0) { + throw new TuningError('tuning file battle.jsonc: earlyLeaveTicketWeight + earlyLeaveKillWeight must be positive'); + } + return { + rewardMultiplierSilverLions: reader.number('rewardMultiplierSilverLions', { min: 0, max: 100 }), + rewardMultiplierResearchPoints: reader.number('rewardMultiplierResearchPoints', { min: 0, max: 100 }), + maxPlayers, + maxBots, + smallTeamsMaxPlayers, + subModeChance: reader.number('subModeChance', { min: 0, max: 1 }), + brSpreadMrank: reader.int('brSpreadMrank', { min: 0, max: 12 }), + botPoolLimitPerType: reader.int('botPoolLimitPerType', { min: 4, max: 200 }), + rbCoalitionMinCountries, + rbCoalitionMaxCountries, + rbGroundMixedChance: reader.number('rbGroundMixedChance', { min: 0, max: 1 }), + rbAirMixedChance: reader.number('rbAirMixedChance', { min: 0, max: 1 }), + rbNavalMixedChance: reader.number('rbNavalMixedChance', { min: 0, max: 1 }), + simColdWarMinMrank: reader.int('simColdWarMinMrank', { min: 0, max: 40 }), + tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }), + airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }), + earlyLeaveTicketWeight, + earlyLeaveKillWeight, + }; +} diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index 4e488d3..150193d 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -1,4 +1,4 @@ -/** Char action names mapped to their handlers (full list of names: research-data/char_actions_37.json). */ +/** Char action names mapped to their protocol handlers. */ import type { AccountStore } from '../../accounts/account-store.ts'; import type { ClanStore } from '../../clans/clan-store.ts'; import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts'; @@ -66,11 +66,13 @@ import { entitlementsFull, initialMeta, legacyUserData } from './online-init-act import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts'; import { priceEx } from './price-actions.ts'; import { buyAircraft, buySlot } from './purchase-actions.ts'; -import { convertExp, resetResearchable, setResearchable } from './research-actions.ts'; +import { convertExp, moveExpToModuleAction, moveExpToUnitAction, resetResearchable, setResearchable } from './research-actions.ts'; import { buyNotResearchedClanUnitAction, flushClanExpToUnitAction, setResearchClanUnitAction } from './squadron-research-actions.ts'; import { setStartingInfo } from './starting-info-actions.ts'; import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts'; import { buyUnlockAction } from './unlock-actions.ts'; +import { finishBattleAction, type BattleActionDependencies } from './battle-actions.ts'; +import { hangarMiscActionEntries } from './hangar-misc-actions.ts'; export interface ClanActionDependencies { readonly store: ClanStore; @@ -91,14 +93,17 @@ export interface ActionDependencies { readonly trophies: TrophyCatalogue; readonly clans?: ClanActionDependencies; readonly cloudSettings?: CloudSettingsStore; + readonly battle?: BattleActionDependencies; readonly notifyInventoryChanged?: () => void; } export function actionTable(deps: ActionDependencies): ReadonlyMap { const entries: Array<[string, CharActionHandler]> = [ ...coreActionEntries(deps), + ...hangarMiscActionEntries(deps), ...(deps.clans ? clanActionEntries(deps, deps.clans) : []), ...(deps.cloudSettings ? cloudActionEntries(deps.accounts, deps.cloudSettings) : []), + ...(deps.battle ? [['cln_wto_finish_battle', finishBattleAction(deps, deps.battle)] as [string, CharActionHandler]] : []), ]; return new Map(entries); } @@ -118,6 +123,8 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH ['cln_set_researchable', setResearchable(deps.profiles, deps.accounts, deps.research, deps.equipment)], ['cln_reset_researchable', resetResearchable(deps.profiles, deps.accounts, deps.research)], ['cln_convert_exp', convertExp(deps.profiles, deps.accounts, deps.research)], + ['cln_move_exp_to_unit', moveExpToUnitAction(deps.profiles, deps.accounts, deps.research)], + ['cln_move_exp_to_module', moveExpToModuleAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_buy_aircraft', buyAircraft(deps.profiles, deps.accounts, deps.research)], ['cln_buy_slot', buySlot(deps.profiles, deps.accounts, deps.research)], ['cln_get_price_ex', priceEx({ techTree, equipment: deps.equipment, decor: deps.decor, crew: deps.crew, unlocks: deps.unlocks, items: deps.items, trophies: deps.trophies })], diff --git a/packages/local-service/src/char/actions/battle-actions.ts b/packages/local-service/src/char/actions/battle-actions.ts new file mode 100644 index 0000000..5d0e5e0 --- /dev/null +++ b/packages/local-service/src/char/actions/battle-actions.ts @@ -0,0 +1,53 @@ +/** + * Char action `cln_wto_finish_battle`: receives the client's local-battle debriefing stats + * (`stat_get_exp()`), settles Silver Lions, Research Points, equipment refills, and + * `EULT_SESSION_RESULT` into the player's save, and answers the updated profile. + */ +import type { AccountStore } from '../../accounts/account-store.ts'; +import { parseBattleReport } from '../../battle/battle-report.ts'; +import type { BattleSessionStore } from '../../battle/battle-session-store.ts'; +import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts'; +import type { BattleTuning } from '../../battle/battle-tuning.ts'; +import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts'; +import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; +import { clientProfile } from '../../profile/client-profile.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; +import type { CharActionHandler } from '../char-action.ts'; +import { withAccount } from './account-context.ts'; + +export interface BattleActionDependencies { + readonly sessions: BattleSessionStore; + readonly tuning: BattleTuning; +} + +export interface FinishBattleContext { + readonly profiles: PlayerProfiles; + readonly accounts: AccountStore; + readonly research: ResearchRules; + readonly equipment: EquipmentCatalogue; + readonly crew: CrewSkillCatalogue; +} + +export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler { + const settlementDeps: BattleSettlementDeps = { + research: ctx.research, + equipment: ctx.equipment, + crew: ctx.crew, + tuning: battle.tuning, + }; + return (context) => withAccount(context, ctx.accounts, (account) => { + const report = context.payload && parseBattleReport(context.payload); + if (!report) return { kind: 'error', code: 'BAD_PARAMS' }; + const session = battle.sessions.findForUser(report.sessionId, account.userId); + if (!session) return { kind: 'error', code: 'BAD_PARAMS' }; + if (session.settled) { + return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) }; + } + const updated = ctx.profiles.update(account.userId, (profile) => { + settleBattle(profile, report, session, settlementDeps); + }); + battle.sessions.markSettled(session.sessionId); + return { kind: 'data', blk: clientProfile(updated, account) }; + }); +} diff --git a/packages/local-service/src/char/actions/hangar-misc-actions.ts b/packages/local-service/src/char/actions/hangar-misc-actions.ts new file mode 100644 index 0000000..73f2ed8 --- /dev/null +++ b/packages/local-service/src/char/actions/hangar-misc-actions.ts @@ -0,0 +1,232 @@ +/** + * Miscellaneous hangar char actions that mutate the player's profile and return the full + * updated clientProfile: + * - GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.37 0xeb5f60, profile mask + * 0x301800822fbf at 0xeb61c4) applies both job type 13 (char_send_blk, 0x2991f0) and job + * type 7 (shop_repair_all 0x29a370 / shop_repair_aircraft 0x29a610) as full profile updates. + * + * Covered actions: + * - cln_set_dest_rp_unit_type (scripts/shop/shop.nut:2353, job type 13) + * - cln_unlock_crew (scripts/crew/crewActions.nut:18, job type 13) + * - cln_prepare_aircraft (scripts/unit/unitActions.nut:147 job 13; 0x29a610 job 7) + * - cln_repair_all (shop_repair_all 0x29a370, job type 7) + * - cln_repair_all_in_slots (shop_repair_all 0x29a370, job type 7) + * - cln_add_to_wish_list (scripts/wishlist/wishlistManager.nut:39, job type 13) + * - cln_remove_from_wish_list (scripts/wishlist/wishlistManager.nut:48, job type 13) + */ +import { findBlock, type BlkBlock } from '@wto/blk'; +import type { AccountStore } from '../../accounts/account-store.ts'; +import { int64Field, removeParam } from '../../profile/blk-fields.ts'; +import { clientProfile } from '../../profile/client-profile.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import { allCrews, crewOf, crewVehiclesOfCountry } from '../../profile/profile-crews.ts'; +import { canAfford, pay } from '../../profile/profile-currency.ts'; +import { applySetDestinationRpRule } from '../../profile/profile-dest-rp.ts'; +import { ownsVehicle } from '../../profile/profile-hangar.ts'; +import { + addWishlistUnit, + DEFAULT_WISHLIST_LIMITS, + removeWishlistUnit, + type WishlistLimits, +} from '../../profile/profile-wishlist.ts'; +import { serverTimeNow, serverTimeToUnixSeconds } from '../../profile/server-time.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../../research/rule-outcome.ts'; +import type { TechTree } from '../../research/tech-tree.ts'; +import type { CharActionContext, CharActionHandler } from '../char-action.ts'; +import { withAccount } from './account-context.ts'; +import { + headerOrPayloadBool, + headerOrPayloadInt, + headerOrPayloadString, + realParam, +} from './payload-params.ts'; + +export type ActionEntry = [string, CharActionHandler]; + +export interface HangarMiscActionDependencies { + readonly profiles: PlayerProfiles; + readonly accounts: AccountStore; + readonly research: ResearchRules; + readonly wishlistLimits?: WishlistLimits; +} + +const HANGAR_BLOCK = 'hangar'; +const ALL_COUNTRIES = 'all'; +const WISHLIST_UNIT_TYPE = 'unit'; +const FULL_VEHICLE_HP = 1.0; + +export function hangarMiscActionEntries(deps: HangarMiscActionDependencies): ActionEntry[] { + const { profiles, accounts, research } = deps; + const { techTree } = research; + const limits = deps.wishlistLimits ?? DEFAULT_WISHLIST_LIMITS; + return [ + ['cln_set_dest_rp_unit_type', setDestRpUnitTypeAction(profiles, accounts, techTree)], + ['cln_unlock_crew', unlockCrewAction(profiles, accounts)], + ['cln_prepare_aircraft', prepareAircraftAction(profiles, accounts)], + ['cln_repair_all', repairVehiclesAction(profiles, accounts, techTree, false)], + ['cln_repair_all_in_slots', repairVehiclesAction(profiles, accounts, techTree, true)], + ['cln_add_to_wish_list', addToWishlistAction(profiles, accounts, techTree, limits)], + ['cln_remove_from_wish_list', removeFromWishlistAction(profiles, accounts)], + ]; +} + +function runProfileRule( + context: CharActionContext, + profiles: PlayerProfiles, + accounts: AccountStore, + rule: (profile: BlkBlock) => RuleOutcome, +) { + return withAccount(context, accounts, (account) => { + let outcome: RuleOutcome = refused('BAD_PARAMS'); + const updated = profiles.updateWhen(account.userId, (saved) => { + outcome = rule(saved); + return outcome.ok; + }); + if (updated) return { kind: 'data', blk: clientProfile(updated, account) }; + return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal }; + }); +} + +function setDestRpUnitTypeAction(profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree): CharActionHandler { + return (context) => { + const country = headerOrPayloadString(context, 'country'); + const srcType = headerOrPayloadInt(context, 'srcType'); + const destType = headerOrPayloadInt(context, 'destType'); + if (!country || srcType === undefined || destType === undefined) return { kind: 'error', code: 'BAD_PARAMS' }; + return runProfileRule(context, profiles, accounts, (saved) => + applySetDestinationRpRule(saved, techTree, country, srcType, destType)); + }; +} + +function unlockCrewAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return (context) => { + const crewId = headerOrPayloadInt(context, 'crew'); + const byGold = headerOrPayloadBool(context, 'gold') ?? false; + const cost = headerOrPayloadInt(context, 'cost') ?? 0; + const costGold = headerOrPayloadInt(context, 'costGold') ?? 0; + if (crewId === undefined || crewId < 0 || cost < 0 || costGold < 0) return { kind: 'error', code: 'BAD_PARAMS' }; + + return runProfileRule(context, profiles, accounts, (saved) => { + const crew = crewOf(saved, crewId); + if (!crew) return refused('BAD_PARAMS'); + const nowSec = BigInt(serverTimeToUnixSeconds(serverTimeNow())); + const lockedTill = int64Field(crew, 'lockedTill', 0n); + if (lockedTill > nowSec) { + const price = { silverLions: byGold ? 0 : cost, goldenEagles: byGold ? costGold : 0 }; + if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY'); + pay(saved, price); + } + // Crew lock state in profile.blk (aces.exe 0x8fa632, 0x93ae07..0x93ae1b): lockedTill:i64, lockedRoomId:i64. + removeParam(crew, 'lockedTill'); + removeParam(crew, 'lockedRoomId'); + return ACCEPTED; + }); + }; +} + +function prepareAircraftAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return (context) => { + const unit = headerOrPayloadString(context, 'name') ?? headerOrPayloadString(context, 'aircraft'); + const cost = headerOrPayloadInt(context, 'cost') ?? 0; + const costGold = headerOrPayloadInt(context, 'costGold') ?? 0; + if (!unit || cost < 0 || costGold < 0) return { kind: 'error', code: 'BAD_PARAMS' }; + + return runProfileRule(context, profiles, accounts, (saved) => { + if (!ownsVehicle(saved, unit)) return refused('NOT_AVAILABLE'); + const hangar = findBlock(saved, HANGAR_BLOCK); + const unitBlock = hangar && findBlock(hangar, unit); + if (unitBlock && isDamagedVehicleBlock(unitBlock) && (cost > 0 || costGold > 0)) { + const price = { silverLions: cost, goldenEagles: costGold }; + if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY'); + pay(saved, price); + } + if (unitBlock) clearVehicleDamage(unitBlock); + return ACCEPTED; + }); + }; +} + +function repairVehiclesAction( + profiles: PlayerProfiles, + accounts: AccountStore, + techTree: TechTree, + inSlotsOnly: boolean, +): CharActionHandler { + return (context) => { + const rawCountry = headerOrPayloadString(context, 'country'); + const country = rawCountry && rawCountry.length > 0 ? rawCountry : ALL_COUNTRIES; + if (country !== ALL_COUNTRIES && !techTree.hasCountry(country)) return { kind: 'error', code: 'BAD_PARAMS' }; + + return runProfileRule(context, profiles, accounts, (saved) => { + const hangar = findBlock(saved, HANGAR_BLOCK); + if (!hangar) return ACCEPTED; + const targets = collectRepairTargetUnits(saved, hangar, techTree, country, inSlotsOnly); + for (const unitBlock of hangar.blocks) { + if (targets.has(unitBlock.name)) clearVehicleDamage(unitBlock); + } + return ACCEPTED; + }); + }; +} + +function collectRepairTargetUnits( + profile: BlkBlock, + hangar: BlkBlock, + techTree: TechTree, + country: string, + inSlotsOnly: boolean, +): Set { + if (inSlotsOnly) { + if (country !== ALL_COUNTRIES) return new Set(crewVehiclesOfCountry(profile, country)); + const slotted = new Set(); + for (const crew of allCrews(profile)) { + const current = findBlock(crew, 'aircrafts')?.params.find((param) => param.name === 'current')?.value; + if (current?.type === 'string' && current.value.length > 0) slotted.add(current.value); + } + return slotted; + } + if (country === ALL_COUNTRIES) return new Set(hangar.blocks.map((entry) => entry.name)); + return new Set( + hangar.blocks + .filter((entry) => techTree.vehicle(entry.name)?.country === country) + .map((entry) => entry.name), + ); +} + +/** AircraftInfo::serialize (aces.exe 0x94061f..0x940abc): hp:r (default 1.0f) and time:i64. */ +function isDamagedVehicleBlock(unitBlock: BlkBlock): boolean { + const hp = realParam(unitBlock, 'hp'); + return hp !== undefined && hp < FULL_VEHICLE_HP; +} + +function clearVehicleDamage(unitBlock: BlkBlock): void { + removeParam(unitBlock, 'hp'); + removeParam(unitBlock, 'time'); +} + +function addToWishlistAction( + profiles: PlayerProfiles, + accounts: AccountStore, + techTree: TechTree, + limits: WishlistLimits, +): CharActionHandler { + return (context) => { + const itemType = headerOrPayloadString(context, 'type') ?? WISHLIST_UNIT_TYPE; + const unit = headerOrPayloadString(context, 'unit'); + const comment = headerOrPayloadString(context, 'comment') ?? ''; + if (itemType !== WISHLIST_UNIT_TYPE || !unit) return { kind: 'error', code: 'BAD_PARAMS' }; + const nowSec = serverTimeToUnixSeconds(serverTimeNow()); + return runProfileRule(context, profiles, accounts, (saved) => + addWishlistUnit(saved, techTree, unit, comment, nowSec, limits)); + }; +} + +function removeFromWishlistAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return (context) => { + const itemType = headerOrPayloadString(context, 'type') ?? WISHLIST_UNIT_TYPE; + const unit = headerOrPayloadString(context, 'unit'); + if (itemType !== WISHLIST_UNIT_TYPE || !unit) return { kind: 'error', code: 'BAD_PARAMS' }; + return runProfileRule(context, profiles, accounts, (saved) => removeWishlistUnit(saved, unit)); + }; +} diff --git a/packages/local-service/src/char/actions/payload-params.ts b/packages/local-service/src/char/actions/payload-params.ts index 631c382..4e2a564 100644 --- a/packages/local-service/src/char/actions/payload-params.ts +++ b/packages/local-service/src/char/actions/payload-params.ts @@ -12,6 +12,14 @@ export function intParam(payload: BlkBlock, name: string): number | undefined { return param?.type === 'int' ? param.value : undefined; } +export function realParam(payload: BlkBlock, name: string): number | undefined { + const param = findParam(payload, name)?.value; + if (param?.type === 'real' || param?.type === 'int') { + return Number.isFinite(param.value) ? param.value : undefined; + } + return undefined; +} + export function boolParam(payload: BlkBlock, name: string): boolean | undefined { const param = findParam(payload, name)?.value; return param?.type === 'bool' ? param.value : undefined; diff --git a/packages/local-service/src/char/actions/price-table.ts b/packages/local-service/src/char/actions/price-table.ts index 2039063..84ffb7a 100644 --- a/packages/local-service/src/char/actions/price-table.ts +++ b/packages/local-service/src/char/actions/price-table.ts @@ -1,6 +1,5 @@ /** - * The price table the char server sends for cln_get_price_ex (implementation notes, - * implementation notes). + * The price table the char server sends for cln_get_price_ex. * * The client keeps the answer whole as its price table (aces.exe 2.61.0.37 0xeb7a88, job type * 0x21; stored in the save-data object at +0x3f5c0, which warpoints::init makes the price @@ -16,6 +15,7 @@ * mods{ { cost:i costGold:i openCostGold:i } } * weapons{ { cost:i costGold:i } } * spare{ cost:i costGold:i } + * specialization{ spec_expert{ cost:i } spec_ace{ costGold:i } } * } * } * skins{ "/"{ cost:i costGold:i } } decorations (get_skin_cost_*, 0x17a8910...) @@ -24,7 +24,7 @@ * skills{ { costGold:i } } skill point packs (0x916380) * unlocks{ { cost:i costGold:i } } unlocks for sale (0x9170c0) * items{ { cost:i costGold:i } } classic items for sale, price per piece - * (wp_get_item_cost, 0x10531e0; implementation notes) + * (wp_get_item_cost, 0x10531e0) * trophy{ { cost:i costGold:i } } classic trophy prices * } * trophy{ { ... } } classic trophy definitions & drop weights @@ -32,8 +32,8 @@ * Every entry is read as cost:i (silver lions), costGold:i (golden eagles), discount:i (percent * off, not sent: no discounts), each 0 when missing (so zero prices are left out); openCostGold * is the outright price of a modification before research progress (0xec0910). Anything the - * lookup does not find costs 0 for the client, which then offers it at 0 (lab round 20). The - * prices are config/wpcost.blk value and costGold (decorations: config/skins.blk, decals.blk, + * lookup does not find costs 0 for the client, which then offers it at 0. The prices are + * config/wpcost.blk value and costGold (decorations: config/skins.blk, decals.blk, * attachable.blk; unlocks: config/unlocks.blk), the same the purchase rules charge. */ import type { BlkBlock, BlkParam } from '@wto/blk'; @@ -67,7 +67,7 @@ export function priceTable(sources: PriceTableSources): BlkBlock { name: COMMON_SECTION, params: [], blocks: [ - vehicleSection(sources.techTree, sources.equipment), + vehicleSection(sources.techTree, sources.equipment, sources.crew), ...decorSections(sources.decor), skillPackSection(sources.crew), unlockSection(sources.unlocks), @@ -80,7 +80,7 @@ export function priceTable(sources: PriceTableSources): BlkBlock { }; } -function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue): BlkBlock { +function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue, crew: CrewSkillCatalogue): BlkBlock { const vehicles: BlkBlock[] = []; for (const vehicle of techTree.all()) { const entry: BlkBlock = { name: vehicle.name, params: priceParams(vehicle.silverLions, vehicle.goldenEagles), blocks: [] }; @@ -97,6 +97,13 @@ function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue): BlkB if (weapons.length) entry.blocks.push({ name: 'weapons', params: [], blocks: weapons }); if (fitted.spare) entry.blocks.push({ name: 'spare', params: priceParams(fitted.spare.silverLions, fitted.spare.goldenEagles), blocks: [] }); } + const training = crew.training(vehicle.name); + if (training && (training.expert > 0 || training.aceGoldenEagles > 0)) { + const specBlocks: BlkBlock[] = []; + if (training.expert > 0) specBlocks.push({ name: 'spec_expert', params: priceParams(training.expert, 0), blocks: [] }); + if (training.aceGoldenEagles > 0) specBlocks.push({ name: 'spec_ace', params: priceParams(0, training.aceGoldenEagles), blocks: [] }); + entry.blocks.push({ name: 'specialization', params: [], blocks: specBlocks }); + } if (entry.blocks.length || vehicle.silverLions > 0 || vehicle.goldenEagles > 0) vehicles.push(entry); } return { name: 'aircrafts', params: [], blocks: vehicles }; diff --git a/packages/local-service/src/char/actions/research-actions.ts b/packages/local-service/src/char/actions/research-actions.ts index 9925366..a72fc0d 100644 --- a/packages/local-service/src/char/actions/research-actions.ts +++ b/packages/local-service/src/char/actions/research-actions.ts @@ -1,25 +1,18 @@ /** - * Research actions. All are sent with char_send_blk (job type 13), - * so the client applies each answer as a profile update and each answers the whole profile. + * Vehicle and modification research char actions. Sent via `char_send_blk` (job type 13), + * each updates the profile and answers the updated client profile: * - * cln_set_researchable (shop_set_researchable_unit, aces.exe 2.61.0.37 0x17a3e80): - * unit:t the vehicle to research - * type:i its vehicle type number - * or, for a modification (shop_set_researchable_unit_module, 0x17a3e00; implementation notes): - * unit:t the owned vehicle - * mod:t the modification to research - * cln_reset_researchable (shop_reset_researchable_unit, 0x17a3f00): the player closed the - * "research finished" prompt without choosing. - * country:t, type:i - * cln_convert_exp (shop_convert_free_exp_for_unit, 0x17a4ec0): free research points into a - * vehicle, paid with golden eagles. - * unit:t, amount:i research points + * - `cln_set_researchable` (`shop_set_researchable_unit` `0x17a3e80` / + * `shop_set_researchable_unit_module` `0x17a3e00`): `unit:t, type:i` or `unit:t, mod:t`. + * - `cln_reset_researchable` (`shop_reset_researchable_unit` `0x17a3f00`): `country:t, type:i`. + * - `cln_convert_exp` (`shop_convert_free_exp_for_unit` `0x17a4ec0`): `unit:t, amount:i`. + * - `cln_move_exp_to_unit` / `cln_move_exp_to_module`: spend banked excess RP. */ import type { AccountStore } from '../../accounts/account-store.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; -import { chooseModuleResearch } from '../../modifications/module-research-target.ts'; +import { chooseModuleResearch, moveExcessExpToModule } from '../../modifications/module-research-target.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; -import { chooseResearchTarget, convertFreeResearchPoints, dismissFinishedResearch } from '../../research/research-progress.ts'; +import { chooseResearchTarget, convertFreeResearchPoints, dismissFinishedResearch, moveExcessExpToUnit } from '../../research/research-progress.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; import type { CharActionHandler } from '../char-action.ts'; import { intParam, stringParam } from './payload-params.ts'; @@ -58,3 +51,24 @@ export function convertExp(profiles: PlayerProfiles, accounts: AccountStore, rul return (profile) => convertFreeResearchPoints(profile, rules, vehicle, amount); }); } + +export function moveExpToUnitAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const vehicle = stringParam(payload, 'unit'); + if (vehicle === undefined) return undefined; + return (profile) => moveExcessExpToUnit(profile, rules, vehicle); + }); +} + +export function moveExpToModuleAction( + profiles: PlayerProfiles, + accounts: AccountStore, + equipment: EquipmentCatalogue, +): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const vehicle = stringParam(payload, 'unit'); + const modification = stringParam(payload, 'mod'); + if (vehicle === undefined || modification === undefined) return undefined; + return (profile) => moveExcessExpToModule(profile, equipment, vehicle, modification); + }); +} diff --git a/packages/local-service/src/chat/irc-protocol.ts b/packages/local-service/src/chat/irc-protocol.ts new file mode 100644 index 0000000..d57446c --- /dev/null +++ b/packages/local-service/src/chat/irc-protocol.ts @@ -0,0 +1,88 @@ +/** + * RFC 1459 + Gaijin IRC wire parser and line formatters used by the local chat server. + */ + +export const IRC_SERVER_HOST = 'wt.local'; + +export interface IrcCommand { + readonly verb: string; + readonly params: readonly string[]; +} + +const HANDSHAKE_PREFIX = /^(?:PASS |NICK |USER |CAP |PING |QUIT(?: |\r|\n|$))/i; + +export function startsIrcHandshake(firstChunk: Buffer): boolean { + if (firstChunk.length < 4) return false; + const head = firstChunk.subarray(0, Math.min(firstChunk.length, 16)).toString('latin1'); + return HANDSHAKE_PREFIX.test(head); +} + +export function parseIrcLine(rawLine: string): IrcCommand | undefined { + let rest = rawLine.replace(/[\r\n]+$/, ''); + if (rest.length === 0) return undefined; + if (rest.startsWith(':')) { + const space = rest.indexOf(' '); + if (space < 0) return undefined; + rest = rest.slice(space + 1).trimStart(); + } + if (rest.length === 0) return undefined; + + const verbEnd = rest.indexOf(' '); + if (verbEnd < 0) { + return { verb: rest.toUpperCase(), params: [] }; + } + const verb = rest.slice(0, verbEnd).toUpperCase(); + let cursor = rest.slice(verbEnd + 1); + const params: string[] = []; + while (cursor.length > 0) { + while (cursor.startsWith(' ')) cursor = cursor.slice(1); + if (cursor.length === 0) break; + if (cursor.startsWith(':')) { + params.push(cursor.slice(1)); + break; + } + const nextSpace = cursor.indexOf(' '); + if (nextSpace < 0) { + params.push(cursor); + break; + } + params.push(cursor.slice(0, nextSpace)); + cursor = cursor.slice(nextSpace + 1); + } + return { verb, params }; +} + +export function formatServerNumeric(code: string, nick: string, params: readonly string[], trailing?: string): string { + const target = sanitizeToken(nick || '*'); + const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : ''; + const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : ''; + return `:${IRC_SERVER_HOST} ${code} ${target}${middle}${suffix}\r\n`; +} + +export function formatServerCommand(verb: string, params: readonly string[], trailing?: string): string { + const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : ''; + const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : ''; + return `:${IRC_SERVER_HOST} ${verb}${middle}${suffix}\r\n`; +} + +export function formatUserEvent(nick: string, user: string, verb: string, params: readonly string[], trailing?: string): string { + const safeNick = sanitizeToken(nick || 'Player'); + const safeUser = sanitizeToken(user || '0'); + const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : ''; + const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : ''; + return `:${safeNick}!${safeUser}@127.0.0.1 ${verb}${middle}${suffix}\r\n`; +} + +export function sanitizeChannelName(raw: string): string { + const trimmed = sanitizeToken(raw); + if (trimmed.length === 0) return '#general'; + return trimmed.startsWith('#') || trimmed.startsWith('&') ? trimmed : `#${trimmed}`; +} + +function sanitizeToken(text: string): string { + return text.replace(/[\r\n\0 ]+/g, ''); +} + +function sanitizeTrailing(text: string): string { + return text.replace(/[\r\n\0]+/g, ' '); +} diff --git a/packages/local-service/src/chat/irc-server.ts b/packages/local-service/src/chat/irc-server.ts new file mode 100644 index 0000000..432cfe3 --- /dev/null +++ b/packages/local-service/src/chat/irc-server.ts @@ -0,0 +1,284 @@ +/** + * In-process RFC 1459 + Gaijin IRC chat server (`IRCClient` in `aces.exe` 0x133c5e0). + * + * Serves hangar general rooms, custom player rooms, discussion threads (`XTJOIN` / `XTMETA`), + * private messages, and session presence so `gchat_is_connected()` and `gchat_is_enabled()` + * evaluate `true` natively in both hangar and battle. + */ +import type { Duplex } from 'node:stream'; +import { + formatServerCommand, + formatServerNumeric, + formatUserEvent, + IRC_SERVER_HOST, + parseIrcLine, + sanitizeChannelName, + type IrcCommand, +} from './irc-protocol.ts'; + +interface IrcSession { + readonly socket: Duplex; + nick: string; + user: string; + realName: string; + registered: boolean; + buffer: string; + readonly channels: Set; +} + +interface IrcChannel { + readonly name: string; + topic: string; + readonly members: Set; +} + +const MAX_BUFFER_CHARS = 65_536; + +export class IrcServer { + readonly #sessions = new Set(); + readonly #channels = new Map(); + #nextThreadId = 1; + + accept(socket: Duplex): void { + const session: IrcSession = { + socket, nick: '', user: '', realName: '', registered: false, buffer: '', channels: new Set(), + }; + this.#sessions.add(session); + + socket.on('data', (chunk: Buffer | string) => { + session.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8'); + if (session.buffer.length > MAX_BUFFER_CHARS) { + socket.destroy(); + return; + } + let nl = session.buffer.indexOf('\n'); + while (nl >= 0) { + const rawLine = session.buffer.slice(0, nl); + session.buffer = session.buffer.slice(nl + 1); + const cmd = parseIrcLine(rawLine); + if (cmd) this.#handleCommand(session, cmd); + nl = session.buffer.indexOf('\n'); + } + }); + socket.once('close', () => this.#removeSession(session, 'Client disconnected')); + socket.once('error', () => socket.destroy()); + } + + #handleCommand(session: IrcSession, cmd: IrcCommand): void { + const [p0 = '', p1 = ''] = cmd.params; + switch (cmd.verb) { + case 'CAP': if (p0.toUpperCase() === 'LS') this.#send(session, formatServerCommand('CAP', ['*', 'LS'], '')); return; + case 'PASS': + case 'PONG': return; + case 'NICK': this.#handleNick(session, p0); return; + case 'USER': + session.user = p0 || '0'; + session.realName = cmd.params[3] ?? session.user; + this.#tryCompleteRegistration(session); + return; + case 'PING': this.#send(session, formatServerCommand('PONG', [IRC_SERVER_HOST], p0 || IRC_SERVER_HOST)); return; + case 'JOIN': this.#handleJoin(session, p0); return; + case 'PART': this.#handlePart(session, p0, p1); return; + case 'PRIVMSG': + case 'NOTICE': this.#handleMessage(session, cmd.verb, p0, p1); return; + case 'NAMES': this.#sendNames(session, sanitizeChannelName(p0 || '#general')); return; + case 'LIST': this.#handleList(session); return; + case 'TOPIC': this.#handleTopic(session, cmd.params); return; + case 'MODE': this.#handleMode(session, p0); return; + case 'WHO': this.#handleWho(session, p0); return; + case 'WHOIS': this.#handleWhois(session, p0); return; + case 'XTJOIN': this.#handleXtJoin(session, cmd.params); return; + case 'XTMETA': this.#handleXtMeta(session, cmd.params); return; + case 'QUIT': + this.#removeSession(session, p0 || 'Quit'); + session.socket.end(); + return; + default: return; + } + } + + #handleNick(session: IrcSession, rawNick: string): void { + const nextNick = rawNick.trim() || `Player${this.#sessions.size}`; + const prevNick = session.nick; + session.nick = nextNick; + if (session.registered && prevNick && prevNick !== nextNick) { + this.#send(session, formatUserEvent(prevNick, session.user, 'NICK', [], nextNick)); + return; + } + this.#tryCompleteRegistration(session); + } + + #tryCompleteRegistration(session: IrcSession): void { + if (session.registered || !session.nick || !session.user) return; + session.registered = true; + const { nick, user } = session; + this.#send(session, formatServerNumeric('001', nick, [], `Welcome to the War Thunder Local Chat Network ${nick}!${user}@127.0.0.1`)); + this.#send(session, formatServerNumeric('002', nick, [], `Your host is ${IRC_SERVER_HOST}, running version 1.0`)); + this.#send(session, formatServerNumeric('003', nick, [], 'This server was created locally')); + this.#send(session, formatServerNumeric('004', nick, [IRC_SERVER_HOST, '1.0', 'iow', 'ntov'])); + this.#send(session, formatServerNumeric('375', nick, [], `- ${IRC_SERVER_HOST} Message of the Day -`)); + this.#send(session, formatServerNumeric('372', nick, [], '- Local offline chat service active')); + this.#send(session, formatServerNumeric('376', nick, [], 'End of /MOTD command.')); + } + + #handleJoin(session: IrcSession, rawTargets: string): void { + if (!rawTargets) return; + if (rawTargets === '0') { + for (const chan of [...session.channels]) this.#partOne(session, chan, ''); + return; + } + for (const raw of rawTargets.split(',')) { + if (!raw.trim()) continue; + this.#joinChannel(session, sanitizeChannelName(raw), ''); + } + } + + #joinChannel(session: IrcSession, channelName: string, initialTopic: string): void { + let channel = this.#channels.get(channelName); + if (!channel) { + channel = { name: channelName, topic: initialTopic, members: new Set() }; + this.#channels.set(channelName, channel); + } else if (initialTopic && !channel.topic) { + channel.topic = initialTopic; + } + channel.members.add(session); + session.channels.add(channelName); + + const joinLine = formatUserEvent(session.nick, session.user, 'JOIN', [], channelName); + for (const member of channel.members) this.#send(member, joinLine); + if (channel.topic) { + this.#send(session, formatServerNumeric('332', session.nick, [channelName], channel.topic)); + } else { + this.#send(session, formatServerNumeric('331', session.nick, [channelName], 'No topic is set')); + } + this.#sendNames(session, channelName); + } + + #handlePart(session: IrcSession, rawTargets: string, reason: string): void { + for (const raw of rawTargets.split(',')) { + if (!raw.trim()) continue; + this.#partOne(session, sanitizeChannelName(raw), reason); + } + } + + #partOne(session: IrcSession, channelName: string, reason: string): void { + const channel = this.#channels.get(channelName); + if (!channel || !channel.members.has(session)) return; + const partLine = formatUserEvent(session.nick, session.user, 'PART', [channelName], reason || undefined); + for (const member of channel.members) this.#send(member, partLine); + channel.members.delete(session); + session.channels.delete(channelName); + if (channel.members.size === 0) this.#channels.delete(channelName); + } + + #handleMessage(session: IrcSession, verb: 'PRIVMSG' | 'NOTICE', target: string, text: string): void { + if (!target) return; + if (target.startsWith('#') || target.startsWith('&')) { + const channel = this.#channels.get(sanitizeChannelName(target)); + if (!channel) { + if (verb === 'PRIVMSG') this.#send(session, formatServerNumeric('403', session.nick, [target], 'No such channel')); + return; + } + const line = formatUserEvent(session.nick, session.user, verb, [channel.name], text); + for (const member of channel.members) { + if (member !== session) this.#send(member, line); + } + return; + } + const recipient = [...this.#sessions].find((peer) => peer.registered && peer.nick === target); + if (!recipient) { + if (verb === 'PRIVMSG') this.#send(session, formatServerNumeric('401', session.nick, [target], 'No such nick/channel')); + return; + } + this.#send(recipient, formatUserEvent(session.nick, session.user, verb, [recipient.nick], text)); + } + + #sendNames(session: IrcSession, channelName: string): void { + const channel = this.#channels.get(channelName); + const nicks = channel ? [...channel.members].map((m) => m.nick).filter(Boolean).join(' ') : session.nick; + this.#send(session, formatServerNumeric('353', session.nick, ['=', channelName], nicks)); + this.#send(session, formatServerNumeric('366', session.nick, [channelName], 'End of /NAMES list.')); + } + + #handleList(session: IrcSession): void { + this.#send(session, formatServerNumeric('321', session.nick, ['Channel'], 'Users Name')); + for (const channel of this.#channels.values()) { + if (channel.name === '#___empty___') continue; + this.#send(session, formatServerNumeric('322', session.nick, [channel.name, String(channel.members.size)], channel.topic)); + } + this.#send(session, formatServerNumeric('323', session.nick, [], 'End of /LIST')); + } + + #handleTopic(session: IrcSession, params: readonly string[]): void { + const channelName = sanitizeChannelName(params[0] ?? ''); + const channel = this.#channels.get(channelName); + if (!channel) { + this.#send(session, formatServerNumeric('403', session.nick, [channelName], 'No such channel')); + return; + } + if (params.length >= 2) { + channel.topic = params[1] ?? ''; + const line = formatUserEvent(session.nick, session.user, 'TOPIC', [channelName], channel.topic); + for (const member of channel.members) this.#send(member, line); + return; + } + if (channel.topic) this.#send(session, formatServerNumeric('332', session.nick, [channelName], channel.topic)); + else this.#send(session, formatServerNumeric('331', session.nick, [channelName], 'No topic is set')); + } + + #handleMode(session: IrcSession, target: string): void { + if (target.startsWith('#') || target.startsWith('&')) { + this.#send(session, formatServerNumeric('324', session.nick, [sanitizeChannelName(target), '+nt'])); + } else this.#send(session, formatServerNumeric('221', session.nick, ['+i'])); + } + + #handleWho(session: IrcSession, target: string): void { + const channel = target.startsWith('#') ? this.#channels.get(sanitizeChannelName(target)) : undefined; + for (const m of channel?.members ?? []) { + this.#send(session, formatServerNumeric('352', session.nick, [channel!.name, m.user, '127.0.0.1', IRC_SERVER_HOST, m.nick, 'H'], `0 ${m.realName}`)); + } + this.#send(session, formatServerNumeric('315', session.nick, [target || '*'], 'End of /WHO list.')); + } + + #handleWhois(session: IrcSession, targetNick: string): void { + const found = [...this.#sessions].find((peer) => peer.nick === targetNick); + if (found) this.#send(session, formatServerNumeric('311', session.nick, [found.nick, found.user, '127.0.0.1', '*'], found.realName)); + this.#send(session, formatServerNumeric('318', session.nick, [targetNick || '*'], 'End of /WHOIS list.')); + } + + #handleXtJoin(session: IrcSession, params: readonly string[]): void { + this.#joinChannel(session, `#___xthread_${this.#nextThreadId++}`, params[1] ?? params[0] ?? 'Discussion'); + } + + #handleXtMeta(session: IrcSession, params: readonly string[]): void { + const channelName = sanitizeChannelName(params[0] ?? ''); + const channel = this.#channels.get(channelName); + if (!channel || params[1]?.toLowerCase() !== 'topic') return; + channel.topic = params[2] ?? ''; + const line = formatUserEvent(session.nick, session.user, 'TOPIC', [channelName], channel.topic); + for (const member of channel.members) this.#send(member, line); + } + + #removeSession(session: IrcSession, reason: string): void { + if (!this.#sessions.delete(session)) return; + const quitLine = session.registered ? formatUserEvent(session.nick, session.user, 'QUIT', [], reason) : ''; + const notified = new Set(); + for (const channelName of session.channels) { + const channel = this.#channels.get(channelName); + if (!channel) continue; + channel.members.delete(session); + for (const peer of quitLine ? channel.members : []) { + if (!notified.has(peer)) { + notified.add(peer); + this.#send(peer, quitLine); + } + } + if (channel.members.size === 0) this.#channels.delete(channelName); + } + session.channels.clear(); + } + + #send(session: IrcSession, line: string): void { + if (!session.socket.destroyed && session.socket.writable) session.socket.write(line); + } +} diff --git a/packages/local-service/src/cloud-settings/cloud-settings-store.ts b/packages/local-service/src/cloud-settings/cloud-settings-store.ts index 45f7c12..8603437 100644 --- a/packages/local-service/src/cloud-settings/cloud-settings-store.ts +++ b/packages/local-service/src/cloud-settings/cloud-settings-store.ts @@ -1,9 +1,15 @@ /** - * Per-player cloud settings persistence inside `/saves//cloud-settings/` - *. Keeping cloud settings inside each player's save directory means - * copying `saves//` to another machine or fresh client folder carries all game - * options, keybinds, HUD settings, presets, and map preferences along automatically. + * Per-player cloud settings persistence inside `/saves//cloud-settings/`. + * Keeping cloud settings inside each player's save directory means copying `saves//` + * to another machine or fresh client folder carries all game options, keybinds, HUD settings, + * presets, and map preferences along automatically. + * + * When an account has no saved `GBT_GENERAL_SETTINGS.blk` yet, version 1 is seeded once with + * `hudShowFuel = 2` and `hudShowAmmo = 2` ("Always", `aces.exe` 0xf4cc1f..0xf4cc55) so the + * top-left ground/air weapon and fuel HUD indicators are visible out of the box without + * overriding any subsequent change the player makes in the in-game Options menu. */ +import { createHash } from 'node:crypto'; import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, setParam, type BlkBlock } from '@wto/blk'; @@ -27,6 +33,7 @@ export const GENERAL_BLK_TYPES = [ export const SUPPORTED_CLOUD_COMPRESSIONS = 'zstd;zlib;gzip'; const SUPPORTED_BLK_TYPE_SET: ReadonlySet = new Set(GENERAL_BLK_TYPES); +const HUD_SHOW_ALWAYS = 2; export interface ParsedGblkUpload { readonly blkType: string; @@ -54,6 +61,7 @@ export class CloudSettingsStore { } buildMetaBlk(userId?: string, blockName?: string): BlkBlock { + if (userId && isValidUserId(userId)) this.#ensureDefaultGeneralSettings(userId); const meta = blockName ? emptyBlock(blockName) : emptyBlock(); setParam(meta, 'machineHash', { type: 'string', value: `hhh${userId ?? '0'}` }); setParam(meta, 'compressionSupported', { type: 'string', value: SUPPORTED_CLOUD_COMPRESSIONS }); @@ -78,6 +86,7 @@ export class CloudSettingsStore { loadContainer(userId: string, blkType: string): BlkBlock | undefined { if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined; + if (blkType === 'GBT_GENERAL_SETTINGS') this.#ensureDefaultGeneralSettings(userId); const blkPath = this.#blkPath(userId, blkType); if (!existsSync(blkPath)) return undefined; try { @@ -111,6 +120,18 @@ export class CloudSettingsStore { return savedCount; } + #ensureDefaultGeneralSettings(userId: string): void { + const blkPath = this.#blkPath(userId, 'GBT_GENERAL_SETTINGS'); + if (existsSync(blkPath)) return; + const { container, contentHash } = buildDefaultGeneralSettings(); + this.saveUpload(userId, { + blkType: 'GBT_GENERAL_SETTINGS', + version: 1, + contentHash, + container, + }); + } + #loadMeta(userId: string): CloudSettingsMetaFile { const metaPath = this.#metaPath(userId); if (!existsSync(metaPath)) return { formatVersion: 1, blocks: {} }; @@ -138,6 +159,24 @@ export class CloudSettingsStore { } } +function buildDefaultGeneralSettings(): { readonly container: BlkBlock; readonly contentHash: string } { + const content = emptyBlock('content'); + const profile = ensureBlock(content, 'profile'); + const settings = ensureBlock(profile, 'settings'); + setParam(settings, 'hudShowFuel', { type: 'int', value: HUD_SHOW_ALWAYS }); + setParam(settings, 'hudShowAmmo', { type: 'int', value: HUD_SHOW_ALWAYS }); + + const hashRoot = emptyBlock(); + hashRoot.params.push(...content.params); + hashRoot.blocks.push(...content.blocks); + const contentHash = createHash('md5').update(encodeBlk(hashRoot)).digest('hex'); + + const container = emptyBlock(); + setParam(container, 'version', { type: 'int', value: 1 }); + container.blocks.push(content); + return { container, contentHash }; +} + function isValidUserId(userId: string): boolean { return /^\d+$/.test(userId); } diff --git a/packages/local-service/src/crew/crew-skill-rules.ts b/packages/local-service/src/crew/crew-skill-rules.ts index b3fa43a..72de651 100644 --- a/packages/local-service/src/crew/crew-skill-rules.ts +++ b/packages/local-service/src/crew/crew-skill-rules.ts @@ -1,5 +1,5 @@ /** - * Crew skill upgrades, skill point packs and specializations. + * Crew skill upgrades, skill point packs and specializations: * * cln_upgrade_crew raise skills: { :i=levels to add } id:i * cost = sum of the per-level costs of the new levels @@ -7,12 +7,21 @@ * cln_purchase_skill_points id:i pack:t: warpoints.blk crewSkillPointsCost, golden eagles * cln_specialize_crew id:i aircraft:t: one step up for a trained vehicle, * expert (wpcost.blk train2Cost, silver lions) then - * ace (train3Cost_gold, golden eagles) + * ace (train3Cost_gold discounted by expert_to_ace_cost_reduce) */ import type { BlkBlock } from '@wto/blk'; -import type { CrewSkillData, CrewTrainingPrices, SkillFacts, SkillPointPack } from '../game-data/datasets/crew-skills.ts'; +import type { AceDiscountStage, CrewSkillData, CrewTrainingPrices, SkillFacts, SkillPointPack } from '../game-data/datasets/crew-skills.ts'; import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; -import { addSkillPoints, isTrainedFor, setSkillLevel, setSpecialization, skillLevel, skillPoints, specializationOf } from '../profile/profile-crew-skills.ts'; +import { + addSkillPoints, + expertToAceRp, + isTrainedFor, + setSkillLevel, + setSpecialization, + skillLevel, + skillPoints, + specializationOf, +} from '../profile/profile-crew-skills.ts'; import { crewOf } from '../profile/profile-crews.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; @@ -22,11 +31,13 @@ export class CrewSkillCatalogue { readonly #skills = new Map(); readonly #packs: ReadonlyMap; readonly #training: ReadonlyMap; + readonly #aceDiscountStages: readonly AceDiscountStage[]; constructor(data: CrewSkillData) { for (const page of data.pages) for (const skill of page.skills) this.#skills.set(`${page.name}/${skill.name}`, skill); this.#packs = new Map(data.packs.map((pack) => [pack.name, pack])); this.#training = new Map(data.training.map((prices) => [prices.vehicle, prices])); + this.#aceDiscountStages = data.aceDiscountStages; } skill(page: string, skill: string): SkillFacts | undefined { @@ -44,6 +55,21 @@ export class CrewSkillCatalogue { training(vehicle: string): CrewTrainingPrices | undefined { return this.#training.get(vehicle); } + + aceGoldenEaglesPrice(vehicle: string, earnedAceRp: number): number { + const prices = this.#training.get(vehicle); + if (!prices) return 0; + const baseGold = Math.max(0, prices.aceGoldenEagles); + const targetRp = prices.aceResearchPoints; + if (baseGold === 0 || targetRp <= 0 || earnedAceRp <= 0) return baseGold; + if (earnedAceRp >= targetRp) return 0; + const progressPercent = Math.floor((earnedAceRp * 100) / targetRp); + let discount = 0; + for (const stage of this.#aceDiscountStages) { + if (progressPercent >= stage.percent && stage.discount > discount) discount = stage.discount; + } + return Math.max(0, baseGold - Math.floor((baseGold * discount) / 100)); + } } export interface SkillRaise { @@ -89,7 +115,9 @@ export function specializeCrew(profile: BlkBlock, catalogue: CrewSkillCatalogue, if (!crew || !prices || !isTrainedFor(crew, vehicle)) return refused('BAD_PARAMS'); const spec = specializationOf(crew, vehicle); if (spec >= ACE) return refused('NOT_AVAILABLE'); - const price: Price = spec === 0 ? { silverLions: prices.expert, goldenEagles: 0 } : { silverLions: 0, goldenEagles: prices.aceGoldenEagles }; + const price: Price = spec === 0 + ? { silverLions: prices.expert, goldenEagles: 0 } + : { silverLions: 0, goldenEagles: catalogue.aceGoldenEaglesPrice(vehicle, expertToAceRp(crew, vehicle)) }; if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); pay(profile, price); setSpecialization(crew, vehicle, spec + 1); diff --git a/packages/local-service/src/downloadable-content/content-indexes.ts b/packages/local-service/src/downloadable-content/content-indexes.ts index 166b6ec..ff24aef 100644 --- a/packages/local-service/src/downloadable-content/content-indexes.ts +++ b/packages/local-service/src/downloadable-content/content-indexes.ts @@ -1,13 +1,23 @@ /** - * The indexes of downloadable skins and decals (user-made content fetched from Gaijin's CDN). - * The local service offers none, so both indexes are empty. + * Downloadable skin and decal indexes served on the dldata CDN hosts. * - * Why they are served at all: the client waits up to 60 seconds, twice, for these indexes - * before giving up (aces.exe 2.61.0.37 0xd3fa20, "webcache: downloadable ... index hasn't - * arrived yet"); with dldata_s.info missing, start-up took two minutes longer - *. + * Why both indexes are served: + * - Startup waits up to 60 seconds per index before giving up (aces.exe 2.61.0.37 0xd3fa20, + * "webcache: downloadable ... index hasn't arrived yet"). + * - For decals, webdlcontent::getDecalsBlk (0xd41050) merges downloadable_decals..blk + * into sharedDecalsBlk (0xd47e20), overlays char.vromfs.bin config/decals.blk (0xd48380), + * and deletes any block lacking both lod0:t and a "*" managed texture (0xd415d6..0xd4183d). + * Populating downloadable_decals..blk from config/decals.blk + local DXP2 decal textures + * keeps all 1,598 Hangar Customization decals and Marketplace decal coupons active offline: + * 0xd44fc0 resolves "*?" via get_managed_texture_id (0x31aec00) directly to the local DXP + * texture without registering webcache HTTP downloads. */ -import { emptyBlock, encodeBlk } from '@wto/blk'; +import { emptyBlock, encodeBlk, type BlkBlock } from '@wto/blk'; +import { + makeDdsxDxt5HeaderBase64, + type DecalConfigEntry, + type DxpDecalTexture, +} from '../game-data/datasets/decal-textures.ts'; import { contentHash } from './content-hash.ts'; export type IndexKind = 'skins' | 'decals'; @@ -19,9 +29,77 @@ export interface ContentIndex { readonly hash: string; } +/** Stock decals.dxp.bin built-in texture names and dimensions when no DXP pack is scanned. */ +const DEFAULT_SQUARE_TEX: DxpDecalTexture = { + name: 'star', + width: 512, + height: 512, + aspectRatio: 1, + ddsxHeaderBase64: makeDdsxDxt5HeaderBase64(512, 512), +}; + +const DEFAULT_WIDE_TEX: DxpDecalTexture = { + name: 'panther', + width: 512, + height: 256, + aspectRatio: 2, + ddsxHeaderBase64: makeDdsxDxt5HeaderBase64(512, 256), +}; + +const WIDE_ASPECT_THRESHOLD = 1.5; + +export function buildContentIndexes( + decals: readonly DecalConfigEntry[] = [], + localDxp: ReadonlyMap = new Map(), +): ReadonlyMap { + const skinsBytes = encodeBlk(emptyBlock()); + const decalsBytes = encodeBlk(decals.length > 0 ? buildDecalsIndexBlk(decals, localDxp) : emptyBlock()); + return new Map([ + ['skins', { kind: 'skins', bytes: skinsBytes, hash: contentHash(skinsBytes) }], + ['decals', { kind: 'decals', bytes: decalsBytes, hash: contentHash(decalsBytes) }], + ]); +} + export function emptyContentIndexes(): ReadonlyMap { - return new Map((['skins', 'decals'] as const).map((kind) => { - const bytes = encodeBlk(emptyBlock()); - return [kind, { kind, bytes, hash: contentHash(bytes) }]; - })); + return buildContentIndexes(); +} + +function buildDecalsIndexBlk( + decals: readonly DecalConfigEntry[], + localDxp: ReadonlyMap, +): BlkBlock { + const squareFallback = localDxp.get('star') ?? firstDxpTexture(localDxp) ?? DEFAULT_SQUARE_TEX; + const wideFallback = localDxp.get('panther') ?? widestDxpTexture(localDxp) ?? DEFAULT_WIDE_TEX; + return { + name: '', + params: [], + blocks: decals.map((entry) => { + const target = localDxp.get(entry.name.toLowerCase()) + ?? (entry.aspectRatio >= WIDE_ASPECT_THRESHOLD ? wideFallback : squareFallback); + return { + name: entry.name, + params: [ + { name: 'category', value: { type: 'string', value: '' } }, + { name: 'aspect_ratio', value: { type: 'real', value: entry.aspectRatio } }, + { name: 'hdr0', value: { type: 'string', value: target.ddsxHeaderBase64 } }, + { name: 'lod0', value: { type: 'string', value: target.name } }, + { name: 'hdr1', value: { type: 'string', value: target.ddsxHeaderBase64 } }, + { name: 'lod1', value: { type: 'string', value: target.name } }, + ], + blocks: [], + }; + }), + }; +} + +function firstDxpTexture(localDxp: ReadonlyMap): DxpDecalTexture | undefined { + return localDxp.values().next().value; +} + +function widestDxpTexture(localDxp: ReadonlyMap): DxpDecalTexture | undefined { + let best: DxpDecalTexture | undefined; + for (const candidate of localDxp.values()) { + if (!best || candidate.aspectRatio > best.aspectRatio) best = candidate; + } + return best; } diff --git a/packages/local-service/src/downloadable-content/downloadable-content-service.ts b/packages/local-service/src/downloadable-content/downloadable-content-service.ts index b37880a..184bb8d 100644 --- a/packages/local-service/src/downloadable-content/downloadable-content-service.ts +++ b/packages/local-service/src/downloadable-content/downloadable-content-service.ts @@ -10,8 +10,9 @@ * checks size and SHA-1 against the hash (content-hash.ts). */ import { emptyBlock, encodeBlk, formatBlkText, setParam } from '@wto/blk'; +import { scanLocalDecalDxp, type DecalConfigEntry } from '../game-data/datasets/decal-textures.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; -import { emptyContentIndexes, type ContentIndex } from './content-indexes.ts'; +import { buildContentIndexes, type ContentIndex, type IndexKind } from './content-indexes.ts'; const INFO_HOST = /^public-configs[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/; const INFO_PATH = /^\/[a-z0-9_-]+\/dldata_s\.info$/; @@ -22,8 +23,15 @@ const BINARY = { 'content-type': 'application/octet-stream' }; export class DownloadableContentService implements Service { readonly name = 'dldata'; - readonly #indexes = emptyContentIndexes(); - readonly #info = this.#infoBlk(); + readonly #indexes: ReadonlyMap; + readonly #decalCount: number; + readonly #info: { readonly bytes: Uint8Array; readonly text: string }; + + constructor(decals: readonly DecalConfigEntry[] = [], gameFolder?: string) { + this.#indexes = buildContentIndexes(decals, scanLocalDecalDxp(gameFolder)); + this.#decalCount = decals.length; + this.#info = this.#infoBlk(); + } accepts(request: ServiceRequest): boolean { const host = request.originalHost; @@ -40,7 +48,8 @@ export class DownloadableContentService implements Service { if (!index || index.hash !== match?.[2]) { return { status: 404, body: 'unknown index', logNotes: { summary: `index ${request.path}: not one this service listed` } }; } - return { status: 200, headers: BINARY, body: index.bytes, logNotes: { summary: `downloadable_${index.kind} (empty)` } }; + const detail = index.kind === 'decals' && this.#decalCount > 0 ? `${this.#decalCount} decals` : 'empty'; + return { status: 200, headers: BINARY, body: index.bytes, logNotes: { summary: `downloadable_${index.kind} (${detail})` } }; } #infoBlk(): { readonly bytes: Uint8Array; readonly text: string } { diff --git a/packages/local-service/src/game-data/datasets/battle-spawn-rules.ts b/packages/local-service/src/game-data/datasets/battle-spawn-rules.ts new file mode 100644 index 0000000..b426281 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/battle-spawn-rules.ts @@ -0,0 +1,184 @@ +/** + * Dataset: Ground RB special spawn aircraft (`missionSupportPlane` nuclear bombers and + * `ucav_*_killstreak` strike UCAVs) and `RandomSpawnUnits` auto-supplemented vehicle pools. + * + * aces.vromfs.bin config/gameplay.blk + * missionSupportPlane{ tank_event_in_random_battles_historical{ UnitPreset{ ... } } } + * RandomSpawnUnits{ { { { minPlayerMRank:i ... { ... } } } } } + * char.vromfs.bin config/wpcost.blk + * _killstreak{ country:t economicRankHistorical:i economicRankTankHistorical:i weapons{ ... } } + */ +import { findBlock, findParam, type BlkBlock } from '@wto/blk'; +import { numberField, stringField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +export interface NuclearAircraftEntry { + readonly country: string; + readonly unitName: string; + readonly weapon: string; + readonly tankRealisticMrank: number; +} + +export interface NuclearPresetBracket { + readonly minMrank: number; + readonly maxMrank: number; + readonly spawnScore: number; + readonly entries: readonly NuclearAircraftEntry[]; +} + +export interface StrikeUcavEntry { + readonly country: string; + readonly unitName: string; + readonly weapon: string; + readonly historicalMrank: number; +} + +export interface RandomSpawnCandidate { + readonly unitName: string; + readonly forceWeapon?: string; +} + +export interface RandomSpawnGroupRule { + readonly groupName: string; + readonly minPlayerMRank: number; + readonly maxDiffBetweenTopUnitAndSessionRank: number; + readonly mRanksCount: number; + readonly units: readonly RandomSpawnCandidate[]; +} + +export interface RandomSpawnEventRule { + readonly eventName: string; + readonly countries: Readonly>; +} + +export interface BattleSpawnRulesData { + readonly nuclearBrackets: readonly NuclearPresetBracket[]; + readonly strikeUcavs: readonly StrikeUcavEntry[]; + readonly randomSpawnEvents: readonly RandomSpawnEventRule[]; +} + +const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/; + +export const battleSpawnRules: Dataset = { + id: 'battle-spawn-rules', + version: 1, + extract: (source) => { + const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk'); + const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk'); + const wpcostByUnit = new Map(wpcost.blocks.map((block) => [block.name, block])); + return { + nuclearBrackets: extractNuclearBrackets(gameplay, wpcostByUnit), + strikeUcavs: extractStrikeUcavs(wpcost.blocks), + randomSpawnEvents: extractRandomSpawnEvents(gameplay), + }; + }, +}; + +function extractNuclearBrackets( + gameplay: BlkBlock, + wpcostByUnit: ReadonlyMap, +): NuclearPresetBracket[] { + const msp = findBlock(gameplay, 'missionSupportPlane'); + const tankRb = msp && findBlock(msp, 'tank_event_in_random_battles_historical'); + if (!tankRb) return []; + + const brackets: NuclearPresetBracket[] = []; + for (const preset of tankRb.blocks) { + if (preset.name !== 'UnitPreset') continue; + if (stringField(preset, 'killStreakTagName') !== 'bomber_nuclear') continue; + const range = ipoint2Field(preset, 'rankRange'); + const spawnScore = numberField(preset, 'spawnScoreToUse'); + if (!range || spawnScore === undefined || spawnScore <= 0) continue; + + const entries: NuclearAircraftEntry[] = []; + for (const countryBlk of preset.blocks) { + if (!countryBlk.name.startsWith('country_')) continue; + const unitName = stringField(countryBlk, 'unitName') ?? ''; + const weapon = stringField(countryBlk, 'weapon') ?? ''; + if (!unitName || !weapon) continue; + const costBlk = wpcostByUnit.get(unitName); + const tankRealisticMrank = (costBlk && ( + numberField(costBlk, 'economicRankTankHistorical') + ?? numberField(costBlk, 'economicRankHistorical') + ?? numberField(costBlk, 'economicRank') + )) ?? range[0]; + entries.push({ country: countryBlk.name, unitName, weapon, tankRealisticMrank }); + } + if (entries.length > 0) { + brackets.push({ minMrank: range[0], maxMrank: range[1], spawnScore, entries }); + } + } + return brackets.sort((a, b) => a.minMrank - b.minMrank); +} + +function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcavEntry[] { + const entries: StrikeUcavEntry[] = []; + for (const unitBlk of wpcostBlocks) { + if (!STRIKE_UCAV_PATTERN.test(unitBlk.name)) continue; + const country = stringField(unitBlk, 'country') ?? ''; + if (!country.startsWith('country_')) continue; + const historicalMrank = numberField(unitBlk, 'economicRankTankHistorical') + ?? numberField(unitBlk, 'economicRankHistorical') + ?? numberField(unitBlk, 'economicRank') + ?? 0; + const weapon = pickArmedUcavWeapon(unitBlk); + entries.push({ country, unitName: unitBlk.name, weapon, historicalMrank }); + } + return entries; +} + +function pickArmedUcavWeapon(unitBlk: BlkBlock): string { + const weaponsBlk = findBlock(unitBlk, 'weapons'); + const presets = (weaponsBlk?.blocks ?? []).filter((b) => + b.name !== 'custom_presets' + && !b.name.startsWith('bombguns_') + && !b.name.startsWith('containers_') + && !b.name.startsWith('rocketguns_')); + const armed = presets.find((preset) => + (numberField(preset, 'atgmMaxDistance') ?? 0) > 0 + || (numberField(preset, 'totalBombRocketMass') ?? 0) > 0 + || (numberField(preset, 'totalGuidedBombMass') ?? 0) > 0); + return armed?.name ?? presets[0]?.name ?? ''; +} + +function extractRandomSpawnEvents(gameplay: BlkBlock): RandomSpawnEventRule[] { + const root = findBlock(gameplay, 'RandomSpawnUnits'); + if (!root) return []; + const events: RandomSpawnEventRule[] = []; + for (const eventBlk of root.blocks) { + const countries: Record = {}; + for (const countryBlk of eventBlk.blocks) { + if (!countryBlk.name.startsWith('country_')) continue; + const groups: RandomSpawnGroupRule[] = []; + for (const groupBlk of countryBlk.blocks) { + const minPlayerMRank = numberField(groupBlk, 'minPlayerMRank') ?? 0; + const maxDiff = numberField(groupBlk, 'maxDiffBetweenTopUnitAndSessionRank') ?? 0; + const mRanksCount = numberField(groupBlk, 'mRanksCount') ?? 0; + const units: RandomSpawnCandidate[] = groupBlk.blocks + .filter((u) => u.name.length > 0) + .map((u) => { + const forceWeapon = stringField(u, 'forceWeapon'); + return forceWeapon ? { unitName: u.name, forceWeapon } : { unitName: u.name }; + }); + if (units.length > 0) { + groups.push({ + groupName: groupBlk.name, + minPlayerMRank, + maxDiffBetweenTopUnitAndSessionRank: maxDiff, + mRanksCount, + units, + }); + } + } + if (groups.length > 0) countries[countryBlk.name] = groups; + } + events.push({ eventName: eventBlk.name, countries }); + } + return events; +} + +function ipoint2Field(block: BlkBlock, name: string): readonly [number, number] | undefined { + const value = findParam(block, name)?.value; + if (value?.type === 'ipoint2') return value.value; + return undefined; +} diff --git a/packages/local-service/src/game-data/datasets/crew-skills.ts b/packages/local-service/src/game-data/datasets/crew-skills.ts index d03054a..02a92bb 100644 --- a/packages/local-service/src/game-data/datasets/crew-skills.ts +++ b/packages/local-service/src/game-data/datasets/crew-skills.ts @@ -1,15 +1,16 @@ /** - * Dataset: crew skills, skill point packs and per-vehicle crew training prices - *. + * Dataset: crew skills, skill point packs, per-vehicle crew training prices, and + * Expert-to-Ace Golden Eagles discount stages. * * char.vromfs.bin config/crew_skills.blk * crew_skills{ { type:t { skill_level_exp{ level1:i ... levelN:i } } } } * levelN is the skill point cost of level N (the scripts add them up into costTbl). * char.vromfs.bin config/warpoints.blk * crewSkillPointsCost{ { costGold:i crewExp:i } } + * expert_to_ace_cost_reduce{ stage{ percent:i discount:i } } * char.vromfs.bin config/wpcost.blk, per vehicle * trainCost:i (training a crew, silver lions), train2Cost:i (expert, silver lions), - * train3Cost_gold:i (ace, golden eagles) + * train3Cost_gold:i (ace, golden eagles), train3Cost_exp:i (free ace RP threshold) */ import type { BlkBlock } from '@wto/blk'; import { findBlock } from '@wto/blk'; @@ -34,33 +35,48 @@ export interface SkillPointPack { readonly points: number; } +export interface AceDiscountStage { + readonly percent: number; + readonly discount: number; +} + export interface CrewTrainingPrices { readonly vehicle: string; readonly training: number; readonly expert: number; readonly aceGoldenEagles: number; + readonly aceResearchPoints: number; } export interface CrewSkillData { readonly pages: readonly SkillPage[]; readonly packs: readonly SkillPointPack[]; + readonly aceDiscountStages: readonly AceDiscountStage[]; readonly training: readonly CrewTrainingPrices[]; } export const crewSkillData: Dataset = { id: 'crew-skills', - version: 1, + version: 2, extract: (source) => { const skills = findBlock(source.readBlk('char.vromfs.bin', 'config/crew_skills.blk'), 'crew_skills'); - const packs = findBlock(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'crewSkillPointsCost'); + const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk'); + const packs = findBlock(warpoints, 'crewSkillPointsCost'); + const aceReduce = findBlock(warpoints, 'expert_to_ace_cost_reduce'); return { pages: (skills?.blocks ?? []).map(pageOf), packs: (packs?.blocks ?? []).map((pack) => ({ name: pack.name, goldenEagles: numberField(pack, 'costGold') ?? 0, points: numberField(pack, 'crewExp') ?? 0 })), + aceDiscountStages: (aceReduce?.blocks ?? []) + .filter((stage) => stage.name === 'stage') + .map((stage) => ({ percent: numberField(stage, 'percent') ?? 0, discount: numberField(stage, 'discount') ?? 0 })) + .filter((stage) => stage.percent > 0 && stage.discount > 0) + .sort((a, b) => a.percent - b.percent), training: source.readBlk('char.vromfs.bin', 'config/wpcost.blk').blocks.map((vehicle) => ({ vehicle: vehicle.name, training: numberField(vehicle, 'trainCost') ?? 0, expert: numberField(vehicle, 'train2Cost') ?? 0, aceGoldenEagles: numberField(vehicle, 'train3Cost_gold') ?? 0, + aceResearchPoints: numberField(vehicle, 'train3Cost_exp') ?? 0, })), }; }, diff --git a/packages/local-service/src/game-data/datasets/decal-textures.ts b/packages/local-service/src/game-data/datasets/decal-textures.ts new file mode 100644 index 0000000..f398e4e --- /dev/null +++ b/packages/local-service/src/game-data/datasets/decal-textures.ts @@ -0,0 +1,198 @@ +/** + * Dataset and local DXP2 scanner for Hangar and Marketplace decals. + * + * Why this exists: + * - char.vromfs.bin config/decals.blk lists all stock and marketplace decals (1,598 blocks) + * with category, group, costGold, unlock, marketplaceItemdefId, and aspect_ratio, but omits + * lod0 / lod1 texture fields because the online client merges downloadable_decals..blk + * into sharedDecalsBlk first (aces.exe 2.61.0.37 0xd41050 -> 0xd47e20 -> 0xd48380). + * - In webdlcontent::getDecalsBlk (0xd415d6..0xd4183d), any decal block without a lod0 string + * and without a local managed texture "*" (get_managed_texture_id, 0x31aec00) is + * deleted from sharedDecalsBlk ("failed to find texture for decal '%s', skipping it"). + * - Stock client installations only ship built-in decal textures in content/base/res/decals.dxp.bin + * (DxP2 v2 pack: lang, panther, star). Extracting the decal list via DatasetCache and scanning + * any local *decal*.dxp.bin headers lets DownloadableContentService populate every decal block + * with valid lod0/lod1 and 32-byte DDSx headers without outbound CDN requests. + */ +import { closeSync, existsSync, openSync, readdirSync, readSync } from 'node:fs'; +import { join } from 'node:path'; +import { numberField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +const DECALS_CONFIG_PATH = 'config/decals.blk'; + +/** DxP2 v2 pack header constants (verified on content/base/res/decals.dxp.bin). */ +const DXP2_MAGIC = 0x32507844; // "DxP2" +const DXP2_VERSION = 2; +const DXP2_PREAMBLE_BYTES = 0x10; +const DXP2_MAX_HEADER_BYTES = 4 * 1024 * 1024; + +/** Dagor ddsx::Header binary layout constants (32 bytes, verified at aces.exe 0xd49e00). */ +const DDSX_HEADER_BYTES = 32; +const DDSX_MAGIC = 0x78534444; // "DDSx" +const DDSX_DXT5_FOURCC = 0x35545844; // "DXT5" +const DDSX_COMPRESSION_MASK = 0x0fffffff; +const DDSX_UNPACKED_DECAL_FLAGS = 0x00000044; +const DDSX_DECAL_QUALITY_WORD = 0x7401; +const DXT5_BLOCK_BYTES = 16; + +export interface DecalConfigEntry { + readonly name: string; + readonly aspectRatio: number; +} + +export interface DxpDecalTexture { + readonly name: string; + readonly width: number; + readonly height: number; + readonly aspectRatio: number; + /** Base64-encoded 32-byte unpacked ddsx::Header expected in hdr0 / hdr1 (0xd49e00). */ + readonly ddsxHeaderBase64: string; +} + +export const decalTextures: Dataset = { + id: 'decal-textures', + version: 1, + extract: (source) => + source.readBlk('char.vromfs.bin', DECALS_CONFIG_PATH).blocks.map((entry) => { + const ratio = numberField(entry, 'aspect_ratio'); + return { + name: entry.name, + aspectRatio: ratio !== undefined && Number.isFinite(ratio) && ratio > 0 ? ratio : 1, + }; + }), +}; + +/** Scan local *decal*.dxp.bin headers inside the game folder, keyed by lowercase texture name. */ +export function scanLocalDecalDxp(gameFolder?: string): ReadonlyMap { + const found = new Map(); + if (!gameFolder || !existsSync(gameFolder)) return found; + for (const dxpPath of candidateDecalDxpPaths(gameFolder)) { + for (const entry of readDxp2DecalHeaders(dxpPath)) { + const key = entry.name.toLowerCase(); + if (!found.has(key)) found.set(key, entry); + } + } + return found; +} + +/** Synthesize a 32-byte Dagor DXT5 ddsx::Header (base64) matching downloadable_decals.blk. */ +export function makeDdsxDxt5HeaderBase64(width: number, height: number): string { + const header = Buffer.alloc(DDSX_HEADER_BYTES); + header.writeUInt32LE(DDSX_MAGIC, 0); + header.writeUInt32LE(DDSX_DXT5_FOURCC, 4); + header.writeUInt32LE(DDSX_UNPACKED_DECAL_FLAGS, 8); + header.writeUInt16LE(width, 12); + header.writeUInt16LE(height, 14); + const { levels, memSize } = dxt5MipChainSize(width, height); + header[16] = levels; + header.writeUInt16LE(DDSX_DECAL_QUALITY_WORD, 22); + header.writeUInt32LE(memSize, 24); + return header.toString('base64'); +} + +function dxt5MipChainSize(width: number, height: number): { readonly levels: number; readonly memSize: number } { + let w = Math.max(1, Math.trunc(width)); + let h = Math.max(1, Math.trunc(height)); + let levels = 0; + let memSize = 0; + for (;;) { + levels += 1; + memSize += Math.max(1, Math.ceil(w / 4)) * Math.max(1, Math.ceil(h / 4)) * DXT5_BLOCK_BYTES; + if (w === 1 && h === 1) break; + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + return { levels, memSize }; +} + +function candidateDecalDxpPaths(gameFolder: string): string[] { + const paths = new Set(); + const addResFolder = (resFolder: string): void => { + if (!existsSync(resFolder)) return; + try { + for (const item of readdirSync(resFolder, { withFileTypes: true })) { + if (item.isFile() && /decal.*\.dxp\.bin$/i.test(item.name)) paths.add(join(resFolder, item.name)); + } + } catch { /* unreadable optional pack folder */ } + }; + addResFolder(join(gameFolder, 'res')); + addResFolder(join(gameFolder, 'content', 'base', 'res')); + const contentRoot = join(gameFolder, 'content'); + if (existsSync(contentRoot)) { + try { + for (const pkg of readdirSync(contentRoot, { withFileTypes: true })) { + if (pkg.isDirectory() && pkg.name !== 'base') addResFolder(join(contentRoot, pkg.name, 'res')); + } + } catch { /* unreadable optional content root */ } + } + return [...paths]; +} + +function readDxp2DecalHeaders(dxpPath: string): DxpDecalTexture[] { + const headerBuf = readDxp2HeaderSlice(dxpPath); + if (!headerBuf) return []; + const count = headerBuf.readUInt32LE(0x08); + const namesTable = DXP2_PREAMBLE_BYTES + headerBuf.readUInt32LE(0x10); + const ddsxTable = DXP2_PREAMBLE_BYTES + headerBuf.readUInt32LE(0x20); + if (namesTable + count * 8 > headerBuf.length || ddsxTable + count * DDSX_HEADER_BYTES > headerBuf.length) { + return []; + } + const textures: DxpDecalTexture[] = []; + for (let i = 0; i < count; i++) { + const nameOffset = DXP2_PREAMBLE_BYTES + Number(headerBuf.readBigUInt64LE(namesTable + i * 8)); + const rawName = readNullTerminatedAscii(headerBuf, nameOffset); + const starIndex = rawName.indexOf('*'); + const cleanName = (starIndex >= 0 ? rawName.slice(0, starIndex) : rawName).trim(); + const ddsxSlice = headerBuf.subarray(ddsxTable + i * DDSX_HEADER_BYTES, ddsxTable + (i + 1) * DDSX_HEADER_BYTES); + if (!cleanName || ddsxSlice.readUInt32LE(0) !== DDSX_MAGIC) continue; + const width = ddsxSlice.readUInt16LE(12); + const height = ddsxSlice.readUInt16LE(14); + if (width === 0 || height === 0) continue; + textures.push({ + name: cleanName, + width, + height, + aspectRatio: width / height, + ddsxHeaderBase64: normalizeDdsxHeader(ddsxSlice), + }); + } + return textures; +} + +function readDxp2HeaderSlice(dxpPath: string): Buffer | undefined { + let fd: number | undefined; + try { + fd = openSync(dxpPath, 'r'); + const preamble = Buffer.alloc(DXP2_PREAMBLE_BYTES); + if (readSync(fd, preamble, 0, DXP2_PREAMBLE_BYTES, 0) < DXP2_PREAMBLE_BYTES) return undefined; + if (preamble.readUInt32LE(0) !== DXP2_MAGIC || preamble.readUInt32LE(4) !== DXP2_VERSION) return undefined; + const hdrSize = preamble.readUInt32LE(0x0c); + if (hdrSize === 0 || hdrSize > DXP2_MAX_HEADER_BYTES) return undefined; + const total = DXP2_PREAMBLE_BYTES + hdrSize; + const full = Buffer.alloc(total); + preamble.copy(full, 0); + if (readSync(fd, full, DXP2_PREAMBLE_BYTES, hdrSize, DXP2_PREAMBLE_BYTES) < hdrSize) return undefined; + return full; + } catch { + return undefined; + } finally { + if (fd !== undefined) { + try { closeSync(fd); } catch { /* ignore close failure */ } + } + } +} + +function normalizeDdsxHeader(rawHeader: Uint8Array): string { + const unpacked = Buffer.from(rawHeader); + unpacked.writeUInt32LE(unpacked.readUInt32LE(8) & DDSX_COMPRESSION_MASK, 8); + unpacked.writeUInt32LE(0, 28); + return unpacked.toString('base64'); +} + +function readNullTerminatedAscii(buffer: Buffer, offset: number): string { + if (offset < 0 || offset >= buffer.length) return ''; + let end = offset; + while (end < buffer.length && buffer[end] !== 0) end += 1; + return buffer.subarray(offset, end).toString('ascii'); +} diff --git a/packages/local-service/src/game-data/datasets/multiplayer-missions.ts b/packages/local-service/src/game-data/datasets/multiplayer-missions.ts index 72b8938..aad63f4 100644 --- a/packages/local-service/src/game-data/datasets/multiplayer-missions.ts +++ b/packages/local-service/src/game-data/datasets/multiplayer-missions.ts @@ -32,6 +32,8 @@ export interface MissionHeader { readonly type?: string; readonly environment?: string; readonly weather?: string; + readonly locName?: string; + readonly postfix?: string; readonly countryAxis?: string; readonly countryAllies?: string; readonly timeLimit?: number; @@ -50,7 +52,7 @@ export interface MultiplayerMissions { export const multiplayerMissions: Dataset = { id: 'multiplayer-missions', - version: 1, + version: 2, extract(source: DatasetSource): MultiplayerMissions { const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION); if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`); @@ -93,6 +95,8 @@ function readHeader(name: string, path: string, document: BlkBlock): MissionHead type: stringField(mission, 'type'), environment: stringField(mission, 'environment'), weather: stringField(mission, 'weather'), + locName: stringField(mission, 'locName'), + postfix: stringField(mission, 'postfix'), countryAxis: stringField(mission, 'country_axis'), countryAllies: stringField(mission, 'country_allies'), timeLimit: numberField(mission, 'timeLimit'), diff --git a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts index 6615070..2bb4548 100644 --- a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts +++ b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts @@ -60,11 +60,18 @@ export interface CatalogueVehicle { readonly openCostGold: number; /** wpcost.blk minOpenCostGold (minimum GE buyout floor for squadron vehicles, implementation notes). */ readonly minOpenCostGold: number; + /** wpcost.blk economicRank and per-difficulty matchmaking ranks. */ + readonly economicRank: number; + readonly economicRankArcade: number; + readonly economicRankHistorical: number; + readonly economicRankSimulation: number; + readonly economicRankTankHistorical?: number; + readonly economicRankTankSimulation?: number; } export const vehicleCatalogue: Dataset = { id: 'vehicle-catalogue', - version: 5, + version: 6, extract: (source) => { const shopEntries = shopEntriesByName(source); const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index])); @@ -77,6 +84,9 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr const researchType = stringField(vehicle, 'researchType'); const requiredUnlock = stringField(shopEntry, 'reqUnlock'); const marketplaceItemdefId = numberField(shopEntry, 'marketplaceItemdefId') ?? numberField(vehicle, 'marketplaceItemdefId'); + const economicRank = numberField(vehicle, 'economicRank') ?? 0; + const economicRankTankHistorical = numberField(vehicle, 'economicRankTankHistorical'); + const economicRankTankSimulation = numberField(vehicle, 'economicRankTankSimulation'); return { name: vehicle.name, country: stringField(vehicle, 'country') ?? '', @@ -98,5 +108,11 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr ...(marketplaceItemdefId !== undefined ? { marketplaceItemdefId } : {}), openCostGold: numberField(vehicle, 'openCostGold') ?? 0, minOpenCostGold: numberField(vehicle, 'minOpenCostGold') ?? 0, + economicRank, + economicRankArcade: numberField(vehicle, 'economicRankArcade') ?? economicRank, + economicRankHistorical: numberField(vehicle, 'economicRankHistorical') ?? economicRank, + economicRankSimulation: numberField(vehicle, 'economicRankSimulation') ?? economicRank, + ...(economicRankTankHistorical !== undefined ? { economicRankTankHistorical } : {}), + ...(economicRankTankSimulation !== undefined ? { economicRankTankSimulation } : {}), }; } diff --git a/packages/local-service/src/game-modes/catalogue/catalogue.ts b/packages/local-service/src/game-modes/catalogue/catalogue.ts index 3935099..b55bc8e 100644 --- a/packages/local-service/src/game-modes/catalogue/catalogue.ts +++ b/packages/local-service/src/game-modes/catalogue/catalogue.ts @@ -4,21 +4,29 @@ import { PVE_BATTLES } from './pve-battles.ts'; import { RANDOM_BATTLES } from './random-battles.ts'; import { SIMULATOR_BATTLES } from './simulator-battles.ts'; import { SPECIAL_EVENTS } from './special-events.ts'; +import { SUB_GAME_MODES } from './sub-game-modes.ts'; export const GAME_MODE_CATALOGUE: readonly GameModeDeclaration[] = checked([ ...RANDOM_BATTLES, + ...SUB_GAME_MODES, ...SIMULATOR_BATTLES, ...PVE_BATTLES, ...SPECIAL_EVENTS, ]); function checked(modes: readonly GameModeDeclaration[]): readonly GameModeDeclaration[] { - for (const key of ['gameModeId', 'name'] as const) { - const seen = new Set(); - for (const mode of modes) { - if (seen.has(mode[key])) throw new Error(`game-mode catalogue: ${key} ${String(mode[key])} is used twice`); - seen.add(mode[key]); + const seenIds = new Set(); + const seenNameTags = new Set(); + for (const mode of modes) { + if (seenIds.has(mode.gameModeId)) { + throw new Error(`game-mode catalogue: gameModeId ${mode.gameModeId} is used twice`); } + seenIds.add(mode.gameModeId); + const nameTag = `${mode.name}\0${mode.tag ?? ''}`; + if (seenNameTags.has(nameTag)) { + throw new Error(`game-mode catalogue: (${mode.name}, tag="${mode.tag ?? ''}") is used twice`); + } + seenNameTags.add(nameTag); } return modes; } diff --git a/packages/local-service/src/game-modes/catalogue/game-mode-declaration.ts b/packages/local-service/src/game-modes/catalogue/game-mode-declaration.ts index 449b669..00cf4a7 100644 --- a/packages/local-service/src/game-modes/catalogue/game-mode-declaration.ts +++ b/packages/local-service/src/game-modes/catalogue/game-mode-declaration.ts @@ -31,6 +31,12 @@ export interface GameModeDeclaration { readonly gameModeId: number; /** The stock name where the game has one (docs/implementation notes). */ readonly name: string; + /** + * Sub-mode tag prefix recognized by `scripts/matching/matchinggamemodes.nut:28-42` + * (`regular_with_night_`, `small_teams_`, `bullet_hell_`, `nuclear_escalation_`, + * `naval_ec_ab_`, `naval_ec_rb_`). Empty or omitted for primary modes. + */ + readonly tag?: string; readonly economicName: string; /** A single key of the game's localization (a composite key makes the stock UI log an error). */ readonly locName: string; @@ -38,6 +44,27 @@ export interface GameModeDeclaration { readonly displayType: DisplayType; /** Events-window chapter; only for modes shown there. */ readonly chapter?: string; + /** + * Whether multiple crew slots participate (`scripts/events/eventsstate.nut:76`). Defaults to + * `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode). + */ + readonly multiSlot?: boolean; + /** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */ + readonly minMRankForNightBattles?: number; + /** Minimum `mrank` exposed on the parent mode for Tactical Skies (`scripts/events/eventinfo.nut:137`). */ + readonly minMRankForSmallTeamsBattles?: number; + /** Minimum suitable vehicles required in the crew bar (`scripts/events/secondgamemodesutils.nut:70-71`). */ + readonly minCraftsToPlay?: number; + /** Minimum `mrank` per vehicle class emitted into `teamA`/`teamB.allowedCrafts` (`mranks.min`). */ + readonly allowedCraftMinMrank?: Partial>>; + /** Explicit `minTeamSize` / `maxTeamSize` override (`scripts/events/secondgamemodesutils.nut:40-54`). */ + readonly teamSizeOverride?: { readonly min: number; readonly max: number }; + /** Minimum `mrank` enforced by local matchmaking before selecting this sub-mode. */ + readonly minQueueMrank?: number; + /** Mission time-of-day override applied when launching this mode (e.g. `"Night"`). */ + readonly environmentOverride?: string; + /** Uses `BattleTuning.smallTeamsMaxPlayers` instead of `BattleTuning.maxPlayers` when true. */ + readonly isSmallTeams?: boolean; /** The vehicle class a player must bring; the mode is greyed out without one. */ readonly requiredClass: UnitClass; readonly allowedClasses: readonly UnitClass[]; diff --git a/packages/local-service/src/game-modes/catalogue/mission-pools.ts b/packages/local-service/src/game-modes/catalogue/mission-pools.ts index 70cd009..f10c354 100644 --- a/packages/local-service/src/game-modes/catalogue/mission-pools.ts +++ b/packages/local-service/src/game-modes/catalogue/mission-pools.ts @@ -27,3 +27,18 @@ export const NAVAL_BATTLE_MISSIONS: MissionSelection = { requireAllowed: ['ship'], exclude: NEWBIE_MISSIONS, }; + +export const BULLET_HELL_MISSIONS: MissionSelection = { + categories: ['bullet_hell'], + requireAllowed: ['aircraft'], +}; + +export const NUCLEAR_ESCALATION_MISSIONS: MissionSelection = { + categories: ['nuclear_escalation'], + requireAllowed: ['aircraft'], +}; + +export const NAVAL_EC_MISSIONS: MissionSelection = { + categories: ['naval_n2m'], + requireAllowed: ['ship'], +}; diff --git a/packages/local-service/src/game-modes/catalogue/random-battles.ts b/packages/local-service/src/game-modes/catalogue/random-battles.ts index 878f5d7..eb363f1 100644 --- a/packages/local-service/src/game-modes/catalogue/random-battles.ts +++ b/packages/local-service/src/game-modes/catalogue/random-battles.ts @@ -5,10 +5,17 @@ * names are the game's "missions/_event_" texts (lang menu_events.csv); * economic names of ground and naval modes are the ones the leaderboard scripts use * (scripts/leaderboard/leaderboardCategoryType.nut). + * + * `minMRankForSmallTeamsBattles` (27 = BR 10.0, Air RB) and `minMRankForNightBattles` + * (27 = BR 10.0, Ground RB) come from `scripts/events/secondgamemodesutils.nut:25-26`, + * `scripts/unlocks/personalunlocks.nut:12`, and `config/unlocks.blk` (`title_prowler_in_the_night`). */ import type { GameModeDeclaration } from './game-mode-declaration.ts'; import { AIR_BATTLE_MISSIONS, GROUND_BATTLE_MISSIONS, NAVAL_BATTLE_MISSIONS } from './mission-pools.ts'; +const AIR_REALISTIC_SMALL_TEAMS_MIN_MRANK = 27; +const GROUND_REALISTIC_NIGHT_MIN_MRANK = 27; + const AIR = { requiredClass: 'aircraft', allowedClasses: ['aircraft'], missions: AIR_BATTLE_MISSIONS } as const; const GROUND = { requiredClass: 'tank', allowedClasses: ['tank', 'aircraft', 'helicopter'], missions: GROUND_BATTLE_MISSIONS } as const; const NAVAL = { requiredClass: 'ship', allowedClasses: ['ship', 'aircraft'], missions: NAVAL_BATTLE_MISSIONS } as const; @@ -20,7 +27,8 @@ export const RANDOM_BATTLES: readonly GameModeDeclaration[] = [ }, { gameModeId: 2, name: 'air_realistic', economicName: 'air_realistic', locName: 'missions/air_event_historical', - difficulty: 'realistic', displayType: 'random_battle', ...AIR, + difficulty: 'realistic', displayType: 'random_battle', multiSlot: false, + minMRankForSmallTeamsBattles: AIR_REALISTIC_SMALL_TEAMS_MIN_MRANK, ...AIR, }, { gameModeId: 3, name: 'tank_event_in_random_battles_arcade', economicName: 'tank_arcade', @@ -28,7 +36,8 @@ export const RANDOM_BATTLES: readonly GameModeDeclaration[] = [ }, { gameModeId: 4, name: 'tank_event_in_random_battles_historical', economicName: 'tank_realistic', - locName: 'missions/tank_event_in_random_battles_historical', difficulty: 'realistic', displayType: 'random_battle', ...GROUND, + locName: 'missions/tank_event_in_random_battles_historical', difficulty: 'realistic', displayType: 'random_battle', + minMRankForNightBattles: GROUND_REALISTIC_NIGHT_MIN_MRANK, ...GROUND, }, { gameModeId: 5, name: 'ship_event_in_random_battles_arcade', economicName: 'test_ship_arcade', diff --git a/packages/local-service/src/game-modes/catalogue/sub-game-modes.ts b/packages/local-service/src/game-modes/catalogue/sub-game-modes.ts new file mode 100644 index 0000000..5d38044 --- /dev/null +++ b/packages/local-service/src/game-modes/catalogue/sub-game-modes.ts @@ -0,0 +1,119 @@ +/** + * Stock 2.61.0.37 sub-game-modes (`secondGameModesPanel`, `scripts/matching/matchinggamemodes.nut:28-42` + * and `scripts/events/secondgamemodesutils.nut:25-30, 355-390, 606-654`): + * + * Each sub-mode shares its parent mode's `name` and `economicName` (`matchinggamemodes.nut:74-77, 93` + * and `config/unlocks.blk` `title_prowler_in_the_night`), while carrying its stock `tag` prefix so: + * - `matchingGameModes.notifyGmChanged()` excludes it from the top-level mode drawer (`isSubGameMode`); + * - `mapPreferencesParams.getMapsListImpl()` excludes it from the parent mode's map-ban list; + * - `secondGameModesUtils.nut` binds each toggle strictly to the matching `economicName` (Ground RB + * only gets Night Battles; Air RB gets Nuclear Escalation, Tactical Skies, and Bullet Hell; Naval + * AB/RB get Enduring Confrontation; Ground AB and Air AB get none); + * - `queueEvent.nut` includes or excludes its `gameModeId` in `match.enqueue` `game_modes_list`. + */ +import type { GameModeDeclaration } from './game-mode-declaration.ts'; +import { + AIR_BATTLE_MISSIONS, + BULLET_HELL_MISSIONS, + GROUND_BATTLE_MISSIONS, + NAVAL_EC_MISSIONS, + NUCLEAR_ESCALATION_MISSIONS, +} from './mission-pools.ts'; + +/** Protocol thresholds defined in `scripts/events/secondgamemodesutils.nut:25-30`. */ +const MIN_MRANK_NIGHT_BATTLES = 27; +const MIN_MRANK_SMALL_TEAMS = 27; +const MIN_MRANK_BULLET_HELL = 22; +const MIN_CRAFTS_BULLET_HELL = 2; +const MIN_MRANK_NUCLEAR_ESCALATION = 23; +const MIN_MRANK_NAVAL_EC = 7; + +export const SUB_GAME_MODES: readonly GameModeDeclaration[] = [ + { + gameModeId: 101, + name: 'tank_event_in_random_battles_historical', + tag: 'regular_with_night_tank_realistic', + economicName: 'tank_realistic', + locName: 'missions/tank_event_in_random_battles_historical', + difficulty: 'realistic', + displayType: 'random_battle', + minQueueMrank: MIN_MRANK_NIGHT_BATTLES, + environmentOverride: 'Night', + requiredClass: 'tank', + allowedClasses: ['tank', 'aircraft', 'helicopter'], + missions: GROUND_BATTLE_MISSIONS, + }, + { + gameModeId: 102, + name: 'air_realistic', + tag: 'small_teams_air_realistic', + economicName: 'air_realistic', + locName: 'missions/air_event_historical', + difficulty: 'realistic', + displayType: 'random_battle', + multiSlot: false, + teamSizeOverride: { min: 6, max: 12 }, + minQueueMrank: MIN_MRANK_SMALL_TEAMS, + isSmallTeams: true, + requiredClass: 'aircraft', + allowedClasses: ['aircraft'], + missions: AIR_BATTLE_MISSIONS, + }, + { + gameModeId: 103, + name: 'air_realistic', + tag: 'nuclear_escalation_air_realistic', + economicName: 'air_realistic', + locName: 'missions/air_event_historical', + difficulty: 'realistic', + displayType: 'random_battle', + allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION }, + minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION, + requiredClass: 'aircraft', + allowedClasses: ['aircraft'], + missions: NUCLEAR_ESCALATION_MISSIONS, + }, + { + gameModeId: 104, + name: 'air_realistic', + tag: 'bullet_hell_air_realistic', + economicName: 'air_realistic', + locName: 'missions/air_event_historical', + difficulty: 'realistic', + displayType: 'random_battle', + minCraftsToPlay: MIN_CRAFTS_BULLET_HELL, + allowedCraftMinMrank: { aircraft: MIN_MRANK_BULLET_HELL }, + minQueueMrank: MIN_MRANK_BULLET_HELL, + requiredClass: 'aircraft', + allowedClasses: ['aircraft'], + missions: BULLET_HELL_MISSIONS, + }, + { + gameModeId: 105, + name: 'ship_event_in_random_battles_arcade', + tag: 'naval_ec_ab_ship_arcade', + economicName: 'test_ship_arcade', + locName: 'missions/ship_event_arcade', + difficulty: 'arcade', + displayType: 'random_battle', + allowedCraftMinMrank: { ship: MIN_MRANK_NAVAL_EC }, + minQueueMrank: MIN_MRANK_NAVAL_EC, + requiredClass: 'ship', + allowedClasses: ['ship', 'aircraft'], + missions: NAVAL_EC_MISSIONS, + }, + { + gameModeId: 106, + name: 'ship_event_in_random_battles_realistic', + tag: 'naval_ec_rb_ship_realistic', + economicName: 'test_ship_realistic', + locName: 'missions/ship_event_historical', + difficulty: 'realistic', + displayType: 'random_battle', + allowedCraftMinMrank: { ship: MIN_MRANK_NAVAL_EC }, + minQueueMrank: MIN_MRANK_NAVAL_EC, + requiredClass: 'ship', + allowedClasses: ['ship', 'aircraft'], + missions: NAVAL_EC_MISSIONS, + }, +]; diff --git a/packages/local-service/src/game-modes/game-modes.ts b/packages/local-service/src/game-modes/game-modes.ts index 1d28c1d..72a243f 100644 --- a/packages/local-service/src/game-modes/game-modes.ts +++ b/packages/local-service/src/game-modes/game-modes.ts @@ -6,37 +6,72 @@ * The same object will serve the battle flow later (docs/implementation notes): which missions * and team rules a chosen mode has. */ -import type { MultiplayerMissions } from '../game-data/datasets/multiplayer-missions.ts'; +import type { MissionHeader, MultiplayerMissions } from '../game-data/datasets/multiplayer-missions.ts'; import { GAME_MODE_CATALOGUE } from './catalogue/catalogue.ts'; import type { GameModeDeclaration } from './catalogue/game-mode-declaration.ts'; import { selectMissions } from './mission-pool.ts'; import { buildModeDefinition, type ModeDefinition } from './mode-definition.ts'; +export interface OfferedGameMode { + readonly declaration: GameModeDeclaration; + readonly missions: readonly MissionHeader[]; + readonly definition: ModeDefinition; +} + export class GameModes { - readonly #definitions = new Map(); + readonly #byId = new Map(); + readonly #byName = new Map(); + readonly #byEconomicName = new Map(); + readonly #countries: readonly string[]; constructor(missions: MultiplayerMissions, countries: readonly string[], report: (line: string) => void, catalogue: readonly GameModeDeclaration[] = GAME_MODE_CATALOGUE) { + this.#countries = [...countries]; for (const mode of catalogue) { const selected = selectMissions(mode.missions, missions); if (selected.length === 0) { - report(`game mode ${mode.name}: no missions in the game files, left out`); + report(`game mode ${mode.name}${mode.tag ? `.${mode.tag}` : ''}: no missions in the game files, left out`); continue; } - this.#definitions.set(mode.gameModeId, buildModeDefinition(mode, selected, countries)); + const offered: OfferedGameMode = { + declaration: mode, + missions: selected, + definition: buildModeDefinition(mode, selected, countries), + }; + this.#byId.set(mode.gameModeId, offered); + if (!mode.tag) this.#byName.set(mode.name, offered); + const group = this.#byEconomicName.get(mode.economicName) ?? []; + group.push(offered); + this.#byEconomicName.set(mode.economicName, group); } - report(`game modes: ${this.#definitions.size} of ${catalogue.length} offered`); + report(`game modes: ${this.#byId.size} of ${catalogue.length} offered`); } ids(): number[] { - return [...this.#definitions.keys()]; + return [...this.#byId.keys()]; + } + + countries(): readonly string[] { + return this.#countries; + } + + byId(id: number): OfferedGameMode | undefined { + return this.#byId.get(id); + } + + byName(name: string): OfferedGameMode | undefined { + return this.#byName.get(name); + } + + byEconomicName(economicName: string): readonly OfferedGameMode[] { + return this.#byEconomicName.get(economicName) ?? []; } /** Definitions of the known ids among those asked for, in the order asked. */ definitions(ids: readonly number[]): ModeDefinition[] { return ids.flatMap((id): ModeDefinition[] => { - const definition = this.#definitions.get(id); - return definition ? [definition] : []; + const offered = this.#byId.get(id); + return offered ? [offered.definition] : []; }); } } diff --git a/packages/local-service/src/game-modes/mode-definition.ts b/packages/local-service/src/game-modes/mode-definition.ts index 1fc0574..f7de30b 100644 --- a/packages/local-service/src/game-modes/mode-definition.ts +++ b/packages/local-service/src/game-modes/mode-definition.ts @@ -12,10 +12,10 @@ * createEventGameMode). * - mission_decl.missions_list: mission name -> {} (a value may carry "enableIf" rank * limits, scripts/missions/mapPreferencesParams.nut; none are set). - * - tag: required, the script reads it unguarded (scripts/matching/matchingGameModes.nut, + * - tag: required, the script reads it unguarded (scripts/matching/matchingGameModes.nut, * onGameModesUpdated; local verification stopped there without it). Tag prefixes mark sub-modes - * (night battles, small teams, …, SUB_GAME_MODE_TAG_PREFIXES); our modes have none, so - * the tag is empty. + * (night battles, small teams, bullet hell, nuclear escalation, naval EC; + * SUB_GAME_MODE_TAG_PREFIXES in matchingGameModes.nut:28-42). * - rankCalcMode: required, read unguarded when the slotbar computes the lineup's battle * rating (scripts/slotbar/slotbarPresets/calcRanks.nut calculateBR; local verification). * "average" or "maximum" (lang: multiplayer/battleRatingCalcHint/*); random battles @@ -34,7 +34,7 @@ const MATCHING_DIFFICULTY: Readonly> = { simulator: 'simulation', }; -const MISSION_DIFFICULTY: Readonly> = { +export const MISSION_DIFFICULTY: Readonly> = { arcade: 'arcade', realistic: 'realistic', simulator: 'hardcore', @@ -44,23 +44,35 @@ export type ModeDefinition = Readonly>; export function buildModeDefinition(mode: GameModeDeclaration, missions: readonly MissionHeader[], countries: readonly string[]): ModeDefinition { + const minTeamSize = mode.teamSizeOverride?.min ?? 1; + const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions); const team = { countries: [...countries], - allowedCrafts: mode.allowedClasses.map((unitClass) => ({ class: unitClass })), + allowedCrafts: mode.allowedClasses.map((unitClass) => { + const minMrank = mode.allowedCraftMinMrank?.[unitClass]; + return minMrank === undefined + ? { class: unitClass } + : { class: unitClass, mranks: { min: minMrank } }; + }), requiredCrafts: [{ class: mode.requiredClass }], - minTeamSize: 1, - maxTeamSize: teamSize(mode, missions), + minTeamSize, + maxTeamSize, }; return { gameModeId: mode.gameModeId, name: mode.name, - tag: '', + tag: mode.tag ?? '', economicName: mode.economicName, loc_name: mode.locName, difficulty: MATCHING_DIFFICULTY[mode.difficulty], rankCalcMode: 'maximum', displayType: mode.displayType, + multiSlot: mode.multiSlot ?? true, + minTeamSize, ...(mode.chapter === undefined ? {} : { chapter: mode.chapter }), + ...(mode.minCraftsToPlay === undefined ? {} : { minCraftsToPlay: mode.minCraftsToPlay }), + ...(mode.minMRankForNightBattles === undefined ? {} : { minMRankForNightBattles: mode.minMRankForNightBattles }), + ...(mode.minMRankForSmallTeamsBattles === undefined ? {} : { minMRankForSmallTeamsBattles: mode.minMRankForSmallTeamsBattles }), visible: true, disabled: false, teamA: team, diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index eb98c68..120edbe 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -1,9 +1,11 @@ /** - * Assemble the local service: data layer, save layer, rules, the - * protocol-layer services, and the listening port. + * Assemble the local service: data layer, save layer, rules, protocol-layer services, + * and the single loopback listening port. */ import type { Server } from 'node:net'; import { AccountStore } from './accounts/account-store.ts'; +import { BattleMatchmaker } from './battle/battle-matchmaker.ts'; +import { BattleSessionStore } from './battle/battle-session-store.ts'; import { actionTable } from './char/actions/action-table.ts'; import { CharService } from './char/char-service.ts'; import { ClanStore } from './clans/clan-store.ts'; @@ -11,9 +13,11 @@ import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts'; import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts'; import { DecorShop } from './decor/decor-purchase.ts'; import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; +import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts'; import { clanEconomy } from './game-data/datasets/clan-economy.ts'; import { crewSkillData } from './game-data/datasets/crew-skills.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; +import { decalTextures } from './game-data/datasets/decal-textures.ts'; import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts'; import { externalItemSources } from './game-data/datasets/external-item-sources.ts'; import { itemCatalogue } from './game-data/datasets/item-catalogue.ts'; @@ -75,6 +79,8 @@ export async function startLocalService(options: LocalServiceOptions): Promise matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' }); + const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept); + const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules); const router = new Router([ webUi, @@ -104,12 +112,28 @@ export async function startLocalService(options: LocalServiceOptions): Promise matching?.notifyUser(userId, 'mrpc.generic_notify', payload), + }, + }), + log, + loadOrCreateCredentials(options.dataFolder), + ); matching = listener.matching; await listen(listener.server, options.port); return { diff --git a/packages/local-service/src/matching/battle-queue-requests.ts b/packages/local-service/src/matching/battle-queue-requests.ts new file mode 100644 index 0000000..1872c2f --- /dev/null +++ b/packages/local-service/src/matching/battle-queue-requests.ts @@ -0,0 +1,180 @@ +/** + * Matching-server RPC handlers for hangar battle-rating display and battle queueing + *: + * - `wtmm_static.calc_ranks` (scripts/battlerating.nut:179) + * - `match.enqueue` (scripts/matching/servicenotifications/match.nut:75) + * - `match.leave_queue` (scripts/queue/queuestate.nut:28) + * - `match.check_reconnect` + */ +import type { BattleLaunchPlan, BattleMatchmaker } from '../battle/battle-matchmaker.ts'; +import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts'; +import type { BattleSessionStore } from '../battle/battle-session-store.ts'; +import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts'; +import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts'; +import type { PlayerProfiles } from '../profile/player-profiles.ts'; +import type { MatchingRequestHandler } from './matching-requests.ts'; + +export interface BattleLaunchNotifyPayload extends BattleLaunchPlan, Record { + readonly from: 'wto_battle'; + readonly func: 'launch'; +} + +export interface BattleQueueDependencies { + readonly gameModes: GameModes; + readonly profiles: PlayerProfiles; + readonly matchmaker: BattleMatchmaker; + readonly sessions: BattleSessionStore; + readonly notifyLaunch: (userId: string, payload: BattleLaunchNotifyPayload) => void; +} + +export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> { + return [ + ['wtmm_static.calc_ranks', (request) => answerCalcRanks(request.params, deps.gameModes)], + ['match.enqueue', (request, session) => handleEnqueue(request.params, session, deps)], + ['match.leave_queue', (_request, session) => { + const userId = session.authenticatedUserId(); + if (userId) deps.sessions.cancelPendingForUser(userId); + return {}; + }], + ['match.check_reconnect', () => ({})], + ]; +} + +function answerCalcRanks(params: Readonly>, gameModes: GameModes): Record { + const mode = typeof params.gameModeId === 'number' ? gameModes.byId(params.gameModeId) : undefined; + const players = Array.isArray(params.players) ? params.players : []; + const answer: Record> = {}; + for (const rawPlayer of players) { + if (!isRecord(rawPlayer) || typeof rawPlayer.name !== 'string' || !rawPlayer.name) continue; + const crafts = parsePlayerCrafts(rawPlayer.crafts); + const slot = typeof rawPlayer.slot === 'number' && Number.isInteger(rawPlayer.slot) ? rawPlayer.slot : -1; + const singleSlotCraft = mode?.declaration.multiSlot === false && slot >= 0 && slot < crafts.length + ? crafts[slot] + : undefined; + const scopedCrafts = singleSlotCraft && singleSlotCraft.unitClass === mode?.declaration.requiredClass + ? [singleSlotCraft] + : crafts; + const mrank = mode + ? maxModeMrank(scopedCrafts, mode.declaration.requiredClass, mode.declaration.allowedClasses) + : scopedCrafts.reduce((max, craft) => Math.max(max, craft.mrank), 0); + answer[rawPlayer.name] = [{ mrank }]; + } + return answer; +} + +function handleEnqueue( + params: Readonly>, + session: { authenticatedUserId(): string | undefined; note(text: string): void }, + deps: BattleQueueDependencies, +): Record { + const userId = session.authenticatedUserId(); + if (!userId) { + session.note('rejected: matching session is not authenticated'); + return { error: 'AUTH_REQ_ERROR' }; + } + const modes = resolveQueuedModes(params, deps.gameModes); + if (modes.length === 0) { + session.note('rejected: unknown game mode'); + return { error: 'UNKNOWN_GAME_MODE' }; + } + const playerEntry = extractPlayerEntry(params, userId); + if (!playerEntry) { + session.note('rejected: missing player country in match.enqueue'); + return { error: 'BAD_PARAMS' }; + } + const profile = deps.profiles.profileOf(userId); + const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country); + const selectedSlotVehicle = playerEntry.selectedSlot !== undefined + ? crewSlotVehicleOfCountry(profile, playerEntry.country, playerEntry.selectedSlot) + : undefined; + const outcome = deps.matchmaker.enqueue({ + userId, + mode: modes[0]!, + modes, + country: playerEntry.country, + slotVehicles, + ...(selectedSlotVehicle !== undefined ? { selectedSlotVehicle } : {}), + bannedMissions: playerEntry.bannedMissions, + dislikedMissions: playerEntry.dislikedMissions, + }); + if (!outcome.ok) { + session.note(`rejected: ${outcome.error}`); + return { error: outcome.error }; + } + const { launch } = outcome; + session.note(`mode=${launch.modeName}, mission=${launch.missionName}, mrank=${launch.minMrank}..${launch.maxMrank}`); + setImmediate(() => { + if (!deps.sessions.isPending(userId, launch.sessionId)) return; + deps.sessions.clearPending(userId, launch.sessionId); + deps.notifyLaunch(userId, { from: 'wto_battle', func: 'launch', ...launch }); + }); + return {}; +} + +function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] { + if (!Array.isArray(rawCrafts)) return []; + return rawCrafts.flatMap((craft): CraftRankEntry[] => { + if (!isRecord(craft) || typeof craft.mrank !== 'number' || !Number.isFinite(craft.mrank)) return []; + const fromExp = typeof craft.craftType === 'string' ? unitClassOfExpClass(craft.craftType) : undefined; + const fromCode = typeof craft.unitTypeCode === 'number' ? unitClassOfTypeCode(craft.unitTypeCode) : undefined; + return [{ unitClass: fromExp ?? fromCode, mrank: Math.max(0, Math.trunc(craft.mrank)) }]; + }); +} + +/** + * Resolve every candidate `OfferedGameMode` allowed by `match.enqueue` (`scripts/queue/queue/queueevent.nut:191-207`): + * - `game_mode_id`: explicit single mode ID; + * - `game_modes_list`: filtered IDs after applying `onlyTags` / `excludedTags`; + * - `mode`: sent when `onlyTags` and `excludedTags` are both empty (classic mode plus every + * sub-mode of that `economicName` is enabled; server-side BR/craft guards still apply). + */ +function resolveQueuedModes(params: Readonly>, gameModes: GameModes): OfferedGameMode[] { + if (typeof params.game_mode_id === 'number') { + const found = gameModes.byId(params.game_mode_id); + return found ? [found] : []; + } + if (Array.isArray(params.game_modes_list)) { + return params.game_modes_list.flatMap((id) => (typeof id === 'number' ? gameModes.byId(id) ?? [] : [])); + } + if (typeof params.mode === 'string' && params.mode) { + const primary = gameModes.byName(params.mode); + if (!primary) return []; + const family = gameModes.byEconomicName(primary.declaration.economicName); + return family.length > 0 ? [...family] : [primary]; + } + return []; +} + +function extractPlayerEntry( + params: Readonly>, + userId: string, +): { + readonly country: string; + readonly selectedSlot?: number; + readonly bannedMissions: Set; + readonly dislikedMissions: Set; +} | undefined { + const players = isRecord(params.players) ? params.players : undefined; + const entry = players && isRecord(players[userId]) ? players[userId] : undefined; + const rawCountry = typeof entry?.country === 'string' ? entry.country.trim() : ''; + if (!rawCountry) return undefined; + const country = rawCountry.startsWith('country_') ? rawCountry : `country_${rawCountry}`; + const slots = isRecord(entry?.slots) ? entry.slots : undefined; + const rawSlot = slots?.[country] ?? slots?.[rawCountry]; + const selectedSlot = typeof rawSlot === 'number' && Number.isInteger(rawSlot) && rawSlot >= 0 ? rawSlot : undefined; + return { + country, + ...(selectedSlot !== undefined ? { selectedSlot } : {}), + bannedMissions: toStringSet(entry?.bannedMissions), + dislikedMissions: toStringSet(entry?.dislikedMissions), + }; +} + +function toStringSet(raw: unknown): Set { + if (!Array.isArray(raw)) return new Set(); + return new Set(raw.filter((item): item is string => typeof item === 'string' && item.length > 0)); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/packages/local-service/src/matching/game-settings.ts b/packages/local-service/src/matching/game-settings.ts new file mode 100644 index 0000000..5f55f16 --- /dev/null +++ b/packages/local-service/src/matching/game-settings.ts @@ -0,0 +1,22 @@ +/** + * Static matching-server feature flags (`wtmm_static.fetch_game_settings`, + * `scripts/matching/matchinggamesettings.nut` -> `scripts/user/matchingfeature.nut`). + * + * Stock `matchingfeature.nut` defaults `hasChat`, `hasBattleChatModeAll`, and + * `hasBattleChatModeTeam` to `false` until `wtmm_static.fetch_game_settings` returns + * `features. = true`. Enabling them lets DaRG `hudLogs.nut` and the built-in + * LocalMP host chat dispatcher (`aces.exe` 0x154f540 -> 0x133ba10) accept in-battle + * All/Team/Squad chat and quick-radio voice messages. + */ +import type { MatchingRequestHandler } from './matching-requests.ts'; + +export const fetchGameSettings: MatchingRequestHandler = () => ({ + features: { + hasChat: true, + hasMenuChat: true, + hasBattleChatModeAll: true, + hasBattleChatModeTeam: true, + hasBattleChatModeSquad: true, + hasMenuChatMPlobby: true, + }, +}); diff --git a/packages/local-service/src/matching/matching-requests.ts b/packages/local-service/src/matching/matching-requests.ts index 0a19462..f110fc7 100644 --- a/packages/local-service/src/matching/matching-requests.ts +++ b/packages/local-service/src/matching/matching-requests.ts @@ -8,9 +8,12 @@ * Nothing local checks the credentials (single-player machine); the session key is needed * because the client encrypts everything after this request. */ +import type { AccountStore } from '../accounts/account-store.ts'; import type { GameModes } from '../game-modes/game-modes.ts'; +import { battleQueueRequests, type BattleQueueDependencies } from './battle-queue-requests.ts'; import { fetchClustersList } from './cluster-list.ts'; import { gameModeRequests } from './game-modes-requests.ts'; +import { fetchGameSettings } from './game-settings.ts'; import type { MatchingRequest } from './matching-message.ts'; import { jwtDecryptsWith, unwrapSessionKey } from './session-crypto/session-key.ts'; @@ -18,6 +21,10 @@ import { jwtDecryptsWith, unwrapSessionKey } from './session-crypto/session-key. export interface MatchingSessionControl { /** Encrypt this connection from the answer to the current request on. */ useSessionKey(key: Buffer): void; + /** Bind this matching connection to a verified local account. */ + authenticateUser(userId: string): void; + /** The local account bound during `mlogin.login`, or undefined when unauthenticated. */ + authenticatedUserId(): string | undefined; /** Add a line to the traffic log entry of the current request. */ note(text: string): void; } @@ -28,18 +35,23 @@ export type MatchingRequestTable = ReadonlyMap; export interface MatchingRules { readonly gameModes: GameModes; + readonly accounts?: AccountStore; + readonly battle?: BattleQueueDependencies; } -export function matchingRequests({ gameModes }: MatchingRules): MatchingRequestTable { +export function matchingRequests({ gameModes, accounts, battle }: MatchingRules): MatchingRequestTable { return new Map([ - ['mlogin.login', signIn], + ['mlogin.login', (request, session) => signIn(request, session, accounts)], ['wtmm_static.fetch_clusters_list', fetchClustersList], + ['wtmm_static.fetch_game_settings', fetchGameSettings], + ['mrooms.leave_room', () => ({})], ...gameModeRequests(gameModes), + ...(battle ? battleQueueRequests(battle) : []), ]); } -function signIn(request: MatchingRequest, session: MatchingSessionControl): Record { - const { login, auth_jwt_enc: authJwtEnc } = request.params; +function signIn(request: MatchingRequest, session: MatchingSessionControl, accounts?: AccountStore): Record { + const { login, auth_jwt_enc: authJwtEnc, user_id: rawUserId } = request.params; if (typeof login === 'string') { const { sessionKey, fields } = unwrapSessionKey(login); const verified = typeof authJwtEnc === 'string' && jwtDecryptsWith(sessionKey, authJwtEnc); @@ -48,5 +60,14 @@ function signIn(request: MatchingRequest, session: MatchingSessionControl): Reco } else { session.note('no sealed login field: the connection stays unencrypted'); } + + const userIdText = typeof rawUserId === 'number' && Number.isSafeInteger(rawUserId) + ? String(rawUserId) + : typeof rawUserId === 'string' ? rawUserId.trim() : ''; + const account = userIdText && accounts ? accounts.byUserId(userIdText) : undefined; + if (account) { + session.authenticateUser(account.userId); + session.note(`authenticated user ${account.userId} (${account.nick})`); + } return {}; } diff --git a/packages/local-service/src/matching/matching-service.ts b/packages/local-service/src/matching/matching-service.ts index db7b278..182f25d 100644 --- a/packages/local-service/src/matching/matching-service.ts +++ b/packages/local-service/src/matching/matching-service.ts @@ -49,6 +49,16 @@ export class MatchingService { const message = notifyMessage(name, data); for (const session of this.#sessions) session.pushNotify(message, name); } + + /** Push a matching notification only to active sessions authenticated as `userId`. */ + notifyUser(userId: string, name: string, data: Record): boolean { + const message = notifyMessage(name, data); + let sent = false; + for (const session of this.#sessions) { + if (session.userId() === userId && session.pushNotify(message, name)) sent = true; + } + return sent; + } } class MatchingSession { @@ -59,6 +69,7 @@ class MatchingSession { readonly #packets = new PacketReader(); #sessionKey: Buffer | undefined; #envelopes: EnvelopeReader | undefined; + #userId: string | undefined; constructor(socket: Socket, connectionId: number, requests: MatchingRequestTable, log: TrafficLog) { this.#socket = socket; @@ -67,6 +78,10 @@ class MatchingSession { this.#log = log; } + userId(): string | undefined { + return this.#userId; + } + receive(chunk: Buffer): void { if (this.#envelopes) { for (const plaintext of this.#envelopes.push(chunk)) this.#readPackets(plaintext); @@ -109,6 +124,10 @@ class MatchingSession { this.#sessionKey = key; this.#envelopes = new EnvelopeReader(key); }, + authenticateUser: (userId) => { + this.#userId = userId; + }, + authenticatedUserId: () => this.#userId, note: (text) => notes.push(text), }; const data = handler ? handler(request, control) : {}; @@ -123,10 +142,11 @@ class MatchingSession { this.#socket.write(this.#sessionKey ? sealEnvelope(this.#sessionKey, packet) : packet); } - pushNotify(message: MatchingMessage, summaryName: string): void { - if (!this.#sessionKey || this.#socket.destroyed) return; + pushNotify(message: MatchingMessage, summaryName: string): boolean { + if (!this.#sessionKey || this.#socket.destroyed) return false; this.#record('out', message, `notify ${summaryName} (encrypted)`, false); this.#send(message); + return true; } #record(direction: 'in' | 'out', message: MatchingMessage, summary: string, unhandled: boolean): void { diff --git a/packages/local-service/src/modifications/ammo-refill.ts b/packages/local-service/src/modifications/ammo-refill.ts index 0ef6c18..13cddd5 100644 --- a/packages/local-service/src/modifications/ammo-refill.ts +++ b/packages/local-service/src/modifications/ammo-refill.ts @@ -1,25 +1,10 @@ /** * Initial full stocking and `autoRefillWeapons` Silver-Lion top-up for an owned vehicle's - * modifications, ammunition belts/shells, expendables (`tank_medical_kit_expendable`), and - * secondary weapon presets. + * modifications, ammunition belts/shells, expendables, and secondary weapon presets. * - * Rules: - * 1. Zero-cost modifications (`isFree`) whose `requires` are all owned cannot be bought by the - * client (`weaponsPurchase.nut` `canBuyItem` rejects zero cost) and receive `count = 1` in - * name + topological order, honoring `defaultEnabled` and non-bullet `exclusiveGroup` mutual - * exclusion. - * 2. Free secondary weapon presets (`isFreeWeapon`, excluding `isWeaponForCustomSlot` containers) - * whose `requires` (direct + `sum_weapons` container inheritance) are all owned receive - * `count = 1` so `shop_is_weapon_purchased` allows selecting them. - * 3. Silver-Lion counted modifications (`isCounted` with `goldenEagles === 0`, covering all - * 12,800 shells, gun belts, and `tank_medical_kit_expendable`) and paid weapon presets - * (`isPaidWeapon` with `goldenEagles === 0`) whose `requires` are all owned: - * - When no profile record exists yet (`record === undefined`, i.e. newly acquired vehicle or - * newly unlocked prerequisite modification), receive their initial full load (`maxCount`) - * at no extra Silver-Lion charge (`itemInfo.nut` `getAllModsCost` skips `maxAmount > 1`). - * - When a record already exists with `count < maxCount` (consumed in battle) and hangar - * `autoRefillWeapons` is enabled, buy as many missing pieces with Silver Lions in - * deterministic name order as the player's balance affords. + * Returns the total Silver Lions spent on refilling consumed ammunition, expendables, and + * paid weapon presets during this call (`0` on initial free stocking or when `autoRefill` + * is disabled). */ import type { BlkBlock } from '@wto/blk'; import type { ModificationFacts, VehicleEquipment, WeaponFacts } from '../game-data/datasets/vehicle-equipment.ts'; @@ -29,17 +14,27 @@ import { weaponRecord, writeWeaponRecord } from '../profile/profile-weapons.ts'; import { isCounted, isFree, isFreeWeapon, isPaidWeapon } from './equipment-catalogue.ts'; import { arePrerequisitesOwned } from './module-status.ts'; -export function stockAndRefillEquipment(profile: BlkBlock, equipment: VehicleEquipment, autoRefill: boolean): void { +export interface EquipmentRefillResult { + readonly silverLionsSpent: number; +} + +export function stockAndRefillEquipment( + profile: BlkBlock, + equipment: VehicleEquipment, + autoRefill: boolean, +): EquipmentRefillResult { const modifications = [...equipment.modifications].sort((a, b) => a.name.localeCompare(b.name)); const weapons = [...equipment.weapons].sort((a, b) => a.name.localeCompare(b.name)); grantUnlockedFreeModifications(profile, equipment.vehicle, modifications); grantUnlockedFreeWeapons(profile, equipment.vehicle, weapons); + let silverLionsSpent = 0; for (const modification of modifications) { - stockOrRefillCountedModification(profile, equipment.vehicle, modification, autoRefill); + silverLionsSpent += stockOrRefillCountedModification(profile, equipment.vehicle, modification, autoRefill); } for (const weapon of weapons) { - stockOrRefillPaidWeapon(profile, equipment.vehicle, weapon, autoRefill); + silverLionsSpent += stockOrRefillPaidWeapon(profile, equipment.vehicle, weapon, autoRefill); } + return { silverLionsSpent }; } function grantUnlockedFreeModifications(profile: BlkBlock, vehicle: string, modifications: readonly ModificationFacts[]): void { @@ -84,9 +79,9 @@ function stockOrRefillCountedModification( vehicle: string, modification: ModificationFacts, autoRefill: boolean, -): void { - if (!isCounted(modification) || modification.goldenEagles > 0) return; - if (!arePrerequisitesOwned(profile, vehicle, modification.requires)) return; +): number { + if (!isCounted(modification) || modification.goldenEagles > 0) return 0; + if (!arePrerequisitesOwned(profile, vehicle, modification.requires)) return 0; const record = modificationRecord(profile, vehicle, modification.name); if (record === undefined) { writeModificationRecord(profile, vehicle, modification.name, { @@ -95,11 +90,11 @@ function stockOrRefillCountedModification( enabled: modification.defaultEnabled, count: modification.maxCount, }); - return; + return 0; } - if (!autoRefill || record.count >= modification.maxCount) return; + if (!autoRefill || record.count >= modification.maxCount) return 0; const toBuy = affordableUnits(profile, modification.maxCount - record.count, modification.silverLions); - if (toBuy <= 0) return; + if (toBuy <= 0) return 0; const cost = toBuy * modification.silverLions; if (cost > 0) pay(profile, { silverLions: cost, goldenEagles: 0 }); writeModificationRecord(profile, vehicle, modification.name, { @@ -107,19 +102,25 @@ function stockOrRefillCountedModification( silverLionsSpent: record.silverLionsSpent + cost, count: record.count + toBuy, }); + return cost; } -function stockOrRefillPaidWeapon(profile: BlkBlock, vehicle: string, weapon: WeaponFacts, autoRefill: boolean): void { - if (!isPaidWeapon(weapon) || weapon.goldenEagles > 0) return; - if (!arePrerequisitesOwned(profile, vehicle, weapon.requires)) return; +function stockOrRefillPaidWeapon( + profile: BlkBlock, + vehicle: string, + weapon: WeaponFacts, + autoRefill: boolean, +): number { + if (!isPaidWeapon(weapon) || weapon.goldenEagles > 0) return 0; + if (!arePrerequisitesOwned(profile, vehicle, weapon.requires)) return 0; const record = weaponRecord(profile, vehicle, weapon.name); if (record === undefined) { writeWeaponRecord(profile, vehicle, weapon.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, count: weapon.maxCount }); - return; + return 0; } - if (!autoRefill || record.count >= weapon.maxCount) return; + if (!autoRefill || record.count >= weapon.maxCount) return 0; const toBuy = affordableUnits(profile, weapon.maxCount - record.count, weapon.silverLions); - if (toBuy <= 0) return; + if (toBuy <= 0) return 0; const cost = toBuy * weapon.silverLions; if (cost > 0) pay(profile, { silverLions: cost, goldenEagles: 0 }); writeWeaponRecord(profile, vehicle, weapon.name, { @@ -127,6 +128,7 @@ function stockOrRefillPaidWeapon(profile: BlkBlock, vehicle: string, weapon: Wea goldenEaglesSpent: record.goldenEaglesSpent, count: record.count + toBuy, }); + return cost; } function affordableUnits(profile: BlkBlock, missing: number, unitSilverCost: number): number { diff --git a/packages/local-service/src/modifications/module-research-target.ts b/packages/local-service/src/modifications/module-research-target.ts index f65681b..26143af 100644 --- a/packages/local-service/src/modifications/module-research-target.ts +++ b/packages/local-service/src/modifications/module-research-target.ts @@ -1,19 +1,67 @@ /** - * Choosing the modification a vehicle researches: cln_set_researchable - * with unit:t and mod:t (script shop_set_researchable_unit_module). The modification has to be - * researchable now; it goes into hangar//investMode, and the client shows it as "in - * research" from there. + * Choosing the modification an owned vehicle researches (`cln_set_researchable` with + * `unit:t` and `mod:t`) and pouring banked `excessExp` into a modification + * (`cln_move_exp_to_module`). */ import type { BlkBlock } from '@wto/blk'; -import { setModuleResearchTarget } from '../profile/profile-vehicle-state.ts'; +import { ownedVehicles } from '../profile/profile-hangar.ts'; +import { moduleResearchPoints, setModuleResearchPoints } from '../profile/profile-module-research.ts'; +import { + setFinishedModuleResearch, + setModuleResearchTarget, + setVehicleExcessRp, + vehicleExcessRp, +} from '../profile/profile-vehicle-state.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import type { EquipmentCatalogue } from './equipment-catalogue.ts'; import { currentModuleStatus } from './module-state.ts'; import { ModuleStatus } from './module-status.ts'; -export function chooseModuleResearch(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, modification: string): RuleOutcome { +export function chooseModuleResearch( + profile: BlkBlock, + catalogue: EquipmentCatalogue, + vehicle: string, + modification: string, +): RuleOutcome { + if (modification === '') { + if (!catalogue.vehicle(vehicle) || !ownedVehicles(profile).has(vehicle)) return refused('BAD_PARAMS'); + setModuleResearchTarget(profile, vehicle, ''); + setFinishedModuleResearch(profile, vehicle, ''); + return ACCEPTED; + } if (!catalogue.modification(vehicle, modification)) return refused('BAD_PARAMS'); - if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); + if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) { + return refused('NOT_AVAILABLE'); + } setModuleResearchTarget(profile, vehicle, modification); + setFinishedModuleResearch(profile, vehicle, ''); + return ACCEPTED; +} + +export function moveExcessExpToModule( + profile: BlkBlock, + catalogue: EquipmentCatalogue, + vehicle: string, + modification: string, +): RuleOutcome { + const modFacts = catalogue.modification(vehicle, modification); + if (!modFacts || modFacts.researchPoints <= 0) return refused('BAD_PARAMS'); + if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) { + return refused('NOT_AVAILABLE'); + } + const available = vehicleExcessRp(profile, vehicle); + const before = moduleResearchPoints(profile, vehicle, modification); + const moved = Math.min(available, Math.max(0, modFacts.researchPoints - before)); + if (moved <= 0) return ACCEPTED; + const remaining = available - moved; + setVehicleExcessRp(profile, vehicle, remaining); + setModuleResearchPoints(profile, vehicle, modification, before + moved); + if (before + moved >= modFacts.researchPoints) { + setModuleResearchTarget(profile, vehicle, ''); + setFinishedModuleResearch(profile, vehicle, ''); + } else { + setModuleResearchTarget(profile, vehicle, modification); + setFinishedModuleResearch(profile, vehicle, ''); + } return ACCEPTED; } diff --git a/packages/local-service/src/modifications/module-state.ts b/packages/local-service/src/modifications/module-state.ts index 78bce57..11faef1 100644 --- a/packages/local-service/src/modifications/module-state.ts +++ b/packages/local-service/src/modifications/module-state.ts @@ -1,23 +1,30 @@ /** - * Bringing the modification state of a profile up to date, like research/research-state.ts does - * for vehicles: whenever a profile is handed out or changed (profiles-setup.ts), for every owned - * vehicle (sorted by name for deterministic auto-refill deduction): - * modifications & weapons unlocked free items, initial full stock of newly unlocked - * ammunition / expendables / paid presets, and Silver-Lion - * top-ups when `autoRefillWeapons` is enabled (ammo-refill.ts) - * hangar//tierNumber the highest open tier - * modsResearch the status of every modification not owned yet; locked ones - * only keep an entry while they hold research points - * hangar//investMode cleared when that modification is no longer researchable + * Keeping every owned vehicle's modification state synchronized with its owned equipment + * and modification research points: + * - grants newly unlocked free items, stocks newly unlocked counted items, and runs SL + * top-ups when `autoRefillWeapons` is enabled; + * - writes `hangar//tierNumber` and `modsResearch` statuses; + * - maintains `investMode` so finished-modification prompts (`investModePrev != ""`) open + * `WeaponsModalHandler` in `researchMode` when researchable modifications remain (or signal + * `isResearchLast` with `investMode = ""` when the vehicle is spaded), without overwriting + * an intentionally empty `investMode` while `excessExp > 0` inside the modal. */ import type { BlkBlock } from '@wto/blk'; +import type { VehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts'; import { isAutoRefillWeaponsEnabled } from '../profile/profile-client-settings.ts'; import { ownedVehicles } from '../profile/profile-hangar.ts'; import { moduleResearchPoints, removeModuleResearch, setModuleStatus } from '../profile/profile-module-research.ts'; -import { moduleResearchTarget, setModuleResearchTarget, setOpenTier } from '../profile/profile-vehicle-state.ts'; +import { + finishedModuleResearch, + moduleResearchTarget, + setModuleResearchTarget, + setOpenTier, + setVehicleExcessRp, + vehicleExcessRp, +} from '../profile/profile-vehicle-state.ts'; import { stockAndRefillEquipment } from './ammo-refill.ts'; -import type { EquipmentCatalogue } from './equipment-catalogue.ts'; -import { ModuleStatus, vehicleModuleState } from './module-status.ts'; +import { isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts'; +import { isModuleResearched, ModuleStatus, vehicleModuleState, type VehicleModuleState } from './module-status.ts'; export function refreshModuleState(profile: BlkBlock, catalogue: EquipmentCatalogue): void { const autoRefill = isAutoRefillWeaponsEnabled(profile); @@ -32,16 +39,51 @@ export function refreshModuleState(profile: BlkBlock, catalogue: EquipmentCatalo const status = state.statuses.get(modification.name); if (status === undefined || (status === ModuleStatus.LOCKED && moduleResearchPoints(profile, vehicle, modification.name) === 0)) { removeModuleResearch(profile, vehicle, modification.name); + } else { + setModuleStatus(profile, vehicle, modification.name, status); } - else setModuleStatus(profile, vehicle, modification.name, status); } - const target = moduleResearchTarget(profile, vehicle); - if (target && state.statuses.get(target) !== ModuleStatus.CAN_RESEARCH) setModuleResearchTarget(profile, vehicle, ''); + syncVehicleInvestMode(profile, equipment, state); } } -/** The status of one modification the player does not own; undefined when owned, unknown or the vehicle is not owned. */ -export function currentModuleStatus(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, modification: string): ModuleStatus | undefined { +function syncVehicleInvestMode(profile: BlkBlock, equipment: VehicleEquipment, state: VehicleModuleState): void { + const vehicle = equipment.vehicle; + const target = moduleResearchTarget(profile, vehicle); + if (target && state.statuses.get(target) === ModuleStatus.CAN_RESEARCH) return; + + const hasAnyUnresearched = equipment.modifications.some( + (mod) => isResearchable(mod) && !isModuleResearched(profile, vehicle, mod), + ); + if (!hasAnyUnresearched) { + setModuleResearchTarget(profile, vehicle, ''); + setVehicleExcessRp(profile, vehicle, 0); + return; + } + + const nextMod = pickDefaultResearchableModule(equipment, state); + const prevMod = finishedModuleResearch(profile, vehicle); + const excess = vehicleExcessRp(profile, vehicle); + if (prevMod !== '' || excess === 0) { + setModuleResearchTarget(profile, vehicle, nextMod); + } else { + setModuleResearchTarget(profile, vehicle, ''); + } +} + +export function pickDefaultResearchableModule(equipment: VehicleEquipment, state: VehicleModuleState): string { + const ordered = [...equipment.modifications] + .filter((mod) => isResearchable(mod) && state.statuses.get(mod.name) === ModuleStatus.CAN_RESEARCH) + .sort((a, b) => (a.tier !== b.tier ? a.tier - b.tier : a.name.localeCompare(b.name))); + return ordered[0]?.name ?? ''; +} + +export function currentModuleStatus( + profile: BlkBlock, + catalogue: EquipmentCatalogue, + vehicle: string, + modification: string, +): ModuleStatus | undefined { const equipment = catalogue.vehicle(vehicle); if (!equipment || !ownedVehicles(profile).has(vehicle)) return undefined; return vehicleModuleState(profile, equipment).statuses.get(modification); diff --git a/packages/local-service/src/modifications/module-status.ts b/packages/local-service/src/modifications/module-status.ts index 562672c..e3e2f80 100644 --- a/packages/local-service/src/modifications/module-status.ts +++ b/packages/local-service/src/modifications/module-status.ts @@ -1,7 +1,7 @@ /** - * The status of each modification of an owned vehicle. The client - * works out "owned" and "mounted" from the modifications records and "in research" from - * investMode itself; the server supplies the rest through modsResearch: + * The status of each modification of an owned vehicle. The client works out "owned" and + * "mounted" from the modifications records and "in research" from `investMode` itself; the + * server supplies the rest through `modsResearch`: * * researchable modification (tier 1+, research points) * tier not open LOCKED diff --git a/packages/local-service/src/profile/profile-crew-skills.ts b/packages/local-service/src/profile/profile-crew-skills.ts index 7f0448b..ae025cb 100644 --- a/packages/local-service/src/profile/profile-crew-skills.ts +++ b/packages/local-service/src/profile/profile-crew-skills.ts @@ -1,10 +1,11 @@ /** - * Crew skills, skill points and specializations inside a crew block: + * Crew skills, skill points, specializations, and Expert-to-Ace RP inside a crew block: * * crews{ * c0{ * country:t="country_usa" * aircrafts{ trained:t="us_m2a4" spec:i=1 trained:t="us_m22_locust" spec:i=0 current:t="us_m2a4" } + * expertToAceProgress{ us_m2a4:i=12000 } * commander{ crewMember_0{ eyesight:i64=5 field_repair:i64=2 } } * skillPointsStat:i64=0 * skillPointsManualChanges:i64=150000 @@ -15,7 +16,8 @@ * kept times 100: the client shows (skillPointsStat + skillPointsManualChanges) / 100 * (get_crew_info, 0x179dbac); the local service books what the player buys and spends in * skillPointsManualChanges. Every trained vehicle is followed by its spec (0 none, 1 expert, - * 2 ace), as the client writes them (0x939ed0..0x939f55). + * 2 ace), as the client writes them (0x939ed0..0x939f55), and per-vehicle Expert-to-Ace RP sits + * in expertToAceProgress/:i (0x93b0d0..0x93b4eb). */ import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; @@ -26,6 +28,7 @@ const POINTS_SCALE = 100; const VEHICLES = 'aircrafts'; const TRAINED = 'trained'; const SPEC = 'spec'; +const ACE_PROGRESS = 'expertToAceProgress'; export function skillLevel(crew: BlkBlock, page: string, skill: string): number { const pageBlock = findBlock(crew, page); @@ -78,6 +81,18 @@ export function trainedPairs(crew: BlkBlock): { vehicle: string; spec: number }[ return pairs; } +export function expertToAceRp(crew: BlkBlock, vehicle: string): number { + const progress = findBlock(crew, ACE_PROGRESS); + return progress ? intOf(progress, vehicle) : 0; +} + +export function addExpertToAceRp(crew: BlkBlock, vehicle: string, deltaRp: number, maxRp: number): void { + if (deltaRp <= 0 || maxRp <= 0) return; + const current = expertToAceRp(crew, vehicle); + const next = Math.min(maxRp, Math.max(0, current + Math.trunc(deltaRp))); + if (next !== current) setParam(ensureBlock(crew, ACE_PROGRESS), vehicle, { type: 'int', value: next }); +} + function intOf(block: BlkBlock, name: string): number { const value = findParam(block, name)?.value; if (value?.type === 'int64') return Number(value.value); diff --git a/packages/local-service/src/profile/profile-crews.ts b/packages/local-service/src/profile/profile-crews.ts index a335296..73b47a7 100644 --- a/packages/local-service/src/profile/profile-crews.ts +++ b/packages/local-service/src/profile/profile-crews.ts @@ -33,6 +33,38 @@ export function crewCountOf(profile: BlkBlock, country: string): number { return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => crewCountry(crew) === country).length; } +/** Non-empty vehicles currently slotted in the country's crews, in profile order. */ +export function crewVehiclesOfCountry(profile: BlkBlock, country: string): string[] { + return allCrews(profile) + .filter((crew) => crewCountry(crew) === country) + .flatMap((crew) => { + const current = crew.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value; + return current?.type === 'string' && current.value.length > 0 ? [current.value] : []; + }); +} + +/** Vehicle slotted in the country's `slotIndex`-th crew (`idInCountry`), if non-empty. */ +export function crewSlotVehicleOfCountry(profile: BlkBlock, country: string, slotIndex: number): string | undefined { + if (!Number.isInteger(slotIndex) || slotIndex < 0) return undefined; + const crew = allCrews(profile).filter((entry) => crewCountry(entry) === country)[slotIndex]; + const current = crew?.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value; + return current?.type === 'string' && current.value.length > 0 ? current.value : undefined; +} + +/** Crew block in `country` currently equipping `vehicle` (or trained for it as fallback). */ +export function crewForVehicleInCountry(profile: BlkBlock, country: string, vehicle: string): BlkBlock | undefined { + const crews = allCrews(profile).filter((entry) => crewCountry(entry) === country); + const slotted = crews.find((entry) => { + const current = entry.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value; + return current?.type === 'string' && current.value === vehicle; + }); + if (slotted) return slotted; + return crews.find((entry) => + (entry.blocks.find((block) => block.name === VEHICLES)?.params ?? []).some( + (param) => param.name === TRAINED && param.value.type === 'string' && param.value.value === vehicle, + )); +} + /** Add an empty crew for the country, numbered after every existing crew; returns its id. */ export function addCrew(profile: BlkBlock, country: string): number { const crews = ensureBlock(profile, CREWS); diff --git a/packages/local-service/src/profile/profile-dest-rp.ts b/packages/local-service/src/profile/profile-dest-rp.ts new file mode 100644 index 0000000..5342abd --- /dev/null +++ b/packages/local-service/src/profile/profile-dest-rp.ts @@ -0,0 +1,96 @@ +/** + * Cross-branch research-point redirection in profile.blk ("Research helicopters by playing + * ground vehicles", gui.vromfs.bin scripts/shop/shop.nut:2341-2354). + * + * Profile contract (verified in aces.exe 2.61.0.37 0x930150..0x93082a & 0x903ca0): + * researchUnits{ + * country_usa{ + * destTypeRPTank:t="Helicopter" + * } + * } + * - Reader (0x93020e..0x930247): reads "destTypeRP" inside researchUnits. + * and maps it against VEHICLE_TYPES (0..6); missing or unrecognized values become -1 + * (ES_UNIT_TYPE_INVALID), exposed to Squirrel by getDestinationRPUnitType (0x15532f0). + * - Writer (0x9307eb..0x93082a): writes "destTypeRP" only when 0 <= destType <= 6 + * and omits the parameter when disabled (-1). + */ +import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { TechTree } from '../research/tech-tree.ts'; +import { VEHICLE_TYPES, vehicleTypeById, type VehicleType } from '../research/vehicle-types.ts'; +import { removeParam, stringField } from './blk-fields.ts'; +import { researchTarget } from './profile-research-targets.ts'; + +const RESEARCH_UNITS = 'researchUnits'; +const DEST_TYPE_PREFIX = 'destTypeRP'; +const INVALID_UNIT_TYPE = -1; + +export type VehicleDomain = VehicleType; + +const VALID_DOMAINS: ReadonlySet = new Set(VEHICLE_TYPES); + +export function destinationRpDomain( + profile: BlkBlock, + country: string, + sourceDomain: VehicleDomain, +): VehicleDomain | undefined { + const countryBlock = findBlock(findBlock(profile, RESEARCH_UNITS) ?? { name: '', params: [], blocks: [] }, country); + const raw = stringField(countryBlock, `${DEST_TYPE_PREFIX}${sourceDomain}`); + if (!raw || !VALID_DOMAINS.has(raw) || raw === sourceDomain) return undefined; + return raw as VehicleDomain; +} + +export function setDestinationRpDomain( + profile: BlkBlock, + country: string, + sourceDomain: VehicleDomain, + destinationDomain: VehicleDomain | undefined, +): void { + const countryBlock = ensureBlock(ensureBlock(profile, RESEARCH_UNITS), country); + const paramName = `${DEST_TYPE_PREFIX}${sourceDomain}`; + if (!destinationDomain || destinationDomain === sourceDomain) { + removeParam(countryBlock, paramName); + return; + } + removeParam(countryBlock, paramName); + countryBlock.params.push({ name: paramName, value: { type: 'string', value: destinationDomain } }); +} + +/** Validate and apply cln_set_dest_rp_unit_type (country:t, srcType:i, destType:i). */ +export function applySetDestinationRpRule( + profile: BlkBlock, + techTree: TechTree, + country: string, + srcTypeId: number, + destTypeId: number, +): RuleOutcome { + const sourceDomain = vehicleTypeById(srcTypeId); + if (!country || !techTree.hasCountry(country) || !sourceDomain) return refused('BAD_PARAMS'); + if (destTypeId === INVALID_UNIT_TYPE) { + setDestinationRpDomain(profile, country, sourceDomain, undefined); + return ACCEPTED; + } + const destinationDomain = vehicleTypeById(destTypeId); + if (!destinationDomain || destinationDomain === sourceDomain) return refused('BAD_PARAMS'); + const hasDestinationBranch = techTree.branches().some( + (branch) => branch.country === country && branch.type === destinationDomain, + ); + if (!hasDestinationBranch) return refused('NOT_AVAILABLE'); + setDestinationRpDomain(profile, country, sourceDomain, destinationDomain); + return ACCEPTED; +} + +/** + * Resolve the effective research branch for battle settlement: returns the redirected domain + * (such as 'Helicopter' when playing 'Tank') when configured and that branch still has an + * active currUnit research target, otherwise falls back to sourceDomain. + */ +export function readRedirectedResearchDomain( + profile: BlkBlock, + country: string, + sourceDomain: VehicleDomain, +): VehicleDomain { + const redirected = destinationRpDomain(profile, country, sourceDomain); + if (!redirected) return sourceDomain; + return researchTarget(profile, country, redirected) !== '' ? redirected : sourceDomain; +} diff --git a/packages/local-service/src/profile/profile-research-points.ts b/packages/local-service/src/profile/profile-research-points.ts index 1f007d6..daec80f 100644 --- a/packages/local-service/src/profile/profile-research-points.ts +++ b/packages/local-service/src/profile/profile-research-points.ts @@ -23,6 +23,12 @@ export function spendFreeResearchPoints(profile: BlkBlock, amount: number): void setCounter(profile, SPENT, counter(profile, SPENT) + amount); } +/** Credit convertible (free) research points earned in battle (`experience:i64`). */ +export function addFreeResearchPoints(profile: BlkBlock, amount: number): void { + if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`); + if (amount > 0) setCounter(profile, EARNED, counter(profile, EARNED) + amount); +} + /** Make the free research points this amount (the save editor). */ export function setFreeResearchPoints(profile: BlkBlock, amount: number): void { if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`); diff --git a/packages/local-service/src/profile/profile-research-targets.ts b/packages/local-service/src/profile/profile-research-targets.ts index 2956a8d..020ecc9 100644 --- a/packages/local-service/src/profile/profile-research-targets.ts +++ b/packages/local-service/src/profile/profile-research-targets.ts @@ -1,6 +1,6 @@ /** - * The current research target and the just-finished research of each country and vehicle - * type. + * Current research target, just-finished research vehicle, and banked excess RP per country + * and vehicle branch (`aces.exe` `0x930150`): * * researchUnits{ * country_usa{ @@ -24,6 +24,7 @@ import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto const RESEARCH_UNITS = 'researchUnits'; const CURRENT = 'currUnit'; const FINISHED = 'prevUnit'; +const EXCESS_EXP = 'exp'; export function researchTarget(profile: BlkBlock, country: string, vehicleType: string): string { return field(profile, country, `${CURRENT}${vehicleType}`); @@ -41,6 +42,22 @@ export function setFinishedResearch(profile: BlkBlock, country: string, vehicleT setField(profile, country, `${FINISHED}${vehicleType}`, vehicle); } +export function branchExcessRp(profile: BlkBlock, country: string, vehicleType: string): number { + const units = findBlock(profile, RESEARCH_UNITS); + const block = units && findBlock(units, country); + const value = block && findParam(block, `${EXCESS_EXP}${vehicleType}`)?.value; + if (value?.type === 'int64') return Math.max(0, Number(value.value)); + return value?.type === 'int' ? Math.max(0, value.value) : 0; +} + +export function setBranchExcessRp(profile: BlkBlock, country: string, vehicleType: string, amount: number): void { + const clamped = Math.max(0, Math.trunc(amount)); + setParam(ensureBlock(ensureBlock(profile, RESEARCH_UNITS), country), `${EXCESS_EXP}${vehicleType}`, { + type: 'int64', + value: BigInt(clamped), + }); +} + function field(profile: BlkBlock, country: string, name: string): string { const units = findBlock(profile, RESEARCH_UNITS); const block = units && findBlock(units, country); diff --git a/packages/local-service/src/profile/profile-trophies-log.ts b/packages/local-service/src/profile/profile-trophies-log.ts index 14b4385..f3b9715 100644 --- a/packages/local-service/src/profile/profile-trophies-log.ts +++ b/packages/local-service/src/profile/profile-trophies-log.ts @@ -12,7 +12,8 @@ const TROPHIES = 'trophies'; const USERLOGS = 'userlogs'; const PURCHASE_RECEIPT = 'purchaseReceipt'; -// Registered by the client at 0x1a5569e (2.61.0.37). +// Registered by the client at 0x1a554dc / 0x1a5569e / 0x1a5599b (2.61.0.37). +export const EULT_SESSION_RESULT = 2; const EULT_BUYENTITLEMENT = 13; export const EULT_OPEN_TROPHY = 30; export const EULT_BUY_TROPHY = 20; @@ -32,6 +33,7 @@ export function incrementTrophyOpenCount(profile: BlkBlock, trophyId: string, de export interface NewUserLogEntry { readonly type: number; readonly timeSec: number; + readonly roomId?: bigint; readonly bodyParams: readonly BlkParam[]; readonly bodyBlocks?: readonly BlkBlock[]; } @@ -53,7 +55,7 @@ export function appendUserLog(profile: BlkBlock, entry: NewUserLogEntry): string params: [ { name: 'type', value: { type: 'int', value: entry.type } }, { name: 'time', value: { type: 'int', value: entry.timeSec } }, - { name: 'roomId', value: { type: 'int64', value: 0n } }, + { name: 'roomId', value: { type: 'int64', value: entry.roomId ?? 0n } }, ], blocks: [{ name: 'body', diff --git a/packages/local-service/src/profile/profile-vehicle-state.ts b/packages/local-service/src/profile/profile-vehicle-state.ts index aa76d14..399b7a5 100644 --- a/packages/local-service/src/profile/profile-vehicle-state.ts +++ b/packages/local-service/src/profile/profile-vehicle-state.ts @@ -1,17 +1,20 @@ /** - * Per-vehicle fields of owned vehicles: hangar{ { ... } }, - * read by name by AircraftInfo::serialize (aces.exe 0x940510). Only the fields the local - * service maintains are handled here: - * investMode:t the modification being researched (empty = none) - * tierNumber:i the highest open modification tier (script is_tier_available) - * spareAircraftsCount:i spares the player has for this vehicle + * Per-vehicle fields of owned vehicles under `hangar{ { ... } }`, read by name in + * `AircraftInfo::serialize` (`aces.exe` `0x940510`): + * investMode:t the modification currently selected for research (`+0x100`) + * investModePrev:t the modification whose research just finished (`+0x108`) + * tierNumber:i the highest open modification tier + * spareAircraftsCount:i vehicle-specific backups owned + * excessExp:i64 banked modification overflow RP (`+0x70`) */ import { findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; const HANGAR = 'hangar'; const RESEARCH_TARGET = 'investMode'; +const FINISHED_TARGET = 'investModePrev'; const OPEN_TIER = 'tierNumber'; const SPARES = 'spareAircraftsCount'; +const EXCESS_EXP = 'excessExp'; export function moduleResearchTarget(profile: BlkBlock, vehicle: string): string { const value = fieldOf(profile, vehicle, RESEARCH_TARGET); @@ -23,6 +26,16 @@ export function setModuleResearchTarget(profile: BlkBlock, vehicle: string, modi if (entry) setParam(entry, RESEARCH_TARGET, { type: 'string', value: modification }); } +export function finishedModuleResearch(profile: BlkBlock, vehicle: string): string { + const value = fieldOf(profile, vehicle, FINISHED_TARGET); + return value?.type === 'string' ? value.value : ''; +} + +export function setFinishedModuleResearch(profile: BlkBlock, vehicle: string, modification: string): void { + const entry = vehicleEntry(profile, vehicle); + if (entry) setParam(entry, FINISHED_TARGET, { type: 'string', value: modification }); +} + export function setOpenTier(profile: BlkBlock, vehicle: string, tier: number): void { const entry = vehicleEntry(profile, vehicle); if (entry) setParam(entry, OPEN_TIER, { type: 'int', value: tier }); @@ -38,6 +51,17 @@ export function setSpareCount(profile: BlkBlock, vehicle: string, count: number) if (entry) setParam(entry, SPARES, { type: 'int', value: count }); } +export function vehicleExcessRp(profile: BlkBlock, vehicle: string): number { + const value = fieldOf(profile, vehicle, EXCESS_EXP); + if (value?.type === 'int64') return Math.max(0, Number(value.value)); + return value?.type === 'int' ? Math.max(0, value.value) : 0; +} + +export function setVehicleExcessRp(profile: BlkBlock, vehicle: string, amount: number): void { + const entry = vehicleEntry(profile, vehicle); + if (entry) setParam(entry, EXCESS_EXP, { type: 'int64', value: BigInt(Math.max(0, Math.trunc(amount))) }); +} + function fieldOf(profile: BlkBlock, vehicle: string, name: string) { const entry = vehicleEntry(profile, vehicle); return entry && findParam(entry, name)?.value; diff --git a/packages/local-service/src/profile/profile-wishlist.ts b/packages/local-service/src/profile/profile-wishlist.ts new file mode 100644 index 0000000..846a67c --- /dev/null +++ b/packages/local-service/src/profile/profile-wishlist.ts @@ -0,0 +1,98 @@ +/** + * Vehicle wishlist persistence in profile.blk (cln_add_to_wish_list / cln_remove_from_wish_list). + * + * Binary & script contract (verified in aces.exe 2.61.0.37 0x967c30..0x96891b, getWishList + * 0x1553470, and gui.vromfs.bin scripts/wishlist/wishlistManager.nut): + * wishList{ + * units{ + * us_m1_abrams{ + * cmnts:t="optional note" + * ts:i64=1764260000 + * } + * } + * } + * - When reading profile.blk (0x967c40..0x967d8a), if top-level "wishList" is absent the client + * returns early without clearing its in-memory wishlist vector ([econ + 0xe868]). Keeping an + * empty wishList { units {} } block on removal ensures 0x967ebd..0x967f19 clears the client's + * vector immediately upon profile sync. + * - Static limits come from char.vromfs.bin config/warpoints.blk: maxWishListSize:i=100 and + * maxWishListCommentSize:i=100 (exposed via getMaxWishListSize 0x1553450 and + * getMaxWishListCommentSize 0x1553460). + */ +import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { TechTree } from '../research/tech-tree.ts'; +import { int64Field, stringField } from './blk-fields.ts'; +import { ownsVehicle } from './profile-hangar.ts'; + +const WISH_LIST_BLOCK = 'wishList'; +const UNITS_BLOCK = 'units'; +const COMMENT_PARAM = 'cmnts'; +const TIMESTAMP_PARAM = 'ts'; + +/** Limits defined in char.vromfs.bin config/warpoints.blk (maxWishListSize / maxWishListCommentSize). */ +export const DEFAULT_WISHLIST_LIMITS: WishlistLimits = { + maxSize: 100, + maxCommentLength: 100, +}; + +export interface WishlistLimits { + readonly maxSize: number; + readonly maxCommentLength: number; +} + +export interface WishlistEntry { + readonly unit: string; + readonly comment: string; + readonly timestampSec: number; +} + +export function readWishlist(profile: BlkBlock): WishlistEntry[] { + const unitsBlock = findBlock(findBlock(profile, WISH_LIST_BLOCK) ?? { name: '', params: [], blocks: [] }, UNITS_BLOCK); + if (!unitsBlock) return []; + return unitsBlock.blocks + .filter((entry) => entry.name.length > 0) + .map((entry) => ({ + unit: entry.name, + comment: stringField(entry, COMMENT_PARAM), + timestampSec: Number(int64Field(entry, TIMESTAMP_PARAM, 0n)), + })); +} + +export function hasWishlistUnit(profile: BlkBlock, unit: string): boolean { + const unitsBlock = findBlock(findBlock(profile, WISH_LIST_BLOCK) ?? { name: '', params: [], blocks: [] }, UNITS_BLOCK); + return unitsBlock !== undefined && unitsBlock.blocks.some((entry) => entry.name === unit); +} + +export function addWishlistUnit( + profile: BlkBlock, + techTree: TechTree, + unit: string, + comment: string, + timestampSec: number, + limits: WishlistLimits = DEFAULT_WISHLIST_LIMITS, +): RuleOutcome { + if (!unit || [...comment].length > limits.maxCommentLength) return refused('BAD_PARAMS'); + const vehicle = techTree.vehicle(unit); + if (!vehicle || vehicle.kind === 'part' || vehicle.kind === 'hidden') return refused('BAD_PARAMS'); + if (ownsVehicle(profile, unit) || hasWishlistUnit(profile, unit)) return refused('NOT_AVAILABLE'); + const unitsBlock = ensureWishlistUnitsBlock(profile); + if (unitsBlock.blocks.length >= limits.maxSize) return refused('NOT_AVAILABLE'); + + const params: BlkParam[] = []; + if (comment.length > 0) params.push({ name: COMMENT_PARAM, value: { type: 'string', value: comment } }); + params.push({ name: TIMESTAMP_PARAM, value: { type: 'int64', value: BigInt(Math.max(0, Math.trunc(timestampSec))) } }); + unitsBlock.blocks.push({ name: unit, params, blocks: [] }); + return ACCEPTED; +} + +export function removeWishlistUnit(profile: BlkBlock, unit: string): RuleOutcome { + if (!unit) return refused('BAD_PARAMS'); + const unitsBlock = ensureWishlistUnitsBlock(profile); + unitsBlock.blocks = unitsBlock.blocks.filter((entry) => entry.name !== unit); + return ACCEPTED; +} + +function ensureWishlistUnitsBlock(profile: BlkBlock): BlkBlock { + return ensureBlock(ensureBlock(profile, WISH_LIST_BLOCK), UNITS_BLOCK); +} diff --git a/packages/local-service/src/research/research-progress.ts b/packages/local-service/src/research/research-progress.ts index 869de40..222e9d2 100644 --- a/packages/local-service/src/research/research-progress.ts +++ b/packages/local-service/src/research/research-progress.ts @@ -1,31 +1,32 @@ /** - * Choosing what to research and putting research points into a vehicle (implementation notes - * sections 1.2, 4.3 and 5). - * - * - Choosing a research target (cln_set_researchable) makes a researchable vehicle the - * target of its country and type and closes the "research finished" prompt. - * - Dismissing that prompt (cln_reset_researchable) only closes it. - * - Converting free research points (cln_convert_exp) costs the points and golden eagles: - * one golden eagle per researchPointsPerGoldenEagle points, rounded up. The stock window - * (scripts/convertExp/convertExpHandler.nut) never asks for more than the vehicle still - * needs; more is cut down to that. - * - When a vehicle's research points reach what it needs and it is the target, the target is - * cleared and the vehicle recorded as just finished, which makes the client offer the next - * research; the refresh after the change (research-state.ts) then picks the next target. + * Choosing a vehicle research target (`cln_set_researchable`), dismissing a finished-research + * prompt (`cln_reset_researchable`), converting free RP (`cln_convert_exp`), and investing + * banked branch excess RP (`cln_move_exp_to_unit`). */ import type { BlkBlock } from '@wto/blk'; import { balanceOf, pay } from '../profile/profile-currency.ts'; import { freeResearchPoints, spendFreeResearchPoints } from '../profile/profile-research-points.ts'; -import { researchTarget, setFinishedResearch, setResearchTarget } from '../profile/profile-research-targets.ts'; +import { + branchExcessRp, + researchTarget, + setBranchExcessRp, + setFinishedResearch, + setResearchTarget, +} from '../profile/profile-research-targets.ts'; import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts'; -import { currentStatus } from './research-state.ts'; import type { ResearchRules } from './research-rules.ts'; +import { currentStatus } from './research-state.ts'; import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts'; import type { TreeVehicle } from './tech-tree.ts'; import { VehicleStatus } from './vehicle-status.ts'; import { vehicleTypeById } from './vehicle-types.ts'; -export function chooseResearchTarget(profile: BlkBlock, rules: ResearchRules, vehicleName: string, typeId: number): RuleOutcome { +export function chooseResearchTarget( + profile: BlkBlock, + rules: ResearchRules, + vehicleName: string, + typeId: number, +): RuleOutcome { const vehicle = rules.techTree.vehicle(vehicleName); if (!vehicle || vehicleTypeById(typeId) !== vehicle.type) return refused('BAD_PARAMS'); if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); @@ -34,14 +35,24 @@ export function chooseResearchTarget(profile: BlkBlock, rules: ResearchRules, ve return ACCEPTED; } -export function dismissFinishedResearch(profile: BlkBlock, rules: ResearchRules, country: string, typeId: number): RuleOutcome { +export function dismissFinishedResearch( + profile: BlkBlock, + rules: ResearchRules, + country: string, + typeId: number, +): RuleOutcome { const type = vehicleTypeById(typeId); if (!type || !rules.techTree.hasCountry(country)) return refused('BAD_PARAMS'); setFinishedResearch(profile, country, type, ''); return ACCEPTED; } -export function convertFreeResearchPoints(profile: BlkBlock, rules: ResearchRules, vehicleName: string, requested: number): RuleOutcome { +export function convertFreeResearchPoints( + profile: BlkBlock, + rules: ResearchRules, + vehicleName: string, + requested: number, +): RuleOutcome { const vehicle = rules.techTree.vehicle(vehicleName); if (!vehicle || !Number.isSafeInteger(requested) || requested <= 0) return refused('BAD_PARAMS'); if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); @@ -55,7 +66,28 @@ export function convertFreeResearchPoints(profile: BlkBlock, rules: ResearchRule return ACCEPTED; } -/** Add research points to a vehicle; finishing the research target opens the next-research prompt. */ +export function moveExcessExpToUnit(profile: BlkBlock, rules: ResearchRules, vehicleName: string): RuleOutcome { + const vehicle = rules.techTree.vehicle(vehicleName); + if (!vehicle) return refused('BAD_PARAMS'); + if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); + const available = branchExcessRp(profile, vehicle.country, vehicle.type); + const before = researchPointsOf(profile, vehicle.name); + const needed = Math.max(0, vehicle.researchPoints - before); + const moved = Math.min(available, needed); + if (moved <= 0) return ACCEPTED; + const remaining = available - moved; + setBranchExcessRp(profile, vehicle.country, vehicle.type, remaining); + setResearchPoints(profile, vehicle.name, before + moved); + if (before + moved >= vehicle.researchPoints) { + setResearchTarget(profile, vehicle.country, vehicle.type, ''); + setFinishedResearch(profile, vehicle.country, vehicle.type, remaining > 0 ? '' : vehicle.name); + } else { + setResearchTarget(profile, vehicle.country, vehicle.type, vehicle.name); + setFinishedResearch(profile, vehicle.country, vehicle.type, ''); + } + return ACCEPTED; +} + export function addResearchPoints(profile: BlkBlock, vehicle: TreeVehicle, amount: number): void { const before = researchPointsOf(profile, vehicle.name); setResearchPoints(profile, vehicle.name, before + amount); diff --git a/packages/local-service/src/research/research-rules.ts b/packages/local-service/src/research/research-rules.ts index 3e9596d..c1a9f93 100644 --- a/packages/local-service/src/research/research-rules.ts +++ b/packages/local-service/src/research/research-rules.ts @@ -1,6 +1,6 @@ /** - * The static facts vehicle research and purchase rules use, loaded once at start-up from - * the player's game files (implementation notes; implementation notes). + * Static facts used by vehicle research and purchase rules, loaded once at startup from game + * files. */ import type { DatasetCache } from '../game-data/datasets/dataset-cache.ts'; import { crewSlotPrices, eraRequirements, type CrewSlotPrices, type EraRequirements } from '../game-data/datasets/rank-settings.ts'; @@ -16,7 +16,6 @@ export interface ResearchRules { readonly vehicleUnlocks: readonly UnlockDefinition[]; readonly crewSlotPrices: CrewSlotPrices; readonly researchPointsPerGoldenEagle: number; - /** How a branch without a research target gets one (tuning/research.jsonc; implementation notes). */ readonly researchTuning: ResearchTuning; } diff --git a/packages/local-service/src/research/research-state.ts b/packages/local-service/src/research/research-state.ts index b9a409e..6fb6ad6 100644 --- a/packages/local-service/src/research/research-state.ts +++ b/packages/local-service/src/research/research-state.ts @@ -1,30 +1,32 @@ /** - * Bringing the research state of a profile up to date. The char - * server keeps it current online; the local service does it whenever a profile is handed out - * or changed (profile/player-profiles.ts), so the state always follows from the facts: - * owned vehicles, research points, earned unlocks. - * - * 1. Open ranks and earn unlocks until neither changes anything (an unlock can give a vehicle, - * a vehicle can open a rank, a rank can earn an unlock). - * 2. Write every vehicle's status into unitResearch: owned vehicles have no entry, locked - * vehicles only keep one while they hold research points. - * 3. Keep every branch researching while it can: a target that is no - * longer researchable (bought, researched, ...) is replaced, and a branch without one gets - * one, picked by auto-research-target.ts; "" only when nothing can be researched. + * Keeping a player's vehicle research state consistent with owned vehicles, earned unlocks, + * and branch research progress: + * 1. Open ranks and earn unlocks until neither changes anything. + * 2. Write every non-owned vehicle's status into `unitResearch`. + * 3. Maintain `currUnit` without overwriting an intentionally empty target while + * banked `exp` is being spent inside `ShopCheckResearch`, while seeding a default + * target on brand-new branches (`currUnit === "" && prevUnit === "" && excessRp === 0`) + * and autosetting a 0-RP cursor candidate when `prevUnit !== ""` so stock + * `researchActions.nut` (`checkNonApprovedResearches`) opens `ShopCheckResearch`. */ import type { BlkBlock } from '@wto/blk'; -import { pickResearchTarget } from './auto-research-target.ts'; -import type { TreeVehicle } from './tech-tree.ts'; import { ownedVehicles } from '../profile/profile-hangar.ts'; -import { finishedResearch, researchTarget, setResearchTarget } from '../profile/profile-research-targets.ts'; +import { + branchExcessRp, + finishedResearch, + researchTarget, + setBranchExcessRp, + setResearchTarget, +} from '../profile/profile-research-targets.ts'; import { earnedUnlocks } from '../profile/profile-unlocks.ts'; import { removeVehicleResearch, researchPointsOf, setVehicleStatus } from '../profile/profile-vehicle-research.ts'; +import { pickResearchTarget } from './auto-research-target.ts'; import { openEarnedRanks } from './era-progress.ts'; import type { ResearchRules } from './research-rules.ts'; -import { earnVehicleUnlocks } from './vehicle-unlock-rules.ts'; +import type { TreeVehicle } from './tech-tree.ts'; import { VehicleStatus, vehicleStatuses } from './vehicle-status.ts'; +import { earnVehicleUnlocks } from './vehicle-unlock-rules.ts'; -/** More rounds than any chain in the game data needs; stops a faulty data loop. */ const MAX_ROUNDS = 16; export function refreshResearchState(profile: BlkBlock, rules: ResearchRules): void { @@ -39,26 +41,33 @@ export function refreshResearchState(profile: BlkBlock, rules: ResearchRules): v const statuses = vehicleStatuses({ profile, owned, earnedUnlocks: earned, techTree: rules.techTree }); for (const vehicle of rules.techTree.all()) { const status = statuses.get(vehicle.name); - if (status === undefined || (status === VehicleStatus.LOCKED && researchPointsOf(profile, vehicle.name) === 0)) removeVehicleResearch(profile, vehicle.name); - else setVehicleStatus(profile, vehicle.name, status); + if (status === undefined || (status === VehicleStatus.LOCKED && researchPointsOf(profile, vehicle.name) === 0)) { + removeVehicleResearch(profile, vehicle.name); + } else { + setVehicleStatus(profile, vehicle.name, status); + } } const candidates = researchCandidates(rules, statuses); + const unresearchedBranches = branchesWithUnresearchedTreeVehicles(rules, statuses); for (const { country, type } of rules.techTree.branches()) { + const key = `${country}/${type}`; + if (!unresearchedBranches.has(key)) { + setBranchExcessRp(profile, country, type, 0); + } const target = researchTarget(profile, country, type); if (target && statuses.get(target) === VehicleStatus.CAN_RESEARCH) continue; - const previous = target || finishedResearch(profile, country, type); - const next = pickResearchTarget(candidates.get(`${country}/${type}`) ?? [], rules.researchTuning, previous); - setResearchTarget(profile, country, type, next?.name ?? ''); + if (target) setResearchTarget(profile, country, type, ''); + + const prev = finishedResearch(profile, country, type); + const excess = branchExcessRp(profile, country, type); + if (prev !== '' || excess === 0) { + const next = pickResearchTarget(candidates.get(key) ?? [], rules.researchTuning, target || prev); + setResearchTarget(profile, country, type, next?.name ?? ''); + } } } -/** - * The vehicles a branch target can be chosen from, by "country/type": what the stock scripts - * offer as a research target (scripts/unit/unitStatus.nut canResearchUnit; squadron vehicles - * have their own target, implementation notes, and are left out as scripts/shop/shopCheckResearch.nut - * getMaxRankResearchingUnitByCountry does). - */ function researchCandidates(rules: ResearchRules, statuses: ReadonlyMap): Map { const byBranch = new Map(); for (const vehicle of rules.techTree.all()) { @@ -71,7 +80,26 @@ function researchCandidates(rules: ResearchRules, statuses: ReadonlyMap, +): Set { + const branches = new Set(); + for (const vehicle of rules.techTree.all()) { + if (vehicle.kind !== 'research') continue; + const status = statuses.get(vehicle.name); + if (status === VehicleStatus.CAN_RESEARCH || status === VehicleStatus.LOCKED) { + branches.add(`${vehicle.country}/${vehicle.type}`); + } + } + return branches; +} + export function currentStatus(profile: BlkBlock, rules: ResearchRules, vehicle: string): VehicleStatus | undefined { - return vehicleStatuses({ profile, owned: ownedVehicles(profile), earnedUnlocks: earnedUnlocks(profile), techTree: rules.techTree }).get(vehicle); + return vehicleStatuses({ + profile, + owned: ownedVehicles(profile), + earnedUnlocks: earnedUnlocks(profile), + techTree: rules.techTree, + }).get(vehicle); } diff --git a/packages/local-service/src/server/port-listener.ts b/packages/local-service/src/server/port-listener.ts index bd86f88..5fdc393 100644 --- a/packages/local-service/src/server/port-listener.ts +++ b/packages/local-service/src/server/port-listener.ts @@ -1,14 +1,17 @@ /** - * The local service's one listening port. Every address in the game's network.blk points - * here, and the network hook library sends every other connection of the - * game here too (5.1), so connections arrive in several protocols. The first bytes of a - * connection decide where it goes: the matching protocol (first byte 1, see - * matching/matching-frame.ts) to the matching service; a TLS handshake (record type 0x16) is - * answered with the local certificate and the decrypted stream goes to the HTTP server; - * everything else (HTTP, other) goes to the HTTP server directly. + * The local service's single listening port. Every address in the game's network.blk points + * here, and the network hook library routes all other outbound game connections here as well. + * The first bytes of a connection decide which protocol handler accepts it: + * - Matching binary packet (first byte 1) -> MatchingService; + * - Plaintext IRC handshake (`PASS` / `NICK` / `USER` / `CAP` / `PING`) -> IrcServer; + * - TLS ClientHello (record type 0x16) -> decrypted with the local certificate, then routed + * to IrcServer or the HTTP server based on the first decrypted bytes; + * - Everything else -> HTTP server directly. */ import { createServer, type Server, type Socket } from 'node:net'; import { createSecureContext, TLSSocket } from 'node:tls'; +import { startsIrcHandshake } from '../chat/irc-protocol.ts'; +import { IrcServer } from '../chat/irc-server.ts'; import type { TlsCredentials } from './tls/tls-certificate.ts'; import type { MatchingRequestTable } from '../matching/matching-requests.ts'; import { MatchingService } from '../matching/matching-service.ts'; @@ -34,6 +37,7 @@ export function createPortListener(router: Router, matchingRequests: MatchingReq let lastNumber = 0; const http = createHttpServer(router, log, (socket) => numbers.get(socket) ?? 0); const matching = new MatchingService(matchingRequests, log); + const irc = new IrcServer(); const server = createServer((socket) => { lastNumber += 1; @@ -51,11 +55,18 @@ export function createPortListener(router: Router, matchingRequests: MatchingReq socket.pause(); socket.unshift(first); if (startsMatchingPacket(first)) matching.accept(socket, number); + else if (startsIrcHandshake(first)) irc.accept(socket); else if (first[0] === TLS_HANDSHAKE) { const secure = new TLSSocket(socket, { isServer: true, secureContext }); numbers.set(secure, number); secure.on('error', () => socket.destroy()); - http.emit('connection', secure); + secure.once('data', (innerFirst: Buffer) => { + secure.pause(); + secure.unshift(innerFirst); + if (startsIrcHandshake(innerFirst)) irc.accept(secure); + else http.emit('connection', secure); + process.nextTick(() => secure.resume()); + }); } else http.emit('connection', socket); process.nextTick(() => socket.resume()); }); diff --git a/packages/local-service/src/store/store-web-api.ts b/packages/local-service/src/store/store-web-api.ts index fcb863b..b665fac 100644 --- a/packages/local-service/src/store/store-web-api.ts +++ b/packages/local-service/src/store/store-web-api.ts @@ -1,6 +1,5 @@ /** - * The JSON requests of the local store page (/store, shown in the game's built-in browser; - * implementation notes): + * The JSON requests of the local store page (/store, shown in the game's built-in browser): * GET /store/api/state?userId= balances, products and redeem code help for one account * POST /store/api/buy { userId, productId } * POST /store/api/cart { userId, productId, action } diff --git a/packages/local-service/src/store/web/gallery.js b/packages/local-service/src/store/web/gallery.js index 07d4d31..76164c1 100644 --- a/packages/local-service/src/store/web/gallery.js +++ b/packages/local-service/src/store/web/gallery.js @@ -2,6 +2,7 @@ 'use strict'; const galleryPlayers = new WeakMap(); +const CLIP_TIMEOUT_MS = 23_000; function stopStoreGallery(root) { const stage = root.querySelector('.media-stage'); @@ -29,8 +30,7 @@ function galleryItems(product) { return entries; } -function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable) { - galleryPlayers.get(stage)?.(); +function createClipVideoElement(poster, autoplay) { const video = document.createElement('video'); video.controls = true; video.playsInline = true; @@ -41,6 +41,12 @@ function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable) video.loop = true; } if (poster) video.poster = poster; + return video; +} + +function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable) { + galleryPlayers.get(stage)?.(); + const video = createClipVideoElement(poster, autoplay); const playable = sources.filter((url) => video.canPlayType(/\.webm(?:$|\?)/i.test(url) ? 'video/webm' : 'video/mp4')); let nextSource = 0; let timer; @@ -64,34 +70,125 @@ function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable) return; } video.src = url; - timer = setTimeout(attempt, 23_000); + timer = setTimeout(attempt, CLIP_TIMEOUT_MS); void video.play().catch(() => {}); } video.onerror = attempt; - video.oncanplay = () => { - clearTimeout(timer); - onReady(); - }; + video.oncanplay = () => { clearTimeout(timer); onReady(); }; stage.replaceChildren(video); galleryPlayers.set(stage, dispose); attempt(); } function appendScreenshot(container, item, loaded, eager = false) { + const candidates = storeImageCandidates(item.screenshot); const image = makeElement('img', 'gallery-screenshot'); image.alt = eager ? item.label : ''; image.loading = eager ? 'eager' : 'lazy'; + image.crossOrigin = 'anonymous'; + image.referrerPolicy = 'no-referrer'; + let index = 0; + + function tryNext() { + const nextUrl = candidates[index++]; + if (!nextUrl) { + image.onload = image.onerror = null; + image.remove(); + loaded(false); + return; + } + image.src = nextUrl; + } + image.onload = () => { + image.onload = image.onerror = null; image.classList.add('ready'); loaded(true); }; - image.onerror = () => loaded(false); - image.src = item.screenshot; + image.onerror = tryNext; container.append(image); + tryNext(); return image; } +function renderStageScreenshot(stage, status, product, item) { + const gameArt = WtoUi.tieredImg([], productArtwork(product), ''); + gameArt.loading = 'eager'; + stage.append(gameArt); + status.textContent = t('screenshotLoading'); + status.hidden = false; + const image = appendScreenshot(stage, item, (ok) => { + if (image.parentNode !== stage) return; + if (ok) { + gameArt.remove(); + status.hidden = true; + } else { + status.textContent = t('screenshotUnavailable'); + } + }, true); +} + +function renderStageMedia(stage, status, product, item, showPlay, onPlay) { + stage.replaceChildren(); + if (item.screenshot) { + renderStageScreenshot(stage, status, product, item); + return; + } + const image = item.image(); + image.loading = 'eager'; + image.alt = item.label; + stage.append(image); + if (!showPlay) return; + const play = storeButton('media-play', '▶ ' + t('playVideo')); + play.onclick = () => onPlay(item, false); + stage.append(play); +} + +function startStageVideo(stage, status, product, item, autoplay) { + const image = stage.querySelector('img'); + const poster = image?.currentSrc || image?.getAttribute('src'); + status.textContent = t('videoLoading'); + status.hidden = false; + playStoreClip(stage, item.sources, poster, autoplay, () => { status.hidden = true; }, () => { + renderStageMedia(stage, status, product, item, true, (target, auto) => startStageVideo(stage, status, product, target, auto)); + status.textContent = t('videoUnavailable'); + status.hidden = false; + }); +} + +function createGalleryThumb(item, index, onSelect) { + const button = storeButton('media-thumb'); + button.setAttribute('aria-label', item.label); + button.setAttribute('aria-pressed', 'false'); + button.title = item.label; + if (item.screenshot) { + const label = makeElement('span', 'media-placeholder', item.label); + button.append(label); + appendScreenshot(button, item, (ok) => { if (ok) label.remove(); }); + } else { + button.append(item.image()); + } + if (item.sources) button.append(makeElement('span', 'thumb-play', '▶')); + button.onclick = () => onSelect(index, true); + return button; +} + +function bindGalleryControls(nav, rail, prev, next, buttons, itemsLength, getActive, onSelect) { + prev.setAttribute('aria-label', t('previousMedia')); + next.setAttribute('aria-label', t('nextMedia')); + prev.onclick = () => onSelect(getActive() - 1); + next.onclick = () => onSelect(getActive() + 1); + rail.append(...buttons); + rail.onkeydown = (event) => { + if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return; + event.preventDefault(); + onSelect(getActive() + (event.key === 'ArrowRight' ? 1 : -1)); + buttons[getActive()].focus({ preventScroll: true }); + }; + nav.hidden = itemsLength === 1; +} + function mountStoreGallery(root, product, autoplay) { const items = galleryItems(product); root.innerHTML = '
' @@ -106,51 +203,7 @@ function mountStoreGallery(root, product, autoplay) { const caption = root.querySelector('.media-caption'); const status = root.querySelector('.media-status'); let active = 0; - - function showImage(item, showPlay) { - stage.replaceChildren(); - if (item.screenshot) { - showScreenshot(item); - return; - } - const image = item.image(); - image.loading = 'eager'; - image.alt = item.label; - stage.append(image); - if (!showPlay) return; - const play = storeButton('media-play', '▶ ' + t('playVideo')); - play.onclick = () => playItem(item); - stage.append(play); - } - - function showScreenshot(item) { - const gameArt = WtoUi.tieredImg([], productArtwork(product), ''); - gameArt.loading = 'eager'; - stage.append(gameArt); - status.textContent = t('screenshotLoading'); - status.hidden = false; - const image = appendScreenshot(stage, item, (ok) => { - if (image.parentNode !== stage) return; - if (ok) { - gameArt.remove(); - status.hidden = true; - } else { - status.textContent = t('screenshotUnavailable'); - } - }, true); - } - - function playItem(item, autoplay = false) { - const image = stage.querySelector('img'); - const poster = image?.currentSrc || image?.getAttribute('src'); - status.textContent = t('videoLoading'); - status.hidden = false; - playStoreClip(stage, item.sources, poster, autoplay, () => { status.hidden = true; }, () => { - showImage(item, true); - status.textContent = t('videoUnavailable'); - status.hidden = false; - }); - } + const playItem = (item, auto = false) => startStageVideo(stage, status, product, item, auto); function select(index, play = false, scroll = true) { if (index < 0 || index >= items.length) return; @@ -158,47 +211,20 @@ function mountStoreGallery(root, product, autoplay) { buttons[active].setAttribute('aria-pressed', 'false'); active = index; const item = items[index]; - const button = buttons[index]; - button.setAttribute('aria-pressed', 'true'); - if (scroll) button.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + buttons[index].setAttribute('aria-pressed', 'true'); + if (scroll) buttons[index].scrollIntoView({ block: 'nearest', inline: 'nearest' }); prev.disabled = index === 0; next.disabled = index === items.length - 1; caption.querySelector('.media-label').textContent = item.label; caption.querySelector('.media-position').textContent = (index + 1) + ' / ' + items.length; status.hidden = true; - showImage(item, !!item.sources); - if (play && item.sources) playItem(item); + renderStageMedia(stage, status, product, item, !!item.sources, playItem); + if (play && item.sources) playItem(item, false); } - const buttons = items.map((item, index) => { - const button = storeButton('media-thumb'); - button.setAttribute('aria-label', item.label); - button.setAttribute('aria-pressed', 'false'); - button.title = item.label; - if (item.screenshot) { - const label = makeElement('span', 'media-placeholder', item.label); - button.append(label); - appendScreenshot(button, item, (ok) => { if (ok) label.remove(); }); - } else { - button.append(item.image()); - } - if (item.sources) button.append(makeElement('span', 'thumb-play', '▶')); - button.onclick = () => select(index, true); - return button; - }); - prev.setAttribute('aria-label', t('previousMedia')); - next.setAttribute('aria-label', t('nextMedia')); - prev.onclick = () => select(active - 1); - next.onclick = () => select(active + 1); - rail.append(...buttons); - rail.onkeydown = (event) => { - if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return; - event.preventDefault(); - select(active + (event.key === 'ArrowRight' ? 1 : -1)); - buttons[active].focus({ preventScroll: true }); - }; - nav.hidden = caption.hidden = items.length === 1; + const buttons = items.map((item, index) => createGalleryThumb(item, index, select)); + bindGalleryControls(nav, rail, prev, next, buttons, items.length, () => active, select); + caption.hidden = items.length === 1; select(0, false, false); - const initial = items[0]; - if (autoplay && initial.sources) playItem(initial, true); + if (autoplay && items[0].sources) playItem(items[0], true); } diff --git a/packages/local-service/src/store/web/products.js b/packages/local-service/src/store/web/products.js index 3e56a01..b6b77fb 100644 --- a/packages/local-service/src/store/web/products.js +++ b/packages/local-service/src/store/web/products.js @@ -24,19 +24,31 @@ function rankLabel(rank) { return t('rank', { rank: ROMAN[rank] || rank }); } +const LOCAL_STORE_MEDIA_PREFIX = '/_wto/ui/store-media/'; +const PUBLIC_STORE_CDN = 'https://static-store.gaijin.net/'; + +function storeImageCandidates(localUrl) { + if (!localUrl) return []; + if (!localUrl.startsWith(LOCAL_STORE_MEDIA_PREFIX)) return [localUrl]; + return [localUrl, PUBLIC_STORE_CDN + localUrl.slice(LOCAL_STORE_MEDIA_PREFIX.length)]; +} + function productArtwork(product) { const image = product.unitName ? WtoUi.artworkUrl('vehicle', product.unitName) : WtoUi.artworkUrl('product', product.kind); - return product.artworkGroup ? [WtoUi.artworkUrl('group', product.artworkGroup), image] : [image]; + const fallbacks = product.artworkGroup ? [WtoUi.artworkUrl('group', product.artworkGroup), image] : [image]; + if (product.unitName) fallbacks.push('/_wto/ui/vehicle/' + encodeURIComponent(product.unitName) + '.svg'); + return fallbacks; } function productImage(product, className = '') { const { cover } = WtoUi.storeMedia(product.id); - const urls = product.unitName ? [cover, ...WtoUi.vehicleUrls(product.unitName)] : [cover]; + const candidates = storeImageCandidates(cover); + const urls = product.unitName ? [...candidates, ...WtoUi.vehicleUrls(product.unitName)] : candidates; return WtoUi.tieredImg(urls, productArtwork(product), className); } function productScreenshot(product, url, className = '') { - return WtoUi.tieredImg([url], productArtwork(product), className); + return WtoUi.tieredImg(storeImageCandidates(url), productArtwork(product), className); } function vehicleMeta(vehicle) { diff --git a/packages/local-service/src/tuning/limits-tuning.ts b/packages/local-service/src/tuning/limits-tuning.ts index 9d12930..5324b2a 100644 --- a/packages/local-service/src/tuning/limits-tuning.ts +++ b/packages/local-service/src/tuning/limits-tuning.ts @@ -4,11 +4,13 @@ import type { TuningReader } from './tuning-reader.ts'; export interface LimitsTuning { readonly itemPiecesPerPurchase: number; readonly userLogsKept: number; + readonly battleSessionsKept: number; } export function readLimitsTuning(file: TuningReader): LimitsTuning { return { itemPiecesPerPurchase: file.int('itemPiecesPerPurchase', { min: 1 }), userLogsKept: file.int('userLogsKept', { min: 1 }), + battleSessionsKept: file.int('battleSessionsKept', { min: 1 }), }; } diff --git a/packages/local-service/src/tuning/tuning.ts b/packages/local-service/src/tuning/tuning.ts index feeac14..5f6b241 100644 --- a/packages/local-service/src/tuning/tuning.ts +++ b/packages/local-service/src/tuning/tuning.ts @@ -4,6 +4,7 @@ * limits, preset content). Values the game data already has are read from the game files * instead, and protocol constants stay in the code next to their source. */ +import { readBattleTuning, type BattleTuning } from '../battle/battle-tuning.ts'; import { readClanTuning, type ClanTuning } from '../clans/clan-tuning.ts'; import { readMarketplaceTuning, type MarketplaceTuning } from '../inventory/marketplace-tuning.ts'; import { readRecyclingTuning, type RecyclingTuning } from '../inventory/recycling-tuning.ts'; @@ -26,6 +27,7 @@ export interface Tuning { readonly recycling: RecyclingTuning; readonly trophies: TrophyTuning; readonly clans: ClanTuning; + readonly battle: BattleTuning; readonly limits: LimitsTuning; } @@ -41,6 +43,7 @@ export function loadTuning(dataFolder: string, report: (line: string) => void): recycling: readRecyclingTuning(files.read('recycling')), trophies: readTrophyTuning(files.read('trophies')), clans: readClanTuning(files.read('clans')), + battle: readBattleTuning(files.read('battle')), limits: readLimitsTuning(files.read('limits')), }; } diff --git a/packages/local-service/src/web-ui/store-media-cache.ts b/packages/local-service/src/web-ui/store-media-cache.ts index d8fec2a..dbdccb2 100644 --- a/packages/local-service/src/web-ui/store-media-cache.ts +++ b/packages/local-service/src/web-ui/store-media-cache.ts @@ -1,12 +1,18 @@ -/** Fetch and cache only public media named in the bundled store manifest. */ +/** + * Serve pre-cached store covers, screenshots, and demo clips from local disk only. + * + * The local service listens strictly on loopback and never initiates outbound network + * requests: files present in the player's offline asset pack or local media cache are + * served directly (with HTTP byte-range support for video playback), while uncached + * paths immediately return 404 so the browser UI falls back without stalling. + */ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import type { ServiceResponse } from '../server/exchange.ts'; -import { writeFileAtomic } from '../storage/atomic-file.ts'; export const STORE_MEDIA_PREFIX = 'store-media/'; -const CDN = 'https://static-store.gaijin.net/'; +const STORE_HOST = 'static-store.gaijin.net'; const MANIFEST = new URL('./web/official-store-media.json', import.meta.url); const CONTENT_TYPES: Readonly> = { jpg: 'image/jpeg', webm: 'video/webm', mp4: 'video/mp4', @@ -32,28 +38,30 @@ function knownAssets(): ReadonlyMap { export class StoreMediaCache { readonly #assets = knownAssets(); - readonly #packFolder: string; - readonly #cacheFolder: string; - readonly #pending = new Map>(); - readonly #retryAfter = new Map(); + readonly #roots: readonly string[]; constructor(dataFolder: string) { - this.#packFolder = join(dataFolder, 'asset-pack', new URL(CDN).hostname); - this.#cacheFolder = join(dataFolder, 'cache', 'store-media'); + this.#roots = [ + join(dataFolder, 'asset-pack', STORE_HOST), + join(dataFolder, 'cache', 'store-media'), + join(dataFolder, 'store-media-cache'), + join(dataFolder, 'store-assets'), + ]; } - async serve(path: string, range: string | undefined): Promise { + serve(path: string, range: string | undefined): ServiceResponse { const type = this.#assets.get(path); if (!type) return { status: 404, logNotes: { summary: 'unknown store media' } }; - const cachedPath = join(this.#cacheFolder, path); - const bytes = readCached(join(this.#packFolder, path)) ?? readCached(cachedPath) - ?? await this.#downloadOnce(path, type, cachedPath); - - const logNotes = { summary: 'store media: ' + path, omitResponseBody: true }; + const bytes = this.#readLocal(path); if (!bytes) { - return { status: 503, headers: { 'cache-control': 'no-store' }, logNotes: { ...logNotes, summary: 'store media unavailable: ' + path } }; + return { + status: 404, + headers: { 'cache-control': 'no-store' }, + logNotes: { summary: 'store media not cached: ' + path }, + }; } + const logNotes = { summary: 'store media: ' + path, omitResponseBody: true }; const headers = { 'content-type': type, 'cache-control': 'public, max-age=86400', 'accept-ranges': 'bytes' }; if (!range) return { status: 200, headers: { ...headers, 'content-length': String(bytes.length) }, body: bytes, logNotes }; const span = parseRange(range, bytes.length); @@ -68,22 +76,12 @@ export class StoreMediaCache { }; } - async #downloadOnce(path: string, type: string, cachedPath: string): Promise { - if ((this.#retryAfter.get(path) ?? 0) > Date.now()) return undefined; - const pending = this.#pending.get(path); - if (pending) return pending; - - const work = downloadAsset(path, type).then((bytes) => { - if (bytes) { - this.#retryAfter.delete(path); - try { writeFileAtomic(cachedPath, bytes); } catch { /* The response is usable even if the disk cache is unavailable. */ } - } else { - this.#retryAfter.set(path, Date.now() + 30_000); - } - return bytes; - }).finally(() => { this.#pending.delete(path); }); - this.#pending.set(path, work); - return work; + #readLocal(path: string): Buffer | undefined { + for (const root of this.#roots) { + const bytes = readCached(join(root, path)); + if (bytes) return bytes; + } + return undefined; } } @@ -97,49 +95,6 @@ function readCached(path: string): Buffer | undefined { } } -async function downloadAsset(path: string, type: string): Promise { - const video = type.startsWith('video/'); - const signal = AbortSignal.timeout(video ? 20_000 : 7_500); - for (let attempt = 0; attempt < 2 && !signal.aborted; attempt++) { - try { - const response = await fetch(new URL(path, CDN), { signal, redirect: 'error' }); - if (response.ok && response.headers.get('content-type')?.split(';', 1)[0] === type) { - return await readMediaBody(response, (video ? 64 : 8) * 1024 * 1024); - } - await response.body?.cancel(); - if (response.status < 500) return undefined; - } catch { - // Retry a transient connection error within the original time limit. - } - } - return undefined; -} - -async function readMediaBody(response: Response, limit: number): Promise { - const reader = response.body?.getReader(); - if (!reader) return undefined; - try { - if (Number(response.headers.get('content-length')) > limit) { - await reader.cancel(); - return undefined; - } - const chunks: Uint8Array[] = []; - let bytes = 0; - for (;;) { - const { done, value } = await reader.read(); - if (done) return bytes ? Buffer.concat(chunks, bytes) : undefined; - bytes += value.length; - if (bytes > limit) { - await reader.cancel(); - return undefined; - } - chunks.push(value); - } - } finally { - reader.releaseLock(); - } -} - function parseRange(range: string, size: number): readonly [number, number] | undefined { const match = /^bytes=(\d*)-(\d*)$/.exec(range); if (!match || (!match[1] && !match[2])) return undefined; diff --git a/packages/local-service/tuning/battle.jsonc b/packages/local-service/tuning/battle.jsonc new file mode 100644 index 0000000..2bb29a6 --- /dev/null +++ b/packages/local-service/tuning/battle.jsonc @@ -0,0 +1,41 @@ +// Offline battle session capacity, AI bot pool rules, nation coalitions, and post-battle multipliers. +{ + // Global post-battle Silver Lions and Research Points multipliers (1.0 matches stock rates). + "rewardMultiplierSilverLions": 1.0, + "rewardMultiplierResearchPoints": 1.0, + + // LocalMP session capacity (16v16 = 32 total slots: 1 local player + up to 31 AI bots). + "maxPlayers": 32, + "maxBots": 31, + + // Reduced LocalMP session capacity when Tactical Skies (`small_teams_`) is selected (8v8 = 16). + "smallTeamsMaxPlayers": 16, + + // Chance (0..1) of rolling an enabled sub-mode (Night Battles, Tactical Skies, Bullet Hell, + // Nuclear Escalation, Naval EC) when queued alongside the classic mode; 1.0 when classic is off. + "subModeChance": 0.5, + + // Matchmaking economic-rank spread around the player's lineup mrank (3 steps = +/- 1.0 BR). + "brSpreadMrank": 3, + + // Maximum vehicles per unit category (tanks, aircraft, ships) emitted into customBots. + "botPoolLimitPerType": 80, + + // Realistic Battles multi-nation coalition size bounds and mixed-battle probabilities. + "rbCoalitionMinCountries": 2, + "rbCoalitionMaxCountries": 5, + "rbGroundMixedChance": 0.08, + "rbAirMixedChance": 0.25, + "rbNavalMixedChance": 0.70, + + // Simulator Battles Cold War / modern bloc cutoff mrank (18 = BR 7.0). + "simColdWarMinMrank": 18, + + // AI bot respawn limits per battle in multi-slot versus modes. + "tankBotRespawns": 3, + "airBotRespawns": 2, + + // Team win-inference weights when the player leaves while the battle is still running. + "earlyLeaveTicketWeight": 0.7, + "earlyLeaveKillWeight": 0.3 +} diff --git a/packages/local-service/tuning/limits.jsonc b/packages/local-service/tuning/limits.jsonc index 016efe5..1cb07c0 100644 --- a/packages/local-service/tuning/limits.jsonc +++ b/packages/local-service/tuning/limits.jsonc @@ -3,5 +3,7 @@ // Maximum classic item quantity per cln_buy_item purchase. "itemPiecesPerPurchase": 1000, // Number of recent user logs to retain. Older unread purchase receipts are kept until acknowledged. - "userLogsKept": 80 + "userLogsKept": 80, + // Number of recent in-memory battle sessions retained for idempotent settlement checks. + "battleSessionsKept": 256 } diff --git a/tools/src/wtotools/cli/__init__.py b/tools/src/wtotools/cli/__init__.py index 305fd0f..97d4890 100644 --- a/tools/src/wtotools/cli/__init__.py +++ b/tools/src/wtotools/cli/__init__.py @@ -2,6 +2,7 @@ Each group of commands lives in its own module and registers itself here: - exe_commands: check-patches, patch-exe +- gui_commands: check-gui Run `wtotools --help` for the arguments of one command. """ @@ -9,14 +10,14 @@ from __future__ import annotations import argparse -from . import exe_commands +from . import exe_commands, gui_commands def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="wtotools", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) commands = parser.add_subparsers(dest="command", required=True) - for group in (exe_commands,): + for group in (exe_commands, gui_commands): group.register(commands) args = parser.parse_args(argv) return args.handler(args) diff --git a/tools/src/wtotools/cli/exe_commands.py b/tools/src/wtotools/cli/exe_commands.py index d3878d3..4c61042 100644 --- a/tools/src/wtotools/cli/exe_commands.py +++ b/tools/src/wtotools/cli/exe_commands.py @@ -1,6 +1,7 @@ """Commands that work on the game executable. wtotools check-patches --exe [--patches exe-patches] + wtotools check-offsets --exe [--header native/wto-net/src/local_mp_offsets.h] wtotools patch-exe --exe --out [--patches exe-patches] [--force] The input executable is only ever read. `patch-exe` refuses to write over its input and @@ -15,9 +16,11 @@ from pathlib import Path from ..exepatch import apply_writes, changed_ranges, load_patches, plan_patches from ..exepatch.assemble import disagreement +from ..offset_check import parse_offset_header, verify_offsets from ..pe import PeImage DEFAULT_PATCHES = Path("exe-patches") +DEFAULT_OFFSET_HEADER = Path("native/wto-net/src/local_mp_offsets.h") def register(commands: argparse._SubParsersAction) -> None: @@ -25,6 +28,11 @@ def register(commands: argparse._SubParsersAction) -> None: _add_common(check) check.set_defaults(handler=_check_patches) + offsets = commands.add_parser("check-offsets", help="verify native LocalMP signatures and anchor strings") + offsets.add_argument("--exe", type=Path, required=True, help="the game executable to read") + offsets.add_argument("--header", type=Path, default=DEFAULT_OFFSET_HEADER, help="C header with LMP_SIG_* and @anchor tags") + offsets.set_defaults(handler=_check_offsets) + patch = commands.add_parser("patch-exe", help="apply every patch to a copy of the executable") _add_common(patch) patch.add_argument("--out", type=Path, required=True, help="where to write the patched copy") @@ -55,6 +63,14 @@ def _check_patches(args: argparse.Namespace) -> int: return 0 if plan.complete and not mismatched else 1 +def _check_offsets(args: argparse.Namespace) -> int: + spec = parse_offset_header(args.header) + ok, lines = verify_offsets(PeImage(args.exe.read_bytes()), spec) + for line in lines: + print(line) + return 0 if ok else 1 + + def _patch_exe(args: argparse.Namespace) -> int: if args.out.resolve() == args.exe.resolve(): print("refusing to write over the input executable; choose a different --out", file=sys.stderr) diff --git a/tools/src/wtotools/cli/gui_commands.py b/tools/src/wtotools/cli/gui_commands.py new file mode 100644 index 0000000..318ed19 --- /dev/null +++ b/tools/src/wtotools/cli/gui_commands.py @@ -0,0 +1,39 @@ +"""Command to verify `gui-patches/` against `gui.vromfs.bin` with Quirrel bytecode compilation. + + wtotools check-gui --gui [--patches gui-patches] [--sq build/quirrel-check/sq.exe] +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from ..gui_check import verify_gui_patches + +DEFAULT_GUI_PATCHES = Path("gui-patches") +DEFAULT_SQ_EXE = Path("build/quirrel-check/sq.exe") + + +def register(commands: argparse._SubParsersAction) -> None: + check = commands.add_parser( + "check-gui", + help="apply gui-patches in memory and bytecode-compile every modified .nut script", + ) + check.add_argument("--gui", type=Path, required=True, help="stock gui.vromfs.bin to read") + check.add_argument("--patches", type=Path, default=DEFAULT_GUI_PATCHES, help="gui-patches directory") + check.add_argument("--sq", type=Path, default=DEFAULT_SQ_EXE, help="Quirrel compiler sq.exe path") + check.set_defaults(handler=_check_gui) + + +def _check_gui(args: argparse.Namespace) -> int: + if not args.sq.exists(): + print(f"Quirrel compiler not found: {args.sq}", file=sys.stderr) + return 2 + report = verify_gui_patches(args.gui, args.patches, args.sq) + print(f"{report.patches_applied} GUI patch(es) applied across {report.files_checked} .nut file(s)") + if report.errors: + for error in report.errors: + print(f" {error}", file=sys.stderr) + return 1 + print(" every patched .nut file compiled to Quirrel bytecode with zero lexical/constant errors") + return 0 diff --git a/tools/src/wtotools/gui_check.py b/tools/src/wtotools/gui_check.py new file mode 100644 index 0000000..34d0360 --- /dev/null +++ b/tools/src/wtotools/gui_check.py @@ -0,0 +1,309 @@ +"""Offline Quirrel bytecode & lexical-scope verifier for `gui-patches/`. + +`sq.exe --syntax-check` only runs `sq_parsetoast` and skips `CodeGenVisitor`, missing +`Unknown variable`, forward references, and `Named binding name conflicts with existing +constant/enum/import`. Driving `sq.exe` via `compilestring(src, chunkname, bindings)` +with the target script's real `gui.vromfs.bin` imports runs the full `SQParser` + +`CodeGenVisitor` pipeline without executing any game code. +""" +from __future__ import annotations + +import json +import re +import subprocess +import tempfile +from dataclasses import dataclass +from pathlib import Path + +from .vromfs import Archive, read_archive + +MOUNT_PREFIXES: tuple[tuple[str, str], ...] = ( + ("%scripts/", "scripts/"), + ("%globalScripts/", "globalscripts/"), + ("%sqstd/", "std/"), + ("%sqStdLibs/", "sqstdlibs/"), + ("%appGlobals/", "globals/"), + ("%gui/", "gui/"), + ("%rGui/", "reactivegui/"), + ("%darg/", "darg/"), +) + +MODULE_BUILTINS: tuple[str, ...] = ( + "require", + "require_optional", + "persist", + "keepref", + "__name__", + "__filename__", + "__static_analysis__", +) + +HARNESS_SOURCE = """\ +let io = require("io") +let types = require("types") +class DummyClass {} +class Proxy { + function _get(_k) { return this } + function _add(_o) { return 0 } + function _sub(_o) { return 0 } + function _mul(_o) { return 0 } + function _div(_o) { return 1 } + function _modulo(_o) { return 0 } + function _unm() { return 0 } + function _cmp(_o) { return 0 } +} +let proxy = Proxy() +let typeMap = { + String = types.String + Table = types.Table + Array = types.Array + Function = types.Function + Integer = types.Integer + Float = types.Float + Bool = types.Bool +} +function readText(p) { + let f = io.file(p, "rb") + let s = f.readblob(f.len()).as_string() + f.close() + return s +} +let manifestPath = __argv[0] +let lines = readText(manifestPath).split("\\n") +local failed = 0 +foreach (line in lines) { + let trimmed = line.strip() + if (trimmed == "") + continue + let parts = trimmed.split("\\t") + let filePath = parts[0] + let display = parts[1] + let names = parts.len() > 2 && parts[2] != "" ? parts[2].split(",") : [] + let classNames = parts.len() > 3 && parts[3] != "" ? parts[3].split(",") : [] + let bindings = {} + foreach (n in names) + bindings[n] <- (n in typeMap) ? typeMap[n] : proxy + foreach (cn in classNames) + bindings[cn] <- DummyClass + let src = readText(filePath) + try { + compilestring(src, display, bindings) + } catch (e) { + print($"COMPILE_ERROR {display}: {e}\\n") + failed++ + } +} +if (failed > 0) + throw $"Quirrel bytecode check failed on {failed} file(s)" +""" + + +@dataclass(frozen=True) +class GuiCheckReport: + patches_applied: int + files_checked: int + errors: tuple[str, ...] + + +def verify_gui_patches( + gui_pack_path: Path, + patches_dir: Path, + sq_exe: Path, + endpoint: str = "127.0.0.1:47115", +) -> GuiCheckReport: + archive = read_archive(gui_pack_path.read_bytes()) + patch_files = sorted(patches_dir.rglob("patch.json")) + touched_files: list[str] = [] + errors: list[str] = [] + + for patch_path in patch_files: + raw = json.loads(patch_path.read_text(encoding="utf-8")) + target = raw["file"].lower() + if target not in archive.files: + errors.append(f"{raw['id']}: missing file {target} in gui.vromfs.bin") + continue + current = archive.files[target].decode("utf-8") + find_text = raw["edit"]["find"] + first = current.find(find_text) + if first == -1: + errors.append(f"{raw['id']}: target snippet not found in {target}") + continue + if current.find(find_text, first + len(find_text)) != -1: + errors.append(f"{raw['id']}: target snippet appears more than once in {target}") + continue + replace_text = raw["edit"]["replace"].replace("{{LOCAL_ENDPOINT}}", endpoint) + if "`" in replace_text: + errors.append(f"{raw['id']}: backtick string syntax is unsupported by 2.61.0.37 Quirrel VM; use $\"...\" or +") + continue + updated = current[:first] + replace_text + current[first + len(find_text):] + archive.put(target, updated.encode("utf-8")) + if target not in touched_files: + touched_files.append(target) + + if errors: + return GuiCheckReport(len(patch_files), 0, tuple(errors)) + + export_cache: dict[str, set[str]] = {} + native_syms = _collect_all_named_imports(archive) + stock_archive = read_archive(gui_pack_path.read_bytes()) + + for patch_path in patch_files: + raw = json.loads(patch_path.read_text(encoding="utf-8")) + target = raw["file"].lower() + stock_src = stock_archive.files[target].decode("utf-8") + imp_names, imp_classes = _resolve_file_bindings(stock_src, stock_archive, export_cache, native_syms) + reserved = (imp_names | imp_classes) - set(MODULE_BUILTINS) + new_locals = _declared_locals(raw["edit"]["replace"]) - _declared_locals(raw["edit"]["find"]) + collisions = sorted(new_locals & reserved) + if collisions: + errors.append(f"{raw['id']}: local binding(s) {collisions} conflict with module imports in {target}") + + if errors: + return GuiCheckReport(len(patch_files), 0, tuple(errors)) + + with tempfile.TemporaryDirectory(prefix="wto-gui-check-") as tmp: + tmp_dir = Path(tmp) + harness_path = tmp_dir / "harness.nut" + harness_path.write_text(HARNESS_SOURCE, encoding="utf-8") + manifest_lines: list[str] = [] + + for index, rel_path in enumerate(touched_files): + source = archive.files[rel_path].decode("utf-8") + names, class_names = _resolve_file_bindings(source, archive, export_cache, native_syms) + nut_file = tmp_dir / f"check_{index}.nut" + nut_file.write_bytes(archive.files[rel_path]) + manifest_lines.append( + f"{nut_file}\t{rel_path}\t{','.join(sorted(names))}\t{','.join(sorted(class_names))}" + ) + + manifest_path = tmp_dir / "manifest.tsv" + manifest_path.write_text("\n".join(manifest_lines), encoding="utf-8") + proc = subprocess.run( + [str(sq_exe), str(harness_path), str(manifest_path)], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + if proc.returncode != 0: + out = (proc.stdout + "\n" + proc.stderr).strip() + for line in out.splitlines(): + if line.strip(): + errors.append(line.strip()) + + return GuiCheckReport(len(patch_files), len(touched_files), tuple(errors)) + + +def _resolve_vromfs_path(spec: str) -> str | None: + for prefix, target in MOUNT_PREFIXES: + if spec.startswith(prefix): + return (target + spec[len(prefix):]).lower() + if spec.endswith(".nut"): + return spec.lstrip("/").lower() + return None + + +def _collect_all_named_imports(archive: Archive) -> dict[str, set[str]]: + by_mod: dict[str, set[str]] = {} + pattern = re.compile(r'^from\s+"([^"]+)"\s+import\s+([^\r\n]+(?:\r?\n\s*,[^\r\n]+)*)', re.MULTILINE) + for content in archive.files.values(): + text = content.decode("utf-8", errors="ignore") + for match in pattern.finditer(text): + mod, items = match.group(1), match.group(2) + if items.strip() == "*": + continue + bucket = by_mod.setdefault(mod, set()) + for raw_item in items.replace("\r", " ").replace("\n", " ").split(","): + token = raw_item.strip() + if not token: + continue + orig = token.split()[0] + if orig.isidentifier(): + bucket.add(orig) + return by_mod + + +def _exports_of_module(spec: str, archive: Archive, cache: dict[str, set[str]], native_syms: dict[str, set[str]]) -> set[str]: + if spec in cache: + return cache[spec] + vpath = _resolve_vromfs_path(spec) + if not vpath or vpath not in archive.files: + res = set(native_syms.get(spec, set())) + cache[spec] = res + return res + + cache[spec] = set() + text = archive.files[vpath].decode("utf-8", errors="ignore") + keys: set[str] = set(native_syms.get(spec, set())) + + if vpath == "scripts/dagui_library.nut": + keys |= _exports_of_module("%globalScripts/logs.nut", archive, cache, native_syms) + keys |= _exports_of_module("%scripts/sqDagui/daguiNativeApi.nut", archive, cache, native_syms) + keys |= _exports_of_module("%globalScripts/sharedEnums.nut", archive, cache, native_syms) + + for arr_match in re.finditer(r"let\s+fields\s*=\s*\[(.*?)\]", text, re.DOTALL): + for s_match in re.finditer(r'"([A-Za-z_][A-Za-z0-9_]*)"', arr_match.group(1)): + keys.add(s_match.group(1)) + + for ret_match in re.finditer(r"return\s+(?:freeze\s*\(\s*)?\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}", text, re.DOTALL): + body = ret_match.group(1) + for line in body.splitlines(): + stripped = line.strip().rstrip(",") + if not stripped or stripped.startswith("//"): + continue + m_assign = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=", stripped) + if m_assign: + keys.add(m_assign.group(1)) + elif stripped.isidentifier(): + keys.add(stripped) + + for m_slot in re.finditer(r'\b(?:export|res)\s*(?:\.\s*([A-Za-z_][A-Za-z0-9_]*)|\[\s*"([A-Za-z_][A-Za-z0-9_]*)"\s*\])\s*<-', text): + keys.add(m_slot.group(1) or m_slot.group(2)) + + cache[spec] = keys + return keys + + +def _resolve_file_bindings( + source: str, + archive: Archive, + cache: dict[str, set[str]], + native_syms: dict[str, set[str]], +) -> tuple[set[str], set[str]]: + names: set[str] = set(MODULE_BUILTINS) + class_names: set[str] = set() + used_as_base = set(re.findall(r"\bclass\s*(?:[A-Za-z_][A-Za-z0-9_]*)?\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)", source)) + + for match in re.finditer(r'^import\s+"([^"]+)"\s+as\s+([A-Za-z_][A-Za-z0-9_]*)', source, re.MULTILINE): + alias = match.group(2) + (class_names if alias in used_as_base else names).add(alias) + + from_pattern = re.compile(r'^from\s+"([^"]+)"\s+import\s+([^\r\n]+(?:\r?\n\s*,[^\r\n]+)*)', re.MULTILINE) + for match in from_pattern.finditer(source): + spec, raw_items = match.group(1), match.group(2).strip() + if raw_items == "*": + for sym in _exports_of_module(spec, archive, cache, native_syms): + (class_names if sym in used_as_base else names).add(sym) + continue + for token in raw_items.replace("\r", " ").replace("\n", " ").split(","): + parts = token.strip().split() + if not parts: + continue + bound = parts[2] if len(parts) >= 3 and parts[1] == "as" else parts[0] + if bound.isidentifier(): + (class_names if bound in used_as_base else names).add(bound) + + return names - class_names, class_names + + +def _declared_locals(snippet: str) -> set[str]: + found: set[str] = set() + for m in re.finditer(r"\b(?:let|local)\s+([A-Za-z_][A-Za-z0-9_]*)\s*=", snippet): + found.add(m.group(1)) + for m in re.finditer(r"\b(?:let|local)\s*\{([^}]+)\}\s*=", snippet): + for tok in m.group(1).split(","): + parts = tok.strip().split(":") + ident = parts[-1].strip() + if ident.isidentifier(): + found.add(ident) + return found diff --git a/tools/src/wtotools/offset_check.py b/tools/src/wtotools/offset_check.py new file mode 100644 index 0000000..a2e4fba --- /dev/null +++ b/tools/src/wtotools/offset_check.py @@ -0,0 +1,134 @@ +"""Verify native LocalMP signatures, RIP opcodes, and English anchor strings against aces.exe. + +Parses `native/wto-net/src/local_mp_offsets.h` directly as the single source of truth so +C hook code and binary calibration checks can never drift apart across game updates. +""" +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +from .pe import PeImage + +_SIG_RE = re.compile(r'^#define\s+(LMP_SIG_\w+)\s+"([0-9a-fA-F? ]+)"', re.MULTILINE) +_RIP_RE = re.compile(r"@rip_check\s+(LMP_SIG_\w+)\s*\+\s*0x([0-9a-fA-F]+)\s*:\s*([0-9a-fA-F ]+)") +_ANCHOR_RE = re.compile(r'^\s*\*\s*@anchor\s+"([^"]+)"', re.MULTILINE) +_LEA_RE = re.compile(rb"[\x48\x4c]\x8d[\x05\x0d\x15\x1d\x25\x2d\x35\x3d](....)", re.DOTALL) + + +@dataclass(frozen=True) +class RipCheckSpec: + sig_name: str + offset: int + expected_prefix: bytes + + +@dataclass(frozen=True) +class OffsetHeaderSpec: + signatures: list[tuple[str, str]] + rip_checks: list[RipCheckSpec] + anchors: list[str] + + +def parse_offset_header(header_path: Path) -> OffsetHeaderSpec: + source = header_path.read_text(encoding="utf-8") + signatures = _SIG_RE.findall(source) + rip_checks = [ + RipCheckSpec(name, int(off_hex, 16), bytes.fromhex(prefix_hex)) + for name, off_hex, prefix_hex in _RIP_RE.findall(source) + ] + anchors = list(dict.fromkeys(_ANCHOR_RE.findall(source))) + return OffsetHeaderSpec(signatures=signatures, rip_checks=rip_checks, anchors=anchors) + + +def _compile_signature(spec: str) -> re.Pattern[bytes]: + parts: list[bytes] = [] + for token in spec.split(): + if token == "??": + parts.append(b".") + else: + parts.append(re.escape(bytes([int(token, 16)]))) + return re.compile(b"".join(parts), re.DOTALL) + + +def _index_rip_lea_targets(text_rva: int, text_bytes: bytes) -> dict[int, list[int]]: + targets: dict[int, list[int]] = {} + for match in _LEA_RE.finditer(text_bytes): + insn_rva = text_rva + match.start() + disp = int.from_bytes(match.group(1), "little", signed=True) + target_rva = insn_rva + 7 + disp + bucket = targets.get(target_rva) + if bucket is None: + targets[target_rva] = [insn_rva] + elif len(bucket) < 4: + bucket.append(insn_rva) + return targets + + +def _find_cstring_rvas(pe: PeImage, text: str) -> list[int]: + needle = text.encode("ascii") + b"\x00" + rvas: list[int] = [] + for sec in pe.sections: + if sec.name == ".text" or sec.raw_size == 0: + continue + raw = pe.data[sec.raw_offset : sec.raw_offset + min(sec.virtual_size, sec.raw_size)] + pos = 0 + while True: + idx = raw.find(needle, pos) + if idx < 0: + break + rvas.append(sec.rva + idx) + pos = idx + len(needle) + return rvas + + +def verify_offsets(pe: PeImage, spec: OffsetHeaderSpec) -> tuple[bool, list[str]]: + lines: list[str] = [] + failures = 0 + text_sec = pe.section(".text") + text_bytes = pe.section_bytes(".text") + resolved_sigs: dict[str, int] = {} + + lines.append(f"Checking {len(spec.signatures)} .text signature(s):") + for name, pattern in spec.signatures: + hits = [text_sec.rva + m.start() for m in _compile_signature(pattern).finditer(text_bytes)] + if len(hits) == 1: + resolved_sigs[name] = hits[0] + lines.append(f" [OK] {name:<34} -> {hits[0]:#09x}") + else: + failures += 1 + lines.append(f" [FAIL] {name:<34} -> {len(hits)} match(es)") + + lines.append(f"Checking {len(spec.rip_checks)} RIP displacement anchor(s):") + for chk in spec.rip_checks: + base_rva = resolved_sigs.get(chk.sig_name) + if base_rva is None: + failures += 1 + lines.append(f" [FAIL] {chk.sig_name} + {chk.offset:#x}: base signature unresolved") + continue + actual = pe.read(base_rva + chk.offset, len(chk.expected_prefix)) + if actual == chk.expected_prefix: + lines.append(f" [OK] {chk.sig_name} + {chk.offset:#x} == {actual.hex(' ')}") + else: + failures += 1 + lines.append( + f" [FAIL] {chk.sig_name} + {chk.offset:#x}: expected {chk.expected_prefix.hex(' ')}, got {actual.hex(' ')}" + ) + + lea_targets = _index_rip_lea_targets(text_sec.rva, text_bytes) + lines.append(f"Checking {len(spec.anchors)} English anchor string(s):") + for anchor in spec.anchors: + str_rvas = _find_cstring_rvas(pe, anchor) + xrefs = [xr for sr in str_rvas for xr in lea_targets.get(sr, ())] + if str_rvas and xrefs: + fn_range = pe.function_containing(xrefs[0]) + fn_str = f"{fn_range[0]:#x}" if fn_range else f"{xrefs[0]:#x}" + lines.append(f" [OK] {anchor!r:<58} -> str {str_rvas[0]:#x}, fn {fn_str}") + elif str_rvas: + lines.append(f" [OK] {anchor!r:<58} -> str {str_rvas[0]:#x} (table/data ref)") + else: + failures += 1 + lines.append(f" [FAIL] {anchor!r}: string not found in image") + + return failures == 0, lines