Compare commits
69
Commits
7bd17c4f74
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3282320fb7 | ||
|
|
6d0abf9caf | ||
|
|
194417a388 | ||
|
|
480496ca93 | ||
|
|
428b2d3601 | ||
|
|
2d3287937f | ||
|
|
37cbcd806f | ||
|
|
0af4183cb1 | ||
|
|
65363ce9de | ||
|
|
69d95df88e | ||
|
|
b3f9ff589c | ||
|
|
85532cd930 | ||
|
|
651b023d2a | ||
|
|
1d3e47b082 | ||
|
|
ac35c25851 | ||
|
|
d5008baeff | ||
|
|
45ff082a36 | ||
|
|
80113bdd2e | ||
|
|
314bdfe68e | ||
|
|
9229045042 | ||
|
|
7e5eb99696 | ||
|
|
73bae4785f | ||
|
|
89242e91f0 | ||
|
|
5e521295a3 | ||
|
|
885e3bbb5d | ||
|
|
bb680c6abd | ||
|
|
975a28441a | ||
|
|
4ac3484f56 | ||
|
|
a2fdcc1f15 | ||
|
|
e79866b96e | ||
|
|
e2ac4fa744 | ||
|
|
01bafb6db7 | ||
|
|
18637cf1ff | ||
|
|
10427912e2 | ||
|
|
214f9d7f4b | ||
|
|
f6b00bc787 | ||
|
|
638bc75724 | ||
|
|
02fe867cf1 | ||
|
|
742094ea1e | ||
|
|
c8ba395e4f | ||
|
|
4e99d2c484 | ||
|
|
42b8275151 | ||
|
|
594ff5ab54 | ||
|
|
41088d5377 | ||
|
|
d94c8fe687 | ||
|
|
de967dd993 | ||
|
|
dc5e637e20 | ||
|
|
240ee81712 | ||
|
|
6e65cec4c0 | ||
|
|
aa952e7cca | ||
|
|
5983e3f3e2 | ||
|
|
662e837ab2 | ||
|
|
8636d0b71d | ||
|
|
97707f533d | ||
|
|
ada635ecc7 | ||
|
|
deffcd6dde | ||
|
|
4e72bf3746 | ||
|
|
3aac60c8a3 | ||
|
|
dbc21182a2 | ||
|
|
5c09c4e47a | ||
|
|
dce9b59765 | ||
|
|
e8122d7c6b | ||
|
|
aa7a6e7d02 | ||
|
|
fd9d25d346 | ||
|
|
8fbaeb4228 | ||
|
|
4999c7f5a3 | ||
|
|
d0e4797fe7 | ||
|
|
f1ec034994 | ||
|
|
646be7afb9 |
No files matched your search
@@ -0,0 +1,97 @@
|
|||||||
|
## 简体中文
|
||||||
|
|
||||||
|
`v0.1.3` 是 WTOffline的一次大型功能更新,正式引入**第一版模组系统(开放社区模组制作)**、初步接通**原子雷霆**模式,并包含多项对局机制、存档容量、贴花导入与更新链路修复。
|
||||||
|
|
||||||
|
### 该下载哪一个文件?
|
||||||
|
|
||||||
|
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.3-win-x64.exe`** ,下载后安装即可。
|
||||||
|
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** ,解压到任意目录后运行其中的启动器即可。
|
||||||
|
|
||||||
|
### 重点新功能
|
||||||
|
|
||||||
|
- **第一版模组系统与开放模组制作(实验性)。**
|
||||||
|
- 启动器新增「模组」管理页:支持为每个客户端独立开关模组、调整加载顺序、保存/切换模组方案以及自定义模组目录,并可直接一键打开完整模组开发文档。
|
||||||
|
- 支持客户端数据包增量覆写(BLK / CSV / 附加包挂载,且核心隔离补丁受保护不可被误覆盖)、服务端 JS/TS 脚本钩子与独立模组数据存储,以及数值列表增量修改。
|
||||||
|
- 内置并首次自动生成 3 套官方示例模组模板(含可直接使用的「官方地图选择器」、服务端脚本示例与载具参数微调示例),配套完整中英文 `mod-dev-docs` 开发手册,欢迎玩家与创作者制作并分享自己的模组。
|
||||||
|
- **接通「原子雷霆」模式。**
|
||||||
|
- 完整接入空战历史子模式「原子雷霆」的专用 HUD、阶段推进门槛、不限出击次数与机场独立冷却机制,并按 10 国与房间权重自动分配战术核弹载机(5 kt / 30 kt)。
|
||||||
|
- 在启动器「数值 → 对局」新增「原子雷霆战略核轰炸机」开关(默认开启),可在阶段 3 追加战略核轰炸机(`B-52H` / `Tu-95M`)。
|
||||||
|
|
||||||
|
### 修复与改进
|
||||||
|
|
||||||
|
- **对局与战斗体验**:
|
||||||
|
- 恢复陆战街机空中支援事件(呼叫战斗机 / 攻击机 / 轰炸机);
|
||||||
|
- 修复本地主机下玩家乘员技能与专家 / 王牌资格在战局内未生效的问题;
|
||||||
|
- 恢复空战街机模式下的空中重新装填弹药;
|
||||||
|
- 修复部分载具出生时改装件效果反转,以及单弹链航空武器被未选中的隐身弹链覆盖导致无曳光弹的问题;
|
||||||
|
- 恢复对战模式飞机有限燃油消耗与油量倒计时,并修复局内小队黄色标记;
|
||||||
|
- 支持在机库切换并保存载具的可选分房权重(如部分直升机 / 挂载升档),开局按所选权重参与匹配;
|
||||||
|
- 修复空战街机等多槽模式下 AI 飞机重生次数受限,以及坦克 AI 重生次数配置未对全部模式生效的问题(感谢 `duduyagame`);
|
||||||
|
- 修复新手教程完成进度未保存的问题:通关后重启不再反复提示教程,并按原版规则发放首次通关的贴花、基础教程金鹰及各难度银狮奖励(感谢 `duduyagame`)。
|
||||||
|
- **启动器、存档与更新链路**:
|
||||||
|
- 修复新版在线客户端贴花与可下载涂装缓存导入失败的问题(兼容现行 `regional.vromfs.bin` + `.ddsx` 及旧版缓存格式);
|
||||||
|
- 修复全车库改装件总数超过 65,535 个时的存档溢出问题;
|
||||||
|
- 将启动器「存档 → 载具和研发」中的「全部研发」与「获得常规载具」合并为一步到位的「全部研发并购买」;
|
||||||
|
- 优化默认更新线路并保留 GitHub 自动回退,全流程继续保持 Ed25519 签名校验;
|
||||||
|
- 「关于」页改版为双栏布局,新增「项目主页」与「Discord」快捷入口,修复切换页面时维护进度丢失的问题。
|
||||||
|
|
||||||
|
### 社区交流与模组分享
|
||||||
|
|
||||||
|
欢迎加入 WTOffline 官方 Discord 服务器,一起交流玩法、反馈 Bug、分享你的调参或自制模组,并关注最新客户端适配进度:
|
||||||
|
|
||||||
|
- **Discord 社区**:https://discord.gg/P566xWNpEs
|
||||||
|
- **项目主页**:https://wto-project.net
|
||||||
|
|
||||||
|
### 客户端兼容性
|
||||||
|
|
||||||
|
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动尝试适配后续小版本更新。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
`v0.1.3` is a major feature release of WTOffline introducing the **first version of the experimental Mod System** (opening up community mod authoring), Add support for **Nuclear Escalation**, and a broad set of battle, save, decal import, and launcher fixes.
|
||||||
|
|
||||||
|
### Which file should I download?
|
||||||
|
|
||||||
|
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.3-win-x64.exe`** — the standard Windows installer with built-in automatic update checks.
|
||||||
|
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **Experimental Mod System v1 & Mod Authoring.**
|
||||||
|
- New **Mods** page in the launcher with per-client enablement, load-order management, presets, custom mod repository folder, and a quick-open button for the mod developer handbook.
|
||||||
|
- Supports additive client archive overlays (BLK / CSV / addon mounts while protecting essential isolation patches), server-side JS/TS lifecycle hooks with isolated mod storage, and tuning list operations.
|
||||||
|
- Ships with 3 bundled example mod templates (including a ready-to-use **Official Map Selector**, a server script example, and a vehicle tweak example) plus full bilingual documentation in `mod-dev-docs/`.
|
||||||
|
- **Nuclear Escalation mode.**
|
||||||
|
- Full support for Air Realistic sub-mode **Nuclear Escalation**, including custom HUD, stage thresholds, unlimited respawns, per-airfield cooldowns, and nation-matched tactical nuclear carriers (5 kt / 30 kt) scaled to room BR.
|
||||||
|
- Added a **Nuclear Escalation strategic bombers** toggle under **Tuning → Battle** (enabled by default) to unlock stage-3 strategic nuclear bombers (`B-52H` / `Tu-95M`).
|
||||||
|
|
||||||
|
### Fixes and improvements
|
||||||
|
|
||||||
|
- **Battles & gameplay**:
|
||||||
|
- Restored Ground Arcade air support events (fighters, attackers, bombers).
|
||||||
|
- Fixed player crew skills and Expert / Ace qualifications not applying on the local host.
|
||||||
|
- Restored in-flight ammunition reload in Air Arcade.
|
||||||
|
- Fixed inverted modification effects on spawn and single-belt aircraft tracers being overwritten by unselected stealth belts.
|
||||||
|
- Restored limited fuel consumption / HUD fuel timer in versus modes and yellow squad target markers.
|
||||||
|
- Persisted selectable battle ratings for units with BR-changing modifications and applied them during matchmaking.
|
||||||
|
- Fixed AI aircraft respawn limits in Air Arcade and other multi-slot modes, and applied configured ground AI respawn counts across all modes (thanks to `duduyagame`).
|
||||||
|
- Persisted stock training/tutorial completion progress so finished tutorials no longer re-prompt after restart, and granted one-time first-completion decals, basic tutorial Golden Eagles, and per-difficulty Silver Lions rewards (thanks to `duduyagame`).
|
||||||
|
- **Launcher, saves & updates**:
|
||||||
|
- Fixed online decal and downloadable skin cache import on modern 2.61 clients (supports both `regional.vromfs.bin` + `.ddsx` and legacy cache layouts).
|
||||||
|
- Fixed save overflow when total owned modifications exceed 65,535 by splitting across native sibling blocks.
|
||||||
|
- Merged "Research all" and "Grant regular vehicles" into a single **Research and buy all** action in the launcher.
|
||||||
|
- Improved default release update routing with automatic GitHub fallback and continued Ed25519 signature verification.
|
||||||
|
- Updated the About page to a two-column layout with **Project homepage** and **Discord** buttons, and preserved copy maintenance progress across tab switches.
|
||||||
|
|
||||||
|
### Community & Mod Sharing
|
||||||
|
|
||||||
|
Join the official WTOffline Discord server to chat, report issues, share tuning presets or custom mods, and follow client adaptation updates:
|
||||||
|
|
||||||
|
- **Discord**: https://discord.gg/P566xWNpEs
|
||||||
|
- **Homepage**: https://wto-project.net
|
||||||
|
|
||||||
|
### Client compatibility
|
||||||
|
|
||||||
|
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates.
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
## 简体中文
|
||||||
|
|
||||||
|
`v0.1.4` 带来**实验性新版陆战 AI(第一阶段)**、启动器全新**「Bot 参数」调参页(含陆战 AI 出车权重)**、**Dagor 风格 `.blk.patch.blk` 模组补丁引擎**,以及多项对局伤害反馈、改装件批量购买与启动器便携更新修复。
|
||||||
|
|
||||||
|
### 该下载哪一个文件?
|
||||||
|
|
||||||
|
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.4-win-x64.exe`**,下载后直接安装即可(覆盖安装保留全部存档与配置)。
|
||||||
|
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.4-win-x64-portable.zip`**,解压到任意目录后运行其中的启动器即可。
|
||||||
|
|
||||||
|
### 重点新功能
|
||||||
|
|
||||||
|
- **实验性新版陆战 AI(第一阶段,默认启用)。**
|
||||||
|
- 引入全新的模块化陆战 AI 架构:包含整队指挥层与任务单(按坚守 / 征服 / 制霸模式分配进攻、侧翼、架枪与防空角色,支持分路包抄、集结出发、占点回防与防空阵位)、曝光积分视觉感知与唯一弹道开火许可门(含植被透光、硬遮挡弹道扫掠与友军走廊防误伤)、单车车体状态机(短停射击预算、掩体装填回缩、摆角、僵持换位与受损维修)、本车目击测速提前量与失联守出口,以及按待发架容量配置主/副双弹种出生装弹与局内自动切弹。
|
||||||
|
- 当前为第一阶段实验版本,默认以完整模式(`full`)运行并持续调优中;若遇到寻路或行为异常,可随时在启动器「数值 → Bot 参数」切回「原版 AI(`stock`)」。
|
||||||
|
- **启动器新增「数值 → Bot 参数」页面。**
|
||||||
|
- 统一集中管理陆战 AI 模式切换、AI 坦克 / 飞机重生次数、每类载具候选池上限、**陆战 AI 出车权重**(中坦 / 主战、重坦、坦歼、轻坦、防空车、其他)与出生携弹策略。
|
||||||
|
- 同时以折叠分组开放全部陆战 AI 进阶参数(指挥配额、占点宏观、状态机、视觉感知、测速偏差、火控开火门、机动寻路、编队避让与地形约束),支持参数校验与一键恢复默认值。
|
||||||
|
- **模组系统新增 Dagor 风格 `.blk.patch.blk` 与 `include` 编译支持。**
|
||||||
|
- 支持原生风格的 `*.blk.patch.blk` 与 `client/config-blk.patch.blk` 增量补丁、编译期 `include` / `includeOnce` 展开,以及 Dagor `@` 指令(`@override`、`@replace`、`@delete`、`@clone`、`@inherit`、`@after`、`@before` 等),同时完全保留 `*.blk.patch.jsonc` 兼容。
|
||||||
|
- 同步重写并补齐中英双语开发者手册(`dev-docs/`)与模组制作手册(`mod-dev-docs/`)。
|
||||||
|
|
||||||
|
### 修复与改进
|
||||||
|
|
||||||
|
- **对局伤害反馈与改装件**:
|
||||||
|
- 修复空战右下角敌机部件受损播报串台(仅显示本机及观战目标,不再混入 AI 互打记录)以及空战持续命中时重复普通命中丢失的问题;
|
||||||
|
- 修正普通命中与跳弹等引擎判定无效命中的奖励分类,并修正右侧部件受损反馈的攻击者与收件人归属;
|
||||||
|
- 修复机库一键「购买所有已研发改装件」时因前置依赖状态与价格核算不一致报「角色服务器内部错误」的问题。
|
||||||
|
- **启动器维护、便携版更新与界面**:
|
||||||
|
- 客户端维护页新增「设置 / 更换在线版安装来源」,方便在线版移动目录后继续一键增量更新;
|
||||||
|
- 复制安装与「从在线版更新」自动跳过并保留玩家自定义内容目录(`UserSkins`、`UserSights`、`WarThunderCDK` 与启动器日志),避免更新覆盖自制涂装或瞄具;
|
||||||
|
- 修复便携版原地更新在 Windows 下的文件复制、Electron `.asar` 检查冲突与进程分离重启问题,并防止客户端或数据目录嵌套于启动器安装目录内;
|
||||||
|
- 更新日志改为支持 Markdown 排版的弹窗展示。
|
||||||
|
|
||||||
|
### 社区交流与反馈
|
||||||
|
|
||||||
|
欢迎加入 WTOffline 官方 Discord 服务器,反馈新版陆战 AI 实机体验、分享你的 Bot 调参或自制模组,并关注最新客户端适配进度:
|
||||||
|
|
||||||
|
- **Discord 社区**:https://discord.gg/P566xWNpEs
|
||||||
|
- **项目主页**:https://wto-project.net
|
||||||
|
|
||||||
|
### 客户端兼容性
|
||||||
|
|
||||||
|
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动适配后续小版本(已在 `2.61.0.60` 通过静态与构建核对)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
`v0.1.4` introduces the **experimental Ground AI Rebuild (Phase 1)**, a new **Bot parameters** page in the launcher (including **ground AI vehicle class weights**), **Dagor-style `.blk.patch.blk` mod patching**, and a set of battle damage feedback, bulk modification purchase, and portable updater fixes.
|
||||||
|
|
||||||
|
### Which file should I download?
|
||||||
|
|
||||||
|
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.4-win-x64.exe`** — the standard Windows installer with built-in automatic update checks (safe to install over previous versions; preserves all saves and tuning).
|
||||||
|
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.4-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **Experimental Ground AI Rebuild (Phase 1, enabled by default).**
|
||||||
|
- Introduces a modular custom ground AI architecture: a team commander & task orders (mode-aware Assault / Flank / Overwatch / SPAA role quotas for Battle, Conquest, and Domination with flank lanes, rally staging, cap recall, and air-aware SPAA positioning), exposure-based visual perception and a single ballistic fire gate (foliage transparency, hard-cover ballistic sweeps, and friendly-fire corridor protection), a hull state machine (short-halt budget, cover reload retreat, angling, stalemate repositioning, and damage repair), sample-based velocity lead estimation with last-seen exit watch, and ready-rack dual-ammo bot spawn loadouts with automatic shell switching.
|
||||||
|
- Ships in `full` mode by default for testing and live tuning; if you run into pathing or behavior issues, you can switch back to **Stock AI (`stock`)** anytime under **Tuning → Bot parameters**.
|
||||||
|
- **New "Tuning → Bot parameters" page in the launcher.**
|
||||||
|
- Brings together ground AI mode selection, AI tank / aircraft respawn limits, per-type AI pool cap, **ground AI vehicle class weights** (Medium/MBT, Heavy, TD, Light, SPAA, Other), and spawn ammunition rules in one place.
|
||||||
|
- Exposes all advanced ground AI tuning sections in collapsible groups (commander, macro, state machine, perception, tactics, estimation, fire control, navigation, crowd, terrain, and runtime cadence/diagnostics) with validation and one-click section reset.
|
||||||
|
- **Dagor-style `.blk.patch.blk` & compile-time `include` support for mods.**
|
||||||
|
- Supports native-style `*.blk.patch.blk` and `client/config-blk.patch.blk` incremental patching, `include` / `includeOnce` expansion, and Dagor `@`-directives (`@override`, `@replace`, `@delete`, `@clone`, `@inherit`, `@after`, `@before`, etc.) while maintaining full backwards compatibility with `*.blk.patch.jsonc`.
|
||||||
|
- Rewrote and expanded both the bilingual Developer Handbook (`dev-docs/`) and Mod Developer Handbook (`mod-dev-docs/`).
|
||||||
|
|
||||||
|
### Fixes and improvements
|
||||||
|
|
||||||
|
- **Battle feedback & modifications**:
|
||||||
|
- Fixed Air battle bottom-right enemy part damage feed bleed-through from AI-vs-AI fights (now filtered to the local player or spectated unit) and stopped dropping repeated normal hits on aircraft.
|
||||||
|
- Corrected normal hit vs. ineffective hit (e.g., ricochet) award classification and right-side component damage feedback ownership.
|
||||||
|
- Fixed "Internal character server error" when clicking **Buy all researched modifications** by emitting native `RESEARCHED` status for prerequisite chains and aligning bulk pricing.
|
||||||
|
- **Launcher maintenance, portable updater & UI**:
|
||||||
|
- Added support for setting or changing the online client update source on the client maintenance page.
|
||||||
|
- Skipped and preserved player-created folders (`UserSkins`, `UserSights`, `WarThunderCDK`, and launcher logs) when copying or updating from the online client.
|
||||||
|
- Fixed portable in-place updates on Windows (`original-fs`, removing unused `default_app.asar`, detached `Start-Process` relaunch) and guarded against nested launcher/data directories.
|
||||||
|
- Rendered launcher release notes in a dedicated Markdown modal.
|
||||||
|
|
||||||
|
### Community & Feedback
|
||||||
|
|
||||||
|
Join the official WTOffline Discord server to share feedback on the new ground AI, post custom Bot tuning presets or mods, and follow client adaptation updates:
|
||||||
|
|
||||||
|
- **Discord**: https://discord.gg/P566xWNpEs
|
||||||
|
- **Homepage**: https://wto-project.net
|
||||||
|
|
||||||
|
### Client compatibility
|
||||||
|
|
||||||
|
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates (static and build checks pass on `2.61.0.60`).
|
||||||
+5
-1
@@ -1,5 +1,8 @@
|
|||||||
# Never commit game files (copyright, size). The build reads them from a game folder.
|
# Never commit game files (copyright, size). The build reads them from a game folder.
|
||||||
*.vromfs.bin
|
*.vromfs.bin
|
||||||
|
# Allow additive patch directories named after target packs inside mod templates (never binary archives).
|
||||||
|
!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/
|
||||||
|
!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/
|
||||||
*.vromfs.bin.orig
|
*.vromfs.bin.orig
|
||||||
aces.exe
|
aces.exe
|
||||||
aces*.exe
|
aces*.exe
|
||||||
@@ -25,10 +28,11 @@ __pycache__/
|
|||||||
*.pyc
|
*.pyc
|
||||||
.venv/
|
.venv/
|
||||||
|
|
||||||
# Saves, logs, local runtime data
|
# Saves, logs, local runtime data, local secrets
|
||||||
/data/
|
/data/
|
||||||
/saves/
|
/saves/
|
||||||
*.log
|
*.log
|
||||||
|
.env*.local
|
||||||
|
|
||||||
# Editors / OS
|
# Editors / OS
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@wto/launcher",
|
"name": "@wto/launcher",
|
||||||
"productName": "WTOffline Launcher",
|
"productName": "WTOffline Launcher",
|
||||||
"version": "0.1.2",
|
"version": "0.1.4",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Installer and launcher of the War Thunder offline project.",
|
"description": "Installer and launcher of the War Thunder offline project.",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -14,10 +14,12 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource/roboto-condensed": "^5.3.0",
|
"@fontsource/roboto-condensed": "^5.3.0",
|
||||||
|
"@wto/mods": "*",
|
||||||
"@wto/patcher": "*",
|
"@wto/patcher": "*",
|
||||||
"@wto/server": "*",
|
"@wto/server": "*",
|
||||||
"fflate": "^0.8.2",
|
"fflate": "^0.8.2",
|
||||||
"i18next": "^26.3.6",
|
"i18next": "^26.3.6",
|
||||||
|
"marked": "^18.4.0",
|
||||||
"react": "^19.2.8",
|
"react": "^19.2.8",
|
||||||
"react-dom": "^19.2.8",
|
"react-dom": "^19.2.8",
|
||||||
"react-i18next": "^17.0.10",
|
"react-i18next": "^17.0.10",
|
||||||
|
|||||||
@@ -17,6 +17,19 @@ import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesSta
|
|||||||
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
|
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
|
||||||
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
||||||
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
|
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
|
||||||
|
import {
|
||||||
|
applyModPreset,
|
||||||
|
autoSortMods,
|
||||||
|
deleteModPreset,
|
||||||
|
exportModPreset,
|
||||||
|
getModsState,
|
||||||
|
importModPreset,
|
||||||
|
openModsFolder,
|
||||||
|
saveModPreset,
|
||||||
|
setModEnabled,
|
||||||
|
setModsFolder,
|
||||||
|
setModsOrder,
|
||||||
|
} from '../services/mods/mods-service.ts';
|
||||||
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
||||||
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
||||||
import { broadcast, handle } from './register.ts';
|
import { broadcast, handle } from './register.ts';
|
||||||
@@ -175,6 +188,48 @@ export function registerIpcHandlers(): void {
|
|||||||
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
|
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
|
||||||
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
|
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
|
||||||
|
|
||||||
|
const requireModsWritable = (): void => {
|
||||||
|
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
|
||||||
|
};
|
||||||
|
handle('mods:getState', ({ copyId }) => getModsState(copyId));
|
||||||
|
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return setModEnabled(copyId, modId, enabled);
|
||||||
|
});
|
||||||
|
handle('mods:setOrder', ({ copyId, order }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return setModsOrder(copyId, order);
|
||||||
|
});
|
||||||
|
handle('mods:autoSort', ({ copyId }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return autoSortMods(copyId);
|
||||||
|
});
|
||||||
|
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return saveModPreset(copyId, name, overwriteId);
|
||||||
|
});
|
||||||
|
handle('mods:applyPreset', ({ copyId, presetId }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return applyModPreset(copyId, presetId);
|
||||||
|
});
|
||||||
|
handle('mods:deletePreset', ({ copyId, presetId }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return deleteModPreset(copyId, presetId);
|
||||||
|
});
|
||||||
|
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
|
||||||
|
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
|
||||||
|
handle('mods:importPreset', ({ copyId }, sender) => {
|
||||||
|
requireModsWritable();
|
||||||
|
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
|
||||||
|
});
|
||||||
|
handle('mods:openFolder', () => openModsFolder());
|
||||||
|
handle('mods:setFolder', async ({ copyId, path }) => {
|
||||||
|
requireModsWritable();
|
||||||
|
const state = await setModsFolder(copyId, path);
|
||||||
|
broadcast('event:settings-changed', await getSettings());
|
||||||
|
return state;
|
||||||
|
});
|
||||||
|
|
||||||
handle('launch:getState', () => getLaunchState());
|
handle('launch:getState', () => getLaunchState());
|
||||||
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
|
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
|
||||||
handle('launch:start', () => {
|
handle('launch:start', () => {
|
||||||
|
|||||||
@@ -22,7 +22,9 @@ import {
|
|||||||
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
|
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
|
||||||
} from '../patch-pack/release-assets.ts';
|
} from '../patch-pack/release-assets.ts';
|
||||||
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
|
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
|
||||||
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts';
|
import {
|
||||||
|
cleanupPreparedPortableInstall, isPortableLauncher, launchPortableUpdater, preparePortableInstall,
|
||||||
|
} from './portable-update.ts';
|
||||||
|
|
||||||
type UpdateMode = 'installer' | 'portable';
|
type UpdateMode = 'installer' | 'portable';
|
||||||
|
|
||||||
@@ -215,7 +217,12 @@ export function installAppUpdate(version: string, launcherBusy: () => boolean):
|
|||||||
try {
|
try {
|
||||||
if (offer.mode === 'portable') {
|
if (offer.mode === 'portable') {
|
||||||
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
|
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
|
||||||
launchPortableUpdater(prepared);
|
try {
|
||||||
|
await launchPortableUpdater(prepared);
|
||||||
|
} catch (launchError) {
|
||||||
|
await cleanupPreparedPortableInstall(prepared);
|
||||||
|
throw launchError;
|
||||||
|
}
|
||||||
app.quit();
|
app.quit();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,21 +7,35 @@
|
|||||||
* only obsolete files listed in the previous portable inventory (never touching unrelated user
|
* only obsolete files listed in the previous portable inventory (never touching unrelated user
|
||||||
* files in the same folder), and restarts the updated executable.
|
* files in the same folder), and restarts the updated executable.
|
||||||
*/
|
*/
|
||||||
import { execFile, spawn } from 'node:child_process';
|
import { execFile } from 'node:child_process';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import * as nodeFs from 'node:fs';
|
||||||
import { existsSync } from 'node:fs';
|
import { existsSync } from 'node:fs';
|
||||||
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||||
import { promisify } from 'node:util';
|
import { promisify } from 'node:util';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const execute = promisify(execFile);
|
const execute = promisify(execFile);
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
|
||||||
export const PORTABLE_MARKER_FILE = 'portable-mode';
|
export const PORTABLE_MARKER_FILE = 'portable-mode';
|
||||||
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
|
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
|
||||||
|
export const PORTABLE_UPDATE_LOG_FILENAME = 'portable-update.log';
|
||||||
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
|
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
|
||||||
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
|
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
|
||||||
|
|
||||||
|
// Electron patches node:fs to expose .asar archives as virtual directories, which makes
|
||||||
|
// lstat().isFile() return false and recursive rm() fail on staged .asar files.
|
||||||
|
function rawFsPromises(): typeof nodeFs.promises {
|
||||||
|
try {
|
||||||
|
return (require('original-fs') as typeof nodeFs).promises;
|
||||||
|
} catch {
|
||||||
|
return nodeFs.promises;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const PortableInventorySchema = z.object({
|
const PortableInventorySchema = z.object({
|
||||||
format: z.literal(1),
|
format: z.literal(1),
|
||||||
version: z.string().min(1),
|
version: z.string().min(1),
|
||||||
@@ -216,6 +230,7 @@ export async function preparePortableInstall(
|
|||||||
): Promise<PreparedPortableUpdate> {
|
): Promise<PreparedPortableUpdate> {
|
||||||
await assertWritableFolder(installDir);
|
await assertWritableFolder(installDir);
|
||||||
await mkdir(updatesRoot, { recursive: true });
|
await mkdir(updatesRoot, { recursive: true });
|
||||||
|
const rawFs = rawFsPromises();
|
||||||
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
|
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
|
||||||
await mkdir(stagingDir, { recursive: true });
|
await mkdir(stagingDir, { recursive: true });
|
||||||
try {
|
try {
|
||||||
@@ -238,7 +253,7 @@ export async function preparePortableInstall(
|
|||||||
}
|
}
|
||||||
for (const rel of newFiles) {
|
for (const rel of newFiles) {
|
||||||
const stagedPath = resolveInside(stagingDir, rel);
|
const stagedPath = resolveInside(stagingDir, rel);
|
||||||
const stats = await lstat(stagedPath);
|
const stats = await rawFs.lstat(stagedPath);
|
||||||
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
|
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,7 +269,7 @@ export async function preparePortableInstall(
|
|||||||
installDir: resolve(installDir),
|
installDir: resolve(installDir),
|
||||||
stagingDir,
|
stagingDir,
|
||||||
archivePath,
|
archivePath,
|
||||||
logPath: join(updatesRoot, 'portable-update.log'),
|
logPath: join(updatesRoot, PORTABLE_UPDATE_LOG_FILENAME),
|
||||||
executable: LAUNCHER_EXECUTABLE,
|
executable: LAUNCHER_EXECUTABLE,
|
||||||
newFiles,
|
newFiles,
|
||||||
staleFiles,
|
staleFiles,
|
||||||
@@ -263,21 +278,46 @@ export async function preparePortableInstall(
|
|||||||
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
|
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
|
||||||
return { scriptPath, planPath, stagingDir };
|
return { scriptPath, planPath, stagingDir };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
await rawFs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void {
|
export async function cleanupPreparedPortableInstall(prepared: PreparedPortableUpdate): Promise<void> {
|
||||||
const child = spawn('powershell.exe', [
|
const rawFs = rawFsPromises();
|
||||||
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
|
await rawFs.rm(prepared.stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
||||||
'-File', prepared.scriptPath, prepared.planPath,
|
await rm(prepared.planPath, { force: true }).catch(() => undefined);
|
||||||
], {
|
}
|
||||||
cwd: dirname(prepared.scriptPath),
|
|
||||||
detached: true,
|
/**
|
||||||
stdio: 'ignore',
|
* Launch the portable apply script in a hidden PowerShell process that survives Electron exit.
|
||||||
windowsHide: true,
|
*
|
||||||
shell: false,
|
* On Windows, spawning powershell.exe directly with Node's `detached: true` sets DETACHED_PROCESS
|
||||||
});
|
* (no console), causing Windows PowerShell 5.1 ConsoleHost to exit silently with code 0 before
|
||||||
child.unref();
|
* running `-File`. Spawning without `detached` lets PowerShell run, but Electron tears down
|
||||||
|
* attached children on `app.quit()`. Using a short hidden PowerShell helper with `Start-Process`
|
||||||
|
* gives the updater its own hidden console and cleanly detaches it before the launcher quits.
|
||||||
|
*/
|
||||||
|
export async function launchPortableUpdater(prepared: PreparedPortableUpdate): Promise<void> {
|
||||||
|
const workDir = dirname(prepared.scriptPath);
|
||||||
|
const launcherPath = join(workDir, `launch-portable-${randomUUID()}.ps1`);
|
||||||
|
const script = [
|
||||||
|
'param([string]$ScriptPath, [string]$PlanPath, [string]$WorkDir)',
|
||||||
|
"$ErrorActionPreference = 'Stop'",
|
||||||
|
'$argsList = @(',
|
||||||
|
" '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',",
|
||||||
|
' \'-File\', "`"$ScriptPath`"", "`"$PlanPath`""',
|
||||||
|
')',
|
||||||
|
"Start-Process -FilePath 'powershell.exe' -WorkingDirectory $WorkDir -WindowStyle Hidden -ArgumentList $argsList",
|
||||||
|
].join('\r\n');
|
||||||
|
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
|
||||||
|
await writeFile(launcherPath, `\uFEFF${script}\r\n`, 'utf8');
|
||||||
|
try {
|
||||||
|
await execute('powershell.exe', [
|
||||||
|
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
||||||
|
'-File', launcherPath, prepared.scriptPath, prepared.planPath, workDir,
|
||||||
|
], { cwd: workDir, windowsHide: true, timeout: 30_000 });
|
||||||
|
} finally {
|
||||||
|
await rm(launcherPath, { force: true }).catch(() => undefined);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
|
|
||||||
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
|
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
|
||||||
|
import { rawFs } from '../../util/raw-fs.ts';
|
||||||
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
|
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
|
||||||
|
|
||||||
export async function fileInfo(path: string) {
|
export async function fileInfo(path: string) {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
try {
|
try {
|
||||||
return await lstat(path);
|
return await fsPromises.lstat(path);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||||
return null;
|
return null;
|
||||||
@@ -28,7 +29,8 @@ export async function changeCopyFiles<T>(
|
|||||||
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
|
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
|
||||||
recordChange: () => Promise<T>,
|
recordChange: () => Promise<T>,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
const work = await mkdtemp(join(dirname(root), '.wto-copy-'));
|
const fsPromises = rawFs().promises;
|
||||||
|
const work = await fsPromises.mkdtemp(join(dirname(root), '.wto-copy-'));
|
||||||
const incoming = join(work, 'new');
|
const incoming = join(work, 'new');
|
||||||
const backups = join(work, 'old');
|
const backups = join(work, 'old');
|
||||||
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
|
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
|
||||||
@@ -44,14 +46,14 @@ export async function changeCopyFiles<T>(
|
|||||||
const entry = { target, saved: null as string | null, replaced: false };
|
const entry = { target, saved: null as string | null, replaced: false };
|
||||||
if (old) {
|
if (old) {
|
||||||
const saved = join(backups, path);
|
const saved = join(backups, path);
|
||||||
await mkdir(dirname(saved), { recursive: true });
|
await fsPromises.mkdir(dirname(saved), { recursive: true });
|
||||||
await rename(target, saved);
|
await fsPromises.rename(target, saved);
|
||||||
entry.saved = saved;
|
entry.saved = saved;
|
||||||
}
|
}
|
||||||
changes.push(entry);
|
changes.push(entry);
|
||||||
if (add) {
|
if (add) {
|
||||||
await mkdir(dirname(target), { recursive: true });
|
await fsPromises.mkdir(dirname(target), { recursive: true });
|
||||||
await rename(join(incoming, path), target);
|
await fsPromises.rename(join(incoming, path), target);
|
||||||
entry.replaced = true;
|
entry.replaced = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,8 +62,8 @@ export async function changeCopyFiles<T>(
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
for (const { target, saved, replaced } of changes.reverse()) {
|
for (const { target, saved, replaced } of changes.reverse()) {
|
||||||
try {
|
try {
|
||||||
if (replaced) await rm(target, { force: true });
|
if (replaced) await fsPromises.rm(target, { force: true });
|
||||||
if (saved) await rename(saved, target);
|
if (saved) await fsPromises.rename(saved, target);
|
||||||
} catch (rollbackError) {
|
} catch (rollbackError) {
|
||||||
keepBackups = true;
|
keepBackups = true;
|
||||||
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
|
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
|
||||||
@@ -70,7 +72,7 @@ export async function changeCopyFiles<T>(
|
|||||||
throw error;
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
|
if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
|
||||||
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
|
await fsPromises.rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,7 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema
|
|||||||
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
|
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
|
||||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||||
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
|
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
|
||||||
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
||||||
import {
|
import {
|
||||||
fileHash,
|
fileHash,
|
||||||
linkVerifiedResource,
|
linkVerifiedResource,
|
||||||
@@ -21,20 +21,10 @@ import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } fro
|
|||||||
import { checkPatches } from '../install/patch-check.ts';
|
import { checkPatches } from '../install/patch-check.ts';
|
||||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||||
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
||||||
|
import { readSource } from './copy-source.ts';
|
||||||
|
|
||||||
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
|
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
|
||||||
|
|
||||||
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
|
|
||||||
if (!record.sourcePath) return null;
|
|
||||||
try {
|
|
||||||
const game = await inspectGameFolder(record.sourcePath);
|
|
||||||
return game.missingFiles.length > 0 ? null : game;
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AppError) return null;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
|
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
|
||||||
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
|
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
|
||||||
}
|
}
|
||||||
@@ -67,7 +57,10 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
|||||||
const linked = record.hardlinkedFiles ?? [];
|
const linked = record.hardlinkedFiles ?? [];
|
||||||
const linkedPaths = new Set(linked.map(key));
|
const linkedPaths = new Set(linked.map(key));
|
||||||
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
|
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
|
||||||
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
|
// Older installs may have tracked files in folders that source scans now skip.
|
||||||
|
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter(
|
||||||
|
(name) => !found.has(key(name)) && !isInSkippedSourceFolder(name),
|
||||||
|
);
|
||||||
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
|
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
|
||||||
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
|
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ import { gameProcessRunning, launchInProgress } from '../launch/launch-controlle
|
|||||||
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
||||||
import { localServerReady } from '../launch/local-server.ts';
|
import { localServerReady } from '../launch/local-server.ts';
|
||||||
import { fileInfo } from './change-copy-files.ts';
|
import { fileInfo } from './change-copy-files.ts';
|
||||||
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
|
import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
|
||||||
|
import { readSource, setCopySource } from './copy-source.ts';
|
||||||
|
|
||||||
let current: {
|
let current: {
|
||||||
stop: AbortController;
|
stop: AbortController;
|
||||||
@@ -92,6 +93,8 @@ export async function maintainCopy(
|
|||||||
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
|
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||||
const { id, operation, steamLocations } = request;
|
const { id, operation, steamLocations } = request;
|
||||||
const record = await requireCopy(id);
|
const record = await requireCopy(id);
|
||||||
|
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
|
||||||
|
|
||||||
const root = await checkedRoot(record);
|
const root = await checkedRoot(record);
|
||||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||||
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
|
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { isAbsolute, join } from 'node:path';
|
||||||
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||||
|
import { canonicalCopyPath, copyPathContains, updateCopyRecord } from '../install/install-record.ts';
|
||||||
|
import { fileInfo } from './change-copy-files.ts';
|
||||||
|
|
||||||
|
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
|
||||||
|
if (!record.sourcePath) return null;
|
||||||
|
try {
|
||||||
|
return await inspectSource(record, record.sourcePath);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AppError) return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setCopySource(record: InstallRecord, path: string | undefined): Promise<Copies> {
|
||||||
|
const source = await inspectSource(record, path);
|
||||||
|
return updateCopyRecord(record.id, (latest) => {
|
||||||
|
if (latest.copyPath !== record.copyPath || latest.dataPath !== record.dataPath) {
|
||||||
|
throw new AppError('maintenance_location');
|
||||||
|
}
|
||||||
|
return { ...latest, sourcePath: source.resolvedPath };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function inspectSource(record: InstallRecord, path: string | undefined): Promise<GameFolderInspection> {
|
||||||
|
if (!path || !isAbsolute(path)) throw new AppError('maintenance_source_invalid');
|
||||||
|
const [game, copyPath, dataPath] = await Promise.all([
|
||||||
|
inspectGameFolder(path), canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath),
|
||||||
|
]);
|
||||||
|
const source = game.resolvedPath;
|
||||||
|
const overlapsCopy = copyPathContains(source, copyPath) || copyPathContains(copyPath, source);
|
||||||
|
if (overlapsCopy || copyPathContains(source, dataPath)) {
|
||||||
|
throw new AppError('maintenance_source_overlap');
|
||||||
|
}
|
||||||
|
if (game.missingFiles.length || !game.version || game.hasOfflineBackup || game.needsStockSource) {
|
||||||
|
throw new AppError('maintenance_source_invalid');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify that the directory has game resources beyond the four files used for patching.
|
||||||
|
const [content, languages, missions] = await Promise.all([
|
||||||
|
fileInfo(join(source, 'content')),
|
||||||
|
fileInfo(join(source, 'lang.vromfs.bin')),
|
||||||
|
fileInfo(join(source, 'mis.vromfs.bin')),
|
||||||
|
]);
|
||||||
|
if (!content?.isDirectory() || !languages?.isFile() || !missions?.isFile()) {
|
||||||
|
throw new AppError('maintenance_source_invalid');
|
||||||
|
}
|
||||||
|
return { ...game, path: source };
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import { zipSync } from 'fflate';
|
|||||||
import { GAME_FILES } from '@wto/patcher';
|
import { GAME_FILES } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import { PORTABLE_UPDATE_LOG_FILENAME } from '../app-update/portable-update.ts';
|
||||||
import { getSettings } from '../config/settings-store.ts';
|
import { getSettings } from '../config/settings-store.ts';
|
||||||
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
|
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
|
||||||
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
|
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
|
||||||
@@ -58,6 +59,11 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
|
|||||||
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
|
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
await addFile(
|
||||||
|
files,
|
||||||
|
`launcher-logs/${PORTABLE_UPDATE_LOG_FILENAME}`,
|
||||||
|
join(userData, 'launcher-updates', PORTABLE_UPDATE_LOG_FILENAME),
|
||||||
|
);
|
||||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||||
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
|
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
|
||||||
if (dataPath) await addServerLogs(files, dataPath);
|
if (dataPath) await addServerLogs(files, dataPath);
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs';
|
import type { BigIntStats, Dirent } from 'node:fs';
|
||||||
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises';
|
import { join, normalize, relative, sep } from 'node:path';
|
||||||
import { join, relative } from 'node:path';
|
|
||||||
import { Transform } from 'node:stream';
|
import { Transform } from 'node:stream';
|
||||||
import { pipeline } from 'node:stream/promises';
|
import { pipeline } from 'node:stream/promises';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import { rawFs } from '../../util/raw-fs.ts';
|
||||||
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
||||||
|
import { findIncompleteUhqPacks, isPathInUhqPacks } from './uhq-packages.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
|
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
|
||||||
@@ -12,14 +13,45 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Top-level folders of an installation that hold what the game produced while the player played
|
* Top-level folders of an installation that hold player-generated data or user content from
|
||||||
* online, not the game itself: logs, the web content cache, replays, screenshots and the player's
|
* playing online, not the stock client itself: logs, the web content cache, replays, screenshots,
|
||||||
* own missions. The offline copy does not take the online game's data (working rules 18); the
|
* and user missions, skins and sights. The offline copy does not take the online game's data; the
|
||||||
* game creates these folders again when it needs them.
|
* game creates these folders again when it needs them.
|
||||||
*/
|
*/
|
||||||
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
|
export const PLAYER_DATA_FOLDERS = new Set([
|
||||||
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */
|
'.game_logs',
|
||||||
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']);
|
'cache',
|
||||||
|
'replays',
|
||||||
|
'screenshots',
|
||||||
|
'usermissions',
|
||||||
|
'userskins',
|
||||||
|
'usersights',
|
||||||
|
]);
|
||||||
|
/**
|
||||||
|
* Top-level folders ignored when scanning a stock source in addition to player data:
|
||||||
|
* official launcher/updater logs and obsolete files, the War Thunder CDK toolkit, and any stray
|
||||||
|
* offline backup directory.
|
||||||
|
*/
|
||||||
|
const SKIPPED_SOURCE_FOLDERS = new Set([
|
||||||
|
...PLAYER_DATA_FOLDERS,
|
||||||
|
'.gaijin_updater_logs',
|
||||||
|
'.launcher_log',
|
||||||
|
'.obsolete',
|
||||||
|
'.start_app_logs',
|
||||||
|
'warthundercdk',
|
||||||
|
'wtoffline',
|
||||||
|
]);
|
||||||
|
const LAUNCHER_EXECUTABLE_LOWER = 'wtoffline launcher.exe';
|
||||||
|
|
||||||
|
/** Whether a relative path starts with a top-level entry excluded from source scans. */
|
||||||
|
export function isInSkippedSourceFolder(relativePath: string): boolean {
|
||||||
|
const [topLevel = ''] = normalize(relativePath).split(sep, 1);
|
||||||
|
return SKIPPED_SOURCE_FOLDERS.has(topLevel.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLauncherFolder(entries: readonly Dirent[]): boolean {
|
||||||
|
return entries.some((entry) => entry.isFile() && entry.name.toLowerCase() === LAUNCHER_EXECUTABLE_LOWER);
|
||||||
|
}
|
||||||
|
|
||||||
interface CopyEntry {
|
interface CopyEntry {
|
||||||
readonly relativePath: string;
|
readonly relativePath: string;
|
||||||
@@ -40,21 +72,34 @@ export interface CopyProgress {
|
|||||||
|
|
||||||
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
|
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
|
||||||
export async function planCopy(source: string): Promise<CopyPlan> {
|
export async function planCopy(source: string): Promise<CopyPlan> {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
const incompleteUhq = await findIncompleteUhqPacks(source);
|
||||||
|
const skippedUhq = new Set(incompleteUhq);
|
||||||
|
if (incompleteUhq.length > 0) {
|
||||||
|
console.warn(`[install] skipping incomplete optional UHQ pack(s) in ${source}: ${incompleteUhq.join(', ')}`);
|
||||||
|
}
|
||||||
const files: CopyEntry[] = [];
|
const files: CopyEntry[] = [];
|
||||||
const folders: string[] = [];
|
const folders: string[] = [];
|
||||||
let totalBytes = 0;
|
let totalBytes = 0;
|
||||||
const pending = [source];
|
const pending = [source];
|
||||||
while (pending.length) {
|
while (pending.length) {
|
||||||
const folder = pending.pop()!;
|
const folder = pending.pop()!;
|
||||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
const entries = await fsPromises.readdir(folder, { withFileTypes: true });
|
||||||
|
if (folder !== source) {
|
||||||
|
// Skip any WTOffline Launcher folder that was previously extracted inside the game directory.
|
||||||
|
if (isLauncherFolder(entries)) continue;
|
||||||
|
folders.push(relative(source, folder));
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
const path = join(folder, entry.name);
|
const path = join(folder, entry.name);
|
||||||
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue;
|
if (folder === source && isInSkippedSourceFolder(entry.name)) continue;
|
||||||
|
const relPath = relative(source, path);
|
||||||
|
if (isPathInUhqPacks(relPath, skippedUhq)) continue;
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
folders.push(relative(source, path));
|
|
||||||
pending.push(path);
|
pending.push(path);
|
||||||
} else if (entry.isFile()) {
|
} else if (entry.isFile()) {
|
||||||
const { size, mtimeMs } = await lstat(path);
|
const { size, mtimeMs } = await fsPromises.lstat(path);
|
||||||
files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs });
|
files.push({ relativePath: relPath, bytes: size, modifiedAt: mtimeMs });
|
||||||
totalBytes += size;
|
totalBytes += size;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,8 +123,10 @@ export async function copyPlannedFiles(
|
|||||||
onProgress: (progress: CopyProgress) => void,
|
onProgress: (progress: CopyProgress) => void,
|
||||||
hardlinks?: ReadonlyMap<string, BigIntStats>,
|
hardlinks?: ReadonlyMap<string, BigIntStats>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await mkdir(target, { recursive: true });
|
const fs = rawFs();
|
||||||
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true });
|
const fsPromises = fs.promises;
|
||||||
|
await fsPromises.mkdir(target, { recursive: true });
|
||||||
|
for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true });
|
||||||
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
|
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
|
||||||
let next = 0;
|
let next = 0;
|
||||||
let doneBytes = 0;
|
let doneBytes = 0;
|
||||||
@@ -95,6 +142,8 @@ export async function copyPlannedFiles(
|
|||||||
// caller cleaning up after an error never races a copy still writing.
|
// caller cleaning up after an error never races a copy still writing.
|
||||||
const stop = new AbortController();
|
const stop = new AbortController();
|
||||||
const stopSignal = AbortSignal.any([signal, stop.signal]);
|
const stopSignal = AbortSignal.any([signal, stop.signal]);
|
||||||
|
let firstError: unknown = null;
|
||||||
|
let hasError = false;
|
||||||
const copyNext = async (): Promise<void> => {
|
const copyNext = async (): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
while (next < plan.files.length) {
|
while (next < plan.files.length) {
|
||||||
@@ -109,30 +158,35 @@ export async function copyPlannedFiles(
|
|||||||
doneBytes += file.bytes;
|
doneBytes += file.bytes;
|
||||||
} else {
|
} else {
|
||||||
await pipeline(
|
await pipeline(
|
||||||
createReadStream(from),
|
fs.createReadStream(from),
|
||||||
countBytes(),
|
countBytes(),
|
||||||
// 'wx': fail instead of overwriting a file that is already there.
|
// 'wx': fail instead of overwriting a file that is already there.
|
||||||
createWriteStream(to, { flags: 'wx' }),
|
fs.createWriteStream(to, { flags: 'wx' }),
|
||||||
{ signal: stopSignal },
|
{ signal: stopSignal },
|
||||||
);
|
);
|
||||||
const modified = new Date(file.modifiedAt);
|
const modified = new Date(file.modifiedAt);
|
||||||
await utimes(to, modified, modified);
|
await fsPromises.utimes(to, modified, modified);
|
||||||
}
|
}
|
||||||
doneFiles += 1;
|
doneFiles += 1;
|
||||||
onProgress({ doneBytes, doneFiles });
|
onProgress({ doneBytes, doneFiles });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (!hasError && !stop.signal.aborted && !signal.aborted) {
|
||||||
|
hasError = true;
|
||||||
|
firstError = error;
|
||||||
|
}
|
||||||
stop.abort(error);
|
stop.abort(error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
|
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
|
||||||
|
if (hasError) throw firstError;
|
||||||
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
|
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
|
||||||
if (failed) throw failed.reason;
|
if (failed) throw failed.reason;
|
||||||
if (linkedTargets) {
|
if (linkedTargets) {
|
||||||
for (const [path, stamp] of linkedTargets) {
|
for (const [path, stamp] of linkedTargets) {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
if (!sameResource(stamp, await fsPromises.lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,9 +196,10 @@ export async function copyPlannedFiles(
|
|||||||
* when the copy started, so everything in it came from the copy.
|
* when the copy started, so everything in it came from the copy.
|
||||||
*/
|
*/
|
||||||
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
|
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
if (!targetExisted) {
|
if (!targetExisted) {
|
||||||
await rm(target, { recursive: true, force: true });
|
await fsPromises.rm(target, { recursive: true, force: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true });
|
for (const entry of await fsPromises.readdir(target)) await fsPromises.rm(join(target, entry), { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
|
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
|
||||||
import { dirname, isAbsolute, join, relative } from 'node:path';
|
import { dirname, isAbsolute, join, relative } from 'node:path';
|
||||||
import { isInSteamLibrary, playerDecalCacheProblem } from '@wto/patcher';
|
import {
|
||||||
|
isInSteamLibrary,
|
||||||
|
playerDecalCacheProblem,
|
||||||
|
resolvePlayerDecalCacheFolder,
|
||||||
|
writeDecalCacheIndexSnapshot,
|
||||||
|
} from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { Copies } from '@shared/schemas/install.ts';
|
import type { Copies } from '@shared/schemas/install.ts';
|
||||||
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
|
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
|
||||||
@@ -33,8 +38,13 @@ export async function importDecalCache(
|
|||||||
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
|
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
|
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
|
||||||
const source = await realpath(sourcePath).catch(() => null);
|
const rawSource = await realpath(sourcePath).catch(() => null);
|
||||||
if (!source || playerDecalCacheProblem(source)) throw new AppError('decal_source_invalid');
|
const source = rawSource ? await realpath(resolvePlayerDecalCacheFolder(rawSource)).catch(() => null) : null;
|
||||||
|
const problem = source ? playerDecalCacheProblem(source) : 'selected folder could not be resolved';
|
||||||
|
if (!source || problem) {
|
||||||
|
console.warn('[decals] invalid decal cache source:', sourcePath, '->', problem);
|
||||||
|
throw new AppError('decal_source_invalid');
|
||||||
|
}
|
||||||
|
|
||||||
const root = await cacheRoot(dataPath, steamDataConfirmed);
|
const root = await cacheRoot(dataPath, steamDataConfirmed);
|
||||||
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
||||||
@@ -56,7 +66,12 @@ export async function importDecalCache(
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
if (playerDecalCacheProblem(target)) throw new AppError('decal_source_invalid');
|
writeDecalCacheIndexSnapshot(source, target);
|
||||||
|
const copiedProblem = playerDecalCacheProblem(target);
|
||||||
|
if (copiedProblem) {
|
||||||
|
console.warn('[decals] copied decal cache failed validation:', copiedProblem);
|
||||||
|
throw new AppError('decal_source_invalid');
|
||||||
|
}
|
||||||
return id;
|
return id;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await discardDecalCache(dataPath, id, steamDataConfirmed);
|
await discardDecalCache(dataPath, id, steamDataConfirmed);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { BigIntStats } from 'node:fs';
|
import type { BigIntStats } from 'node:fs';
|
||||||
import { access, mkdir } from 'node:fs/promises';
|
import { access, mkdir } from 'node:fs/promises';
|
||||||
import { dirname, isAbsolute, join, relative } from 'node:path';
|
import { dirname, isAbsolute, join, relative } from 'node:path';
|
||||||
|
import { app } from 'electron';
|
||||||
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
|
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
|
||||||
import { AppError } from '@shared/errors.ts';
|
import { AppError } from '@shared/errors.ts';
|
||||||
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||||
@@ -140,6 +141,12 @@ async function inspectInstallation(request: InstallRequest) {
|
|||||||
const [copyPath, dataPath, sourcePath] = await Promise.all([
|
const [copyPath, dataPath, sourcePath] = await Promise.all([
|
||||||
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
|
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
|
||||||
]);
|
]);
|
||||||
|
if (request.method === 'copy' && app.isPackaged) {
|
||||||
|
const launcherDir = await canonicalCopyPath(dirname(process.execPath));
|
||||||
|
if (copyPathContains(sourcePath, launcherDir)) {
|
||||||
|
throw new AppError('launcher_inside_source');
|
||||||
|
}
|
||||||
|
}
|
||||||
await requireAvailableCopy(request.id, copyPath, dataPath);
|
await requireAvailableCopy(request.id, copyPath, dataPath);
|
||||||
const dataProblem = dataFolderProblem(
|
const dataProblem = dataFolderProblem(
|
||||||
dataPath,
|
dataPath,
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { join, normalize } from 'node:path';
|
||||||
|
import { rawFs } from '../../util/raw-fs.ts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detection of incomplete optional UHQ texture packs (`uhq_vehicles`, `uhq_aircraft`,
|
||||||
|
* `uhq_environment`, etc.) inside a War Thunder folder.
|
||||||
|
*
|
||||||
|
* War Thunder writes `content/pkg_<name>.rq2` when an optional pack is requested and only writes
|
||||||
|
* `content/pkg_<name>.ver` once its download finishes (`PACKAGE_STATUS_OK`). However, at startup
|
||||||
|
* `aces.exe` mounts `content.hq/<name>/res/grp_hdr.vromfs.bin` without requiring the `.ver` file,
|
||||||
|
* registering every `.dxp.bin` listed in the header and crashing later with fatal error 81110007
|
||||||
|
* (`Can't open TexPack`) if any texture pack is missing.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const UHQ_PACK_PATTERN = /^uhq_[a-z0-9_]+$/i;
|
||||||
|
const UHQ_RQ2_PATTERN = /^pkg_(uhq_[a-z0-9_]+)\.rq2$/i;
|
||||||
|
const UHQ_VER_PATTERN = /^pkg_(uhq_[a-z0-9_]+)\.ver$/i;
|
||||||
|
|
||||||
|
export interface IncompleteUhqPack {
|
||||||
|
readonly name: string;
|
||||||
|
readonly hasHeader: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inspects `root` for optional UHQ packs that are incomplete:
|
||||||
|
* - `content/pkg_<name>.rq2` exists without `content/pkg_<name>.ver` (`PACKAGE_STATUS_REQUESTED`), or
|
||||||
|
* - `content.hq/<name>/res/grp_hdr.vromfs.bin` exists with no `.dxp.bin` texture packs beside it.
|
||||||
|
*/
|
||||||
|
export async function inspectIncompleteUhqPacks(root: string): Promise<IncompleteUhqPack[]> {
|
||||||
|
const rq2Packs = new Set<string>();
|
||||||
|
const verPacks = new Set<string>();
|
||||||
|
const candidates = new Set<string>();
|
||||||
|
|
||||||
|
for (const name of await readDirNames(join(root, 'content'))) {
|
||||||
|
const rq2 = UHQ_RQ2_PATTERN.exec(name);
|
||||||
|
if (rq2) {
|
||||||
|
const pack = rq2[1]!.toLowerCase();
|
||||||
|
rq2Packs.add(pack);
|
||||||
|
candidates.add(pack);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const ver = UHQ_VER_PATTERN.exec(name);
|
||||||
|
if (ver) verPacks.add(ver[1]!.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name of await readDirNames(join(root, 'content.hq'))) {
|
||||||
|
if (UHQ_PACK_PATTERN.test(name)) candidates.add(name.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
const incomplete: IncompleteUhqPack[] = [];
|
||||||
|
for (const pack of [...candidates].sort()) {
|
||||||
|
const resDir = join(root, 'content.hq', pack, 'res');
|
||||||
|
const resFiles = await readDirNames(resDir);
|
||||||
|
const hasHeader = resFiles.some((file) => file.toLowerCase() === 'grp_hdr.vromfs.bin');
|
||||||
|
const hasDxp = resFiles.some((file) => file.toLowerCase().endsWith('.dxp.bin'));
|
||||||
|
const requestedWithoutVer = rq2Packs.has(pack) && !verPacks.has(pack);
|
||||||
|
const emptyHeaderOnly = hasHeader && !hasDxp;
|
||||||
|
if (requestedWithoutVer || emptyHeaderOnly) {
|
||||||
|
incomplete.push({ name: pack, hasHeader });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return incomplete;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Names of all incomplete optional UHQ packs in `root`. */
|
||||||
|
export async function findIncompleteUhqPacks(root: string): Promise<string[]> {
|
||||||
|
return (await inspectIncompleteUhqPacks(root)).map((pack) => pack.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Names of incomplete optional UHQ packs in `root` whose `grp_hdr.vromfs.bin` is present,
|
||||||
|
* which causes `aces.exe` to mount the pack and fail with 81110007 when streaming textures.
|
||||||
|
*/
|
||||||
|
export async function findBlockingIncompleteUhqPacks(root: string): Promise<string[]> {
|
||||||
|
return (await inspectIncompleteUhqPacks(root))
|
||||||
|
.filter((pack) => pack.hasHeader)
|
||||||
|
.map((pack) => pack.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether `relativePath` (relative to the War Thunder root) belongs to any UHQ pack in `packs`:
|
||||||
|
* `content.hq/<pack>/...`, `patch/content.hq/<pack>/...`, or `content/pkg_<pack>.rq2`.
|
||||||
|
*/
|
||||||
|
export function isPathInUhqPacks(relativePath: string, packs: ReadonlySet<string>): boolean {
|
||||||
|
if (packs.size === 0) return false;
|
||||||
|
const parts = normalize(relativePath).replace(/\\/g, '/').toLowerCase().split('/').filter(Boolean);
|
||||||
|
if (parts.length >= 2 && parts[0] === 'content.hq') return packs.has(parts[1]!);
|
||||||
|
if (parts.length >= 3 && parts[0] === 'patch' && parts[1] === 'content.hq') return packs.has(parts[2]!);
|
||||||
|
if (parts.length === 2 && parts[0] === 'content') {
|
||||||
|
const rq2 = UHQ_RQ2_PATTERN.exec(parts[1]!);
|
||||||
|
return rq2 !== null && packs.has(rq2[1]!);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readDirNames(folder: string): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const fsPromises = rawFs().promises;
|
||||||
|
await fsPromises.access(folder);
|
||||||
|
return await fsPromises.readdir(folder);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,8 @@ import type { Settings } from '@shared/schemas/settings.ts';
|
|||||||
import { getSettings } from '../config/settings-store.ts';
|
import { getSettings } from '../config/settings-store.ts';
|
||||||
import { decalCachePath } from '../install/decals.ts';
|
import { decalCachePath } from '../install/decals.ts';
|
||||||
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
|
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
|
||||||
|
import { findBlockingIncompleteUhqPacks } from '../install/uhq-packages.ts';
|
||||||
|
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
|
||||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||||
import { saveBackup } from '../saves/save-archive.ts';
|
import { saveBackup } from '../saves/save-archive.ts';
|
||||||
import { buildCopy } from './build-copy.ts';
|
import { buildCopy } from './build-copy.ts';
|
||||||
@@ -67,9 +69,13 @@ export function startLaunch(report: LaunchJob['report']): LaunchState {
|
|||||||
case 'launch_server_exited':
|
case 'launch_server_exited':
|
||||||
update(job, { phase: 'server-exited', ...context });
|
update(job, { phase: 'server-exited', ...context });
|
||||||
break;
|
break;
|
||||||
default:
|
default: {
|
||||||
update(job, { phase: 'failed', error: code, ...context });
|
const errorParams = error instanceof AppError && Object.keys(error.params).length > 0
|
||||||
|
? { errorParams: { ...error.params } }
|
||||||
|
: {};
|
||||||
|
update(job, { phase: 'failed', error: code, ...errorParams, ...context });
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}).finally(() => {
|
}).finally(() => {
|
||||||
if (active === job) active = null;
|
if (active === job) active = null;
|
||||||
@@ -108,7 +114,7 @@ async function launch(job: LaunchJob): Promise<void> {
|
|||||||
job.copyId = record.id;
|
job.copyId = record.id;
|
||||||
const plan = await planLaunch(job, record, settings);
|
const plan = await planLaunch(job, record, settings);
|
||||||
if (plan === null) return;
|
if (plan === null) return;
|
||||||
const { lab, copyPath, stockPath, dataPath, port } = plan;
|
const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
|
||||||
await buildForLaunch(job, record, plan, settings);
|
await buildForLaunch(job, record, plan, settings);
|
||||||
|
|
||||||
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
||||||
@@ -123,7 +129,15 @@ async function launch(job: LaunchJob): Promise<void> {
|
|||||||
update(job, { phase: 'ready' });
|
update(job, { phase: 'ready' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish);
|
const gameExit = await runOrdinaryLaunch(
|
||||||
|
copyPath,
|
||||||
|
dataPath,
|
||||||
|
port,
|
||||||
|
settings,
|
||||||
|
signal,
|
||||||
|
publish,
|
||||||
|
{ modsDir, enabledModIds },
|
||||||
|
);
|
||||||
update(job, { phase: 'game-exited', gameExit });
|
update(job, { phase: 'game-exited', gameExit });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +148,8 @@ interface LaunchPlan {
|
|||||||
readonly dataPath: string;
|
readonly dataPath: string;
|
||||||
readonly steamLibraryConfirmed: boolean;
|
readonly steamLibraryConfirmed: boolean;
|
||||||
readonly port: number;
|
readonly port: number;
|
||||||
|
readonly modsDir: string;
|
||||||
|
readonly enabledModIds: readonly string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
|
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
|
||||||
@@ -183,13 +199,20 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
|
|||||||
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
|
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
|
||||||
}
|
}
|
||||||
if (games) throw new AppError('launch_game_running');
|
if (games) throw new AppError('launch_game_running');
|
||||||
|
const incompleteUhq = await findBlockingIncompleteUhqPacks(copyPath);
|
||||||
|
if (incompleteUhq.length > 0) {
|
||||||
|
console.warn(`[launch] incomplete optional UHQ pack(s) detected in ${copyPath}: ${incompleteUhq.join(', ')}`);
|
||||||
|
throw new AppError('launch_incomplete_uhq_packs', { packs: incompleteUhq.join(', ') });
|
||||||
|
}
|
||||||
|
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
|
||||||
|
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
|
||||||
const port = await selectPort(requestedPort);
|
const port = await selectPort(requestedPort);
|
||||||
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
|
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
|
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
|
||||||
const signal = job.stop.signal;
|
const signal = job.stop.signal;
|
||||||
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
|
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
|
||||||
if (settings.autoSaveBackups) {
|
if (settings.autoSaveBackups) {
|
||||||
for (const { userId } of new AccountStore(dataPath).all()) {
|
for (const { userId } of new AccountStore(dataPath).all()) {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
@@ -211,6 +234,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
|||||||
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
||||||
hookLogging: settings.loggingEnabled,
|
hookLogging: settings.loggingEnabled,
|
||||||
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
||||||
|
modsDir,
|
||||||
|
enabledModIds,
|
||||||
}, signal, (filesWritten, filesTotal, file) => {
|
}, signal, (filesWritten, filesTotal, file) => {
|
||||||
writtenFiles = filesWritten;
|
writtenFiles = filesWritten;
|
||||||
if (!signal.aborted) update(job, {
|
if (!signal.aborted) update(job, {
|
||||||
|
|||||||
@@ -33,13 +33,22 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface StartLocalServerOptions extends Omit<ServerOptions, 'report' | 'mods'> {
|
||||||
|
readonly modsDir?: string;
|
||||||
|
readonly enabledModIds?: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
export async function startLocalServer(
|
export async function startLocalServer(
|
||||||
{ gameFolder, dataFolder, port, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
|
{ gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
|
||||||
): Promise<LocalServer> {
|
): Promise<LocalServer> {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
|
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
|
||||||
|
if (modsDir && enabledModIds && enabledModIds.length > 0) {
|
||||||
|
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
|
||||||
|
}
|
||||||
const worker = utilityProcess.fork(
|
const worker = utilityProcess.fork(
|
||||||
join(import.meta.dirname, 'server-worker.js'),
|
join(import.meta.dirname, 'server-worker.js'),
|
||||||
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'],
|
workerArgs,
|
||||||
{
|
{
|
||||||
serviceName: 'WTOffline local server',
|
serviceName: 'WTOffline local server',
|
||||||
stdio: 'pipe',
|
stdio: 'pipe',
|
||||||
|
|||||||
@@ -45,12 +45,19 @@ type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-r
|
|||||||
export async function runOrdinaryLaunch(
|
export async function runOrdinaryLaunch(
|
||||||
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
|
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
|
||||||
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
|
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
|
||||||
|
mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] },
|
||||||
): Promise<GameExit> {
|
): Promise<GameExit> {
|
||||||
const args = parseLaunchArguments(settings.launchArguments);
|
const args = parseLaunchArguments(settings.launchArguments);
|
||||||
if (!args) throw new AppError('launch_game_failed');
|
if (!args) throw new AppError('launch_game_failed');
|
||||||
publish('starting-server');
|
publish('starting-server');
|
||||||
const server = await startLocalServer(
|
const server = await startLocalServer(
|
||||||
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled },
|
{
|
||||||
|
gameFolder: copyPath,
|
||||||
|
dataFolder: dataPath,
|
||||||
|
port,
|
||||||
|
loggingEnabled: settings.loggingEnabled,
|
||||||
|
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
|
||||||
|
},
|
||||||
signal,
|
signal,
|
||||||
);
|
);
|
||||||
const stop = new AbortController();
|
const stop = new AbortController();
|
||||||
|
|||||||
@@ -0,0 +1,428 @@
|
|||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
||||||
|
import { isAbsolute, join } from 'node:path';
|
||||||
|
import { app, BrowserWindow, dialog, shell } from 'electron';
|
||||||
|
import {
|
||||||
|
computeAutoSortOrder,
|
||||||
|
discoverMods,
|
||||||
|
emptyClientModsConfig,
|
||||||
|
MOD_API_VERSION,
|
||||||
|
normalizeClientModsConfig,
|
||||||
|
resolveModLoadOrder,
|
||||||
|
type ClientModsConfig,
|
||||||
|
type DiscoveredMod,
|
||||||
|
type ModPreset,
|
||||||
|
} from '@wto/mods';
|
||||||
|
import { AppError } from '@shared/errors.ts';
|
||||||
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
|
||||||
|
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||||
|
import { getSettings, updateSettings } from '../config/settings-store.ts';
|
||||||
|
import { listCopies } from '../install/install-record.ts';
|
||||||
|
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||||
|
|
||||||
|
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
|
||||||
|
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
|
||||||
|
const inFlightSeeds = new Map<string, Promise<void>>();
|
||||||
|
|
||||||
|
export function defaultModsFolder(): string {
|
||||||
|
return join(app.getPath('userData'), 'mods');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
|
||||||
|
const settings = await getSettings();
|
||||||
|
const defaultModsDir = defaultModsFolder();
|
||||||
|
const isCustomModsDir = settings.modsFolder !== null;
|
||||||
|
const modsDir = settings.modsFolder ?? defaultModsDir;
|
||||||
|
await mkdir(modsDir, { recursive: true });
|
||||||
|
await seedBundledExampleModsOnce(modsDir);
|
||||||
|
return { modsDir, defaultModsDir, isCustomModsDir };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
|
||||||
|
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
|
||||||
|
* deleting a bundled template never restores it, while newly added official templates still
|
||||||
|
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
|
||||||
|
*/
|
||||||
|
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
|
||||||
|
const key = modsDir.toLowerCase();
|
||||||
|
const pending = inFlightSeeds.get(key);
|
||||||
|
if (pending) {
|
||||||
|
await pending;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const task = (async () => {
|
||||||
|
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
|
||||||
|
try {
|
||||||
|
const templatesRoot = resourcePaths().modTemplates;
|
||||||
|
if (!(await pathExists(templatesRoot))) return;
|
||||||
|
const seeded = await readSeededTemplateNames(markerPath, modsDir);
|
||||||
|
const templates = await readdir(templatesRoot, { withFileTypes: true });
|
||||||
|
let changed = false;
|
||||||
|
for (const entry of templates) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
if (seeded.has(entry.name)) continue;
|
||||||
|
const dest = join(modsDir, entry.name);
|
||||||
|
if (!(await pathExists(dest))) {
|
||||||
|
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
|
||||||
|
}
|
||||||
|
seeded.add(entry.name);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (changed || !(await pathExists(markerPath))) {
|
||||||
|
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[mods] seeding bundled example mods skipped:', error);
|
||||||
|
}
|
||||||
|
})().finally(() => {
|
||||||
|
inFlightSeeds.delete(key);
|
||||||
|
});
|
||||||
|
inFlightSeeds.set(key, task);
|
||||||
|
await task;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
|
||||||
|
if (!(await pathExists(markerPath))) return new Set();
|
||||||
|
try {
|
||||||
|
const raw = (await readFile(markerPath, 'utf8')).trim();
|
||||||
|
if (raw === '1') {
|
||||||
|
// Legacy marker from initial 2-template version: mark existing folders as already seeded
|
||||||
|
// so newly added official templates (e.g. official-map-selector) are still delivered once.
|
||||||
|
const existing = await readdir(modsDir);
|
||||||
|
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
|
||||||
|
for (const name of existing) set.add(name);
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
const parsed = JSON.parse(raw) as { seeded?: unknown };
|
||||||
|
if (Array.isArray(parsed.seeded)) {
|
||||||
|
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pathExists(path: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await access(path);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openModsFolder(): Promise<void> {
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const failure = await shell.openPath(modsDir);
|
||||||
|
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getModsState(copyId: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
return buildModsStateView(copy);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
activePresetId: null,
|
||||||
|
enabled: { ...current.enabled, [modId]: enabled },
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
activePresetId: null,
|
||||||
|
order: sortedOrder,
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
let presets: ModPreset[];
|
||||||
|
let presetId: string;
|
||||||
|
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
|
||||||
|
presetId = overwriteId;
|
||||||
|
presets = current.presets.map((preset) => (
|
||||||
|
preset.id === overwriteId
|
||||||
|
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
|
||||||
|
: preset
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
presetId = randomUUID();
|
||||||
|
presets = [
|
||||||
|
...current.presets,
|
||||||
|
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
activePresetId: presetId,
|
||||||
|
presets,
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||||
|
const preset = current.presets.find((item) => item.id === presetId);
|
||||||
|
if (!preset) throw new AppError('mods_preset_invalid');
|
||||||
|
|
||||||
|
const next = normalizeClientModsConfig({
|
||||||
|
...current,
|
||||||
|
order: preset.order,
|
||||||
|
enabled: preset.enabled,
|
||||||
|
activePresetId: preset.id,
|
||||||
|
}, discovered.mods);
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const current = await readClientModsConfig(copy.dataPath);
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
|
||||||
|
presets: current.presets.filter((preset) => preset.id !== presetId),
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return buildModsStateView(copy, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exportModPreset(
|
||||||
|
copyId: string,
|
||||||
|
presetId: string,
|
||||||
|
window: BrowserWindow | null,
|
||||||
|
): Promise<{ readonly path: string | null }> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const current = await readClientModsConfig(copy.dataPath);
|
||||||
|
const preset = current.presets.find((item) => item.id === presetId);
|
||||||
|
if (!preset) throw new AppError('mods_preset_invalid');
|
||||||
|
|
||||||
|
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
|
||||||
|
const dialogOptions = {
|
||||||
|
defaultPath: `${safeName}.wto-mods-preset.json`,
|
||||||
|
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||||
|
};
|
||||||
|
const choice = window
|
||||||
|
? await dialog.showSaveDialog(window, dialogOptions)
|
||||||
|
: await dialog.showSaveDialog(dialogOptions);
|
||||||
|
if (choice.canceled || !choice.filePath) return { path: null };
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
format: 1 as const,
|
||||||
|
name: preset.name,
|
||||||
|
order: [...preset.order],
|
||||||
|
enabled: { ...preset.enabled },
|
||||||
|
};
|
||||||
|
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
||||||
|
return { path: choice.filePath };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importModPreset(
|
||||||
|
copyId: string,
|
||||||
|
window: BrowserWindow | null,
|
||||||
|
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
const dialogOptions = {
|
||||||
|
properties: ['openFile'] as Array<'openFile'>,
|
||||||
|
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||||
|
};
|
||||||
|
const choice = window
|
||||||
|
? await dialog.showOpenDialog(window, dialogOptions)
|
||||||
|
: await dialog.showOpenDialog(dialogOptions);
|
||||||
|
if (choice.canceled || !choice.filePaths[0]) {
|
||||||
|
return { imported: false, state: await buildModsStateView(copy) };
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsedRaw: unknown;
|
||||||
|
try {
|
||||||
|
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
|
||||||
|
} catch {
|
||||||
|
throw new AppError('mods_preset_invalid');
|
||||||
|
}
|
||||||
|
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
|
||||||
|
if (!validated.success) throw new AppError('mods_preset_invalid');
|
||||||
|
|
||||||
|
const current = await readClientModsConfig(copy.dataPath);
|
||||||
|
const newPreset: ModPreset = {
|
||||||
|
id: randomUUID(),
|
||||||
|
name: validated.data.name,
|
||||||
|
order: validated.data.order,
|
||||||
|
enabled: validated.data.enabled,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
const next: ClientModsConfig = {
|
||||||
|
...current,
|
||||||
|
presets: [...current.presets, newPreset],
|
||||||
|
};
|
||||||
|
await writeClientModsConfig(copy.dataPath, next);
|
||||||
|
return { imported: true, state: await buildModsStateView(copy, next) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
|
||||||
|
if (folderPath !== null) {
|
||||||
|
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
|
||||||
|
try {
|
||||||
|
await mkdir(folderPath, { recursive: true });
|
||||||
|
const info = await stat(folderPath);
|
||||||
|
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AppError) throw error;
|
||||||
|
throw new AppError('mods_folder_invalid');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await updateSettings({ modsFolder: folderPath });
|
||||||
|
const copy = await requireCopy(copyId);
|
||||||
|
return buildModsStateView(copy);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
|
||||||
|
export async function resolveEnabledModsForLaunch(
|
||||||
|
dataPath: string,
|
||||||
|
gameVersion: string | null,
|
||||||
|
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
|
||||||
|
const { modsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
|
||||||
|
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
|
||||||
|
if (resolved.hasBlockingErrors) {
|
||||||
|
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
|
||||||
|
throw new AppError('mods_blocking_issues');
|
||||||
|
}
|
||||||
|
return { modsDir, enabledMods: resolved.enabledMods };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
|
||||||
|
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
|
||||||
|
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
|
||||||
|
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
|
||||||
|
|
||||||
|
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||||
|
const orderedMods: ModListItem[] = config.order
|
||||||
|
.map((id) => byId.get(id))
|
||||||
|
.filter((mod): mod is DiscoveredMod => mod !== undefined)
|
||||||
|
.map(toModListItem);
|
||||||
|
|
||||||
|
return {
|
||||||
|
modsDir,
|
||||||
|
defaultModsDir,
|
||||||
|
isCustomModsDir,
|
||||||
|
apiVersion: MOD_API_VERSION,
|
||||||
|
mods: orderedMods,
|
||||||
|
discoveryErrors: [...discovered.errors],
|
||||||
|
order: [...config.order],
|
||||||
|
enabled: { ...config.enabled },
|
||||||
|
activePresetId: config.activePresetId,
|
||||||
|
presets: config.presets.map((preset) => ({
|
||||||
|
id: preset.id,
|
||||||
|
name: preset.name,
|
||||||
|
order: [...preset.order],
|
||||||
|
enabled: { ...preset.enabled },
|
||||||
|
updatedAt: preset.updatedAt,
|
||||||
|
})),
|
||||||
|
issues: [...resolved.issues],
|
||||||
|
hasBlockingErrors: resolved.hasBlockingErrors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toModListItem(mod: DiscoveredMod): ModListItem {
|
||||||
|
return {
|
||||||
|
id: mod.manifest.id,
|
||||||
|
folderName: mod.folderName,
|
||||||
|
rootDir: mod.rootDir,
|
||||||
|
name: mod.manifest.name,
|
||||||
|
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
|
||||||
|
version: mod.manifest.version,
|
||||||
|
author: mod.manifest.author,
|
||||||
|
apiVersion: mod.manifest.apiVersion,
|
||||||
|
gameVersions: [...mod.manifest.gameVersions],
|
||||||
|
requires: [...mod.manifest.requires],
|
||||||
|
conflicts: [...mod.manifest.conflicts],
|
||||||
|
loadAfter: [...mod.manifest.loadAfter],
|
||||||
|
loadBefore: [...mod.manifest.loadBefore],
|
||||||
|
badges: [...mod.content.badges],
|
||||||
|
hasServerScript: mod.content.serverEntry !== undefined,
|
||||||
|
serverTuningFiles: [...mod.content.serverTuningFiles],
|
||||||
|
packOperations: [...mod.content.packOperations],
|
||||||
|
guiPatchCount: mod.content.guiPatchDirs.length,
|
||||||
|
exePatchCount: mod.content.exePatchDirs.length,
|
||||||
|
hasClientAddon: mod.content.hasClientAddon,
|
||||||
|
addonFileCount: mod.content.addonRelativeFiles.length,
|
||||||
|
clientFileCount: mod.content.clientFiles.length,
|
||||||
|
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireCopy(copyId: string): Promise<InstallRecord> {
|
||||||
|
const copies = await listCopies();
|
||||||
|
const copy = copies.copies.find((entry) => entry.id === copyId);
|
||||||
|
if (!copy) throw new AppError('copy_not_found');
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
|
||||||
|
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
|
||||||
|
try {
|
||||||
|
const raw = await readJsonOr(path, null);
|
||||||
|
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
|
||||||
|
const obj = raw as Partial<ClientModsConfig>;
|
||||||
|
return {
|
||||||
|
format: 1,
|
||||||
|
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
|
||||||
|
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
|
||||||
|
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
|
||||||
|
presets: Array.isArray(obj.presets) ? obj.presets : [],
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
|
||||||
|
return emptyClientModsConfig();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
|
||||||
|
try {
|
||||||
|
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[mods] writing client mods config failed:', error);
|
||||||
|
throw new AppError('mods_write_failed');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
|
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
|
||||||
* The project repository is tried first, with an optional player-configured fallback.
|
* The primary release source is tried first, followed by any player-configured mirror and default fallbacks.
|
||||||
*/
|
*/
|
||||||
import { net } from 'electron';
|
import { net } from 'electron';
|
||||||
import {
|
import {
|
||||||
@@ -62,6 +62,7 @@ export class ReleasePageLimitError extends Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||||
|
const MAX_RELEASE_NOTES_CHARS = 64 * 1024;
|
||||||
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
|
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
|
||||||
const LauncherReleaseEntry = z.object({
|
const LauncherReleaseEntry = z.object({
|
||||||
draft: z.literal(false),
|
draft: z.literal(false),
|
||||||
@@ -98,18 +99,35 @@ export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean {
|
|||||||
export async function withReleaseSources<T>(
|
export async function withReleaseSources<T>(
|
||||||
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
|
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
const primary = releaseSource(new URL(`https://github.com/${patchPackTuning().repository}`));
|
const tuning = patchPackTuning();
|
||||||
const repository = releaseRepositoryUrl((await getSettings()).updateMirrorUrl);
|
const candidates: ReleaseSource[] = [];
|
||||||
const mirror = repository ? releaseSource(repository) : null;
|
const add = (url: URL | null): void => {
|
||||||
if (!mirror || sameReleaseSource(primary, mirror)) return read(primary);
|
if (!url) return;
|
||||||
const [first, second] = preferred && sameReleaseSource(preferred, mirror) ? [mirror, primary] : [primary, mirror];
|
const source = releaseSource(url);
|
||||||
try {
|
if (!candidates.some((existing) => sameReleaseSource(existing, source))) candidates.push(source);
|
||||||
return await read(first);
|
};
|
||||||
} catch (error) {
|
add(releaseRepositoryUrl(tuning.primarySource));
|
||||||
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
|
add(releaseRepositoryUrl((await getSettings()).updateMirrorUrl));
|
||||||
console.info(`[release-feed] ${first.feed.hostname} was unavailable, trying ${second.feed.hostname}.`);
|
for (const fallback of tuning.fallbackSources) add(releaseRepositoryUrl(fallback));
|
||||||
return read(second);
|
if (candidates.length === 0) throw new FeedUnreachableError('No valid release sources are configured.');
|
||||||
|
|
||||||
|
const ordered = preferred
|
||||||
|
? [preferred, ...candidates.filter((source) => !sameReleaseSource(source, preferred))]
|
||||||
|
: candidates;
|
||||||
|
|
||||||
|
let lastError: unknown;
|
||||||
|
for (let index = 0; index < ordered.length; index += 1) {
|
||||||
|
const current = ordered[index]!;
|
||||||
|
try {
|
||||||
|
return await read(current);
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
|
||||||
|
lastError = error;
|
||||||
|
const next = ordered[index + 1];
|
||||||
|
if (next) console.info(`[release-feed] ${current.feed.hostname} was unavailable, trying ${next.feed.hostname}.`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
throw lastError;
|
||||||
}
|
}
|
||||||
|
|
||||||
function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
|
function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
|
||||||
@@ -248,7 +266,7 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
|
|||||||
return {
|
return {
|
||||||
source,
|
source,
|
||||||
version,
|
version,
|
||||||
notes: body?.trim().slice(0, 1600) ?? '',
|
notes: body?.trim().slice(0, MAX_RELEASE_NOTES_CHARS) ?? '',
|
||||||
installer,
|
installer,
|
||||||
manifest,
|
manifest,
|
||||||
signature,
|
signature,
|
||||||
|
|||||||
@@ -17,6 +17,10 @@ export interface ResourcePaths {
|
|||||||
readonly networkHookLibrary: string;
|
readonly networkHookLibrary: string;
|
||||||
/** Multi-resolution Windows icon for the window and system tray. */
|
/** Multi-resolution Windows icon for the window and system tray. */
|
||||||
readonly appIcon: string;
|
readonly appIcon: string;
|
||||||
|
/** Bundled example mod templates seeded into an empty mods folder on first use. */
|
||||||
|
readonly modTemplates: string;
|
||||||
|
/** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */
|
||||||
|
readonly groundAiScripts: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resourcePaths(): ResourcePaths {
|
export function resourcePaths(): ResourcePaths {
|
||||||
@@ -32,6 +36,8 @@ export function bundledResourcePaths(): ResourcePaths {
|
|||||||
patches: join(process.resourcesPath, 'patches'),
|
patches: join(process.resourcesPath, 'patches'),
|
||||||
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
|
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
|
||||||
appIcon: join(process.resourcesPath, 'icon.ico'),
|
appIcon: join(process.resourcesPath, 'icon.ico'),
|
||||||
|
modTemplates: join(process.resourcesPath, 'mod-templates'),
|
||||||
|
groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// The app path is apps/launcher; the repository is two levels up.
|
// The app path is apps/launcher; the repository is two levels up.
|
||||||
@@ -40,6 +46,8 @@ export function bundledResourcePaths(): ResourcePaths {
|
|||||||
patches: join(repository, 'patches'),
|
patches: join(repository, 'patches'),
|
||||||
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
|
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
|
||||||
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
|
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
|
||||||
|
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
|
||||||
|
groundAiScripts: join(repository, 'game-ai', 'ground'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import * as nodeFs from 'node:fs';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
|
||||||
|
let cached: typeof nodeFs | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return Node's unpatched fs module inside Electron.
|
||||||
|
*
|
||||||
|
* Electron patches `node:fs` to treat any `.asar` file anywhere on disk as a virtual archive
|
||||||
|
* directory, which breaks streaming reads, stats and recursive cleanup when copying or managing
|
||||||
|
* player folders that happen to contain an `.asar` file. Falls back to `node:fs` outside Electron.
|
||||||
|
*/
|
||||||
|
export function rawFs(): typeof nodeFs {
|
||||||
|
if (cached) return cached;
|
||||||
|
try {
|
||||||
|
cached = require('original-fs') as typeof nodeFs;
|
||||||
|
} catch {
|
||||||
|
cached = nodeFs;
|
||||||
|
}
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
@@ -9,9 +9,12 @@ export interface BuildRequest {
|
|||||||
readonly port: number;
|
readonly port: number;
|
||||||
readonly patches: string;
|
readonly patches: string;
|
||||||
readonly networkHookLibrary: string;
|
readonly networkHookLibrary: string;
|
||||||
|
readonly groundAiScripts: string;
|
||||||
readonly decalCache?: string;
|
readonly decalCache?: string;
|
||||||
readonly hookLogging: boolean;
|
readonly hookLogging: boolean;
|
||||||
readonly acceptedUnavailable: readonly string[];
|
readonly acceptedUnavailable: readonly string[];
|
||||||
|
readonly modsDir?: string;
|
||||||
|
readonly enabledModIds?: readonly string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
|
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
|
||||||
|
|||||||
@@ -1,14 +1,34 @@
|
|||||||
import { readFileSync, realpathSync } from 'node:fs';
|
import { readFileSync, realpathSync } from 'node:fs';
|
||||||
import { relative } from 'node:path';
|
import { relative } from 'node:path';
|
||||||
import type { MessageEvent } from 'electron';
|
import type { MessageEvent } from 'electron';
|
||||||
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
|
import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
|
||||||
import { multiVehiclePackIds } from '@wto/server';
|
import {
|
||||||
|
assertWritableCopy,
|
||||||
|
buildGameCopy,
|
||||||
|
computeModsBuildFingerprint,
|
||||||
|
copyPlayerDecalCache,
|
||||||
|
CORE_BUILD_PACKS,
|
||||||
|
GAME_PACK_FILE,
|
||||||
|
isGroundAiActive,
|
||||||
|
playerDecalCacheProblem,
|
||||||
|
prepareOptionalStockPacks,
|
||||||
|
readPlayerDecalIndexFiles,
|
||||||
|
readStockGameFiles,
|
||||||
|
syncExternalModFiles,
|
||||||
|
writeGameCopy,
|
||||||
|
type GameCopyBuild,
|
||||||
|
type GameCopyFile,
|
||||||
|
} from '@wto/patcher';
|
||||||
|
import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server';
|
||||||
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
|
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
|
||||||
|
|
||||||
let prepared: {
|
let prepared: {
|
||||||
readonly request: BuildRequest;
|
readonly request: BuildRequest;
|
||||||
readonly files: readonly GameCopyFile[];
|
readonly files: readonly GameCopyFile[];
|
||||||
readonly decalCache: string | undefined;
|
readonly decalCache: string | undefined;
|
||||||
|
readonly enabledMods: readonly DiscoveredMod[];
|
||||||
|
readonly optionalPacksInBuild: readonly ModdableClientPack[];
|
||||||
|
readonly fingerprint: string;
|
||||||
} | null = null;
|
} | null = null;
|
||||||
|
|
||||||
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
|
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
|
||||||
@@ -31,17 +51,63 @@ function importedDecals(path: string | undefined): string | undefined {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
|
||||||
|
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||||
|
const ordered: DiscoveredMod[] = [];
|
||||||
|
for (const id of enabledModIds) {
|
||||||
|
const mod = byId.get(id);
|
||||||
|
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
|
||||||
|
ordered.push(mod);
|
||||||
|
}
|
||||||
|
return ordered;
|
||||||
|
}
|
||||||
|
|
||||||
|
function logModBuildSummary(result: GameCopyBuild): void {
|
||||||
|
if (result.gamePack) {
|
||||||
|
console.info(`[build] injected ${result.gamePack.modules.length} ground AI module(s) into ${result.gamePack.archiveFolder}`);
|
||||||
|
}
|
||||||
|
if (result.mods.enabledModIds.length === 0) return;
|
||||||
|
console.info(
|
||||||
|
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
|
||||||
|
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
|
||||||
|
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
|
||||||
|
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
|
||||||
|
);
|
||||||
|
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
|
||||||
|
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function build(request: BuildRequest): void {
|
function build(request: BuildRequest): void {
|
||||||
checkBuildLocation(request);
|
checkBuildLocation(request);
|
||||||
const decalCache = importedDecals(request.decalCache);
|
const decalCache = importedDecals(request.decalCache);
|
||||||
|
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
|
||||||
|
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
|
||||||
|
const groundAiConfig = loadGroundAiTuning(request.dataPath, console.info, enabledMods);
|
||||||
|
const groundAiActive = isGroundAiActive(groundAiConfig);
|
||||||
|
const touchedSet = new Set<ModdableClientPack>(
|
||||||
|
touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)),
|
||||||
|
);
|
||||||
|
if (groundAiActive) touchedSet.add(GAME_PACK_FILE);
|
||||||
|
const optionalPacksInBuild = [...touchedSet];
|
||||||
|
const extraStockPacks = optionalPacksInBuild.length > 0
|
||||||
|
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
const result = buildGameCopy({
|
const result = buildGameCopy({
|
||||||
stock: readStockGameFiles(request.stockPath),
|
stock: readStockGameFiles(request.stockPath),
|
||||||
patches: request.patches,
|
patches: request.patches,
|
||||||
networkHookLibrary: readFileSync(request.networkHookLibrary),
|
networkHookLibrary: readFileSync(request.networkHookLibrary),
|
||||||
port: request.port,
|
port: request.port,
|
||||||
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
|
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
|
||||||
placeholderDecals: decalCache === undefined,
|
placeholderDecals: decalCache === undefined,
|
||||||
|
...(decalIndexFiles ? { decalIndexFiles } : {}),
|
||||||
hookLogging: request.hookLogging,
|
hookLogging: request.hookLogging,
|
||||||
|
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
|
||||||
|
...(extraStockPacks ? { extraStockPacks } : {}),
|
||||||
|
groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig },
|
||||||
});
|
});
|
||||||
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
|
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
|
||||||
const accepted = new Set(request.acceptedUnavailable);
|
const accepted = new Set(request.acceptedUnavailable);
|
||||||
@@ -50,7 +116,13 @@ function build(request: BuildRequest): void {
|
|||||||
send({ kind: 'failed', error: 'launch_build_unavailable' });
|
send({ kind: 'failed', error: 'launch_build_unavailable' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
prepared = { request, files: result.files, decalCache };
|
logModBuildSummary(result);
|
||||||
|
const fingerprint = computeModsBuildFingerprint(
|
||||||
|
enabledMods,
|
||||||
|
request.port,
|
||||||
|
`${request.patches}|groundAi=${JSON.stringify(groundAiConfig)}`,
|
||||||
|
);
|
||||||
|
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
|
||||||
send({ kind: 'prepared', total: prepared.files.length });
|
send({ kind: 'prepared', total: prepared.files.length });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,15 +134,22 @@ process.parentPort.on('message', (event: MessageEvent) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!prepared) throw new Error('No build is ready to write.');
|
if (!prepared) throw new Error('No build is ready to write.');
|
||||||
const { request, files, decalCache } = prepared;
|
const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
|
||||||
prepared = null;
|
prepared = null;
|
||||||
checkBuildLocation(request);
|
checkBuildLocation(request);
|
||||||
const { copyPath } = request;
|
const { copyPath, stockPath } = request;
|
||||||
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
|
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
|
||||||
for (const [index, file] of files.entries()) {
|
for (const [index, file] of files.entries()) {
|
||||||
writeGameCopy(copyPath, [file]);
|
writeGameCopy(copyPath, [file]);
|
||||||
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
|
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
|
||||||
}
|
}
|
||||||
|
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
|
||||||
|
for (const warning of deployResult.warnings) {
|
||||||
|
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
|
||||||
|
}
|
||||||
|
if (deployResult.restoredOptionalPacks.length > 0) {
|
||||||
|
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
|
||||||
|
}
|
||||||
send({ kind: 'written' });
|
send({ kind: 'written' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[build] preparing the game copy failed:', error);
|
console.error('[build] preparing the game copy failed:', error);
|
||||||
|
|||||||
@@ -1,16 +1,42 @@
|
|||||||
|
import { discoverMods, type DiscoveredMod } from '@wto/mods';
|
||||||
import { startServer } from '@wto/server';
|
import { startServer } from '@wto/server';
|
||||||
|
|
||||||
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
|
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
|
||||||
|
|
||||||
|
function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] {
|
||||||
|
if (!modsDir || !enabledJson) return [];
|
||||||
|
const ids = JSON.parse(enabledJson) as unknown;
|
||||||
|
if (!Array.isArray(ids) || ids.length === 0) return [];
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||||
|
const mods: DiscoveredMod[] = [];
|
||||||
|
for (const id of ids) {
|
||||||
|
if (typeof id !== 'string') continue;
|
||||||
|
const mod = byId.get(id);
|
||||||
|
if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`);
|
||||||
|
mods.push(mod);
|
||||||
|
}
|
||||||
|
return mods;
|
||||||
|
}
|
||||||
|
|
||||||
async function serve(): Promise<void> {
|
async function serve(): Promise<void> {
|
||||||
const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2);
|
const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2);
|
||||||
const port = Number(portText);
|
const port = Number(portText);
|
||||||
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
|
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||||
throw new Error('Invalid local server arguments.');
|
throw new Error('Invalid local server arguments.');
|
||||||
}
|
}
|
||||||
const loggingEnabled = loggingFlag !== '0';
|
const loggingEnabled = loggingFlag !== '0';
|
||||||
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info });
|
const mods = loadOrderedMods(modsDir, enabledModIdsJson);
|
||||||
|
const server = await startServer({
|
||||||
|
gameFolder,
|
||||||
|
dataFolder,
|
||||||
|
port,
|
||||||
|
loggingEnabled,
|
||||||
|
...(mods.length > 0 ? { mods } : {}),
|
||||||
|
report: console.info,
|
||||||
|
});
|
||||||
if (server.logFolder) console.info('Traffic log:', server.logFolder);
|
if (server.logFolder) console.info('Traffic log:', server.logFolder);
|
||||||
|
if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', '));
|
||||||
process.parentPort.once('message', () => {
|
process.parentPort.once('message', () => {
|
||||||
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
|
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
|
||||||
console.error('Could not close the local server:', error);
|
console.error('Could not close the local server:', error);
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
|
|||||||
import { WizardMain } from './pages/install/WizardMain.tsx';
|
import { WizardMain } from './pages/install/WizardMain.tsx';
|
||||||
import { WizardSide } from './pages/install/WizardSide.tsx';
|
import { WizardSide } from './pages/install/WizardSide.tsx';
|
||||||
import { wizardBar } from './pages/install/wizard-bar.ts';
|
import { wizardBar } from './pages/install/wizard-bar.ts';
|
||||||
|
import { ModsPage } from './pages/mods/ModsPage.tsx';
|
||||||
import { TuningPage } from './pages/tuning/TuningPage.tsx';
|
import { TuningPage } from './pages/tuning/TuningPage.tsx';
|
||||||
import { SavesPage } from './pages/saves/SavesPage.tsx';
|
import { SavesPage } from './pages/saves/SavesPage.tsx';
|
||||||
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
|
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
|
||||||
@@ -32,7 +33,7 @@ import { Background } from './shell/Background.tsx';
|
|||||||
import { BottomBar } from './shell/BottomBar.tsx';
|
import { BottomBar } from './shell/BottomBar.tsx';
|
||||||
import type { BarModel } from './shell/bar-model.ts';
|
import type { BarModel } from './shell/bar-model.ts';
|
||||||
import { Footer } from './shell/Footer.tsx';
|
import { Footer } from './shell/Footer.tsx';
|
||||||
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
|
import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
|
||||||
import { SubNav } from './shell/SubNav.tsx';
|
import { SubNav } from './shell/SubNav.tsx';
|
||||||
import { TitleBar } from './shell/TitleBar.tsx';
|
import { TitleBar } from './shell/TitleBar.tsx';
|
||||||
import { useBackgrounds } from './shell/useBackgrounds.ts';
|
import { useBackgrounds } from './shell/useBackgrounds.ts';
|
||||||
@@ -195,6 +196,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
|||||||
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
|
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
|
||||||
bar: home,
|
bar: home,
|
||||||
};
|
};
|
||||||
|
case 'mods':
|
||||||
|
return {
|
||||||
|
side: <SubNav sections={MODS_SECTIONS} active={route.mods} label={(section) => t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />,
|
||||||
|
main: record
|
||||||
|
? <ModsPage key={record.id} copy={record} section={route.mods} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
|
||||||
|
: <Sheet title={t(`mods.sections.${route.mods}`)}><p className="lead">{t('mods.noCopy')}</p></Sheet>,
|
||||||
|
bar: home,
|
||||||
|
};
|
||||||
case 'copies': {
|
case 'copies': {
|
||||||
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
|
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
|
||||||
if (route.copies === 'list') {
|
if (route.copies === 'list') {
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { createElement, Fragment, useMemo, type ReactNode } from 'react';
|
||||||
|
import { marked, type Token, type Tokens } from 'marked';
|
||||||
|
|
||||||
|
const SAFE_EXTERNAL_URL = /^https?:\/\//i;
|
||||||
|
const HTML_COMMENT = /^<!--[\s\S]*?-->$/;
|
||||||
|
|
||||||
|
function isSafeExternalUrl(href: string | undefined): href is string {
|
||||||
|
return typeof href === 'string' && SAFE_EXTERNAL_URL.test(href.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInline(tokens: readonly Token[], keyPrefix: string): ReactNode {
|
||||||
|
return tokens.map((token, index) => renderInlineToken(token, `${keyPrefix}-${index}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInlineToken(token: Token, key: string): ReactNode {
|
||||||
|
switch (token.type) {
|
||||||
|
case 'text': {
|
||||||
|
const textToken = token as Tokens.Text;
|
||||||
|
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
|
||||||
|
return <Fragment key={key}>{textToken.text}</Fragment>;
|
||||||
|
}
|
||||||
|
case 'escape':
|
||||||
|
return <Fragment key={key}>{(token as Tokens.Escape).text}</Fragment>;
|
||||||
|
case 'strong':
|
||||||
|
return <strong key={key}>{renderInline((token as Tokens.Strong).tokens, key)}</strong>;
|
||||||
|
case 'em':
|
||||||
|
return <em key={key}>{renderInline((token as Tokens.Em).tokens, key)}</em>;
|
||||||
|
case 'del':
|
||||||
|
return <del key={key}>{renderInline((token as Tokens.Del).tokens, key)}</del>;
|
||||||
|
case 'codespan':
|
||||||
|
return <code key={key}>{(token as Tokens.Codespan).text}</code>;
|
||||||
|
case 'br':
|
||||||
|
return <br key={key} />;
|
||||||
|
case 'link': {
|
||||||
|
const link = token as Tokens.Link;
|
||||||
|
const content = link.tokens.length ? renderInline(link.tokens, key) : link.text;
|
||||||
|
if (!isSafeExternalUrl(link.href)) return <Fragment key={key}>{content}</Fragment>;
|
||||||
|
return (
|
||||||
|
<a key={key} href={link.href} title={link.title ?? undefined} target="_blank" rel="noreferrer">
|
||||||
|
{content}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
case 'image':
|
||||||
|
return <Fragment key={key}>{(token as Tokens.Image).text}</Fragment>;
|
||||||
|
case 'html': {
|
||||||
|
const raw = (token as Tokens.HTML).text.trim();
|
||||||
|
if (!raw || HTML_COMMENT.test(raw)) return null;
|
||||||
|
return <Fragment key={key}>{raw}</Fragment>;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 'raw' in token && typeof token.raw === 'string' ? <Fragment key={key}>{token.raw}</Fragment> : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTable(table: Tokens.Table, key: string): ReactNode {
|
||||||
|
return (
|
||||||
|
<div key={key} className="markdown-table-wrap">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{table.header.map((cell, column) => (
|
||||||
|
<th key={`${key}-h-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
|
||||||
|
{renderInline(cell.tokens, `${key}-h-${column}`)}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{table.rows.map((row, rowIndex) => (
|
||||||
|
<tr key={`${key}-r-${rowIndex}`}>
|
||||||
|
{row.map((cell, column) => (
|
||||||
|
<td key={`${key}-r-${rowIndex}-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
|
||||||
|
{renderInline(cell.tokens, `${key}-r-${rowIndex}-${column}`)}
|
||||||
|
</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderListItem(item: Tokens.ListItem, key: string): ReactNode {
|
||||||
|
return (
|
||||||
|
<li key={key}>
|
||||||
|
{item.task && <input type="checkbox" checked={Boolean(item.checked)} disabled readOnly className="markdown-task" />}
|
||||||
|
{renderBlocks(item.tokens, key)}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlock(token: Token, key: string): ReactNode {
|
||||||
|
switch (token.type) {
|
||||||
|
case 'space':
|
||||||
|
case 'def':
|
||||||
|
case 'checkbox':
|
||||||
|
return null;
|
||||||
|
case 'heading': {
|
||||||
|
const heading = token as Tokens.Heading;
|
||||||
|
const level = Math.min(6, Math.max(1, heading.depth));
|
||||||
|
return createElement(`h${level}`, { key }, renderInline(heading.tokens, key));
|
||||||
|
}
|
||||||
|
case 'paragraph':
|
||||||
|
return <p key={key}>{renderInline((token as Tokens.Paragraph).tokens, key)}</p>;
|
||||||
|
case 'text': {
|
||||||
|
const textToken = token as Tokens.Text;
|
||||||
|
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
|
||||||
|
return <Fragment key={key}>{textToken.text}</Fragment>;
|
||||||
|
}
|
||||||
|
case 'blockquote':
|
||||||
|
return <blockquote key={key}>{renderBlocks((token as Tokens.Blockquote).tokens, key)}</blockquote>;
|
||||||
|
case 'list': {
|
||||||
|
const list = token as Tokens.List;
|
||||||
|
const items = list.items.map((item, index) => renderListItem(item, `${key}-i-${index}`));
|
||||||
|
if (list.ordered) {
|
||||||
|
return <ol key={key} start={typeof list.start === 'number' && list.start !== 1 ? list.start : undefined}>{items}</ol>;
|
||||||
|
}
|
||||||
|
return <ul key={key}>{items}</ul>;
|
||||||
|
}
|
||||||
|
case 'code':
|
||||||
|
return (
|
||||||
|
<pre key={key}>
|
||||||
|
<code>{(token as Tokens.Code).text}</code>
|
||||||
|
</pre>
|
||||||
|
);
|
||||||
|
case 'hr':
|
||||||
|
return <hr key={key} />;
|
||||||
|
case 'table':
|
||||||
|
return renderTable(token as Tokens.Table, key);
|
||||||
|
case 'html': {
|
||||||
|
const raw = (token as Tokens.HTML).text.trim();
|
||||||
|
if (!raw || HTML_COMMENT.test(raw)) return null;
|
||||||
|
return <p key={key}>{raw}</p>;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 'raw' in token && typeof token.raw === 'string' && token.raw.trim()
|
||||||
|
? <p key={key}>{token.raw}</p>
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlocks(tokens: readonly Token[], keyPrefix: string): ReactNode {
|
||||||
|
return tokens.map((token, index) => renderBlock(token, `${keyPrefix}-${index}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Safe React renderer for GFM Markdown without injecting raw HTML. */
|
||||||
|
export function MarkdownContent({ markdown }: { readonly markdown: string }) {
|
||||||
|
const tokens = useMemo(() => marked.lexer(markdown, { gfm: true, breaks: false }), [markdown]);
|
||||||
|
return <div className="markdown-body">{renderBlocks(tokens, 'md')}</div>;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@ import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
|||||||
import { AppUpdateSection } from './AppUpdateSection.tsx';
|
import { AppUpdateSection } from './AppUpdateSection.tsx';
|
||||||
import type { PatchPackState } from '../../shell/usePatchPack.ts';
|
import type { PatchPackState } from '../../shell/usePatchPack.ts';
|
||||||
|
|
||||||
|
const HOMEPAGE_URL = 'https://wto-project.net';
|
||||||
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
|
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
|
||||||
|
|
||||||
interface AboutPageProps {
|
interface AboutPageProps {
|
||||||
@@ -37,6 +38,7 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
|
|||||||
<PatchPackSection state={patchPack} />
|
<PatchPackSection state={patchPack} />
|
||||||
</div>
|
</div>
|
||||||
<div className="about-column">
|
<div className="about-column">
|
||||||
|
<HomepageSection />
|
||||||
<CommunitySection />
|
<CommunitySection />
|
||||||
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
|
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
|
||||||
<section className="about-card">
|
<section className="about-card">
|
||||||
@@ -49,6 +51,23 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function HomepageSection() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<section className="about-card">
|
||||||
|
<div className="about-card-head">
|
||||||
|
<h3 className="about-card-title">{t('about.homepage.title')}</h3>
|
||||||
|
<div className="about-card-actions">
|
||||||
|
<a className="button" href={HOMEPAGE_URL} target="_blank" rel="noreferrer">
|
||||||
|
{t('about.homepage.open')}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="about-card-meta">{t('about.homepage.hint')}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function CommunitySection() {
|
function CommunitySection() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Notice } from '../../components/Notice.tsx';
|
import { Notice } from '../../components/Notice.tsx';
|
||||||
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||||
import { formatBytes } from '../../format.ts';
|
import { formatBytes } from '../../format.ts';
|
||||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||||
|
import { ReleaseNotesModal } from './ReleaseNotesModal.tsx';
|
||||||
|
|
||||||
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
|
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [notesOpen, setNotesOpen] = useState(false);
|
||||||
if (!state.supported) return null;
|
if (!state.supported) return null;
|
||||||
const { check, busy, progress } = state;
|
const { check, busy, progress } = state;
|
||||||
|
const available = check?.status === 'available' && busy !== 'checking' ? check : null;
|
||||||
|
const notes = available?.release.notes.trim() ?? '';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="about-card">
|
<section className="about-card">
|
||||||
<div className="about-card-head">
|
<div className="about-card-head">
|
||||||
@@ -21,30 +27,46 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
|
|||||||
<p className="about-card-meta">{t('about.update.check')}</p>
|
<p className="about-card-meta">{t('about.update.check')}</p>
|
||||||
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
|
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
|
||||||
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
|
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
|
||||||
{check?.status === 'available' && busy !== 'checking' && (
|
{available && (
|
||||||
<Notice tone="info">
|
<Notice tone="info">
|
||||||
<p>{t('about.update.available', { version: check.release.version, size: formatBytes(check.release.size) })}</p>
|
<p>{t('about.update.available', { version: available.release.version, size: formatBytes(available.release.size) })}</p>
|
||||||
{check.release.notes && <p className="small update-notes">{check.release.notes}</p>}
|
{busy === 'downloading' && (
|
||||||
{busy === 'downloading' ? (
|
|
||||||
<>
|
<>
|
||||||
<p>{t('about.update.downloading')}</p>
|
<p>{t('about.update.downloading')}</p>
|
||||||
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
|
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
|
||||||
</>
|
</>
|
||||||
) : (
|
)}
|
||||||
<button
|
{(busy !== 'downloading' || notes) && (
|
||||||
type="button"
|
<div className="update-actions">
|
||||||
className="button button-primary"
|
{busy !== 'downloading' && (
|
||||||
disabled={busy !== null}
|
<button
|
||||||
onClick={() => {
|
type="button"
|
||||||
if (check.ready) state.install(check.release.version);
|
className="button button-primary"
|
||||||
else state.download(check.release.version);
|
disabled={busy !== null}
|
||||||
}}
|
onClick={() => {
|
||||||
>
|
if (available.ready) state.install(available.release.version);
|
||||||
{t(busy === 'installing' ? 'about.update.installing' : check.ready ? 'about.update.install' : 'about.update.download')}
|
else state.download(available.release.version);
|
||||||
</button>
|
}}
|
||||||
|
>
|
||||||
|
{t(busy === 'installing' ? 'about.update.installing' : available.ready ? 'about.update.install' : 'about.update.download')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{notes && (
|
||||||
|
<button type="button" className="button button-compact" onClick={() => setNotesOpen(true)}>
|
||||||
|
{t('about.update.viewNotes')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</Notice>
|
</Notice>
|
||||||
)}
|
)}
|
||||||
|
{notesOpen && available && notes && (
|
||||||
|
<ReleaseNotesModal
|
||||||
|
version={available.release.version}
|
||||||
|
notes={notes}
|
||||||
|
onClose={() => setNotesOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { useEffect, useId } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { MarkdownContent } from '../../components/MarkdownContent.tsx';
|
||||||
|
|
||||||
|
interface ReleaseNotesModalProps {
|
||||||
|
readonly version: string;
|
||||||
|
readonly notes: string;
|
||||||
|
readonly onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Standalone dialog displaying rendered Markdown release notes for an available launcher update. */
|
||||||
|
export function ReleaseNotesModal({ version, notes, onClose }: ReleaseNotesModalProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const titleId = useId();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKeyDown = (event: KeyboardEvent): void => {
|
||||||
|
if (event.key === 'Escape') onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKeyDown);
|
||||||
|
return () => window.removeEventListener('keydown', onKeyDown);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
className="modal-backdrop"
|
||||||
|
role="presentation"
|
||||||
|
onClick={(event) => {
|
||||||
|
if (event.target === event.currentTarget) onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="modal-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}>
|
||||||
|
<header className="modal-head">
|
||||||
|
<h3 id={titleId} className="modal-title">{t('about.update.notesTitle', { version })}</h3>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="modal-close"
|
||||||
|
aria-label={t('about.update.closeNotes')}
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<div className="modal-body">
|
||||||
|
<MarkdownContent markdown={notes} />
|
||||||
|
</div>
|
||||||
|
<footer className="modal-foot">
|
||||||
|
<button type="button" className="button" onClick={onClose}>
|
||||||
|
{t('about.update.closeNotes')}
|
||||||
|
</button>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -22,17 +22,24 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
|
setInfo(null);
|
||||||
ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => {
|
ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => {
|
||||||
if (mounted) setInfo(value);
|
if (mounted) setInfo(value);
|
||||||
}).catch(onError);
|
}).catch(onError);
|
||||||
return () => { mounted = false; };
|
return () => { mounted = false; };
|
||||||
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
|
}, [record.id, record.gameVersion, record.sourcePath, record.steamLibraryConfirmation, maintenance.revision, onError]);
|
||||||
|
|
||||||
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
||||||
if (operation === 'delete') setRemoval(null);
|
if (operation === 'delete') setRemoval(null);
|
||||||
maintenance.run(record.id, operation, options);
|
maintenance.run(record.id, operation, options);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const chooseUpdateSource = (): void => {
|
||||||
|
ipcInvoke('dialog:pickFolder', { title: t('copies.maintenance.chooseSource') }).then(({ path }) => {
|
||||||
|
if (path) run('set-source', { sourcePath: path });
|
||||||
|
}).catch(onError);
|
||||||
|
};
|
||||||
|
|
||||||
const active = maintenance.active;
|
const active = maintenance.active;
|
||||||
const busy = active !== null;
|
const busy = active !== null;
|
||||||
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
|
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
|
||||||
@@ -44,6 +51,7 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
|
|||||||
info={info}
|
info={info}
|
||||||
busy={busy}
|
busy={busy}
|
||||||
onRun={run}
|
onRun={run}
|
||||||
|
onChooseSource={chooseUpdateSource}
|
||||||
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
|
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
|
||||||
/>
|
/>
|
||||||
<CopyRemoval
|
<CopyRemoval
|
||||||
|
|||||||
@@ -12,12 +12,20 @@ interface CopyMaintenanceControlsProps {
|
|||||||
|
|
||||||
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
|
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
|
||||||
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
|
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
|
||||||
|
readonly onChooseSource: () => void;
|
||||||
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
|
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSteam }: CopyMaintenanceActionsProps) {
|
export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSource, onConfirmSteam }: CopyMaintenanceActionsProps) {
|
||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const steam = info?.steamLocations;
|
const steam = info?.steamLocations;
|
||||||
|
const updateHint = info?.sourceVersion
|
||||||
|
? t(info.updateAvailable
|
||||||
|
? (record.hardlinkedFiles?.length
|
||||||
|
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
|
||||||
|
: 'copies.maintenance.newVersion')
|
||||||
|
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||||
|
: t(record.sourcePath ? (info ? 'copies.maintenance.noSource' : 'copies.maintenance.phase.checking') : 'copies.maintenance.sourceNotSet');
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{info?.steamConfirmationRequired && steam && (
|
{info?.steamConfirmationRequired && steam && (
|
||||||
@@ -30,13 +38,10 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
|
|||||||
</button>
|
</button>
|
||||||
</Notice>
|
</Notice>
|
||||||
)}
|
)}
|
||||||
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
<Row label={t('copies.maintenance.update')} hint={record.sourcePath ? <>{record.sourcePath}<br />{updateHint}</> : updateHint}>
|
||||||
? t(info.updateAvailable
|
<button type="button" className="button" disabled={busy} onClick={onChooseSource}>
|
||||||
? (record.hardlinkedFiles?.length
|
{t(record.sourcePath ? 'copies.maintenance.changeSource' : 'copies.maintenance.setSource')}
|
||||||
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
|
</button>
|
||||||
: 'copies.maintenance.newVersion')
|
|
||||||
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
|
||||||
: t('copies.maintenance.noSource')}>
|
|
||||||
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
||||||
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
|
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
|
||||||
{t('copies.maintenance.updateAction')}
|
{t('copies.maintenance.updateAction')}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/ma
|
|||||||
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||||
|
|
||||||
export type MaintenanceOperation = MaintenanceRequest['operation'];
|
export type MaintenanceOperation = MaintenanceRequest['operation'];
|
||||||
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
|
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations' | 'sourcePath'>;
|
||||||
|
|
||||||
export interface MaintenanceOutcome {
|
export interface MaintenanceOutcome {
|
||||||
readonly copyId: string;
|
readonly copyId: string;
|
||||||
|
|||||||
@@ -80,8 +80,10 @@ export function homeBar(
|
|||||||
detail: t('launch.versionDetail', { version: state.actualVersion ?? t('source.versionUnknown') }),
|
detail: t('launch.versionDetail', { version: state.actualVersion ?? t('source.versionUnknown') }),
|
||||||
primary: { label: t('launch.check'), onClick: actions.checkVersion },
|
primary: { label: t('launch.check'), onClick: actions.checkVersion },
|
||||||
};
|
};
|
||||||
case 'failed':
|
case 'failed': {
|
||||||
return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_failed'}`), primary: retry };
|
const key = `errors.${state.error ?? 'launch_failed'}` as const;
|
||||||
|
return { tone: 'bad', title: state.errorParams ? t(key, state.errorParams) : t(key), primary: retry };
|
||||||
|
}
|
||||||
case 'ready':
|
case 'ready':
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,591 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState, type DragEvent, type FormEvent } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
|
import type { ModIssueView, ModListItem, ModsStateView } from '@shared/schemas/mods.ts';
|
||||||
|
import { Row } from '../../components/Row.tsx';
|
||||||
|
import { Sheet } from '../../components/Sheet.tsx';
|
||||||
|
import { ipcInvoke } from '../../ipc.ts';
|
||||||
|
import type { ModsSection } from '../../shell/navigation.ts';
|
||||||
|
|
||||||
|
const MOD_DOCS_URL = 'https://wto-project.net/mod-docs';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly copy: InstallRecord;
|
||||||
|
readonly section: ModsSection;
|
||||||
|
readonly readOnly: boolean;
|
||||||
|
readonly onError: (error: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function localized(value: string | Readonly<Record<string, string>> | undefined, language: string): string {
|
||||||
|
if (!value) return '';
|
||||||
|
if (typeof value === 'string') return value;
|
||||||
|
const exact = value[language];
|
||||||
|
if (exact) return exact;
|
||||||
|
const prefix = language.split('-')[0];
|
||||||
|
if (prefix) {
|
||||||
|
const match = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
|
||||||
|
if (match?.[1]) return match[1];
|
||||||
|
}
|
||||||
|
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ModsPage({ copy, section, readOnly, onError }: Props) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const [state, setState] = useState<ModsStateView | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||||
|
const [draggedId, setDraggedId] = useState<string | null>(null);
|
||||||
|
const [presetName, setPresetName] = useState('');
|
||||||
|
const [notice, setNotice] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const load = useCallback(() => {
|
||||||
|
setBusy(true);
|
||||||
|
ipcInvoke('mods:getState', { copyId: copy.id })
|
||||||
|
.then(setState)
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(false));
|
||||||
|
}, [copy.id, onError]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
const sync = (): void => {
|
||||||
|
ipcInvoke('mods:getState', { copyId: copy.id })
|
||||||
|
.then((result) => { if (mounted) setState(result); })
|
||||||
|
.catch(onError);
|
||||||
|
};
|
||||||
|
sync();
|
||||||
|
window.addEventListener('focus', sync);
|
||||||
|
return () => {
|
||||||
|
mounted = false;
|
||||||
|
window.removeEventListener('focus', sync);
|
||||||
|
};
|
||||||
|
}, [copy.id, onError]);
|
||||||
|
|
||||||
|
const runAction = (action: Promise<ModsStateView>, successNotice?: string): void => {
|
||||||
|
setBusy(true);
|
||||||
|
setNotice(null);
|
||||||
|
action
|
||||||
|
.then((next) => {
|
||||||
|
setState(next);
|
||||||
|
if (successNotice) setNotice(successNotice);
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const issuesByMod = useMemo(() => {
|
||||||
|
const map = new Map<string, ModIssueView[]>();
|
||||||
|
for (const issue of state?.issues ?? []) {
|
||||||
|
const list = map.get(issue.modId) ?? [];
|
||||||
|
list.push(issue);
|
||||||
|
map.set(issue.modId, list);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [state]);
|
||||||
|
|
||||||
|
const title = t(`mods.sections.${section}`);
|
||||||
|
if (!state) {
|
||||||
|
return <Sheet title={title} aside={copy.name}><p className="lead">{t('mods.loading')}</p></Sheet>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const disabled = readOnly || busy;
|
||||||
|
const enabledCount = state.mods.filter((mod) => state.enabled[mod.id] === true).length;
|
||||||
|
|
||||||
|
const toggleMod = (modId: string, nextEnabled: boolean): void => {
|
||||||
|
runAction(ipcInvoke('mods:setEnabled', { copyId: copy.id, modId, enabled: nextEnabled }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const reorder = (nextOrder: string[]): void => {
|
||||||
|
runAction(ipcInvoke('mods:setOrder', { copyId: copy.id, order: nextOrder }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveMod = (modId: string, delta: -1 | 1): void => {
|
||||||
|
const idx = state.order.indexOf(modId);
|
||||||
|
const target = idx + delta;
|
||||||
|
if (idx < 0 || target < 0 || target >= state.order.length) return;
|
||||||
|
const next = [...state.order];
|
||||||
|
const [item] = next.splice(idx, 1);
|
||||||
|
next.splice(target, 0, item!);
|
||||||
|
reorder(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDrop = (targetId: string, event: DragEvent<HTMLDivElement>): void => {
|
||||||
|
event.preventDefault();
|
||||||
|
const sourceId = draggedId;
|
||||||
|
setDraggedId(null);
|
||||||
|
if (!sourceId || sourceId === targetId || disabled) return;
|
||||||
|
const from = state.order.indexOf(sourceId);
|
||||||
|
const to = state.order.indexOf(targetId);
|
||||||
|
if (from < 0 || to < 0) return;
|
||||||
|
const next = [...state.order];
|
||||||
|
const [moved] = next.splice(from, 1);
|
||||||
|
next.splice(to, 0, moved!);
|
||||||
|
reorder(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const savePreset = (event: FormEvent<HTMLFormElement>): void => {
|
||||||
|
event.preventDefault();
|
||||||
|
const trimmed = presetName.trim();
|
||||||
|
if (!trimmed) return;
|
||||||
|
runAction(
|
||||||
|
ipcInvoke('mods:savePreset', { copyId: copy.id, name: trimmed }),
|
||||||
|
t('mods.presets.saved', { name: trimmed }),
|
||||||
|
);
|
||||||
|
setPresetName('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const pickCustomFolder = (): void => {
|
||||||
|
ipcInvoke('dialog:pickFolder', { title: t('mods.repo.pickTitle') })
|
||||||
|
.then(({ path }) => {
|
||||||
|
if (!path) return;
|
||||||
|
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path }), t('mods.repo.updated'));
|
||||||
|
})
|
||||||
|
.catch(onError);
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetFolder = (): void => {
|
||||||
|
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path: null }), t('mods.repo.resetDone'));
|
||||||
|
};
|
||||||
|
|
||||||
|
const exportPreset = (presetId: string): void => {
|
||||||
|
setBusy(true);
|
||||||
|
setNotice(null);
|
||||||
|
ipcInvoke('mods:exportPreset', { copyId: copy.id, presetId })
|
||||||
|
.then(({ path }) => {
|
||||||
|
if (path) setNotice(t('mods.presets.exported', { path }));
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const importPreset = (): void => {
|
||||||
|
setBusy(true);
|
||||||
|
setNotice(null);
|
||||||
|
ipcInvoke('mods:importPreset', { copyId: copy.id })
|
||||||
|
.then(({ imported, state: next }) => {
|
||||||
|
setState(next);
|
||||||
|
if (imported) setNotice(t('mods.presets.imported'));
|
||||||
|
})
|
||||||
|
.catch(onError)
|
||||||
|
.finally(() => setBusy(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizedQuery = query.trim().toLowerCase();
|
||||||
|
const visibleMods = normalizedQuery
|
||||||
|
? state.mods.filter((mod) => {
|
||||||
|
const displayName = localized(mod.name, i18n.language).toLowerCase();
|
||||||
|
return displayName.includes(normalizedQuery)
|
||||||
|
|| mod.id.toLowerCase().includes(normalizedQuery)
|
||||||
|
|| mod.author.toLowerCase().includes(normalizedQuery);
|
||||||
|
})
|
||||||
|
: state.mods;
|
||||||
|
|
||||||
|
const canDrag = !disabled && normalizedQuery.length === 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sheet
|
||||||
|
title={title}
|
||||||
|
aside={(
|
||||||
|
<span className="mods-aside">
|
||||||
|
<span>{copy.name} · {t('mods.enabledSummary', { enabled: enabledCount, total: state.mods.length })}</span>
|
||||||
|
<span
|
||||||
|
className="mods-exp-chip"
|
||||||
|
tabIndex={0}
|
||||||
|
aria-label={t('mods.experimentalBody', { api: state.apiVersion })}
|
||||||
|
>
|
||||||
|
<span>{t('mods.experimentalChip')}</span>
|
||||||
|
<span className="mods-exp-icon" aria-hidden="true">i</span>
|
||||||
|
<span className="mods-exp-popover" role="tooltip">
|
||||||
|
<strong>{t('mods.experimentalTitle')}</strong>
|
||||||
|
<span>{t('mods.experimentalBody', { api: state.apiVersion })}</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{readOnly && (
|
||||||
|
<div className="mods-banner mods-banner-warn" role="status">
|
||||||
|
{t('mods.readOnlyNotice')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{notice && (
|
||||||
|
<div className="mods-banner mods-banner-ok" role="status">
|
||||||
|
{notice}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{section === 'list' ? (
|
||||||
|
<>
|
||||||
|
<div className="mods-toolbar">
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
className="input mods-search"
|
||||||
|
placeholder={t('mods.searchPlaceholder')}
|
||||||
|
value={query}
|
||||||
|
onChange={(event) => setQuery(event.target.value)}
|
||||||
|
/>
|
||||||
|
{state.presets.length > 0 && (
|
||||||
|
<select
|
||||||
|
className="select mods-preset-select"
|
||||||
|
aria-label={t('mods.presets.quickSwitch')}
|
||||||
|
disabled={disabled}
|
||||||
|
value={state.activePresetId ?? ''}
|
||||||
|
onChange={(event) => {
|
||||||
|
const id = event.target.value;
|
||||||
|
if (id) runAction(ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: id }));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">{t('mods.presets.customOption')}</option>
|
||||||
|
{state.presets.map((preset) => (
|
||||||
|
<option key={preset.id} value={preset.id}>{preset.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button"
|
||||||
|
disabled={disabled || state.mods.length < 2}
|
||||||
|
onClick={() => runAction(ipcInvoke('mods:autoSort', { copyId: copy.id }), t('mods.autoSorted'))}
|
||||||
|
>
|
||||||
|
{t('mods.autoSort')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" disabled={busy} onClick={load}>
|
||||||
|
{t('mods.refresh')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||||
|
{t('mods.openFolder')}
|
||||||
|
</button>
|
||||||
|
<a className="button" href={MOD_DOCS_URL} target="_blank" rel="noreferrer">
|
||||||
|
{t('mods.openDocs')}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{state.discoveryErrors.length > 0 && (
|
||||||
|
<div className="mods-issues-box mods-issues-error">
|
||||||
|
<div className="mods-issues-title">{t('mods.discoveryErrorsTitle', { count: state.discoveryErrors.length })}</div>
|
||||||
|
<ul>
|
||||||
|
{state.discoveryErrors.map((err) => (
|
||||||
|
<li key={err.folderName}>
|
||||||
|
<code>{err.folderName}</code>: {err.reason}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{state.issues.length > 0 && (
|
||||||
|
<div className={state.hasBlockingErrors ? 'mods-issues-box mods-issues-error' : 'mods-issues-box mods-issues-warn'}>
|
||||||
|
<div className="mods-issues-title">
|
||||||
|
{state.hasBlockingErrors
|
||||||
|
? t('mods.blockingIssuesTitle', { count: state.issues.filter((i) => i.severity === 'error').length })
|
||||||
|
: t('mods.issuesTitle', { count: state.issues.length })}
|
||||||
|
</div>
|
||||||
|
<ul>
|
||||||
|
{state.issues.map((issue, idx) => (
|
||||||
|
<li key={`${issue.modId}-${issue.kind}-${idx}`} className={`mods-issue-${issue.severity}`}>
|
||||||
|
<span className="mods-issue-tag">{t(`mods.severity.${issue.severity}`)}</span>
|
||||||
|
<strong>{issue.modId}</strong>: {issue.detail}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{visibleMods.length === 0 ? (
|
||||||
|
<div className="mods-empty">
|
||||||
|
<p className="lead">{state.mods.length === 0 ? t('mods.emptyTitle') : t('mods.noSearchMatch')}</p>
|
||||||
|
{state.mods.length === 0 && (
|
||||||
|
<>
|
||||||
|
<p className="mods-hint">{t('mods.emptyHint', { path: state.modsDir })}</p>
|
||||||
|
<button type="button" className="button button-primary" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||||
|
{t('mods.openFolder')}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="mods-list">
|
||||||
|
{visibleMods.map((mod) => {
|
||||||
|
const index = state.order.indexOf(mod.id);
|
||||||
|
const isEnabled = state.enabled[mod.id] === true;
|
||||||
|
const isExpanded = expandedId === mod.id;
|
||||||
|
const modIssues = issuesByMod.get(mod.id) ?? [];
|
||||||
|
return (
|
||||||
|
<ModCard
|
||||||
|
key={mod.id}
|
||||||
|
mod={mod}
|
||||||
|
index={index}
|
||||||
|
total={state.order.length}
|
||||||
|
enabled={isEnabled}
|
||||||
|
expanded={isExpanded}
|
||||||
|
disabled={disabled}
|
||||||
|
canDrag={canDrag}
|
||||||
|
language={i18n.language}
|
||||||
|
issues={modIssues}
|
||||||
|
onToggle={(next) => toggleMod(mod.id, next)}
|
||||||
|
onMove={(delta) => moveMod(mod.id, delta)}
|
||||||
|
onToggleExpand={() => setExpandedId(isExpanded ? null : mod.id)}
|
||||||
|
onDragStart={() => setDraggedId(mod.id)}
|
||||||
|
onDrop={(event) => handleDrop(mod.id, event)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<section className="mods-section">
|
||||||
|
<h3 className="mods-subheading">{t('mods.presets.heading')}</h3>
|
||||||
|
<p className="mods-hint">{t('mods.presets.description')}</p>
|
||||||
|
<form className="mods-preset-form" onSubmit={savePreset}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input"
|
||||||
|
maxLength={80}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder={t('mods.presets.namePlaceholder')}
|
||||||
|
value={presetName}
|
||||||
|
onChange={(event) => setPresetName(event.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="submit" className="button button-primary" disabled={disabled || !presetName.trim()}>
|
||||||
|
{t('mods.presets.saveCurrent')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" disabled={disabled} onClick={importPreset}>
|
||||||
|
{t('mods.presets.import')}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{state.presets.length === 0 ? (
|
||||||
|
<p className="mods-hint">{t('mods.presets.empty')}</p>
|
||||||
|
) : (
|
||||||
|
<div className="mods-preset-list">
|
||||||
|
{state.presets.map((preset) => {
|
||||||
|
const active = state.activePresetId === preset.id;
|
||||||
|
const count = Object.values(preset.enabled).filter(Boolean).length;
|
||||||
|
return (
|
||||||
|
<div key={preset.id} className={active ? 'mods-preset-item mods-preset-active' : 'mods-preset-item'}>
|
||||||
|
<div className="mods-preset-meta">
|
||||||
|
<div className="mods-preset-name">
|
||||||
|
{preset.name}
|
||||||
|
{active && <span className="mods-badge mods-badge-data">{t('mods.presets.activeTag')}</span>}
|
||||||
|
</div>
|
||||||
|
<div className="mods-preset-sub">
|
||||||
|
{t('mods.presets.summary', { count, total: preset.order.length })}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="copy-list-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button button-primary"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => runAction(
|
||||||
|
ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: preset.id }),
|
||||||
|
t('mods.presets.applied', { name: preset.name }),
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{t('mods.presets.apply')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => runAction(
|
||||||
|
ipcInvoke('mods:savePreset', { copyId: copy.id, name: preset.name, overwriteId: preset.id }),
|
||||||
|
t('mods.presets.updated', { name: preset.name }),
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{t('mods.presets.overwrite')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" disabled={busy} onClick={() => exportPreset(preset.id)}>
|
||||||
|
{t('mods.presets.export')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => runAction(ipcInvoke('mods:deletePreset', { copyId: copy.id, presetId: preset.id }))}
|
||||||
|
>
|
||||||
|
{t('mods.presets.delete')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="mods-section">
|
||||||
|
<h3 className="mods-subheading">{t('mods.repo.heading')}</h3>
|
||||||
|
<p className="mods-hint">{t('mods.repo.description')}</p>
|
||||||
|
<Row
|
||||||
|
label={t('mods.repo.pathLabel')}
|
||||||
|
hint={state.isCustomModsDir ? t('mods.repo.customNote') : t('mods.repo.defaultNote')}
|
||||||
|
>
|
||||||
|
<code className="mods-path">{state.modsDir}</code>
|
||||||
|
</Row>
|
||||||
|
<div className="copy-list-actions" style={{ marginTop: 12 }}>
|
||||||
|
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||||
|
{t('mods.openFolder')}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" disabled={disabled} onClick={pickCustomFolder}>
|
||||||
|
{t('mods.repo.changeFolder')}
|
||||||
|
</button>
|
||||||
|
{state.isCustomModsDir && (
|
||||||
|
<button type="button" className="button" disabled={disabled} onClick={resetFolder}>
|
||||||
|
{t('mods.repo.resetDefault')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ModCardProps {
|
||||||
|
readonly mod: ModListItem;
|
||||||
|
readonly index: number;
|
||||||
|
readonly total: number;
|
||||||
|
readonly enabled: boolean;
|
||||||
|
readonly expanded: boolean;
|
||||||
|
readonly disabled: boolean;
|
||||||
|
readonly canDrag: boolean;
|
||||||
|
readonly language: string;
|
||||||
|
readonly issues: readonly ModIssueView[];
|
||||||
|
readonly onToggle: (next: boolean) => void;
|
||||||
|
readonly onMove: (delta: -1 | 1) => void;
|
||||||
|
readonly onToggleExpand: () => void;
|
||||||
|
readonly onDragStart: () => void;
|
||||||
|
readonly onDrop: (event: DragEvent<HTMLDivElement>) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ModCard({
|
||||||
|
mod,
|
||||||
|
index,
|
||||||
|
total,
|
||||||
|
enabled,
|
||||||
|
expanded,
|
||||||
|
disabled,
|
||||||
|
canDrag,
|
||||||
|
language,
|
||||||
|
issues,
|
||||||
|
onToggle,
|
||||||
|
onMove,
|
||||||
|
onToggleExpand,
|
||||||
|
onDragStart,
|
||||||
|
onDrop,
|
||||||
|
}: ModCardProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const displayName = localized(mod.name, language) || mod.id;
|
||||||
|
const description = localized(mod.description, language);
|
||||||
|
const errorCount = issues.filter((i) => i.severity === 'error').length;
|
||||||
|
const warnCount = issues.filter((i) => i.severity === 'warning').length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`mods-card${enabled ? ' mods-card-enabled' : ''}`}
|
||||||
|
draggable={canDrag}
|
||||||
|
onDragStart={onDragStart}
|
||||||
|
onDragOver={(event) => { if (canDrag) event.preventDefault(); }}
|
||||||
|
onDrop={onDrop}
|
||||||
|
>
|
||||||
|
<div className="mods-card-row">
|
||||||
|
<span className="mods-order-num" title={t('mods.loadOrderHint')}>#{index + 1}</span>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="mods-checkbox"
|
||||||
|
checked={enabled}
|
||||||
|
disabled={disabled}
|
||||||
|
aria-label={displayName}
|
||||||
|
onChange={(event) => onToggle(event.target.checked)}
|
||||||
|
/>
|
||||||
|
<div className="mods-card-main" onClick={onToggleExpand}>
|
||||||
|
<div className="mods-card-title">
|
||||||
|
<span className="mods-name">{displayName}</span>
|
||||||
|
<span className="mods-version">v{mod.version}</span>
|
||||||
|
<span className="mods-author">· {mod.author}</span>
|
||||||
|
<div className="mods-badges">
|
||||||
|
{mod.badges.map((badge) => (
|
||||||
|
<span key={badge} className={`mods-badge mods-badge-${badge}`}>
|
||||||
|
{t(`mods.badges.${badge}`)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
{errorCount > 0 && <span className="mods-badge mods-badge-error">{t('mods.errorCount', { count: errorCount })}</span>}
|
||||||
|
{warnCount > 0 && <span className="mods-badge mods-badge-warn">{t('mods.warnCount', { count: warnCount })}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{description && <div className="mods-card-desc">{description}</div>}
|
||||||
|
</div>
|
||||||
|
<div className="mods-card-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button mods-move-btn"
|
||||||
|
disabled={disabled || index <= 0}
|
||||||
|
title={t('mods.moveUp')}
|
||||||
|
onClick={() => onMove(-1)}
|
||||||
|
>
|
||||||
|
↑
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button mods-move-btn"
|
||||||
|
disabled={disabled || index < 0 || index >= total - 1}
|
||||||
|
title={t('mods.moveDown')}
|
||||||
|
onClick={() => onMove(1)}
|
||||||
|
>
|
||||||
|
↓
|
||||||
|
</button>
|
||||||
|
<button type="button" className="button" onClick={onToggleExpand}>
|
||||||
|
{expanded ? t('mods.hideDetails') : t('mods.showDetails')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{expanded && (
|
||||||
|
<div className="mods-card-details">
|
||||||
|
<div className="mods-detail-grid">
|
||||||
|
<div><span>ID:</span> <code>{mod.id}</code></div>
|
||||||
|
<div><span>API:</span> <code>{mod.apiVersion}</code></div>
|
||||||
|
<div><span>{t('mods.details.folder')}:</span> <code>{mod.folderName}</code></div>
|
||||||
|
{mod.gameVersions.length > 0 && (
|
||||||
|
<div><span>{t('mods.details.gameVersions')}:</span> <code>{mod.gameVersions.join(', ')}</code></div>
|
||||||
|
)}
|
||||||
|
{mod.requires.length > 0 && (
|
||||||
|
<div><span>{t('mods.details.requires')}:</span> <code>{mod.requires.join(', ')}</code></div>
|
||||||
|
)}
|
||||||
|
{mod.conflicts.length > 0 && (
|
||||||
|
<div><span>{t('mods.details.conflicts')}:</span> <code>{mod.conflicts.join(', ')}</code></div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mods-detail-summary">
|
||||||
|
{mod.serverTuningFiles.length > 0 && (
|
||||||
|
<span>{t('mods.details.tuning', { count: mod.serverTuningFiles.length })}</span>
|
||||||
|
)}
|
||||||
|
{mod.hasServerScript && <span>{t('mods.details.serverScript')}</span>}
|
||||||
|
{mod.packOperations.length > 0 && (
|
||||||
|
<span>{t('mods.details.packOps', { count: mod.packOperations.length })}</span>
|
||||||
|
)}
|
||||||
|
{mod.hasClientAddon && (
|
||||||
|
<span>{t('mods.details.addon', { count: mod.addonFileCount })}</span>
|
||||||
|
)}
|
||||||
|
{mod.guiPatchCount > 0 && (
|
||||||
|
<span>{t('mods.details.guiPatches', { count: mod.guiPatchCount })}</span>
|
||||||
|
)}
|
||||||
|
{mod.exePatchCount > 0 && (
|
||||||
|
<span>{t('mods.details.exePatches', { count: mod.exePatchCount })}</span>
|
||||||
|
)}
|
||||||
|
{mod.clientFileCount > 0 && (
|
||||||
|
<span>{t('mods.details.companionFiles', { count: mod.clientFileCount })}</span>
|
||||||
|
)}
|
||||||
|
{mod.hasConfigBlkPatch && <span>{t('mods.details.configBlk')}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ interface Props {
|
|||||||
readonly onError: (error: unknown) => void;
|
readonly onError: (error: unknown) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ACTIONS = ['research', 'purchase', 'equipment'] as const;
|
const ACTIONS = ['purchase', 'equipment'] as const;
|
||||||
|
|
||||||
export function SaveResearch({ copyId, userId, readOnly, onError }: Props) {
|
export function SaveResearch({ copyId, userId, readOnly, onError }: Props) {
|
||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
|
|||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import { useState, type FormEvent, type ReactNode } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import {
|
||||||
|
GROUND_AI_DRIVE_MODES,
|
||||||
|
GROUND_AI_MODES,
|
||||||
|
TuningPatchSchema,
|
||||||
|
type GroundAiTuningValues,
|
||||||
|
type TuningPatch,
|
||||||
|
type TuningView,
|
||||||
|
} from '@shared/schemas/tuning.ts';
|
||||||
|
import { Row } from '../../components/Row.tsx';
|
||||||
|
import {
|
||||||
|
ALL_BOT_FIELDS,
|
||||||
|
BOT_TUNING_GROUPS,
|
||||||
|
readBotFieldValue,
|
||||||
|
type BotFieldSpec,
|
||||||
|
} from './bot-tuning-fields.ts';
|
||||||
|
|
||||||
|
type DraftMap = Record<string, string | boolean>;
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
readonly data: TuningView;
|
||||||
|
readonly saving: boolean;
|
||||||
|
readonly onSave: (patch: TuningPatch) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toInputValue(value: string | number | boolean): string | boolean {
|
||||||
|
return typeof value === 'boolean' ? value : String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeSection<T extends Record<string, unknown>>(
|
||||||
|
base: T,
|
||||||
|
patch: { readonly [K in keyof T]?: T[K] | undefined } | undefined,
|
||||||
|
): T {
|
||||||
|
if (!patch) return base;
|
||||||
|
const next: Record<string, unknown> = { ...base };
|
||||||
|
for (const [key, value] of Object.entries(patch)) {
|
||||||
|
if (value !== undefined) next[key] = value;
|
||||||
|
}
|
||||||
|
return next as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasValidCrossFieldRules(effective: GroundAiTuningValues, patch: TuningPatch['groundAi']): boolean {
|
||||||
|
if (!patch) return true;
|
||||||
|
const cmd = mergeSection(effective.commander, patch.commander);
|
||||||
|
if (cmd.bttlAssaultPct + cmd.bttlFlankPct + cmd.bttlOverwatchPct > 100) return false;
|
||||||
|
if (cmd.conqAssaultPct + cmd.conqFlankPct > 100) return false;
|
||||||
|
if (cmd.conqHoldDefendPct + cmd.conqHoldOverwatchPct > 100) return false;
|
||||||
|
const macro = mergeSection(effective.macro, patch.macro);
|
||||||
|
if (macro.recaptureMaxBots < macro.recaptureMinBots) return false;
|
||||||
|
const sm = mergeSection(effective.stateMachine, patch.stateMachine);
|
||||||
|
if (sm.coverMaxDistM <= sm.coverMinDistM) return false;
|
||||||
|
const est = mergeSection(effective.estimation, patch.estimation);
|
||||||
|
if (est.watchMaxSec < est.watchMinSec || est.velStableSpanSec <= est.velSampleMinSpanSec) return false;
|
||||||
|
const fc = mergeSection(effective.fireControl, patch.fireControl);
|
||||||
|
if (fc.midRangeM <= fc.closeRangeM || fc.longRangeM <= fc.midRangeM) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BotTuningPanel({ data, saving, onSave }: Props) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const [draft, setDraft] = useState<DraftMap>({});
|
||||||
|
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
|
||||||
|
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>(() =>
|
||||||
|
Object.fromEntries(BOT_TUNING_GROUPS.map((group) => [group.id, group.defaultOpen])),
|
||||||
|
);
|
||||||
|
|
||||||
|
const format = new Intl.NumberFormat(i18n.language);
|
||||||
|
const activeMode = String(draft['groundAi.mode'] ?? data.effective.groundAi.mode);
|
||||||
|
const allOpen = BOT_TUNING_GROUPS.every((group) => openGroups[group.id]);
|
||||||
|
|
||||||
|
const set = (id: string, value: string | boolean): void => {
|
||||||
|
setMessage(null);
|
||||||
|
setDraft((previous) => ({ ...previous, [id]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleAllGroups = (): void => {
|
||||||
|
const nextState = !allOpen;
|
||||||
|
setOpenGroups(Object.fromEntries(BOT_TUNING_GROUPS.map((group) => [group.id, nextState])));
|
||||||
|
};
|
||||||
|
|
||||||
|
const reset = (): void => {
|
||||||
|
setMessage(null);
|
||||||
|
setDraft(Object.fromEntries(
|
||||||
|
ALL_BOT_FIELDS.map((spec) => [spec.id, toInputValue(readBotFieldValue(data.defaults, spec))]),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
const fieldLabel = (spec: BotFieldSpec): string => {
|
||||||
|
if (spec.kind === 'flatInt') return t(`tuning.fields.${spec.id}`);
|
||||||
|
if (spec.kind === 'groundAiMode') return t('tuning.botFields.mode');
|
||||||
|
return t(`tuning.botFields.${spec.section}.${spec.field}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultLabel = (spec: BotFieldSpec): string => {
|
||||||
|
const value = readBotFieldValue(data.defaults, spec);
|
||||||
|
if (spec.kind === 'groundAiMode') return t(`tuning.botModes.${value}`);
|
||||||
|
if (spec.kind === 'driveMode') return t(`tuning.botDriveModes.${value}`);
|
||||||
|
if (spec.kind === 'steerSign') return value === 1 ? t('tuning.botSteer.normal') : t('tuning.botSteer.inverted');
|
||||||
|
if (typeof value === 'boolean') return t(value ? 'tuning.on' : 'tuning.off');
|
||||||
|
const formatted = format.format(Number(value));
|
||||||
|
const unit = 'unit' in spec && spec.unit ? ` ${spec.unit}` : '';
|
||||||
|
return `${formatted}${unit}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderEditor = (spec: BotFieldSpec): ReactNode => {
|
||||||
|
const active = draft[spec.id] ?? toInputValue(readBotFieldValue(data.effective, spec));
|
||||||
|
const label = fieldLabel(spec);
|
||||||
|
|
||||||
|
if (spec.kind === 'bool') {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
aria-label={label}
|
||||||
|
disabled={saving}
|
||||||
|
checked={active === true}
|
||||||
|
onChange={(event) => set(spec.id, event.target.checked)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (spec.kind === 'groundAiMode') {
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="select"
|
||||||
|
aria-label={label}
|
||||||
|
disabled={saving}
|
||||||
|
value={String(active)}
|
||||||
|
onChange={(event) => set(spec.id, event.target.value)}
|
||||||
|
>
|
||||||
|
{GROUND_AI_MODES.map((mode) => (
|
||||||
|
<option key={mode} value={mode}>{t(`tuning.botModes.${mode}`)}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (spec.kind === 'driveMode') {
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="select"
|
||||||
|
aria-label={label}
|
||||||
|
disabled={saving}
|
||||||
|
value={String(active)}
|
||||||
|
onChange={(event) => set(spec.id, event.target.value)}
|
||||||
|
>
|
||||||
|
{GROUND_AI_DRIVE_MODES.map((mode) => (
|
||||||
|
<option key={mode} value={mode}>{t(`tuning.botDriveModes.${mode}`)}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (spec.kind === 'steerSign') {
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="select"
|
||||||
|
aria-label={label}
|
||||||
|
disabled={saving}
|
||||||
|
value={String(active)}
|
||||||
|
onChange={(event) => set(spec.id, event.target.value)}
|
||||||
|
>
|
||||||
|
<option value="1">{t('tuning.botSteer.normal')}</option>
|
||||||
|
<option value="-1">{t('tuning.botSteer.inverted')}</option>
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const isInt = spec.kind === 'int' || spec.kind === 'flatInt';
|
||||||
|
const unit = 'unit' in spec ? spec.unit : undefined;
|
||||||
|
return (
|
||||||
|
<div className="copy-list-actions">
|
||||||
|
<input
|
||||||
|
className="input"
|
||||||
|
aria-label={label}
|
||||||
|
type="number"
|
||||||
|
min={spec.min}
|
||||||
|
max={spec.max}
|
||||||
|
step={isInt ? '1' : 'any'}
|
||||||
|
value={String(active)}
|
||||||
|
disabled={saving}
|
||||||
|
onChange={(event) => set(spec.id, event.target.value)}
|
||||||
|
/>
|
||||||
|
{unit && <span>{unit}</span>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = (event: FormEvent<HTMLFormElement>): void => {
|
||||||
|
event.preventDefault();
|
||||||
|
const rawPatch: Record<string, unknown> = {};
|
||||||
|
const groundAiPatch: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
for (const spec of ALL_BOT_FIELDS) {
|
||||||
|
if (!(spec.id in draft)) continue;
|
||||||
|
const raw = draft[spec.id];
|
||||||
|
if (spec.kind === 'flatInt') {
|
||||||
|
rawPatch[spec.id] = raw === '' ? NaN : Number(raw);
|
||||||
|
} else if (spec.kind === 'groundAiMode') {
|
||||||
|
groundAiPatch['mode'] = raw;
|
||||||
|
} else {
|
||||||
|
const parsed = spec.kind === 'bool' || spec.kind === 'driveMode'
|
||||||
|
? raw
|
||||||
|
: (raw === '' ? NaN : Number(raw));
|
||||||
|
const sectionObj = (groundAiPatch[spec.section] as Record<string, unknown> | undefined) ?? {};
|
||||||
|
sectionObj[spec.field] = parsed;
|
||||||
|
groundAiPatch[spec.section] = sectionObj;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Object.keys(groundAiPatch).length > 0) rawPatch['groundAi'] = groundAiPatch;
|
||||||
|
|
||||||
|
const result = TuningPatchSchema.safeParse(rawPatch);
|
||||||
|
if (!result.success || !hasValidCrossFieldRules(data.effective.groundAi, result.data.groundAi)) {
|
||||||
|
setMessage('invalid');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setMessage(null);
|
||||||
|
onSave(result.data).then(() => {
|
||||||
|
setDraft({});
|
||||||
|
setMessage('saved');
|
||||||
|
}).catch(() => undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={submit}>
|
||||||
|
<div className="tuning-toolbar">
|
||||||
|
<p className="small">{t('tuning.botModeHint')}</p>
|
||||||
|
<button type="button" className="button" onClick={toggleAllGroups}>
|
||||||
|
{t(allOpen ? 'tuning.collapseAll' : 'tuning.expandAll')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{activeMode === 'stock' && (
|
||||||
|
<p className="notice">{t('tuning.botStockNotice')}</p>
|
||||||
|
)}
|
||||||
|
{BOT_TUNING_GROUPS.map((group) => (
|
||||||
|
<details
|
||||||
|
key={group.id}
|
||||||
|
className="tuning-group"
|
||||||
|
open={openGroups[group.id]}
|
||||||
|
onToggle={(event) => {
|
||||||
|
const isOpen = event.currentTarget.open;
|
||||||
|
setOpenGroups((prev) => (prev[group.id] === isOpen ? prev : { ...prev, [group.id]: isOpen }));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<summary className="tuning-group-summary">
|
||||||
|
<span>{t(`tuning.botGroups.${group.id}`)}</span>
|
||||||
|
<small>{t(`tuning.botGroupHints.${group.id}`)}</small>
|
||||||
|
</summary>
|
||||||
|
<div className="tuning-group-body">
|
||||||
|
{group.fields.map((spec) => (
|
||||||
|
<Row
|
||||||
|
key={spec.id}
|
||||||
|
label={fieldLabel(spec)}
|
||||||
|
hint={t('tuning.default', { value: defaultLabel(spec) })}
|
||||||
|
>
|
||||||
|
{renderEditor(spec)}
|
||||||
|
</Row>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
))}
|
||||||
|
<div className="copy-list-actions tuning-actions">
|
||||||
|
<button type="button" className="button" disabled={saving} onClick={reset}>{t('tuning.reset')}</button>
|
||||||
|
<button type="submit" className="button button-primary" disabled={saving || Object.keys(draft).length === 0}>
|
||||||
|
{t('saves.apply')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{message && <p className="small" role={message === 'invalid' ? 'alert' : 'status'}>{t(`tuning.${message}`)}</p>}
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,20 +1,22 @@
|
|||||||
import { useEffect, useState, type FormEvent, type ReactNode } from 'react';
|
import { useEffect, useState, type FormEvent, type ReactNode } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||||
import { AUTO_TARGET_PICKS, TuningPatchSchema, type TuningValues, type TuningView } from '@shared/schemas/tuning.ts';
|
import { AUTO_TARGET_PICKS, TuningPatchSchema, type TuningPatch, type TuningValues, type TuningView } from '@shared/schemas/tuning.ts';
|
||||||
import { Row } from '../../components/Row.tsx';
|
import { Row } from '../../components/Row.tsx';
|
||||||
import { Sheet } from '../../components/Sheet.tsx';
|
import { Sheet } from '../../components/Sheet.tsx';
|
||||||
import { ipcInvoke } from '../../ipc.ts';
|
import { ipcInvoke } from '../../ipc.ts';
|
||||||
import type { TuningSection } from '../../shell/navigation.ts';
|
import type { TuningSection } from '../../shell/navigation.ts';
|
||||||
|
import { BotTuningPanel } from './BotTuningPanel.tsx';
|
||||||
|
|
||||||
type Field = keyof TuningValues;
|
type SimpleSection = Exclude<TuningSection, 'bots'>;
|
||||||
|
type Field = Exclude<keyof TuningValues, 'groundAi'>;
|
||||||
type Draft = Partial<Record<Field, string | boolean>>;
|
type Draft = Partial<Record<Field, string | boolean>>;
|
||||||
const fields = {
|
const fields = {
|
||||||
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
|
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
|
||||||
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore'],
|
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'strikeUcavSpawnScore', 'nuclearEscalationStrategicBombers'],
|
||||||
newProfile: ['silverLions', 'goldenEagles'],
|
newProfile: ['silverLions', 'goldenEagles'],
|
||||||
research: ['preferLineSuccessor', 'autoTargetPick'],
|
research: ['preferLineSuccessor', 'autoTargetPick'],
|
||||||
} as const satisfies Record<TuningSection, readonly Field[]>;
|
} as const satisfies Record<SimpleSection, readonly Field[]>;
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
readonly copy: InstallRecord;
|
readonly copy: InstallRecord;
|
||||||
@@ -34,7 +36,6 @@ export function TuningPage({ copy, section, onError }: Props) {
|
|||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
|
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
|
||||||
const title = t(`tuning.sections.${section}`);
|
const title = t(`tuning.sections.${section}`);
|
||||||
const sectionFields: readonly Field[] = fields[section];
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
@@ -46,6 +47,30 @@ export function TuningPage({ copy, section, onError }: Props) {
|
|||||||
|
|
||||||
if (!data) return <Sheet title={title} aside={copy.name}><p className="lead">{t('tuning.loading')}</p></Sheet>;
|
if (!data) return <Sheet title={title} aside={copy.name}><p className="lead">{t('tuning.loading')}</p></Sheet>;
|
||||||
const loaded = data;
|
const loaded = data;
|
||||||
|
|
||||||
|
const savePatch = async (patch: TuningPatch): Promise<void> => {
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const next = await ipcInvoke('tuning:update', { copyId: copy.id, patch });
|
||||||
|
setData(next);
|
||||||
|
} catch (error) {
|
||||||
|
onError(error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (section === 'bots') {
|
||||||
|
return (
|
||||||
|
<Sheet title={title} aside={copy.name} foot={t('tuning.nextLaunch')}>
|
||||||
|
<p className="small">{t('tuning.shared')}</p>
|
||||||
|
<BotTuningPanel data={loaded} saving={saving} onSave={savePatch} />
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sectionFields: readonly Field[] = fields[section];
|
||||||
const format = new Intl.NumberFormat(i18n.language);
|
const format = new Intl.NumberFormat(i18n.language);
|
||||||
const set = (field: Field, value: string | boolean): void => {
|
const set = (field: Field, value: string | boolean): void => {
|
||||||
setMessage(null);
|
setMessage(null);
|
||||||
@@ -70,7 +95,7 @@ export function TuningPage({ copy, section, onError }: Props) {
|
|||||||
const editor = (field: Field): ReactNode => {
|
const editor = (field: Field): ReactNode => {
|
||||||
const active = draft[field] ?? inputValue(field, loaded.effective[field]);
|
const active = draft[field] ?? inputValue(field, loaded.effective[field]);
|
||||||
const label = t(`tuning.fields.${field}`);
|
const label = t(`tuning.fields.${field}`);
|
||||||
if (field === 'preferLineSuccessor') {
|
if (typeof loaded.defaults[field] === 'boolean') {
|
||||||
return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />;
|
return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />;
|
||||||
}
|
}
|
||||||
if (field === 'autoTargetPick') {
|
if (field === 'autoTargetPick') {
|
||||||
@@ -110,13 +135,11 @@ export function TuningPage({ copy, section, onError }: Props) {
|
|||||||
setMessage('invalid');
|
setMessage('invalid');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSaving(true);
|
|
||||||
setMessage(null);
|
setMessage(null);
|
||||||
ipcInvoke('tuning:update', { copyId: copy.id, patch: result.data }).then((next) => {
|
savePatch(result.data).then(() => {
|
||||||
setData(next);
|
|
||||||
setDraft({});
|
setDraft({});
|
||||||
setMessage('saved');
|
setMessage('saved');
|
||||||
}).catch(onError).finally(() => setSaving(false));
|
}).catch(() => undefined);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -0,0 +1,316 @@
|
|||||||
|
import type { GroundAiTuningValues, TuningValues } from '@shared/schemas/tuning.ts';
|
||||||
|
|
||||||
|
export type FlatBotFieldKey = 'tankBotRespawns' | 'airBotRespawns' | 'botPoolLimitPerType';
|
||||||
|
export type GroundAiSectionKey = Exclude<keyof GroundAiTuningValues, 'mode'>;
|
||||||
|
|
||||||
|
export type BotFieldSpec =
|
||||||
|
| {
|
||||||
|
readonly id: FlatBotFieldKey;
|
||||||
|
readonly kind: 'flatInt';
|
||||||
|
readonly min: number;
|
||||||
|
readonly max: number;
|
||||||
|
readonly unit?: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
readonly id: 'groundAi.mode';
|
||||||
|
readonly kind: 'groundAiMode';
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
readonly id: `groundAi.${GroundAiSectionKey}.${string}`;
|
||||||
|
readonly section: GroundAiSectionKey;
|
||||||
|
readonly field: string;
|
||||||
|
readonly kind: 'int' | 'number' | 'bool' | 'driveMode' | 'steerSign';
|
||||||
|
readonly min?: number;
|
||||||
|
readonly max?: number;
|
||||||
|
readonly unit?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface BotTuningGroup {
|
||||||
|
readonly id: string;
|
||||||
|
readonly defaultOpen: boolean;
|
||||||
|
readonly customOnly?: boolean;
|
||||||
|
readonly fields: readonly BotFieldSpec[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(
|
||||||
|
section: GroundAiSectionKey,
|
||||||
|
field: string,
|
||||||
|
min: number,
|
||||||
|
max: number,
|
||||||
|
unit?: string,
|
||||||
|
): BotFieldSpec {
|
||||||
|
return {
|
||||||
|
id: `groundAi.${section}.${field}`,
|
||||||
|
section,
|
||||||
|
field,
|
||||||
|
kind: 'number',
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
...(unit ? { unit } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function int(
|
||||||
|
section: GroundAiSectionKey,
|
||||||
|
field: string,
|
||||||
|
min: number,
|
||||||
|
max: number,
|
||||||
|
unit?: string,
|
||||||
|
): BotFieldSpec {
|
||||||
|
return {
|
||||||
|
id: `groundAi.${section}.${field}`,
|
||||||
|
section,
|
||||||
|
field,
|
||||||
|
kind: 'int',
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
...(unit ? { unit } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
|
||||||
|
{
|
||||||
|
id: 'general',
|
||||||
|
defaultOpen: true,
|
||||||
|
fields: [
|
||||||
|
{ id: 'groundAi.mode', kind: 'groundAiMode' },
|
||||||
|
{ id: 'tankBotRespawns', kind: 'flatInt', min: 1, max: 10 },
|
||||||
|
{ id: 'airBotRespawns', kind: 'flatInt', min: 1, max: 10 },
|
||||||
|
{ id: 'botPoolLimitPerType', kind: 'flatInt', min: 4, max: 200 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'lineupWeights',
|
||||||
|
defaultOpen: true,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('lineupWeights', 'mediumTank', 0.01, 10),
|
||||||
|
num('lineupWeights', 'heavyTank', 0.01, 10),
|
||||||
|
num('lineupWeights', 'tankDestroyer', 0.01, 10),
|
||||||
|
num('lineupWeights', 'lightTank', 0.01, 10),
|
||||||
|
num('lineupWeights', 'spaa', 0.01, 10),
|
||||||
|
num('lineupWeights', 'other', 0.01, 10),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'loadout',
|
||||||
|
defaultOpen: true,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
int('loadout', 'lowReadyRackThreshold', 1, 60),
|
||||||
|
int('loadout', 'topUpAmmoCount', 4, 80),
|
||||||
|
int('loadout', 'primaryAmmoPct', 50, 100, '%'),
|
||||||
|
int('loadout', 'secondaryMinRounds', 0, 20),
|
||||||
|
int('loadout', 'penetrationCompareDistM', 100, 2000, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'commander',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('commander', 'rebalanceSec', 1, 30, 's'),
|
||||||
|
num('commander', 'roleHoldSec', 0, 120, 's'),
|
||||||
|
int('commander', 'bttlAssaultPct', 0, 100, '%'),
|
||||||
|
int('commander', 'bttlFlankPct', 0, 100, '%'),
|
||||||
|
int('commander', 'bttlOverwatchPct', 0, 100, '%'),
|
||||||
|
int('commander', 'conqAssaultPct', 0, 100, '%'),
|
||||||
|
int('commander', 'conqFlankPct', 0, 100, '%'),
|
||||||
|
int('commander', 'conqHoldDefendPct', 0, 100, '%'),
|
||||||
|
int('commander', 'conqHoldOverwatchPct', 0, 100, '%'),
|
||||||
|
int('commander', 'domAssaultPct', 0, 100, '%'),
|
||||||
|
int('commander', 'domMaxDefendersPerCap', 0, 4),
|
||||||
|
num('commander', 'overwatchStandOffM', 25, 350, 'm'),
|
||||||
|
num('commander', 'flankStandOffM', 25, 300, 'm'),
|
||||||
|
num('commander', 'spaaFollowOffsetM', 40, 500, 'm'),
|
||||||
|
num('commander', 'flankMaxLengthRatio', 1.05, 3),
|
||||||
|
num('commander', 'flankMinSeparationM', 15, 200, 'm'),
|
||||||
|
num('commander', 'rallyProgressFrac', 0.1, 0.75),
|
||||||
|
num('commander', 'rallyWaitSec', 3, 60, 's'),
|
||||||
|
num('commander', 'rallyMinFrac', 0.25, 1),
|
||||||
|
num('commander', 'rallyRadiusM', 15, 140, 'm'),
|
||||||
|
num('commander', 'recallSafeHoldSec', 3, 60, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'macro',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('macro', 'openingSplitSec', 0, 180, 's'),
|
||||||
|
int('macro', 'capMaxInsiders', 1, 8),
|
||||||
|
int('macro', 'recaptureMinBots', 1, 8),
|
||||||
|
int('macro', 'recaptureMaxBots', 1, 12),
|
||||||
|
num('macro', 'capStickyBonusM', 0, 800, 'm'),
|
||||||
|
num('macro', 'deathZoneRadiusM', 10, 250, 'm'),
|
||||||
|
num('macro', 'deathZoneTtlSec', 5, 300, 's'),
|
||||||
|
int('macro', 'deathZoneMinKills', 1, 16),
|
||||||
|
num('macro', 'spaaRearOffsetM', 40, 600, 'm'),
|
||||||
|
num('macro', 'spaaRelocateSec', 5, 180, 's'),
|
||||||
|
num('macro', 'enemySpawnAvoidM', 60, 600, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'stateMachine',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('stateMachine', 'preaimAngleDeg', 1, 30, '°'),
|
||||||
|
num('stateMachine', 'shortHaltMaxSec', 0.5, 12, 's'),
|
||||||
|
num('stateMachine', 'shortHaltCooldownSec', 0.5, 20, 's'),
|
||||||
|
num('stateMachine', 'turnLaunchSpeedMps', 0.5, 6, 'm/s'),
|
||||||
|
num('stateMachine', 'coverMinDistM', 2, 30, 'm'),
|
||||||
|
num('stateMachine', 'coverMaxDistM', 6, 80, 'm'),
|
||||||
|
num('stateMachine', 'coverRetreatBudgetSec', 1.5, 20, 's'),
|
||||||
|
num('stateMachine', 'reloadAdvanceAngleDeg', 0, 45, '°'),
|
||||||
|
num('stateMachine', 'hullAngleTriggerDeg', 15, 75, '°'),
|
||||||
|
num('stateMachine', 'hullAngleTargetDeg', 0, 35, '°'),
|
||||||
|
num('stateMachine', 'maxTotalHaltSec', 3, 40, 's'),
|
||||||
|
int('stateMachine', 'stalemateMissShots', 1, 8),
|
||||||
|
int('stateMachine', 'stalemateNoShotHalts', 1, 6),
|
||||||
|
num('stateMachine', 'repositionMinMoveM', 5, 80, 'm'),
|
||||||
|
num('stateMachine', 'repositionStepM', 15, 120, 'm'),
|
||||||
|
num('stateMachine', 'repairSafeEnemyDistM', 30, 400, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'perception',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('perception', 'foliageTransparency', 0.001, 1),
|
||||||
|
num('perception', 'nearSpotRangeM', 20, 250, 'm'),
|
||||||
|
num('perception', 'firingSpotRangeM', 150, 1500, 'm'),
|
||||||
|
num('perception', 'fastSpotSec', 0.05, 1.5, 's'),
|
||||||
|
num('perception', 'normalSpotSec', 0.1, 3, 's'),
|
||||||
|
num('perception', 'farSpotSec', 0.3, 6, 's'),
|
||||||
|
num('perception', 'decayPerSec', 0.2, 10),
|
||||||
|
num('perception', 'frontConeHalfDeg', 10, 90, '°'),
|
||||||
|
num('perception', 'peripheralCloseM', 30, 250, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'tactics',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('tactics', 'visionRangeM', 200, 3500, 'm'),
|
||||||
|
num('tactics', 'visionFovDeg', 40, 180, '°'),
|
||||||
|
num('tactics', 'peripheralRangeM', 30, 800, 'm'),
|
||||||
|
num('tactics', 'engineAudioRangeM', 10, 250, 'm'),
|
||||||
|
num('tactics', 'shotAudioRangeM', 50, 1200, 'm'),
|
||||||
|
num('tactics', 'radioShareRangeM', 50, 1500, 'm'),
|
||||||
|
num('tactics', 'memoryTtlSec', 1, 45, 's'),
|
||||||
|
num('tactics', 'targetStickinessSec', 0.5, 20, 's'),
|
||||||
|
num('tactics', 'peekCooldownSec', 1, 30, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'estimation',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('estimation', 'watchMinSec', 0.5, 10, 's'),
|
||||||
|
num('estimation', 'watchMaxSec', 1, 15, 's'),
|
||||||
|
num('estimation', 'velSampleMinSpanSec', 0.05, 2, 's'),
|
||||||
|
num('estimation', 'velStableSpanSec', 0.2, 6, 's'),
|
||||||
|
num('estimation', 'velJumpResetMps', 1, 20, 'm/s'),
|
||||||
|
num('estimation', 'baseAimSigmaM', 0, 2, 'm'),
|
||||||
|
num('estimation', 'leadErrorFrac', 0, 1),
|
||||||
|
num('estimation', 'maxBiasM', 0, 6, 'm'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'fireControl',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('fireControl', 'maxEngageRangeM', 150, 3000, 'm'),
|
||||||
|
num('fireControl', 'closeRangeM', 30, 250, 'm'),
|
||||||
|
num('fireControl', 'midRangeM', 100, 600, 'm'),
|
||||||
|
num('fireControl', 'longRangeM', 300, 1500, 'm'),
|
||||||
|
num('fireControl', 'midSlowSpeedRatio', 0.1, 1),
|
||||||
|
num('fireControl', 'midSlowMaxMps', 1, 15, 'm/s'),
|
||||||
|
num('fireControl', 'stopSpeedMaxMps', 0.1, 2, 'm/s'),
|
||||||
|
num('fireControl', 'longRangeWindowSec', 1, 15, 's'),
|
||||||
|
num('fireControl', 'baseAlignDeg', 0.1, 3, '°'),
|
||||||
|
num('fireControl', 'closeHitRadiusM', 0.25, 2.2, 'm'),
|
||||||
|
num('fireControl', 'barrelSettleDegSec', 0.2, 12, '°/s'),
|
||||||
|
num('fireControl', 'closeSettleHoldSec', 0.02, 0.5, 's'),
|
||||||
|
num('fireControl', 'settleHoldSec', 0.05, 1.5, 's'),
|
||||||
|
num('fireControl', 'unstabilizedStopSpeedMps', 0.1, 3, 'm/s'),
|
||||||
|
num('fireControl', 'stabilizedCreepSpeedMps', 1.5, 15, 'm/s'),
|
||||||
|
num('fireControl', 'friendlyCorridorM', 1, 10, 'm'),
|
||||||
|
num('fireControl', 'ballisticStepMaxM', 5, 80, 'm'),
|
||||||
|
num('fireControl', 'ballisticSweepRadiusM', 0.02, 0.5, 'm'),
|
||||||
|
int('fireControl', 'maxPreFireChecksPerTick', 1, 16),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'navigation',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
{ id: 'groundAi.navigation.driveMode', section: 'navigation', field: 'driveMode', kind: 'driveMode' },
|
||||||
|
int('navigation', 'maxPhysBots', 0, 64),
|
||||||
|
{ id: 'groundAi.navigation.steerSign', section: 'navigation', field: 'steerSign', kind: 'steerSign' },
|
||||||
|
num('navigation', 'deadEchoSec', 0.3, 10, 's'),
|
||||||
|
num('navigation', 'controlTimeoutSec', 0.3, 10, 's'),
|
||||||
|
num('navigation', 'cornerBrakeAccel', 0.5, 8),
|
||||||
|
num('navigation', 'pivotAngleDeg', 25, 150, '°'),
|
||||||
|
num('navigation', 'stuckWindowSec', 1, 15, 's'),
|
||||||
|
num('navigation', 'stuckMinMoveM', 0.5, 10, 'm'),
|
||||||
|
num('navigation', 'unstickReverseSec', 0.8, 10, 's'),
|
||||||
|
num('navigation', 'tacticalReverseDistM', 10, 90, 'm'),
|
||||||
|
num('navigation', 'tacticalReverseMaxSec', 2, 25, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'crowd',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('crowd', 'personalSpaceM', 6, 40, 'm'),
|
||||||
|
num('crowd', 'clusterRadiusM', 12, 80, 'm'),
|
||||||
|
int('crowd', 'clusterMaxAllies', 1, 10),
|
||||||
|
num('crowd', 'disperseStepM', 8, 65, 'm'),
|
||||||
|
num('crowd', 'disperseHoldSec', 1, 15, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'terrain',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
num('terrain', 'maxClimbSlopeDeg', 10, 42, '°'),
|
||||||
|
num('terrain', 'maxDropSlopeDeg', 8, 40, '°'),
|
||||||
|
num('terrain', 'maxWaterDepthM', 0.2, 2.5, 'm'),
|
||||||
|
num('terrain', 'collisionMarginM', 0.05, 2, 'm'),
|
||||||
|
num('terrain', 'crestLookaheadM', 8, 80, 'm'),
|
||||||
|
num('terrain', 'ridgeMaxDwellSec', 2, 60, 's'),
|
||||||
|
int('terrain', 'ridgeMaxShots', 1, 10),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'runtime',
|
||||||
|
defaultOpen: false,
|
||||||
|
customOnly: true,
|
||||||
|
fields: [
|
||||||
|
int('cadence', 'maxBots', 1, 64),
|
||||||
|
num('cadence', 'macroTickSec', 0.1, 5, 's'),
|
||||||
|
num('cadence', 'tacticsTickSec', 0.05, 2, 's'),
|
||||||
|
num('cadence', 'navTickSec', 0.05, 2, 's'),
|
||||||
|
{ id: 'groundAi.diagnostics.telemetry', section: 'diagnostics', field: 'telemetry', kind: 'bool' },
|
||||||
|
num('diagnostics', 'telemetryIntervalSec', 0.5, 60, 's'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ALL_BOT_FIELDS: readonly BotFieldSpec[] = BOT_TUNING_GROUPS.flatMap((group) => group.fields);
|
||||||
|
|
||||||
|
export function readBotFieldValue(values: TuningValues, spec: BotFieldSpec): string | number | boolean {
|
||||||
|
if (spec.kind === 'flatInt') return values[spec.id];
|
||||||
|
if (spec.kind === 'groundAiMode') return values.groundAi.mode;
|
||||||
|
const section = values.groundAi[spec.section] as Record<string, string | number | boolean>;
|
||||||
|
return section[spec.field]!;
|
||||||
|
}
|
||||||
@@ -1,17 +1,19 @@
|
|||||||
/**
|
/**
|
||||||
* The window's pages and the sections of those that have a section list in the side panel.
|
* The window's pages and the sections of those that have a section list in the side panel.
|
||||||
* Pages for later features (saves, tuning) join this list when they are built.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const;
|
export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const;
|
||||||
export type PageId = (typeof PAGES)[number];
|
export type PageId = (typeof PAGES)[number];
|
||||||
|
|
||||||
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
|
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
|
||||||
export type SaveSection = (typeof SAVE_SECTIONS)[number];
|
export type SaveSection = (typeof SAVE_SECTIONS)[number];
|
||||||
|
|
||||||
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
|
export const TUNING_SECTIONS = ['rewards', 'battle', 'bots', 'newProfile', 'research'] as const;
|
||||||
export type TuningSection = (typeof TUNING_SECTIONS)[number];
|
export type TuningSection = (typeof TUNING_SECTIONS)[number];
|
||||||
|
|
||||||
|
export const MODS_SECTIONS = ['list', 'presets'] as const;
|
||||||
|
export type ModsSection = (typeof MODS_SECTIONS)[number];
|
||||||
|
|
||||||
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
|
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
|
||||||
export type CopySection = (typeof COPY_SECTIONS)[number];
|
export type CopySection = (typeof COPY_SECTIONS)[number];
|
||||||
|
|
||||||
@@ -23,16 +25,25 @@ export interface Route {
|
|||||||
readonly copies: CopySection;
|
readonly copies: CopySection;
|
||||||
readonly saves: SaveSection;
|
readonly saves: SaveSection;
|
||||||
readonly tuning: TuningSection;
|
readonly tuning: TuningSection;
|
||||||
|
readonly mods: ModsSection;
|
||||||
readonly settings: SettingsSection;
|
readonly settings: SettingsSection;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' };
|
export const START_ROUTE: Route = {
|
||||||
|
page: 'home',
|
||||||
|
saves: 'list',
|
||||||
|
tuning: 'rewards',
|
||||||
|
mods: 'list',
|
||||||
|
copies: 'list',
|
||||||
|
settings: 'general',
|
||||||
|
};
|
||||||
|
|
||||||
/** Where a link points: a page, and for pages with sections, which one. */
|
/** Where a link points: a page, and for pages with sections, which one. */
|
||||||
export type Destination =
|
export type Destination =
|
||||||
| { readonly page: 'home' | 'about' }
|
| { readonly page: 'home' | 'about' }
|
||||||
| { readonly page: 'saves'; readonly section?: SaveSection }
|
| { readonly page: 'saves'; readonly section?: SaveSection }
|
||||||
| { readonly page: 'tuning'; readonly section?: TuningSection }
|
| { readonly page: 'tuning'; readonly section?: TuningSection }
|
||||||
|
| { readonly page: 'mods'; readonly section?: ModsSection }
|
||||||
| { readonly page: 'copies'; readonly section?: CopySection }
|
| { readonly page: 'copies'; readonly section?: CopySection }
|
||||||
| { readonly page: 'settings'; readonly section?: SettingsSection };
|
| { readonly page: 'settings'; readonly section?: SettingsSection };
|
||||||
|
|
||||||
@@ -42,6 +53,8 @@ export function navigate(route: Route, to: Destination): Route {
|
|||||||
return { ...route, page: 'saves', saves: to.section ?? route.saves };
|
return { ...route, page: 'saves', saves: to.section ?? route.saves };
|
||||||
case 'tuning':
|
case 'tuning':
|
||||||
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
|
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
|
||||||
|
case 'mods':
|
||||||
|
return { ...route, page: 'mods', mods: to.section ?? route.mods };
|
||||||
case 'copies':
|
case 'copies':
|
||||||
return { ...route, page: 'copies', copies: to.section ?? route.copies };
|
return { ...route, page: 'copies', copies: to.section ?? route.copies };
|
||||||
case 'settings':
|
case 'settings':
|
||||||
|
|||||||
@@ -252,6 +252,11 @@
|
|||||||
background: var(--red);
|
background: var(--red);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.button-compact {
|
||||||
|
font-size: 13px;
|
||||||
|
padding: 5px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
.link {
|
.link {
|
||||||
font: inherit;
|
font: inherit;
|
||||||
color: var(--white);
|
color: var(--white);
|
||||||
@@ -481,3 +486,245 @@
|
|||||||
left: 100%;
|
left: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== Modal dialog & Markdown content ===== */
|
||||||
|
.modal-backdrop {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 40;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 28px;
|
||||||
|
background: rgba(7, 10, 12, 0.72);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-dialog {
|
||||||
|
width: min(760px, 100%);
|
||||||
|
max-height: min(600px, 100%);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--sheet);
|
||||||
|
border: 1px solid var(--line-strong);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.65);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px 14px 12px 20px;
|
||||||
|
background: linear-gradient(180deg, #343a40, #2b3136);
|
||||||
|
border-bottom: 1px solid #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-title {
|
||||||
|
margin: 0;
|
||||||
|
font: 500 18px var(--font-display);
|
||||||
|
color: var(--white);
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-close {
|
||||||
|
flex: none;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: none;
|
||||||
|
color: var(--text-dim);
|
||||||
|
font-size: 20px;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-close:hover {
|
||||||
|
color: var(--white);
|
||||||
|
background: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-body {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: auto;
|
||||||
|
padding: 18px 22px 22px;
|
||||||
|
user-select: text;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-foot {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 20px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
background: rgba(0, 0, 0, 0.17);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body {
|
||||||
|
font-size: 13.5px;
|
||||||
|
line-height: 1.65;
|
||||||
|
color: var(--text);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body > :first-child {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body > :last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h1,
|
||||||
|
.markdown-body h2,
|
||||||
|
.markdown-body h3,
|
||||||
|
.markdown-body h4,
|
||||||
|
.markdown-body h5,
|
||||||
|
.markdown-body h6 {
|
||||||
|
margin: 18px 0 8px;
|
||||||
|
font-family: var(--font-display);
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--white);
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h1 {
|
||||||
|
font-size: 20px;
|
||||||
|
padding-bottom: 6px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h2 {
|
||||||
|
font-size: 17px;
|
||||||
|
padding-bottom: 5px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h3 {
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h4,
|
||||||
|
.markdown-body h5,
|
||||||
|
.markdown-body h6 {
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body p {
|
||||||
|
margin: 0 0 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body strong {
|
||||||
|
color: var(--white);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body ul,
|
||||||
|
.markdown-body ol {
|
||||||
|
margin: 6px 0 10px;
|
||||||
|
padding-left: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body li {
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body li > ul,
|
||||||
|
.markdown-body li > ol {
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body li > p {
|
||||||
|
margin: 0 0 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body li > p:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body code {
|
||||||
|
padding: 1px 5px;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: #e6eff2;
|
||||||
|
background: rgba(0, 0, 0, 0.34);
|
||||||
|
border: 1px solid var(--line-soft);
|
||||||
|
border-radius: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body pre {
|
||||||
|
margin: 10px 0;
|
||||||
|
padding: 10px 12px;
|
||||||
|
overflow: auto;
|
||||||
|
background: rgba(0, 0, 0, 0.38);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body pre code {
|
||||||
|
padding: 0;
|
||||||
|
background: none;
|
||||||
|
border: 0;
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body blockquote {
|
||||||
|
margin: 10px 0;
|
||||||
|
padding: 6px 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
background: rgba(255, 255, 255, 0.03);
|
||||||
|
border-left: 3px solid var(--line-strong);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body hr {
|
||||||
|
margin: 16px 0;
|
||||||
|
border: 0;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body a {
|
||||||
|
color: #7feaf2;
|
||||||
|
text-decoration: none;
|
||||||
|
border-bottom: 1px solid rgba(127, 234, 242, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body a:hover {
|
||||||
|
color: var(--white);
|
||||||
|
border-bottom-color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-table-wrap {
|
||||||
|
margin: 10px 0;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body th,
|
||||||
|
.markdown-body td {
|
||||||
|
padding: 6px 10px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body th {
|
||||||
|
color: var(--white);
|
||||||
|
background: rgba(255, 255, 255, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-task {
|
||||||
|
margin-right: 6px;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
@@ -344,9 +344,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* ===== About ===== */
|
/* ===== About ===== */
|
||||||
.update-notes {
|
.update-actions {
|
||||||
white-space: pre-line;
|
display: flex;
|
||||||
overflow-wrap: anywhere;
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-top: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.about-head {
|
.about-head {
|
||||||
@@ -435,3 +438,463 @@
|
|||||||
.about-card .notice .button {
|
.about-card .notice .button {
|
||||||
margin-top: 8px;
|
margin-top: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== Mods ===== */
|
||||||
|
.mods-aside {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-chip {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
padding: 2px 7px;
|
||||||
|
font-size: 11.5px;
|
||||||
|
line-height: 1.3;
|
||||||
|
color: rgba(255, 227, 163, 0.9);
|
||||||
|
background: rgba(214, 158, 46, 0.14);
|
||||||
|
border: 1px solid rgba(214, 158, 46, 0.38);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
cursor: help;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-chip:hover,
|
||||||
|
.mods-exp-chip:focus-visible {
|
||||||
|
background: rgba(214, 158, 46, 0.22);
|
||||||
|
border-color: rgba(214, 158, 46, 0.6);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-icon {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 700;
|
||||||
|
font-style: normal;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 1px solid rgba(255, 227, 163, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-popover {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 8px);
|
||||||
|
right: 0;
|
||||||
|
z-index: 40;
|
||||||
|
width: 340px;
|
||||||
|
max-width: min(340px, 70vw);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.5;
|
||||||
|
text-align: left;
|
||||||
|
white-space: normal;
|
||||||
|
color: rgba(255, 244, 218, 0.94);
|
||||||
|
background: rgba(16, 20, 24, 0.97);
|
||||||
|
border: 1px solid rgba(214, 158, 46, 0.5);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
|
||||||
|
opacity: 0;
|
||||||
|
visibility: hidden;
|
||||||
|
pointer-events: none;
|
||||||
|
transform: translateY(-2px);
|
||||||
|
transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-exp-chip:hover .mods-exp-popover,
|
||||||
|
.mods-exp-chip:focus-visible .mods-exp-popover {
|
||||||
|
opacity: 1;
|
||||||
|
visibility: visible;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-banner {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.5;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-banner-warn {
|
||||||
|
background: rgba(206, 65, 55, 0.16);
|
||||||
|
border-color: rgba(206, 65, 55, 0.5);
|
||||||
|
color: #ffd7d4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-banner-ok {
|
||||||
|
background: rgba(68, 170, 102, 0.16);
|
||||||
|
border-color: rgba(68, 170, 102, 0.5);
|
||||||
|
color: #d7ffe4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-search {
|
||||||
|
flex: 1 1 180px;
|
||||||
|
min-width: 140px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-select {
|
||||||
|
max-width: 210px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-box {
|
||||||
|
padding: 10px 12px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-error {
|
||||||
|
background: rgba(206, 65, 55, 0.15);
|
||||||
|
border-color: rgba(206, 65, 55, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-warn {
|
||||||
|
background: rgba(214, 158, 46, 0.13);
|
||||||
|
border-color: rgba(214, 158, 46, 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-title {
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issues-box ul {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 18px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-issue-tag {
|
||||||
|
display: inline-block;
|
||||||
|
margin-right: 6px;
|
||||||
|
padding: 1px 5px;
|
||||||
|
font-size: 11px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: rgba(255, 255, 255, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-empty {
|
||||||
|
padding: 20px 14px;
|
||||||
|
text-align: center;
|
||||||
|
border: 1px dashed var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-hint {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
line-height: 1.5;
|
||||||
|
margin: 6px 0 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: rgba(12, 16, 19, 0.62);
|
||||||
|
transition: border-color 120ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-enabled {
|
||||||
|
border-left: 3px solid var(--red);
|
||||||
|
background: rgba(18, 24, 29, 0.78);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-order-num {
|
||||||
|
min-width: 26px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
text-align: right;
|
||||||
|
cursor: grab;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-checkbox {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
flex: none;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-main {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-title {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-name {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-version,
|
||||||
|
.mods-author {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-desc {
|
||||||
|
margin-top: 3px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badges {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge {
|
||||||
|
padding: 1px 6px;
|
||||||
|
font-size: 11px;
|
||||||
|
border-radius: 2px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.16);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-data {
|
||||||
|
background: rgba(88, 166, 255, 0.16);
|
||||||
|
color: #b7d7ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-gui {
|
||||||
|
background: rgba(163, 113, 247, 0.18);
|
||||||
|
color: #dec8ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-script {
|
||||||
|
background: rgba(214, 158, 46, 0.22);
|
||||||
|
color: #ffe3a3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-exe {
|
||||||
|
background: rgba(206, 65, 55, 0.28);
|
||||||
|
color: #ffc2be;
|
||||||
|
border-color: rgba(206, 65, 55, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-error {
|
||||||
|
background: rgba(206, 65, 55, 0.35);
|
||||||
|
color: #ffd5d2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-badge-warn {
|
||||||
|
background: rgba(214, 158, 46, 0.25);
|
||||||
|
color: #ffe8b3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-move-btn {
|
||||||
|
min-width: 28px;
|
||||||
|
padding: 4px 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-card-details {
|
||||||
|
padding: 10px 12px 12px 48px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-detail-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||||
|
gap: 4px 12px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-detail-summary {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-detail-summary span {
|
||||||
|
padding: 2px 7px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: rgba(255, 255, 255, 0.08);
|
||||||
|
color: rgba(255, 255, 255, 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-section {
|
||||||
|
margin-bottom: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-subheading {
|
||||||
|
margin: 0 0 4px;
|
||||||
|
font: 600 15px var(--font-display);
|
||||||
|
color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-form {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin: 10px 0 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-form .input {
|
||||||
|
flex: 1 1 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-item {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: rgba(12, 16, 19, 0.62);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-active {
|
||||||
|
border-left: 3px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-meta {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-name {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-preset-sub {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mods-path {
|
||||||
|
font-size: 12px;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== Tuning: Bot parameters ===== */
|
||||||
|
.tuning-toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
margin: 8px 0 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-toolbar .small {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-group {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: rgba(12, 16, 19, 0.56);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-group-summary {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
font: 600 14px var(--font-display);
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
color: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-group-summary::-webkit-details-marker {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-group-summary::before {
|
||||||
|
content: '▸';
|
||||||
|
display: inline-block;
|
||||||
|
margin-right: 8px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
transition: transform 120ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-group[open] > .tuning-group-summary::before {
|
||||||
|
transform: rotate(90deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-group-summary small {
|
||||||
|
font: 400 12px var(--font-ui);
|
||||||
|
letter-spacing: 0;
|
||||||
|
color: var(--text-dim);
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-group-body {
|
||||||
|
padding: 0 14px 8px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tuning-actions {
|
||||||
|
margin-top: 14px;
|
||||||
|
}
|
||||||
@@ -24,6 +24,11 @@ export const APP_ERROR_CODES = [
|
|||||||
'diagnostics_export_failed',
|
'diagnostics_export_failed',
|
||||||
'copy_not_found',
|
'copy_not_found',
|
||||||
'tuning_invalid',
|
'tuning_invalid',
|
||||||
|
'mods_read_only',
|
||||||
|
'mods_write_failed',
|
||||||
|
'mods_preset_invalid',
|
||||||
|
'mods_blocking_issues',
|
||||||
|
'mods_folder_invalid',
|
||||||
'save_not_found',
|
'save_not_found',
|
||||||
'save_archive_invalid',
|
'save_archive_invalid',
|
||||||
'save_official_invalid',
|
'save_official_invalid',
|
||||||
@@ -40,6 +45,8 @@ export const APP_ERROR_CODES = [
|
|||||||
'maintenance_busy',
|
'maintenance_busy',
|
||||||
'maintenance_location',
|
'maintenance_location',
|
||||||
'maintenance_no_update',
|
'maintenance_no_update',
|
||||||
|
'maintenance_source_invalid',
|
||||||
|
'maintenance_source_overlap',
|
||||||
'maintenance_cancelled',
|
'maintenance_cancelled',
|
||||||
'maintenance_failed',
|
'maintenance_failed',
|
||||||
'maintenance_source_changed',
|
'maintenance_source_changed',
|
||||||
@@ -69,6 +76,8 @@ export const APP_ERROR_CODES = [
|
|||||||
'launch_game_failed',
|
'launch_game_failed',
|
||||||
/** Core files built for the launch (aces.exe, wto_ws.dll, wto_ws.cfg) are missing or unreadable. */
|
/** Core files built for the launch (aces.exe, wto_ws.dll, wto_ws.cfg) are missing or unreadable. */
|
||||||
'launch_game_files_missing',
|
'launch_game_files_missing',
|
||||||
|
/** Optional UHQ texture packs have a mounted header without completed files (params: packs). */
|
||||||
|
'launch_incomplete_uhq_packs',
|
||||||
/** A folder the player chose does not exist or cannot be read (params: path). */
|
/** A folder the player chose does not exist or cannot be read (params: path). */
|
||||||
'folder_unreadable',
|
'folder_unreadable',
|
||||||
/** The chosen folder lacks the files of a War Thunder installation (params: path). */
|
/** The chosen folder lacks the files of a War Thunder installation (params: path). */
|
||||||
@@ -89,6 +98,8 @@ export const APP_ERROR_CODES = [
|
|||||||
'missing_features_not_accepted',
|
'missing_features_not_accepted',
|
||||||
/** Working out which patches fit failed; the details are in the log. */
|
/** Working out which patches fit failed; the details are in the log. */
|
||||||
'patch_check_failed',
|
'patch_check_failed',
|
||||||
|
/** The packaged launcher itself sits inside the selected stock War Thunder folder. */
|
||||||
|
'launcher_inside_source',
|
||||||
/** Copying the game failed; what was copied has been removed. */
|
/** Copying the game failed; what was copied has been removed. */
|
||||||
'copy_failed',
|
'copy_failed',
|
||||||
'hardlink_unavailable',
|
'hardlink_unavailable',
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ export const IPC_CHANNEL_PREFIXES = [
|
|||||||
'copies:',
|
'copies:',
|
||||||
/** Settings shared by the saves of a game copy. */
|
/** Settings shared by the saves of a game copy. */
|
||||||
'tuning:',
|
'tuning:',
|
||||||
|
/** Additive mods repository, per-copy ordering/toggles, and presets. */
|
||||||
|
'mods:',
|
||||||
/** Local account and save management. */
|
/** Local account and save management. */
|
||||||
'saves:',
|
'saves:',
|
||||||
/** Starting and stopping the active copy. */
|
/** Starting and stopping the active copy. */
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
} from '../schemas/install.ts';
|
} from '../schemas/install.ts';
|
||||||
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
|
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
|
||||||
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
|
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
|
||||||
|
import { ModsStateViewSchema } from '../schemas/mods.ts';
|
||||||
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
|
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
|
||||||
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||||
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
|
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
|
||||||
@@ -262,6 +263,50 @@ export const ipcContract = {
|
|||||||
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
|
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
|
||||||
output: TuningViewSchema,
|
output: TuningViewSchema,
|
||||||
},
|
},
|
||||||
|
'mods:getState': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:setEnabled': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, modId: z.string().min(1), enabled: z.boolean() }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:setOrder': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, order: z.array(z.string()) }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:autoSort': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:savePreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, name: z.string().trim().min(1).max(80), overwriteId: z.string().min(1).optional() }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:applyPreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:deletePreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
|
'mods:exportPreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||||
|
output: z.object({ path: z.string().nullable() }),
|
||||||
|
},
|
||||||
|
'mods:importPreset': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema }),
|
||||||
|
output: z.object({ imported: z.boolean(), state: ModsStateViewSchema }),
|
||||||
|
},
|
||||||
|
'mods:openFolder': {
|
||||||
|
input: z.void(),
|
||||||
|
output: z.void(),
|
||||||
|
},
|
||||||
|
'mods:setFolder': {
|
||||||
|
input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }),
|
||||||
|
output: ModsStateViewSchema,
|
||||||
|
},
|
||||||
'launch:getState': {
|
'launch:getState': {
|
||||||
input: z.void(),
|
input: z.void(),
|
||||||
output: LaunchStateSchema,
|
output: LaunchStateSchema,
|
||||||
|
|||||||
@@ -150,7 +150,7 @@ export type InstallProgress = z.output<typeof InstallProgressSchema>;
|
|||||||
export const InstallRecordSchema = z.object({
|
export const InstallRecordSchema = z.object({
|
||||||
id: CopyIdSchema,
|
id: CopyIdSchema,
|
||||||
name: CopyNameSchema,
|
name: CopyNameSchema,
|
||||||
/** Recorded only for a separate source copied during installation. */
|
/** Separate online installation used as the read-only update source. */
|
||||||
sourcePath: z.string().min(1).nullable(),
|
sourcePath: z.string().min(1).nullable(),
|
||||||
method: z.enum(INSTALL_METHODS),
|
method: z.enum(INSTALL_METHODS),
|
||||||
copyPath: z.string(),
|
copyPath: z.string(),
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export const LaunchStateSchema = z.object({
|
|||||||
actualVersion: z.string().nullable().optional(),
|
actualVersion: z.string().nullable().optional(),
|
||||||
gameExit: GameExitSchema.optional(),
|
gameExit: GameExitSchema.optional(),
|
||||||
error: z.enum(APP_ERROR_CODES).optional(),
|
error: z.enum(APP_ERROR_CODES).optional(),
|
||||||
|
errorParams: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type LaunchState = z.output<typeof LaunchStateSchema>;
|
export type LaunchState = z.output<typeof LaunchStateSchema>;
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { CopyIdSchema } from './install.ts';
|
import { CopyIdSchema } from './install.ts';
|
||||||
|
|
||||||
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam']);
|
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam', 'set-source']);
|
||||||
export const MaintenanceRequestSchema = z.object({
|
export const MaintenanceRequestSchema = z.object({
|
||||||
id: CopyIdSchema,
|
id: CopyIdSchema,
|
||||||
operation: MaintenanceOperationSchema,
|
operation: MaintenanceOperationSchema,
|
||||||
deleteData: z.boolean().default(false),
|
deleteData: z.boolean().default(false),
|
||||||
|
sourcePath: z.string().min(1).optional(),
|
||||||
steamLocations: z.object({
|
steamLocations: z.object({
|
||||||
copyPath: z.string().min(1),
|
copyPath: z.string().min(1),
|
||||||
dataPath: z.string().min(1),
|
dataPath: z.string().min(1),
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const ModRiskBadgeSchema = z.enum(['data', 'gui', 'script', 'exe']);
|
||||||
|
export const ModIssueSeveritySchema = z.enum(['error', 'warning', 'info']);
|
||||||
|
export const LocalizedTextSchema = z.union([z.string(), z.record(z.string(), z.string())]);
|
||||||
|
|
||||||
|
export const ModPackOperationSchema = z.object({
|
||||||
|
pack: z.string(),
|
||||||
|
targetPath: z.string(),
|
||||||
|
action: z.enum(['blk-patch', 'csv-patch', 'file']),
|
||||||
|
sourceRelativePath: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModListItemSchema = z.object({
|
||||||
|
id: z.string(),
|
||||||
|
folderName: z.string(),
|
||||||
|
rootDir: z.string(),
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
description: LocalizedTextSchema.optional(),
|
||||||
|
version: z.string(),
|
||||||
|
author: z.string(),
|
||||||
|
apiVersion: z.string(),
|
||||||
|
gameVersions: z.array(z.string()),
|
||||||
|
requires: z.array(z.string()),
|
||||||
|
conflicts: z.array(z.string()),
|
||||||
|
loadAfter: z.array(z.string()),
|
||||||
|
loadBefore: z.array(z.string()),
|
||||||
|
badges: z.array(ModRiskBadgeSchema),
|
||||||
|
hasServerScript: z.boolean(),
|
||||||
|
serverTuningFiles: z.array(z.string()),
|
||||||
|
packOperations: z.array(ModPackOperationSchema),
|
||||||
|
guiPatchCount: z.number().int().nonnegative(),
|
||||||
|
exePatchCount: z.number().int().nonnegative(),
|
||||||
|
hasClientAddon: z.boolean(),
|
||||||
|
addonFileCount: z.number().int().nonnegative(),
|
||||||
|
clientFileCount: z.number().int().nonnegative(),
|
||||||
|
hasConfigBlkPatch: z.boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModDiscoveryErrorSchema = z.object({
|
||||||
|
folderName: z.string(),
|
||||||
|
rootDir: z.string(),
|
||||||
|
reason: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModIssueSchema = z.object({
|
||||||
|
severity: ModIssueSeveritySchema,
|
||||||
|
kind: z.string(),
|
||||||
|
modId: z.string(),
|
||||||
|
otherModId: z.string().optional(),
|
||||||
|
detail: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModPresetSchema = z.object({
|
||||||
|
id: z.string().min(1),
|
||||||
|
name: z.string().min(1).max(80),
|
||||||
|
order: z.array(z.string()),
|
||||||
|
enabled: z.record(z.string(), z.boolean()),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModsStateViewSchema = z.object({
|
||||||
|
modsDir: z.string(),
|
||||||
|
defaultModsDir: z.string(),
|
||||||
|
isCustomModsDir: z.boolean(),
|
||||||
|
apiVersion: z.string(),
|
||||||
|
mods: z.array(ModListItemSchema),
|
||||||
|
discoveryErrors: z.array(ModDiscoveryErrorSchema),
|
||||||
|
order: z.array(z.string()),
|
||||||
|
enabled: z.record(z.string(), z.boolean()),
|
||||||
|
activePresetId: z.string().nullable(),
|
||||||
|
presets: z.array(ModPresetSchema),
|
||||||
|
issues: z.array(ModIssueSchema),
|
||||||
|
hasBlockingErrors: z.boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ModPresetTransferSchema = z.object({
|
||||||
|
format: z.literal(1),
|
||||||
|
name: z.string().min(1).max(80),
|
||||||
|
order: z.array(z.string()),
|
||||||
|
enabled: z.record(z.string(), z.boolean()),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ModListItem = z.output<typeof ModListItemSchema>;
|
||||||
|
export type ModPresetView = z.output<typeof ModPresetSchema>;
|
||||||
|
export type ModIssueView = z.output<typeof ModIssueSchema>;
|
||||||
|
export type ModsStateView = z.output<typeof ModsStateViewSchema>;
|
||||||
@@ -94,7 +94,7 @@ export const OfficialPreviewSchema = z.object({
|
|||||||
omitted: z.array(z.string()),
|
omitted: z.array(z.string()),
|
||||||
});
|
});
|
||||||
export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) });
|
export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) });
|
||||||
export const ResearchOperationSchema = z.enum(['research', 'purchase', 'equipment']);
|
export const ResearchOperationSchema = z.enum(['purchase', 'equipment']);
|
||||||
export const SaveResearchSchema = z.object({
|
export const SaveResearchSchema = z.object({
|
||||||
branches: z.array(ResearchBranchSchema),
|
branches: z.array(ResearchBranchSchema),
|
||||||
selected: ResearchBranchSchema.nullable(),
|
selected: ResearchBranchSchema.nullable(),
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ export const SettingsSchema = z.object({
|
|||||||
developerMode: z.boolean().default(true),
|
developerMode: z.boolean().default(true),
|
||||||
labStockPath: LabPathSchema.default(null),
|
labStockPath: LabPathSchema.default(null),
|
||||||
labDataPath: LabPathSchema.default(null),
|
labDataPath: LabPathSchema.default(null),
|
||||||
|
/** Custom global mods repository directory; null uses `<userData>/mods`. */
|
||||||
|
modsFolder: LabPathSchema.default(null),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type Settings = z.output<typeof SettingsSchema>;
|
export type Settings = z.output<typeof SettingsSchema>;
|
||||||
@@ -60,6 +62,7 @@ export const SettingsPatchSchema = z.object({
|
|||||||
developerMode: z.boolean().optional(),
|
developerMode: z.boolean().optional(),
|
||||||
labStockPath: LabPathSchema.optional(),
|
labStockPath: LabPathSchema.optional(),
|
||||||
labDataPath: LabPathSchema.optional(),
|
labDataPath: LabPathSchema.optional(),
|
||||||
|
modsFolder: LabPathSchema.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type SettingsPatch = z.output<typeof SettingsPatchSchema>;
|
export type SettingsPatch = z.output<typeof SettingsPatchSchema>;
|
||||||
|
|||||||
@@ -1,6 +1,221 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
export const AUTO_TARGET_PICKS = ['lowestRank', 'highestRank', 'treeOrder'] as const;
|
export const AUTO_TARGET_PICKS = ['lowestRank', 'highestRank', 'treeOrder'] as const;
|
||||||
|
export const GROUND_AI_MODES = ['stock', 'fire', 'drive', 'full'] as const;
|
||||||
|
export const GROUND_AI_DRIVE_MODES = ['vehicle_phys', 'movesys'] as const;
|
||||||
|
|
||||||
|
const GroundAiLoadoutSchema = z.object({
|
||||||
|
lowReadyRackThreshold: z.number().int().min(1).max(60),
|
||||||
|
topUpAmmoCount: z.number().int().min(4).max(80),
|
||||||
|
primaryAmmoPct: z.number().int().min(50).max(100),
|
||||||
|
secondaryMinRounds: z.number().int().min(0).max(20),
|
||||||
|
penetrationCompareDistM: z.number().int().min(100).max(2000),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiLineupWeightsSchema = z.object({
|
||||||
|
spaa: z.number().min(0.01).max(10),
|
||||||
|
lightTank: z.number().min(0.01).max(10),
|
||||||
|
tankDestroyer: z.number().min(0.01).max(10),
|
||||||
|
heavyTank: z.number().min(0.01).max(10),
|
||||||
|
mediumTank: z.number().min(0.01).max(10),
|
||||||
|
other: z.number().min(0.01).max(10),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiCadenceSchema = z.object({
|
||||||
|
maxBots: z.number().int().min(1).max(64),
|
||||||
|
macroTickSec: z.number().min(0.1).max(5),
|
||||||
|
tacticsTickSec: z.number().min(0.05).max(2),
|
||||||
|
navTickSec: z.number().min(0.05).max(2),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiCommanderSchema = z.object({
|
||||||
|
rebalanceSec: z.number().min(1).max(30),
|
||||||
|
roleHoldSec: z.number().min(0).max(120),
|
||||||
|
bttlAssaultPct: z.number().int().min(0).max(100),
|
||||||
|
bttlFlankPct: z.number().int().min(0).max(100),
|
||||||
|
bttlOverwatchPct: z.number().int().min(0).max(100),
|
||||||
|
conqAssaultPct: z.number().int().min(0).max(100),
|
||||||
|
conqFlankPct: z.number().int().min(0).max(100),
|
||||||
|
conqHoldDefendPct: z.number().int().min(0).max(100),
|
||||||
|
conqHoldOverwatchPct: z.number().int().min(0).max(100),
|
||||||
|
domAssaultPct: z.number().int().min(0).max(100),
|
||||||
|
domMaxDefendersPerCap: z.number().int().min(0).max(4),
|
||||||
|
overwatchStandOffM: z.number().min(25).max(350),
|
||||||
|
flankStandOffM: z.number().min(25).max(300),
|
||||||
|
spaaFollowOffsetM: z.number().min(40).max(500),
|
||||||
|
flankMaxLengthRatio: z.number().min(1.05).max(3),
|
||||||
|
flankMinSeparationM: z.number().min(15).max(200),
|
||||||
|
rallyProgressFrac: z.number().min(0.1).max(0.75),
|
||||||
|
rallyWaitSec: z.number().min(3).max(60),
|
||||||
|
rallyMinFrac: z.number().min(0.25).max(1),
|
||||||
|
rallyRadiusM: z.number().min(15).max(140),
|
||||||
|
recallSafeHoldSec: z.number().min(3).max(60),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiMacroSchema = z.object({
|
||||||
|
openingSplitSec: z.number().min(0).max(180),
|
||||||
|
capMaxInsiders: z.number().int().min(1).max(8),
|
||||||
|
recaptureMinBots: z.number().int().min(1).max(8),
|
||||||
|
recaptureMaxBots: z.number().int().min(1).max(12),
|
||||||
|
capStickyBonusM: z.number().min(0).max(800),
|
||||||
|
deathZoneRadiusM: z.number().min(10).max(250),
|
||||||
|
deathZoneTtlSec: z.number().min(5).max(300),
|
||||||
|
deathZoneMinKills: z.number().int().min(1).max(16),
|
||||||
|
spaaRearOffsetM: z.number().min(40).max(600),
|
||||||
|
spaaRelocateSec: z.number().min(5).max(180),
|
||||||
|
enemySpawnAvoidM: z.number().min(60).max(600),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiCrowdSchema = z.object({
|
||||||
|
personalSpaceM: z.number().min(6).max(40),
|
||||||
|
clusterRadiusM: z.number().min(12).max(80),
|
||||||
|
clusterMaxAllies: z.number().int().min(1).max(10),
|
||||||
|
disperseStepM: z.number().min(8).max(65),
|
||||||
|
disperseHoldSec: z.number().min(1).max(15),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiTerrainSchema = z.object({
|
||||||
|
maxClimbSlopeDeg: z.number().min(10).max(42),
|
||||||
|
maxDropSlopeDeg: z.number().min(8).max(40),
|
||||||
|
maxWaterDepthM: z.number().min(0.2).max(2.5),
|
||||||
|
collisionMarginM: z.number().min(0.05).max(2),
|
||||||
|
crestLookaheadM: z.number().min(8).max(80),
|
||||||
|
ridgeMaxDwellSec: z.number().min(2).max(60),
|
||||||
|
ridgeMaxShots: z.number().int().min(1).max(10),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiNavigationSchema = z.object({
|
||||||
|
driveMode: z.enum(GROUND_AI_DRIVE_MODES),
|
||||||
|
maxPhysBots: z.number().int().min(0).max(64),
|
||||||
|
steerSign: z.union([z.literal(1), z.literal(-1)]),
|
||||||
|
deadEchoSec: z.number().min(0.3).max(10),
|
||||||
|
controlTimeoutSec: z.number().min(0.3).max(10),
|
||||||
|
cornerBrakeAccel: z.number().min(0.5).max(8),
|
||||||
|
pivotAngleDeg: z.number().min(25).max(150),
|
||||||
|
stuckWindowSec: z.number().min(1).max(15),
|
||||||
|
stuckMinMoveM: z.number().min(0.5).max(10),
|
||||||
|
unstickReverseSec: z.number().min(0.8).max(10),
|
||||||
|
tacticalReverseDistM: z.number().min(10).max(90),
|
||||||
|
tacticalReverseMaxSec: z.number().min(2).max(25),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiPerceptionSchema = z.object({
|
||||||
|
foliageTransparency: z.number().min(0.001).max(1),
|
||||||
|
nearSpotRangeM: z.number().min(20).max(250),
|
||||||
|
firingSpotRangeM: z.number().min(150).max(1500),
|
||||||
|
fastSpotSec: z.number().min(0.05).max(1.5),
|
||||||
|
normalSpotSec: z.number().min(0.1).max(3),
|
||||||
|
farSpotSec: z.number().min(0.3).max(6),
|
||||||
|
decayPerSec: z.number().min(0.2).max(10),
|
||||||
|
frontConeHalfDeg: z.number().min(10).max(90),
|
||||||
|
peripheralCloseM: z.number().min(30).max(250),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiStateMachineSchema = z.object({
|
||||||
|
preaimAngleDeg: z.number().min(1).max(30),
|
||||||
|
shortHaltMaxSec: z.number().min(0.5).max(12),
|
||||||
|
shortHaltCooldownSec: z.number().min(0.5).max(20),
|
||||||
|
turnLaunchSpeedMps: z.number().min(0.5).max(6),
|
||||||
|
coverMinDistM: z.number().min(2).max(30),
|
||||||
|
coverMaxDistM: z.number().min(6).max(80),
|
||||||
|
coverRetreatBudgetSec: z.number().min(1.5).max(20),
|
||||||
|
reloadAdvanceAngleDeg: z.number().min(0).max(45),
|
||||||
|
hullAngleTriggerDeg: z.number().min(15).max(75),
|
||||||
|
hullAngleTargetDeg: z.number().min(0).max(35),
|
||||||
|
maxTotalHaltSec: z.number().min(3).max(40),
|
||||||
|
stalemateMissShots: z.number().int().min(1).max(8),
|
||||||
|
stalemateNoShotHalts: z.number().int().min(1).max(6),
|
||||||
|
repositionMinMoveM: z.number().min(5).max(80),
|
||||||
|
repositionStepM: z.number().min(15).max(120),
|
||||||
|
repairSafeEnemyDistM: z.number().min(30).max(400),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiTacticsSchema = z.object({
|
||||||
|
visionRangeM: z.number().min(200).max(3500),
|
||||||
|
visionFovDeg: z.number().min(40).max(180),
|
||||||
|
peripheralRangeM: z.number().min(30).max(800),
|
||||||
|
engineAudioRangeM: z.number().min(10).max(250),
|
||||||
|
shotAudioRangeM: z.number().min(50).max(1200),
|
||||||
|
radioShareRangeM: z.number().min(50).max(1500),
|
||||||
|
memoryTtlSec: z.number().min(1).max(45),
|
||||||
|
targetStickinessSec: z.number().min(0.5).max(20),
|
||||||
|
peekCooldownSec: z.number().min(1).max(30),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiEstimationSchema = z.object({
|
||||||
|
watchMinSec: z.number().min(0.5).max(10),
|
||||||
|
watchMaxSec: z.number().min(1).max(15),
|
||||||
|
velSampleMinSpanSec: z.number().min(0.05).max(2),
|
||||||
|
velStableSpanSec: z.number().min(0.2).max(6),
|
||||||
|
velJumpResetMps: z.number().min(1).max(20),
|
||||||
|
baseAimSigmaM: z.number().min(0).max(2),
|
||||||
|
leadErrorFrac: z.number().min(0).max(1),
|
||||||
|
maxBiasM: z.number().min(0).max(6),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiFireControlSchema = z.object({
|
||||||
|
maxEngageRangeM: z.number().min(150).max(3000),
|
||||||
|
closeRangeM: z.number().min(30).max(250),
|
||||||
|
midRangeM: z.number().min(100).max(600),
|
||||||
|
longRangeM: z.number().min(300).max(1500),
|
||||||
|
midSlowSpeedRatio: z.number().min(0.1).max(1),
|
||||||
|
midSlowMaxMps: z.number().min(1).max(15),
|
||||||
|
stopSpeedMaxMps: z.number().min(0.1).max(2),
|
||||||
|
longRangeWindowSec: z.number().min(1).max(15),
|
||||||
|
baseAlignDeg: z.number().min(0.1).max(3),
|
||||||
|
closeHitRadiusM: z.number().min(0.25).max(2.2),
|
||||||
|
barrelSettleDegSec: z.number().min(0.2).max(12),
|
||||||
|
closeSettleHoldSec: z.number().min(0.02).max(0.5),
|
||||||
|
settleHoldSec: z.number().min(0.05).max(1.5),
|
||||||
|
unstabilizedStopSpeedMps: z.number().min(0.1).max(3),
|
||||||
|
stabilizedCreepSpeedMps: z.number().min(1.5).max(15),
|
||||||
|
friendlyCorridorM: z.number().min(1).max(10),
|
||||||
|
ballisticStepMaxM: z.number().min(5).max(80),
|
||||||
|
ballisticSweepRadiusM: z.number().min(0.02).max(0.5),
|
||||||
|
maxPreFireChecksPerTick: z.number().int().min(1).max(16),
|
||||||
|
});
|
||||||
|
|
||||||
|
const GroundAiDiagnosticsSchema = z.object({
|
||||||
|
telemetry: z.boolean(),
|
||||||
|
telemetryIntervalSec: z.number().min(0.5).max(60),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const GroundAiTuningSchema = z.object({
|
||||||
|
mode: z.enum(GROUND_AI_MODES),
|
||||||
|
loadout: GroundAiLoadoutSchema,
|
||||||
|
lineupWeights: GroundAiLineupWeightsSchema,
|
||||||
|
cadence: GroundAiCadenceSchema,
|
||||||
|
commander: GroundAiCommanderSchema,
|
||||||
|
macro: GroundAiMacroSchema,
|
||||||
|
crowd: GroundAiCrowdSchema,
|
||||||
|
terrain: GroundAiTerrainSchema,
|
||||||
|
navigation: GroundAiNavigationSchema,
|
||||||
|
perception: GroundAiPerceptionSchema,
|
||||||
|
stateMachine: GroundAiStateMachineSchema,
|
||||||
|
tactics: GroundAiTacticsSchema,
|
||||||
|
estimation: GroundAiEstimationSchema,
|
||||||
|
fireControl: GroundAiFireControlSchema,
|
||||||
|
diagnostics: GroundAiDiagnosticsSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const GroundAiTuningPatchSchema = z.object({
|
||||||
|
mode: z.enum(GROUND_AI_MODES).optional(),
|
||||||
|
loadout: GroundAiLoadoutSchema.partial().optional(),
|
||||||
|
lineupWeights: GroundAiLineupWeightsSchema.partial().optional(),
|
||||||
|
cadence: GroundAiCadenceSchema.partial().optional(),
|
||||||
|
commander: GroundAiCommanderSchema.partial().optional(),
|
||||||
|
macro: GroundAiMacroSchema.partial().optional(),
|
||||||
|
crowd: GroundAiCrowdSchema.partial().optional(),
|
||||||
|
terrain: GroundAiTerrainSchema.partial().optional(),
|
||||||
|
navigation: GroundAiNavigationSchema.partial().optional(),
|
||||||
|
perception: GroundAiPerceptionSchema.partial().optional(),
|
||||||
|
stateMachine: GroundAiStateMachineSchema.partial().optional(),
|
||||||
|
tactics: GroundAiTacticsSchema.partial().optional(),
|
||||||
|
estimation: GroundAiEstimationSchema.partial().optional(),
|
||||||
|
fireControl: GroundAiFireControlSchema.partial().optional(),
|
||||||
|
diagnostics: GroundAiDiagnosticsSchema.partial().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
export const TuningValuesSchema = z.object({
|
export const TuningValuesSchema = z.object({
|
||||||
rewardMultiplierSilverLions: z.number().min(0).max(100),
|
rewardMultiplierSilverLions: z.number().min(0).max(100),
|
||||||
rewardMultiplierResearchPoints: z.number().min(0).max(100),
|
rewardMultiplierResearchPoints: z.number().min(0).max(100),
|
||||||
@@ -9,16 +224,23 @@ export const TuningValuesSchema = z.object({
|
|||||||
smallTeamsMaxPlayers: z.number().int().min(2).max(64),
|
smallTeamsMaxPlayers: z.number().int().min(2).max(64),
|
||||||
brSpreadMrank: z.number().int().min(0).max(12),
|
brSpreadMrank: z.number().int().min(0).max(12),
|
||||||
subModeChance: z.number().min(0).max(1),
|
subModeChance: z.number().min(0).max(1),
|
||||||
|
botPoolLimitPerType: z.number().int().min(4).max(200),
|
||||||
tankBotRespawns: z.number().int().min(1).max(10),
|
tankBotRespawns: z.number().int().min(1).max(10),
|
||||||
airBotRespawns: z.number().int().min(1).max(10),
|
airBotRespawns: z.number().int().min(1).max(10),
|
||||||
strikeUcavSpawnScore: z.number().int().min(1).max(10000),
|
strikeUcavSpawnScore: z.number().int().min(1).max(10000),
|
||||||
|
nuclearEscalationStrategicBombers: z.boolean(),
|
||||||
silverLions: z.number().int().nonnegative(),
|
silverLions: z.number().int().nonnegative(),
|
||||||
goldenEagles: z.number().int().min(0).max(0x7fffffff),
|
goldenEagles: z.number().int().min(0).max(0x7fffffff),
|
||||||
preferLineSuccessor: z.boolean(),
|
preferLineSuccessor: z.boolean(),
|
||||||
autoTargetPick: z.enum(AUTO_TARGET_PICKS),
|
autoTargetPick: z.enum(AUTO_TARGET_PICKS),
|
||||||
|
groundAi: GroundAiTuningSchema,
|
||||||
|
});
|
||||||
|
export const TuningPatchSchema = TuningValuesSchema.omit({ groundAi: true }).partial().extend({
|
||||||
|
groundAi: GroundAiTuningPatchSchema.optional(),
|
||||||
});
|
});
|
||||||
export const TuningPatchSchema = TuningValuesSchema.partial();
|
|
||||||
export const TuningViewSchema = z.object({ defaults: TuningValuesSchema, effective: TuningValuesSchema });
|
export const TuningViewSchema = z.object({ defaults: TuningValuesSchema, effective: TuningValuesSchema });
|
||||||
|
export type GroundAiTuningValues = z.output<typeof GroundAiTuningSchema>;
|
||||||
|
export type GroundAiTuningPatch = z.output<typeof GroundAiTuningPatchSchema>;
|
||||||
export type TuningValues = z.output<typeof TuningValuesSchema>;
|
export type TuningValues = z.output<typeof TuningValuesSchema>;
|
||||||
export type TuningPatch = z.output<typeof TuningPatchSchema>;
|
export type TuningPatch = z.output<typeof TuningPatchSchema>;
|
||||||
export type TuningView = z.output<typeof TuningViewSchema>;
|
export type TuningView = z.output<typeof TuningViewSchema>;
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@wto/blk": "*",
|
"@wto/blk": "*",
|
||||||
"@wto/jsonc": "*",
|
"@wto/jsonc": "*",
|
||||||
|
"@wto/mods": "*",
|
||||||
"@wto/vromfs": "*"
|
"@wto/vromfs": "*"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -16,6 +16,7 @@ export interface BattleEconomyTuning {
|
|||||||
readonly eventScores: Readonly<Record<VictimGroup, Readonly<Record<ScoredEvent, number>>>>;
|
readonly eventScores: Readonly<Record<VictimGroup, Readonly<Record<ScoredEvent, number>>>>;
|
||||||
readonly captureZoneScore: Readonly<Record<VictimGroup, number>>;
|
readonly captureZoneScore: Readonly<Record<VictimGroup, number>>;
|
||||||
readonly navalDamageScorePerPoint: number;
|
readonly navalDamageScorePerPoint: number;
|
||||||
|
readonly bombingZone: { readonly damageScore: number; readonly destructionScore: number };
|
||||||
readonly referenceScore: Readonly<Record<VictimGroup, number>>;
|
readonly referenceScore: Readonly<Record<VictimGroup, number>>;
|
||||||
readonly friendlyKillPenaltyMul: number;
|
readonly friendlyKillPenaltyMul: number;
|
||||||
}
|
}
|
||||||
@@ -30,6 +31,7 @@ export function readBattleEconomyTuning(reader: TuningReader): BattleEconomyTuni
|
|||||||
for (const expClass of groups.stringList(group)) victimGroups.set(expClass, group);
|
for (const expClass of groups.stringList(group)) victimGroups.set(expClass, group);
|
||||||
}
|
}
|
||||||
const scores = reader.object('eventScores');
|
const scores = reader.object('eventScores');
|
||||||
|
const bombingZone = reader.object('bombingZone');
|
||||||
const perGroup = (key: string, min: number): Record<VictimGroup, number> => {
|
const perGroup = (key: string, min: number): Record<VictimGroup, number> => {
|
||||||
const table = reader.object(key);
|
const table = reader.object(key);
|
||||||
return Object.fromEntries(VICTIM_GROUPS.map((group) => [group, table.number(group, { min, max: 100000 })])) as Record<VictimGroup, number>;
|
return Object.fromEntries(VICTIM_GROUPS.map((group) => [group, table.number(group, { min, max: 100000 })])) as Record<VictimGroup, number>;
|
||||||
@@ -42,6 +44,10 @@ export function readBattleEconomyTuning(reader: TuningReader): BattleEconomyTuni
|
|||||||
})) as Record<VictimGroup, Record<ScoredEvent, number>>,
|
})) as Record<VictimGroup, Record<ScoredEvent, number>>,
|
||||||
captureZoneScore: perGroup('captureZoneScore', 0),
|
captureZoneScore: perGroup('captureZoneScore', 0),
|
||||||
navalDamageScorePerPoint: reader.number('navalDamageScorePerPoint', { min: 0, max: 100 }),
|
navalDamageScorePerPoint: reader.number('navalDamageScorePerPoint', { min: 0, max: 100 }),
|
||||||
|
bombingZone: {
|
||||||
|
damageScore: bombingZone.int('damageScore', { min: 0, max: 100000 }),
|
||||||
|
destructionScore: bombingZone.int('destructionScore', { min: 0, max: 100000 }),
|
||||||
|
},
|
||||||
referenceScore: perGroup('referenceScore', 1),
|
referenceScore: perGroup('referenceScore', 1),
|
||||||
friendlyKillPenaltyMul: reader.number('friendlyKillPenaltyMul', { min: 0, max: 100 }),
|
friendlyKillPenaltyMul: reader.number('friendlyKillPenaltyMul', { min: 0, max: 100 }),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -16,11 +16,13 @@ import { SCORED_EVENTS, VICTIM_GROUPS, type BattleEconomyTuning, type ScoredEven
|
|||||||
/** EXP_EVENT_* codes the LocalMP host reports (gui.vromfs.bin globalScripts/expEventConsts.nut). */
|
/** EXP_EVENT_* codes the LocalMP host reports (gui.vromfs.bin globalScripts/expEventConsts.nut). */
|
||||||
export const ExpEvent = {
|
export const ExpEvent = {
|
||||||
CAPTURE_ZONE: 2,
|
CAPTURE_ZONE: 2,
|
||||||
|
DESTROY_ZONE: 3,
|
||||||
KILL: 5,
|
KILL: 5,
|
||||||
KILL_GROUND: 6,
|
KILL_GROUND: 6,
|
||||||
ASSIST: 9,
|
ASSIST: 9,
|
||||||
CRITICAL_HIT: 10,
|
CRITICAL_HIT: 10,
|
||||||
HIT: 13,
|
HIT: 13,
|
||||||
|
DAMAGE_ZONE: 17,
|
||||||
UNIT_DAMAGE: 24,
|
UNIT_DAMAGE: 24,
|
||||||
SEVERE_DAMAGE: 35,
|
SEVERE_DAMAGE: 35,
|
||||||
KILL_HUMAN: 39,
|
KILL_HUMAN: 39,
|
||||||
@@ -30,7 +32,14 @@ export const ExpEvent = {
|
|||||||
export type DebriefingRow =
|
export type DebriefingRow =
|
||||||
| 'AirKills' | 'GroundKills' | 'NavalKills' | 'HumanKills' | 'FriendlyKills'
|
| 'AirKills' | 'GroundKills' | 'NavalKills' | 'HumanKills' | 'FriendlyKills'
|
||||||
| 'Assist' | 'AirSevereDamage' | 'ShipSevereDamage' | 'Critical' | 'Hit'
|
| 'Assist' | 'AirSevereDamage' | 'ShipSevereDamage' | 'Critical' | 'Hit'
|
||||||
| 'Captures' | 'AwardDamage';
|
| 'Captures' | 'Damage' | 'Destruction' | 'AwardDamage';
|
||||||
|
|
||||||
|
/** LocalMP reports mini-base health as basis points (local_mp_zones.c). */
|
||||||
|
const ZONE_HEALTH_SCALE = 10_000;
|
||||||
|
|
||||||
|
function isBombingZoneEvent(code: number): boolean {
|
||||||
|
return code === ExpEvent.DAMAGE_ZONE || code === ExpEvent.DESTROY_ZONE;
|
||||||
|
}
|
||||||
|
|
||||||
/** What the client reports for one combat event (patches/gui/battle/record-local-battle-awards). */
|
/** What the client reports for one combat event (patches/gui/battle/record-local-battle-awards). */
|
||||||
export interface CombatEventFact {
|
export interface CombatEventFact {
|
||||||
@@ -38,12 +47,13 @@ export interface CombatEventFact {
|
|||||||
readonly expClass: string;
|
readonly expClass: string;
|
||||||
readonly victimIsPlayer: boolean;
|
readonly victimIsPlayer: boolean;
|
||||||
readonly friendly: boolean;
|
readonly friendly: boolean;
|
||||||
|
/** Naval damage points or, for DAMAGE_ZONE, basis points of the zone's full health. */
|
||||||
readonly damage: number;
|
readonly damage: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PricedEvent {
|
export interface PricedEvent {
|
||||||
readonly row: DebriefingRow;
|
readonly row: DebriefingRow;
|
||||||
/** How much the row's counter grows: 1, or the damage points for AwardDamage. */
|
/** How much the stock row's counter grows. Damage counts TNT mass, which is unavailable here. */
|
||||||
readonly count: number;
|
readonly count: number;
|
||||||
readonly wp: number;
|
readonly wp: number;
|
||||||
readonly exp: number;
|
readonly exp: number;
|
||||||
@@ -68,6 +78,7 @@ export interface BannerParams {
|
|||||||
readonly rpClass: Readonly<Record<string, number>>;
|
readonly rpClass: Readonly<Record<string, number>>;
|
||||||
readonly aiKillK: number;
|
readonly aiKillK: number;
|
||||||
readonly friendlyKillPenaltyMul: number;
|
readonly friendlyKillPenaltyMul: number;
|
||||||
|
readonly zoneHealthScale: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RewardMultipliers {
|
export interface RewardMultipliers {
|
||||||
@@ -128,37 +139,46 @@ export class BattleEconomy {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
price(vehicle: string, difficulty: EconomyDifficulty, fact: CombatEventFact): PricedEvent | undefined {
|
price(vehicle: string, difficulty: EconomyDifficulty, modeName: string, fact: CombatEventFact): PricedEvent | undefined {
|
||||||
const economy = this.vehicle(vehicle);
|
const economy = this.vehicle(vehicle);
|
||||||
if (!economy) return undefined;
|
if (!economy) return undefined;
|
||||||
const isCapture = fact.code === ExpEvent.CAPTURE_ZONE;
|
const isCapture = fact.code === ExpEvent.CAPTURE_ZONE;
|
||||||
const group = isCapture ? this.victimGroup(economy.unitClass) : this.victimGroup(fact.expClass);
|
const isBombingZone = isBombingZoneEvent(fact.code);
|
||||||
|
const isZoneDamage = fact.code === ExpEvent.DAMAGE_ZONE;
|
||||||
|
if (isBombingZone && (modeName !== 'air_arcade' || fact.friendly)) return undefined;
|
||||||
|
if (isZoneDamage && (!Number.isInteger(fact.damage) || fact.damage < 1 || fact.damage > ZONE_HEALTH_SCALE)) return undefined;
|
||||||
|
const isObjective = isCapture || isBombingZone;
|
||||||
|
const group = isBombingZone ? 'ground' : this.victimGroup(isCapture ? economy.unitClass : fact.expClass);
|
||||||
const row = debriefingRow(fact, group);
|
const row = debriefingRow(fact, group);
|
||||||
const base = this.baseReward(vehicle, difficulty, fact.code, group);
|
const base = this.baseReward(vehicle, difficulty, fact.code, group);
|
||||||
if (!row || !base) return undefined;
|
if (!row || !base) return undefined;
|
||||||
const count = fact.code === ExpEvent.UNIT_DAMAGE ? Math.max(0, Math.trunc(fact.damage)) : 1;
|
const count = fact.code === ExpEvent.UNIT_DAMAGE ? Math.max(0, Math.trunc(fact.damage)) : 1;
|
||||||
const ai = isCapture || fact.victimIsPlayer ? 1 : this.data.aiKillK;
|
const quantity = isZoneDamage ? fact.damage / ZONE_HEALTH_SCALE : count;
|
||||||
const slClass = isCapture ? 1 : this.data.silverLionsClassFactors[fact.expClass] ?? 1;
|
const ai = isObjective || fact.victimIsPlayer ? 1 : this.data.aiKillK;
|
||||||
const rpClass = isCapture ? 1 : this.data.researchClassFactors[fact.expClass] ?? 1;
|
const slClass = isObjective ? 1 : this.data.silverLionsClassFactors[fact.expClass] ?? 1;
|
||||||
|
const rpClass = isObjective ? 1 : this.data.researchClassFactors[fact.expClass] ?? 1;
|
||||||
if (fact.friendly) {
|
if (fact.friendly) {
|
||||||
return { row: 'FriendlyKills', count: 1, wp: -Math.round(base.wp * slClass * ai * this.#tuning.friendlyKillPenaltyMul), exp: 0 };
|
return { row: 'FriendlyKills', count: 1, wp: -Math.round(base.wp * slClass * ai * this.#tuning.friendlyKillPenaltyMul), exp: 0 };
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
row,
|
row,
|
||||||
count,
|
count: isZoneDamage ? 0 : count,
|
||||||
wp: Math.round(base.wp * slClass * ai * count),
|
wp: Math.round(base.wp * slClass * ai * quantity),
|
||||||
exp: Math.round(base.exp * rpClass * ai * count),
|
exp: Math.round(base.exp * rpClass * ai * quantity),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
bannerParams(vehicles: Iterable<string>, difficulty: EconomyDifficulty): BannerParams {
|
bannerParams(vehicles: Iterable<string>, difficulty: EconomyDifficulty, modeName: string): BannerParams {
|
||||||
const table: Record<string, Record<string, [number, number]>> = {};
|
const table: Record<string, Record<string, [number, number]>> = {};
|
||||||
for (const name of vehicles) {
|
for (const name of vehicles) {
|
||||||
const economy = this.vehicle(name);
|
const economy = this.vehicle(name);
|
||||||
if (!economy || table[name]) continue;
|
if (!economy || table[name]) continue;
|
||||||
const entries: Record<string, [number, number]> = {};
|
const entries: Record<string, [number, number]> = {};
|
||||||
for (const code of Object.values(ExpEvent)) {
|
for (const code of Object.values(ExpEvent)) {
|
||||||
const groups: readonly (VictimGroup | 'own')[] = code === ExpEvent.CAPTURE_ZONE ? ['own'] : ['ground', 'air', 'naval', 'human'];
|
const isBombingZone = isBombingZoneEvent(code);
|
||||||
|
if (isBombingZone && modeName !== 'air_arcade') continue;
|
||||||
|
const groups: readonly (VictimGroup | 'own')[] = code === ExpEvent.CAPTURE_ZONE ? ['own']
|
||||||
|
: isBombingZone ? ['ground'] : VICTIM_GROUPS;
|
||||||
for (const group of groups) {
|
for (const group of groups) {
|
||||||
const priceGroup = group === 'own' ? this.victimGroup(economy.unitClass) : group;
|
const priceGroup = group === 'own' ? this.victimGroup(economy.unitClass) : group;
|
||||||
const base = this.baseReward(name, difficulty, code, priceGroup);
|
const base = this.baseReward(name, difficulty, code, priceGroup);
|
||||||
@@ -174,6 +194,7 @@ export class BattleEconomy {
|
|||||||
rpClass: this.data.researchClassFactors,
|
rpClass: this.data.researchClassFactors,
|
||||||
aiKillK: this.data.aiKillK,
|
aiKillK: this.data.aiKillK,
|
||||||
friendlyKillPenaltyMul: this.#tuning.friendlyKillPenaltyMul,
|
friendlyKillPenaltyMul: this.#tuning.friendlyKillPenaltyMul,
|
||||||
|
zoneHealthScale: ZONE_HEALTH_SCALE,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,7 +204,7 @@ export class BattleEconomy {
|
|||||||
* the official mission scores of tuning/battle-economy.jsonc, and aiKillK for victims that are
|
* the official mission scores of tuning/battle-economy.jsonc, and aiKillK for victims that are
|
||||||
* not players, as in the rewards.
|
* not players, as in the rewards.
|
||||||
*/
|
*/
|
||||||
missionScores(): Readonly<Record<string, number>> {
|
missionScores(modeName: string): Readonly<Record<string, number>> {
|
||||||
const scores: Record<string, number> = {};
|
const scores: Record<string, number> = {};
|
||||||
for (const group of VICTIM_GROUPS) {
|
for (const group of VICTIM_GROUPS) {
|
||||||
for (const event of SCORED_EVENTS) scores[`wtoScore_${event}_${group}`] = this.#tuning.eventScores[group][event];
|
for (const event of SCORED_EVENTS) scores[`wtoScore_${event}_${group}`] = this.#tuning.eventScores[group][event];
|
||||||
@@ -191,6 +212,10 @@ export class BattleEconomy {
|
|||||||
}
|
}
|
||||||
scores.wtoScore_damagePerPoint = this.#tuning.navalDamageScorePerPoint;
|
scores.wtoScore_damagePerPoint = this.#tuning.navalDamageScorePerPoint;
|
||||||
scores.wtoScore_aiMul = this.data.aiKillK;
|
scores.wtoScore_aiMul = this.data.aiKillK;
|
||||||
|
if (modeName === 'air_arcade') {
|
||||||
|
scores.wtoScore_zoneDamage = this.#tuning.bombingZone.damageScore;
|
||||||
|
scores.wtoScore_zoneDestruction = this.#tuning.bombingZone.destructionScore;
|
||||||
|
}
|
||||||
return scores;
|
return scores;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,6 +230,8 @@ export class BattleEconomy {
|
|||||||
case ExpEvent.HIT: return scored('hit');
|
case ExpEvent.HIT: return scored('hit');
|
||||||
case ExpEvent.SEVERE_DAMAGE: return scored('severeDamage');
|
case ExpEvent.SEVERE_DAMAGE: return scored('severeDamage');
|
||||||
case ExpEvent.CAPTURE_ZONE: return this.#tuning.captureZoneScore[group];
|
case ExpEvent.CAPTURE_ZONE: return this.#tuning.captureZoneScore[group];
|
||||||
|
case ExpEvent.DAMAGE_ZONE: return this.#tuning.bombingZone.damageScore;
|
||||||
|
case ExpEvent.DESTROY_ZONE: return this.#tuning.bombingZone.destructionScore;
|
||||||
case ExpEvent.UNIT_DAMAGE: return this.#tuning.navalDamageScorePerPoint;
|
case ExpEvent.UNIT_DAMAGE: return this.#tuning.navalDamageScorePerPoint;
|
||||||
default: return undefined;
|
default: return undefined;
|
||||||
}
|
}
|
||||||
@@ -223,6 +250,8 @@ function debriefingRow(fact: CombatEventFact, group: VictimGroup): DebriefingRow
|
|||||||
case ExpEvent.HIT: return 'Hit';
|
case ExpEvent.HIT: return 'Hit';
|
||||||
case ExpEvent.SEVERE_DAMAGE: return group === 'naval' ? 'ShipSevereDamage' : 'AirSevereDamage';
|
case ExpEvent.SEVERE_DAMAGE: return group === 'naval' ? 'ShipSevereDamage' : 'AirSevereDamage';
|
||||||
case ExpEvent.CAPTURE_ZONE: return 'Captures';
|
case ExpEvent.CAPTURE_ZONE: return 'Captures';
|
||||||
|
case ExpEvent.DAMAGE_ZONE: return 'Damage';
|
||||||
|
case ExpEvent.DESTROY_ZONE: return 'Destruction';
|
||||||
case ExpEvent.UNIT_DAMAGE: return 'AwardDamage';
|
case ExpEvent.UNIT_DAMAGE: return 'AwardDamage';
|
||||||
default: return undefined;
|
default: return undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
import { randomInt } from 'node:crypto';
|
import { randomInt } from 'node:crypto';
|
||||||
import type {
|
import type {
|
||||||
BattleSpawnRulesData,
|
BattleSpawnRulesData,
|
||||||
|
NuclearCarrierUnit,
|
||||||
RandomSpawnGroup,
|
RandomSpawnGroup,
|
||||||
RandomSpawnUnit,
|
RandomSpawnUnit,
|
||||||
SupportPlanePreset,
|
SupportPlanePreset,
|
||||||
@@ -43,6 +44,8 @@ export interface ExtraBattleSlot {
|
|||||||
/** The modifications enabled when not `allModifications`; the unit is otherwise stock. */
|
/** The modifications enabled when not `allModifications`; the unit is otherwise stock. */
|
||||||
readonly modifications: readonly string[];
|
readonly modifications: readonly string[];
|
||||||
readonly forceWeapon?: string;
|
readonly forceWeapon?: string;
|
||||||
|
/** Restricts the respawn weapon dropdown to these presets when multiple mode presets exist. */
|
||||||
|
readonly allowedWeapons?: readonly string[];
|
||||||
/** The RandomSpawnUnits group the vehicle was drawn from. */
|
/** The RandomSpawnUnits group the vehicle was drawn from. */
|
||||||
readonly groupName?: string;
|
readonly groupName?: string;
|
||||||
}
|
}
|
||||||
@@ -56,7 +59,10 @@ export interface ExtraBattleSlotsInput {
|
|||||||
readonly sessionMaxMrank: number;
|
readonly sessionMaxMrank: number;
|
||||||
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
|
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
|
||||||
readonly rules: BattleSpawnRulesData;
|
readonly rules: BattleSpawnRulesData;
|
||||||
readonly tuning: Pick<BattleTuning, 'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore'>;
|
readonly tuning: Pick<
|
||||||
|
BattleTuning,
|
||||||
|
'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore' | 'nuclearEscalationStrategicBombers'
|
||||||
|
>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] {
|
export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] {
|
||||||
@@ -68,6 +74,7 @@ export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly E
|
|||||||
if (supportPlane) supportSlots.push(supportPlane);
|
if (supportPlane) supportSlots.push(supportPlane);
|
||||||
const ucav = strikeUcavSlot(input);
|
const ucav = strikeUcavSlot(input);
|
||||||
if (ucav) supportSlots.push(ucav);
|
if (ucav) supportSlots.push(ucav);
|
||||||
|
supportSlots.push(...nuclearEscalationSlots(input));
|
||||||
|
|
||||||
// Keep room for fixed support vehicles while displaying random vehicle groups first.
|
// Keep room for fixed support vehicles while displaying random vehicle groups first.
|
||||||
const slots: ExtraBattleSlot[] = [];
|
const slots: ExtraBattleSlot[] = [];
|
||||||
@@ -118,6 +125,72 @@ function strikeUcavSlot(input: ExtraBattleSlotsInput): ExtraBattleSlot | undefin
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const NUCLEAR_ESCALATION_TAG_PREFIX = 'nuclear_escalation_';
|
||||||
|
const GROUND_RB_SUPPORT_MODE = 'tank_event_in_random_battles_historical';
|
||||||
|
const EASTERN_STRATEGIC_BOMBER_COUNTRIES = new Set(['country_ussr', 'country_china']);
|
||||||
|
|
||||||
|
function nuclearEscalationSlots(input: ExtraBattleSlotsInput): ExtraBattleSlot[] {
|
||||||
|
if (!input.declaration.tag?.startsWith(NUCLEAR_ESCALATION_TAG_PREFIX)) return [];
|
||||||
|
const slots: ExtraBattleSlot[] = [];
|
||||||
|
const tactical = selectTacticalNuclearCarrier(input);
|
||||||
|
if (tactical) {
|
||||||
|
const weaponNames = tactical.weapons.map((weapon) => weapon.name);
|
||||||
|
slots.push({
|
||||||
|
unitName: tactical.unitName,
|
||||||
|
allModifications: true,
|
||||||
|
modifications: [],
|
||||||
|
...(weaponNames.length === 1 ? { forceWeapon: weaponNames[0]! } : { allowedWeapons: weaponNames }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (input.tuning.nuclearEscalationStrategicBombers) {
|
||||||
|
const strategic = selectStrategicNuclearBomber(input.country, input.rules.nuclearEscalationStrategicBombers);
|
||||||
|
if (strategic) {
|
||||||
|
const weapon = strategic.weapons[0];
|
||||||
|
slots.push({
|
||||||
|
unitName: strategic.unitName,
|
||||||
|
allModifications: true,
|
||||||
|
modifications: [],
|
||||||
|
...(weapon ? { forceWeapon: weapon.name } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return slots;
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectTacticalNuclearCarrier(input: ExtraBattleSlotsInput): NuclearCarrierUnit | undefined {
|
||||||
|
const byCountry = input.rules.nuclearEscalationTacticalCarriers.filter((entry) => entry.country === input.country);
|
||||||
|
if (byCountry.length === 0) return undefined;
|
||||||
|
|
||||||
|
// Prefer the stock Ground RB nuclear carrier for the matching rank bracket when it carries
|
||||||
|
// Nuclear Escalation 5 kt / 30 kt presets; otherwise pick the country's closest-mrank carrier.
|
||||||
|
const groundPresets = input.rules.supportPlanes[GROUND_RB_SUPPORT_MODE] ?? [];
|
||||||
|
const bracket = groundPresets.find((p) => input.sessionMaxMrank >= p.minMrank && input.sessionMaxMrank <= p.maxMrank);
|
||||||
|
const preferredUnit = bracket?.units[input.country]?.unitName;
|
||||||
|
if (preferredUnit) {
|
||||||
|
const matched = byCountry.find((entry) => entry.unitName === preferredUnit);
|
||||||
|
if (matched) return matched;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...byCountry].sort((a, b) => {
|
||||||
|
const distA = Math.abs(a.mrank - input.sessionMaxMrank);
|
||||||
|
const distB = Math.abs(b.mrank - input.sessionMaxMrank);
|
||||||
|
if (distA !== distB) return distA - distB;
|
||||||
|
const underA = a.mrank <= input.sessionMaxMrank ? 0 : 1;
|
||||||
|
const underB = b.mrank <= input.sessionMaxMrank ? 0 : 1;
|
||||||
|
if (underA !== underB) return underA - underB;
|
||||||
|
return a.mrank - b.mrank || a.unitName.localeCompare(b.unitName);
|
||||||
|
})[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectStrategicNuclearBomber(
|
||||||
|
country: string,
|
||||||
|
bombers: readonly NuclearCarrierUnit[],
|
||||||
|
): NuclearCarrierUnit | undefined {
|
||||||
|
if (bombers.length === 0) return undefined;
|
||||||
|
const preferredCountry = EASTERN_STRATEGIC_BOMBER_COUNTRIES.has(country) ? 'country_ussr' : 'country_usa';
|
||||||
|
return bombers.find((entry) => entry.country === preferredCountry) ?? bombers[0];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits,
|
* The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits,
|
||||||
* those of the highest rank below it. Vehicles already in the lineup are left out (offline
|
* those of the highest rank below it. Vehicles already in the lineup are left out (offline
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-ru
|
|||||||
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
|
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
|
||||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||||
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
||||||
import { MISSION_DIFFICULTY, SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
|
import { MISSION_DIFFICULTY, SINGLE_SPAWN, UNLIMITED_RESPAWNS, modeMaxRespawns } from '../game-modes/mode-definition.ts';
|
||||||
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
||||||
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
|
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
|
||||||
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
|
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
|
||||||
@@ -19,11 +19,13 @@ import {
|
|||||||
isModeEligibleForLineup,
|
isModeEligibleForLineup,
|
||||||
lineupMrank,
|
lineupMrank,
|
||||||
selectCustomBots,
|
selectCustomBots,
|
||||||
|
type TankLineupWeights,
|
||||||
type CustomBotsPool,
|
type CustomBotsPool,
|
||||||
} from './battle-ranks.ts';
|
} from './battle-ranks.ts';
|
||||||
import type { BattleSessionStore } from './battle-session-store.ts';
|
import type { BattleSessionStore } from './battle-session-store.ts';
|
||||||
import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts';
|
import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts';
|
||||||
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
|
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
|
||||||
|
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
|
||||||
import type { BattleTuning } from './battle-tuning.ts';
|
import type { BattleTuning } from './battle-tuning.ts';
|
||||||
|
|
||||||
export interface BattleCrewSlot {
|
export interface BattleCrewSlot {
|
||||||
@@ -47,10 +49,12 @@ export interface BattleLaunchPlan {
|
|||||||
readonly sessionId: string;
|
readonly sessionId: string;
|
||||||
readonly modeId: number;
|
readonly modeId: number;
|
||||||
readonly modeName: string;
|
readonly modeName: string;
|
||||||
|
readonly modeTag?: string;
|
||||||
readonly economicName: string;
|
readonly economicName: string;
|
||||||
readonly missionName: string;
|
readonly missionName: string;
|
||||||
/** The mission as the game describes it, including the parameters copied into the mission settings. */
|
/** The mission as the game describes it, including the parameters copied into the mission settings. */
|
||||||
readonly mission: MissionHeader;
|
readonly mission: MissionHeader;
|
||||||
|
readonly missionRuleKeys: readonly string[];
|
||||||
readonly missionFile: string;
|
readonly missionFile: string;
|
||||||
readonly missionType: string;
|
readonly missionType: string;
|
||||||
readonly level?: string;
|
readonly level?: string;
|
||||||
@@ -68,6 +72,8 @@ export interface BattleLaunchPlan {
|
|||||||
readonly maxMrank: number;
|
readonly maxMrank: number;
|
||||||
readonly maxPlayers: number;
|
readonly maxPlayers: number;
|
||||||
readonly maxBots: number;
|
readonly maxBots: number;
|
||||||
|
readonly maxRespawns?: number;
|
||||||
|
readonly allowSpares: boolean;
|
||||||
readonly tankBotRespawns: number;
|
readonly tankBotRespawns: number;
|
||||||
readonly airBotRespawns: number;
|
readonly airBotRespawns: number;
|
||||||
readonly useTankBots: boolean;
|
readonly useTankBots: boolean;
|
||||||
@@ -83,6 +89,16 @@ export type MatchmakeOutcome =
|
|||||||
| { readonly ok: true; readonly launch: BattleLaunchPlan }
|
| { readonly ok: true; readonly launch: BattleLaunchPlan }
|
||||||
| { readonly ok: false; readonly error: string };
|
| { readonly ok: false; readonly error: string };
|
||||||
|
|
||||||
|
export type MissionPoolFilter = (ctx: {
|
||||||
|
readonly userId: string;
|
||||||
|
readonly modeId: number;
|
||||||
|
readonly modeName: string;
|
||||||
|
readonly economicName: string;
|
||||||
|
readonly minMrank: number;
|
||||||
|
readonly maxMrank: number;
|
||||||
|
readonly missions: readonly MissionHeader[];
|
||||||
|
}) => readonly MissionHeader[];
|
||||||
|
|
||||||
export class BattleMatchmaker {
|
export class BattleMatchmaker {
|
||||||
readonly #gameModes: GameModes;
|
readonly #gameModes: GameModes;
|
||||||
readonly #vehicles: readonly CatalogueVehicle[];
|
readonly #vehicles: readonly CatalogueVehicle[];
|
||||||
@@ -91,6 +107,9 @@ export class BattleMatchmaker {
|
|||||||
readonly #tuning: BattleTuning;
|
readonly #tuning: BattleTuning;
|
||||||
readonly #spawnRules: BattleSpawnRulesData;
|
readonly #spawnRules: BattleSpawnRulesData;
|
||||||
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
|
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
|
||||||
|
readonly #tankWeights: TankLineupWeights | undefined;
|
||||||
|
readonly #tankLoadouts: ReadonlyMap<string, BotTankLoadout> | undefined;
|
||||||
|
readonly #filterMissions: MissionPoolFilter | undefined;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
gameModes: GameModes,
|
gameModes: GameModes,
|
||||||
@@ -99,6 +118,9 @@ export class BattleMatchmaker {
|
|||||||
tuning: BattleTuning,
|
tuning: BattleTuning,
|
||||||
spawnRules: BattleSpawnRulesData,
|
spawnRules: BattleSpawnRulesData,
|
||||||
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
|
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
|
||||||
|
tankWeights: TankLineupWeights | undefined,
|
||||||
|
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
|
||||||
|
filterMissions?: MissionPoolFilter,
|
||||||
) {
|
) {
|
||||||
this.#gameModes = gameModes;
|
this.#gameModes = gameModes;
|
||||||
this.#vehicles = vehicles;
|
this.#vehicles = vehicles;
|
||||||
@@ -107,6 +129,9 @@ export class BattleMatchmaker {
|
|||||||
this.#tuning = tuning;
|
this.#tuning = tuning;
|
||||||
this.#spawnRules = spawnRules;
|
this.#spawnRules = spawnRules;
|
||||||
this.#aircraftLoadouts = aircraftLoadouts;
|
this.#aircraftLoadouts = aircraftLoadouts;
|
||||||
|
this.#tankWeights = tankWeights;
|
||||||
|
this.#tankLoadouts = tankLoadouts;
|
||||||
|
this.#filterMissions = filterMissions;
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
|
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
|
||||||
@@ -130,8 +155,20 @@ export class BattleMatchmaker {
|
|||||||
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
|
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
|
||||||
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
|
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
|
||||||
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
|
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
|
||||||
const missions = twoSidedMissionsOf(chosenMode, maxMrank);
|
const rawMissions = twoSidedMissionsOf(chosenMode, maxMrank);
|
||||||
if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
|
if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
|
||||||
|
const filteredMissions = this.#filterMissions
|
||||||
|
? this.#filterMissions({
|
||||||
|
userId: input.userId,
|
||||||
|
modeId: declaration.gameModeId,
|
||||||
|
modeName: declaration.name,
|
||||||
|
economicName: declaration.economicName,
|
||||||
|
minMrank,
|
||||||
|
maxMrank,
|
||||||
|
missions: rawMissions,
|
||||||
|
})
|
||||||
|
: rawMissions;
|
||||||
|
const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions;
|
||||||
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
|
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
|
||||||
const coalitions = selectBattleCoalitions({
|
const coalitions = selectBattleCoalitions({
|
||||||
vehicles: this.#vehicles,
|
vehicles: this.#vehicles,
|
||||||
@@ -153,7 +190,7 @@ export class BattleMatchmaker {
|
|||||||
minMrank,
|
minMrank,
|
||||||
maxMrank,
|
maxMrank,
|
||||||
limitPerType: this.#tuning.botPoolLimitPerType,
|
limitPerType: this.#tuning.botPoolLimitPerType,
|
||||||
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts);
|
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights, this.#tankLoadouts);
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
|
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
|
||||||
@@ -164,7 +201,7 @@ export class BattleMatchmaker {
|
|||||||
const pool = candidates.filter((mode) => isModeEligibleForLineup(
|
const pool = candidates.filter((mode) => isModeEligibleForLineup(
|
||||||
mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
|
mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
|
||||||
));
|
));
|
||||||
if (pool.length === 0) return candidates.find((mode) => mode.declaration.multiSlot !== false);
|
if (pool.length === 0) return undefined;
|
||||||
const classics = pool.filter((mode) => !mode.declaration.tag);
|
const classics = pool.filter((mode) => !mode.declaration.tag);
|
||||||
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
|
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
|
||||||
if (subModes.length > 0 && classics.length > 0) {
|
if (subModes.length > 0 && classics.length > 0) {
|
||||||
@@ -189,12 +226,14 @@ export class BattleMatchmaker {
|
|||||||
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
|
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
|
||||||
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
|
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
|
||||||
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
|
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
|
||||||
|
const maxRespawns = modeMaxRespawns(declaration);
|
||||||
const missionLocName = resolveMissionLocName(mission);
|
const missionLocName = resolveMissionLocName(mission);
|
||||||
const environment = declaration.environmentOverride ?? mission.environment;
|
const environment = declaration.environmentOverride ?? mission.environment;
|
||||||
const session = this.#sessions.create({
|
const session = this.#sessions.create({
|
||||||
userId: input.userId,
|
userId: input.userId,
|
||||||
modeId: declaration.gameModeId,
|
modeId: declaration.gameModeId,
|
||||||
modeName: declaration.name,
|
modeName: declaration.name,
|
||||||
|
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
|
||||||
economicName: declaration.economicName,
|
economicName: declaration.economicName,
|
||||||
difficulty: declaration.difficulty,
|
difficulty: declaration.difficulty,
|
||||||
requiredClass: declaration.requiredClass,
|
requiredClass: declaration.requiredClass,
|
||||||
@@ -221,9 +260,11 @@ export class BattleMatchmaker {
|
|||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
modeId: declaration.gameModeId,
|
modeId: declaration.gameModeId,
|
||||||
modeName: declaration.name,
|
modeName: declaration.name,
|
||||||
|
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
|
||||||
economicName: declaration.economicName,
|
economicName: declaration.economicName,
|
||||||
missionName: mission.name,
|
missionName: mission.name,
|
||||||
mission,
|
mission,
|
||||||
|
missionRuleKeys: declaration.missionRuleKeys ?? [],
|
||||||
missionFile: mission.path,
|
missionFile: mission.path,
|
||||||
missionType: mission.type ?? 'domination',
|
missionType: mission.type ?? 'domination',
|
||||||
...(mission.level !== undefined ? { level: mission.level } : {}),
|
...(mission.level !== undefined ? { level: mission.level } : {}),
|
||||||
@@ -241,6 +282,8 @@ export class BattleMatchmaker {
|
|||||||
maxMrank,
|
maxMrank,
|
||||||
maxPlayers,
|
maxPlayers,
|
||||||
maxBots,
|
maxBots,
|
||||||
|
allowSpares: declaration.multiSlot !== false && maxRespawns !== SINGLE_SPAWN && maxRespawns !== UNLIMITED_RESPAWNS,
|
||||||
|
...(maxRespawns === undefined ? {} : { maxRespawns }),
|
||||||
tankBotRespawns: this.#tuning.tankBotRespawns,
|
tankBotRespawns: this.#tuning.tankBotRespawns,
|
||||||
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
|
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
|
||||||
useTankBots: allowedSet.has('tank'),
|
useTankBots: allowedSet.has('tank'),
|
||||||
|
|||||||
@@ -7,8 +7,8 @@
|
|||||||
* copied here from the mission file, base values first and then the sub-block for the battle's
|
* copied here from the mission file, base values first and then the sub-block for the battle's
|
||||||
* difficulty. `_gameMode` is left to the client, which takes it from its own native constants.
|
* difficulty. `_gameMode` is left to the client, which takes it from its own native constants.
|
||||||
*/
|
*/
|
||||||
import { emptyBlock, ensureBlock, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
|
import { emptyBlock, ensureBlock, findParam, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
|
||||||
import { SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
|
import { UNLIMITED_RESPAWNS } from '../game-modes/mode-definition.ts';
|
||||||
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
|
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
|
||||||
import type { BattleLaunchPlan } from './battle-matchmaker.ts';
|
import type { BattleLaunchPlan } from './battle-matchmaker.ts';
|
||||||
import type { CustomBotsPool } from './battle-ranks.ts';
|
import type { CustomBotsPool } from './battle-ranks.ts';
|
||||||
@@ -23,6 +23,7 @@ const RULE_KEYS: readonly string[] = [
|
|||||||
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
|
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
|
||||||
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
|
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
|
||||||
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
|
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
|
||||||
|
'allowedKillStreaks',
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
|
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
|
||||||
@@ -39,6 +40,13 @@ const VERSUS_SWITCHES: readonly string[] = [
|
|||||||
export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock {
|
export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock {
|
||||||
const settings = emptyBlock();
|
const settings = emptyBlock();
|
||||||
copyMissionParams(settings, plan);
|
copyMissionParams(settings, plan);
|
||||||
|
// Enable Ground Arcade air events when the mission allows killstreaks; the LocalMP host preserves
|
||||||
|
// MissionSettings.useKillStreaks across prepare_local_mission (local_mp_air_events.c).
|
||||||
|
const allowedKillStreaks = findParam(settings, 'allowedKillStreaks')?.value;
|
||||||
|
if (plan.modeName === 'tank_event_in_random_battles_arcade'
|
||||||
|
&& allowedKillStreaks?.type === 'bool' && allowedKillStreaks.value) {
|
||||||
|
setParam(settings, 'useKillStreaks', flag(true));
|
||||||
|
}
|
||||||
if (plan.level !== undefined) setParam(settings, 'level', text(plan.level));
|
if (plan.level !== undefined) setParam(settings, 'level', text(plan.level));
|
||||||
if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
|
if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
|
||||||
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
|
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
|
||||||
@@ -62,13 +70,17 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
|
|||||||
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
|
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
|
||||||
// The native in-flight rearm request and its receiver both require unlimited reserve ammunition.
|
// The native in-flight rearm request and its receiver both require unlimited reserve ammunition.
|
||||||
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
|
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
|
||||||
setParam(settings, 'allowSpare', flag(!plan.selectedSlot));
|
// MissionSettings defaults isLimitedFuel to false, which disables fuel consumption and HUD timers.
|
||||||
|
setParam(settings, 'isLimitedFuel', flag(true));
|
||||||
|
setParam(settings, 'allowSpare', flag(plan.allowSpares));
|
||||||
|
if (plan.maxRespawns !== undefined) setParam(settings, 'maxRespawns', integer(plan.maxRespawns));
|
||||||
if (plan.selectedSlot) {
|
if (plan.selectedSlot) {
|
||||||
setParam(settings, 'maxRespawns', integer(SINGLE_SPAWN));
|
|
||||||
setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true));
|
setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true));
|
||||||
// The native mission loader reads the AI limit at the top level, after its bots.blk default.
|
|
||||||
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
|
|
||||||
}
|
}
|
||||||
|
// MissionSettings::load (2.61.0.37 0x126b1f4..0x126b2e6) reads global config/bots.blk defaults
|
||||||
|
// first, then overrides aircraft and tank AI respawn limits from the mission root, not customBots.
|
||||||
|
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
|
||||||
|
setParam(settings, 'numTankBotRespawns', integer(plan.tankBotRespawns));
|
||||||
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
|
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
|
||||||
setParam(settings, 'useTankBots', flag(plan.useTankBots));
|
setParam(settings, 'useTankBots', flag(plan.useTankBots));
|
||||||
setParam(settings, 'useShipBots', flag(plan.useShipBots));
|
setParam(settings, 'useShipBots', flag(plan.useShipBots));
|
||||||
@@ -90,14 +102,15 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
|
|||||||
}
|
}
|
||||||
|
|
||||||
function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void {
|
function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void {
|
||||||
const wanted = new Set([...LOCALIZATION_KEYS, ...RULE_KEYS]);
|
const ruleKeys = new Set([...RULE_KEYS, ...plan.missionRuleKeys]);
|
||||||
|
const wanted = new Set([...LOCALIZATION_KEYS, ...ruleKeys]);
|
||||||
const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => {
|
const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => {
|
||||||
for (const param of params ?? []) {
|
for (const param of params ?? []) {
|
||||||
if (keys.has(param.name)) setParam(settings, param.name, param.value);
|
if (keys.has(param.name)) setParam(settings, param.name, param.value);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
copy(plan.mission.missionParams, wanted);
|
copy(plan.mission.missionParams, wanted);
|
||||||
copy(plan.mission.difficultyParams[plan.difficulty], new Set(RULE_KEYS));
|
copy(plan.mission.difficultyParams[plan.difficulty], ruleKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */
|
/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */
|
||||||
@@ -117,6 +130,8 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
|
|||||||
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
|
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
|
||||||
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
|
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
|
||||||
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
|
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
|
||||||
|
if (plan.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode));
|
||||||
|
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
|
||||||
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
|
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
|
||||||
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
|
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
|
||||||
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
|
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
|
||||||
@@ -126,6 +141,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
|
|||||||
poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts),
|
poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts),
|
||||||
poolBlock('allowedShips', 'ship', plan.customBots.ships),
|
poolBlock('allowedShips', 'ship', plan.customBots.ships),
|
||||||
);
|
);
|
||||||
|
addTankAmmoParams(bots, plan.customBots.tanks);
|
||||||
return bots;
|
return bots;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,11 +157,26 @@ function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tan
|
|||||||
setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset));
|
setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset));
|
||||||
for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification));
|
for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification));
|
||||||
}
|
}
|
||||||
|
if (entry.tankLoadout !== undefined) {
|
||||||
|
for (const modification of entry.tankLoadout.modifications) appendParam(block, 'addModification', text(modification));
|
||||||
|
}
|
||||||
pool.blocks.push(block);
|
pool.blocks.push(block);
|
||||||
}
|
}
|
||||||
return pool;
|
return pool;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Per-tank bot ammo strings (`weapon|mod0:count0|mod1:count1`) read by local_mp_loadout.c. */
|
||||||
|
function addTankAmmoParams(bots: BlkBlock, entries: CustomBotsPool['tanks']): void {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const entry of entries) {
|
||||||
|
const loadout = entry.tankLoadout;
|
||||||
|
if (!loadout || loadout.bullets.length === 0 || seen.has(entry.name)) continue;
|
||||||
|
seen.add(entry.name);
|
||||||
|
const parts = [loadout.weaponName, ...loadout.bullets.slice(0, 2).map((s) => `${s.modName}:${s.count}`)];
|
||||||
|
setParam(bots, `wtoAmmo_${entry.name}`, text(parts.join('|')));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function text(value: string): BlkValue {
|
function text(value: string): BlkValue {
|
||||||
return { type: 'string', value };
|
return { type: 'string', value };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.t
|
|||||||
import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
|
import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
|
||||||
import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
|
import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
|
||||||
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
|
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
|
||||||
|
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
|
||||||
|
|
||||||
const COUNTRY_PREFIX = 'country_';
|
const COUNTRY_PREFIX = 'country_';
|
||||||
|
|
||||||
@@ -23,6 +24,7 @@ export interface BotPoolEntry {
|
|||||||
readonly country: string;
|
readonly country: string;
|
||||||
readonly weight: number;
|
readonly weight: number;
|
||||||
readonly aircraftLoadout?: BotAircraftLoadout;
|
readonly aircraftLoadout?: BotAircraftLoadout;
|
||||||
|
readonly tankLoadout?: BotTankLoadout;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CustomBotsPool {
|
export interface CustomBotsPool {
|
||||||
@@ -31,6 +33,16 @@ export interface CustomBotsPool {
|
|||||||
readonly ships: readonly BotPoolEntry[];
|
readonly ships: readonly BotPoolEntry[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Offline tank pool weights by vehicle class (`tuning/ground-ai.jsonc` `lineupWeights`). */
|
||||||
|
export interface TankLineupWeights {
|
||||||
|
readonly spaa: number;
|
||||||
|
readonly lightTank: number;
|
||||||
|
readonly tankDestroyer: number;
|
||||||
|
readonly heavyTank: number;
|
||||||
|
readonly mediumTank: number;
|
||||||
|
readonly other: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface BotPoolQuery {
|
export interface BotPoolQuery {
|
||||||
readonly difficulty: ModeDifficulty;
|
readonly difficulty: ModeDifficulty;
|
||||||
readonly requiredClass: UnitClass;
|
readonly requiredClass: UnitClass;
|
||||||
@@ -117,14 +129,25 @@ function lineupVehicleMrank(
|
|||||||
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
|
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Without `tankWeights` every pool entry keeps the stock weight of 1.
|
||||||
|
*/
|
||||||
export function selectCustomBots(
|
export function selectCustomBots(
|
||||||
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
|
vehicles: readonly CatalogueVehicle[],
|
||||||
|
query: BotPoolQuery,
|
||||||
|
aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
|
||||||
|
tankWeights?: TankLineupWeights,
|
||||||
|
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
|
||||||
): CustomBotsPool {
|
): CustomBotsPool {
|
||||||
const allowed = new Set(query.allowedClasses);
|
const allowed = new Set(query.allowedClasses);
|
||||||
const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))];
|
const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))];
|
||||||
const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [];
|
const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [];
|
||||||
|
const rawTanks = allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query, tankWeights) : [];
|
||||||
return {
|
return {
|
||||||
tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [],
|
tanks: tankLoadouts ? rawTanks.map((entry) => {
|
||||||
|
const tankLoadout = tankLoadouts.get(entry.name);
|
||||||
|
return tankLoadout === undefined ? entry : { ...entry, tankLoadout };
|
||||||
|
}) : rawTanks,
|
||||||
aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => {
|
aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => {
|
||||||
const aircraftLoadout = aircraftLoadouts.get(entry.name);
|
const aircraftLoadout = aircraftLoadouts.get(entry.name);
|
||||||
return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout };
|
return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout };
|
||||||
@@ -138,6 +161,7 @@ function pickCategoryPool(
|
|||||||
orderedCountries: readonly string[],
|
orderedCountries: readonly string[],
|
||||||
category: 'tank' | 'aircraft' | 'ship',
|
category: 'tank' | 'aircraft' | 'ship',
|
||||||
query: BotPoolQuery,
|
query: BotPoolQuery,
|
||||||
|
tankWeights?: TankLineupWeights,
|
||||||
): BotPoolEntry[] {
|
): BotPoolEntry[] {
|
||||||
const countrySet = new Set(orderedCountries);
|
const countrySet = new Set(orderedCountries);
|
||||||
const eligible = vehicles.filter((vehicle) =>
|
const eligible = vehicles.filter((vehicle) =>
|
||||||
@@ -161,13 +185,14 @@ function pickCategoryPool(
|
|||||||
return mrank >= query.minMrank && mrank <= query.maxMrank;
|
return mrank >= query.minMrank && mrank <= query.maxMrank;
|
||||||
});
|
});
|
||||||
const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType);
|
const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType);
|
||||||
return roundRobinByCountry(source, orderedCountries, query.limitPerType);
|
return roundRobinByCountry(source, orderedCountries, query.limitPerType, (vehicle) => tankPoolWeight(vehicle, tankWeights));
|
||||||
}
|
}
|
||||||
|
|
||||||
function roundRobinByCountry(
|
function roundRobinByCountry(
|
||||||
vehicles: readonly CatalogueVehicle[],
|
vehicles: readonly CatalogueVehicle[],
|
||||||
orderedCountries: readonly string[],
|
orderedCountries: readonly string[],
|
||||||
limit: number,
|
limit: number,
|
||||||
|
weightOf: (vehicle: CatalogueVehicle) => number,
|
||||||
): BotPoolEntry[] {
|
): BotPoolEntry[] {
|
||||||
const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []]));
|
const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []]));
|
||||||
for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle);
|
for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle);
|
||||||
@@ -177,7 +202,7 @@ function roundRobinByCountry(
|
|||||||
for (const country of orderedCountries) {
|
for (const country of orderedCountries) {
|
||||||
const vehicle = buckets.get(country)?.[index];
|
const vehicle = buckets.get(country)?.[index];
|
||||||
if (!vehicle) continue;
|
if (!vehicle) continue;
|
||||||
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 });
|
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: weightOf(vehicle) });
|
||||||
added = true;
|
added = true;
|
||||||
if (out.length >= limit) break;
|
if (out.length >= limit) break;
|
||||||
}
|
}
|
||||||
@@ -186,6 +211,16 @@ function roundRobinByCountry(
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function tankPoolWeight(vehicle: CatalogueVehicle, weights: TankLineupWeights | undefined): number {
|
||||||
|
if (weights === undefined) return 1;
|
||||||
|
if (vehicle.unitClass === 'exp_SPAA') return weights.spaa;
|
||||||
|
if (vehicle.isLightTank) return weights.lightTank;
|
||||||
|
if (vehicle.unitClass === 'exp_tank_destroyer') return weights.tankDestroyer;
|
||||||
|
if (vehicle.unitClass === 'exp_heavy_tank') return weights.heavyTank;
|
||||||
|
if (vehicle.unitClass === 'exp_tank') return weights.mediumTank;
|
||||||
|
return weights.other;
|
||||||
|
}
|
||||||
|
|
||||||
function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined {
|
function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined {
|
||||||
if (type === 'Tank') return 'tank';
|
if (type === 'Tank') return 'tank';
|
||||||
if (type === 'Aircraft') return 'aircraft';
|
if (type === 'Aircraft') return 'aircraft';
|
||||||
|
|||||||
@@ -17,10 +17,11 @@
|
|||||||
* the final scoreboard
|
* the final scoreboard
|
||||||
* strikes{ s{ time:r } ... } explosions of the local player's
|
* strikes{ s{ time:r } ... } explosions of the local player's
|
||||||
* nuclear bombs (native local_mp_nuke.c)
|
* nuclear bombs (native local_mp_nuke.c)
|
||||||
* spares{ <unit>:i ... } backup vehicles used
|
* spares{ spawn{ slot:i unit:t backup:t } ... } confirmed backup spawns
|
||||||
*/
|
*/
|
||||||
import { findBlock, type BlkBlock } from '@wto/blk';
|
import { findBlock, type BlkBlock } from '@wto/blk';
|
||||||
import type { CombatEventFact } from './battle-economy.ts';
|
import type { CombatEventFact } from './battle-economy.ts';
|
||||||
|
import type { BackupSpawn } from './battle-spares.ts';
|
||||||
|
|
||||||
export type BattleOutcomeKind = 'win' | 'lose' | 'running';
|
export type BattleOutcomeKind = 'win' | 'lose' | 'running';
|
||||||
|
|
||||||
@@ -83,7 +84,7 @@ export interface BattleReport {
|
|||||||
readonly players: readonly ScoreboardPlayer[];
|
readonly players: readonly ScoreboardPlayer[];
|
||||||
/** Mission times at which the local player's nuclear bombs exploded. */
|
/** Mission times at which the local player's nuclear bombs exploded. */
|
||||||
readonly nuclearStrikes: readonly number[];
|
readonly nuclearStrikes: readonly number[];
|
||||||
readonly usedSpares: Readonly<Record<string, number>>;
|
readonly spareSpawns: readonly BackupSpawn[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Undefined when the report is malformed; lives and events that make no sense are dropped. */
|
/** Undefined when the report is malformed; lives and events that make no sense are dropped. */
|
||||||
@@ -139,19 +140,15 @@ export function parseBattleReport(payload: BlkBlock): BattleReport | undefined {
|
|||||||
...Object.fromEntries(SCOREBOARD_FIELDS.map((field) => [field, Math.max(0, intOf(block, field))])) as Record<(typeof SCOREBOARD_FIELDS)[number], number>,
|
...Object.fromEntries(SCOREBOARD_FIELDS.map((field) => [field, Math.max(0, intOf(block, field))])) as Record<(typeof SCOREBOARD_FIELDS)[number], number>,
|
||||||
})),
|
})),
|
||||||
nuclearStrikes: (findBlock(payload, 'strikes')?.blocks ?? []).map((block) => realOf(block, 'time')).sort((a, b) => a - b),
|
nuclearStrikes: (findBlock(payload, 'strikes')?.blocks ?? []).map((block) => realOf(block, 'time')).sort((a, b) => a - b),
|
||||||
usedSpares: parseSpareMap(findBlock(payload, 'spares')),
|
spareSpawns: (findBlock(payload, 'spares')?.blocks ?? []).flatMap((block): BackupSpawn[] => {
|
||||||
|
const slot = intOf(block, 'slot', -1);
|
||||||
|
const unit = strOf(block, 'unit');
|
||||||
|
const backup = strOf(block, 'backup');
|
||||||
|
return slot >= 0 && unit && backup ? [{ slot, unit, backup }] : [];
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseSpareMap(sparesBlk: BlkBlock | undefined): Record<string, number> {
|
|
||||||
const out: Record<string, number> = {};
|
|
||||||
for (const param of sparesBlk?.params ?? []) {
|
|
||||||
const count = param.value.type === 'int' ? param.value.value : 0;
|
|
||||||
if (param.name && count > 0) out[param.name] = count;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
function strOf(block: BlkBlock, name: string): string | undefined {
|
function strOf(block: BlkBlock, name: string): string | undefined {
|
||||||
const value = block.params.find((p) => p.name === name)?.value;
|
const value = block.params.find((p) => p.name === name)?.value;
|
||||||
return value?.type === 'string' && value.value !== '' ? value.value : undefined;
|
return value?.type === 'string' && value.value !== '' ? value.value : undefined;
|
||||||
|
|||||||
@@ -9,7 +9,8 @@
|
|||||||
* container.aircraftsRepaired{ aname<i>:t cost<i>:i } and container.wpExpensesCompensation:i
|
* container.aircraftsRepaired{ aname<i>:t cost<i>:i } and container.wpExpensesCompensation:i
|
||||||
* (userlogviewdata.nut "damaged vehicles", "automatic repair", "expenses compensation").
|
* (userlogviewdata.nut "damaged vehicles", "automatic repair", "expenses compensation").
|
||||||
*/
|
*/
|
||||||
import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
import { emptyBlock, findBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
||||||
|
import { intField, int64Field } from '../profile/blk-fields.ts';
|
||||||
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
|
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
|
||||||
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
||||||
import type { DebriefingRow } from './battle-economy.ts';
|
import type { DebriefingRow } from './battle-economy.ts';
|
||||||
@@ -18,6 +19,11 @@ import type { ResearchPointsUnit } from './battle-rp-investment.ts';
|
|||||||
import type { AutoRepair, VehicleDamage } from './battle-repair.ts';
|
import type { AutoRepair, VehicleDamage } from './battle-repair.ts';
|
||||||
import type { BattleSession } from './battle-session-store.ts';
|
import type { BattleSession } from './battle-session-store.ts';
|
||||||
|
|
||||||
|
export function hasBattleResultLog(profile: BlkBlock, roomId: bigint): boolean {
|
||||||
|
return findBlock(profile, 'userlogs')?.blocks.some((log) =>
|
||||||
|
intField(log, 'type') === EULT_SESSION_RESULT && int64Field(log, 'roomId') === roomId) ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
export interface EarnedRpItem {
|
export interface EarnedRpItem {
|
||||||
readonly unit: string;
|
readonly unit: string;
|
||||||
readonly modification?: string;
|
readonly modification?: string;
|
||||||
@@ -58,6 +64,8 @@ const CONTAINER_OF_ROW: Readonly<Record<DebriefingRow, string | undefined>> = {
|
|||||||
Critical: 'eventCriticalHit',
|
Critical: 'eventCriticalHit',
|
||||||
Hit: 'eventHit',
|
Hit: 'eventHit',
|
||||||
Captures: 'eventCaptureZone',
|
Captures: 'eventCaptureZone',
|
||||||
|
Damage: 'eventDamageZone',
|
||||||
|
Destruction: 'eventDestroyZone',
|
||||||
// No user log list carries naval damage awards; they show in the debriefing table only.
|
// No user log list carries naval damage awards; they show in the debriefing table only.
|
||||||
AwardDamage: undefined,
|
AwardDamage: undefined,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ export interface BattleRewards {
|
|||||||
|
|
||||||
export interface RewardContext {
|
export interface RewardContext {
|
||||||
readonly difficulty: EconomyDifficulty;
|
readonly difficulty: EconomyDifficulty;
|
||||||
|
readonly modeName: string;
|
||||||
/** The mode's economic name, which selects rank.blk ExpSkillBonus. */
|
/** The mode's economic name, which selects rank.blk ExpSkillBonus. */
|
||||||
readonly economicName: string;
|
readonly economicName: string;
|
||||||
readonly premiumAccount: boolean;
|
readonly premiumAccount: boolean;
|
||||||
@@ -133,7 +134,7 @@ export function computeBattleRewards(report: BattleReport, economy: BattleEconom
|
|||||||
|
|
||||||
const events: SettledEvent[] = [];
|
const events: SettledEvent[] = [];
|
||||||
for (const event of report.events) {
|
for (const event of report.events) {
|
||||||
const priced = economy.price(event.unit, ctx.difficulty, event);
|
const priced = economy.price(event.unit, ctx.difficulty, ctx.modeName, event);
|
||||||
if (!priced) continue;
|
if (!priced) continue;
|
||||||
events.push({ event, priced, bonuses: add(event.unit, priced.row, priced.count, priced.wp, priced.exp, ctx.boosters.forEvent(event)) });
|
events.push({ event, priced, bonuses: add(event.unit, priced.row, priced.count, priced.wp, priced.exp, ctx.boosters.forEvent(event)) });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ export interface BattleSession {
|
|||||||
readonly missionLocName?: string;
|
readonly missionLocName?: string;
|
||||||
readonly country: string;
|
readonly country: string;
|
||||||
readonly startedAtSec: number;
|
readonly startedAtSec: number;
|
||||||
|
/** Owned lineup slots that may use a backup in this session. Filled when launch is sent. */
|
||||||
|
spareSlots?: ReadonlyMap<number, string>;
|
||||||
settled: boolean;
|
settled: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import { autoRepairVehicles, damageBattleVehicles, expensesCompensation } from '
|
|||||||
import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts';
|
import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts';
|
||||||
import { computeBattleRewards, type VehicleRewards } from './battle-rewards.ts';
|
import { computeBattleRewards, type VehicleRewards } from './battle-rewards.ts';
|
||||||
import { investBattleRp, type VehicleRp } from './battle-rp-investment.ts';
|
import { investBattleRp, type VehicleRp } from './battle-rp-investment.ts';
|
||||||
|
import { consumeBattleSpares } from './battle-spares.ts';
|
||||||
import { appendStreakLogs } from './battle-streak-log.ts';
|
import { appendStreakLogs } from './battle-streak-log.ts';
|
||||||
import type { BattleStreaks } from './battle-streaks.ts';
|
import type { BattleStreaks } from './battle-streaks.ts';
|
||||||
import type { BattleSession } from './battle-session-store.ts';
|
import type { BattleSession } from './battle-session-store.ts';
|
||||||
@@ -64,6 +65,7 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
|
|||||||
const premiumAccount = remainingPremiumDays(profile, now) > 0;
|
const premiumAccount = remainingPremiumDays(profile, now) > 0;
|
||||||
const rewards = computeBattleRewards(report, deps.economy, {
|
const rewards = computeBattleRewards(report, deps.economy, {
|
||||||
difficulty,
|
difficulty,
|
||||||
|
modeName: session.modeName,
|
||||||
economicName: session.economicName,
|
economicName: session.economicName,
|
||||||
premiumAccount,
|
premiumAccount,
|
||||||
hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN),
|
hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN),
|
||||||
@@ -120,13 +122,14 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
|
|||||||
if (compensation > 0) addSilverLions(profile, compensation);
|
if (compensation > 0) addSilverLions(profile, compensation);
|
||||||
|
|
||||||
const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks, compensation);
|
const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks, compensation);
|
||||||
|
const usedSpares = consumeBattleSpares(profile, session, report.spareSpawns, deps.items, deps.research.techTree);
|
||||||
appendStreakLogs(profile, session, streaks);
|
appendStreakLogs(profile, session, streaks);
|
||||||
appendBattleResultLog(profile, session, {
|
appendBattleResultLog(profile, session, {
|
||||||
country: session.country.startsWith('country_') ? session.country : `country_${session.country}`,
|
country: session.country.startsWith('country_') ? session.country : `country_${session.country}`,
|
||||||
rewards,
|
rewards,
|
||||||
unlocksWp: unlocks.wp,
|
unlocksWp: unlocks.wp,
|
||||||
weaponRefillSl,
|
weaponRefillSl,
|
||||||
usedSpares: report.usedSpares,
|
usedSpares,
|
||||||
rpItems: mergeEarnedRpItems(research.rpItems),
|
rpItems: mergeEarnedRpItems(research.rpItems),
|
||||||
researchUnits: research.units,
|
researchUnits: research.units,
|
||||||
affectedBoosters: boosters.applied.map((booster) => booster.id),
|
affectedBoosters: boosters.applied.map((booster) => booster.id),
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import type { BlkBlock } from '@wto/blk';
|
||||||
|
import type { ItemCatalogue } from '../items/item-catalogue.ts';
|
||||||
|
import { applyUniversalSpares } from '../items/universal-spares.ts';
|
||||||
|
import { dailySparesLeft, recordDailySpare, usedDailySpare } from '../profile/profile-daily-spares.ts';
|
||||||
|
import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts';
|
||||||
|
import type { TechTree } from '../research/tech-tree.ts';
|
||||||
|
import type { BattleSession } from './battle-session-store.ts';
|
||||||
|
|
||||||
|
/** LocalMP uses a source token for an attached backup and the stock UID for an inventory item. */
|
||||||
|
const VEHICLE_BACKUP = 'vehicle';
|
||||||
|
export const DAILY_BACKUP = 'daily_free_spare';
|
||||||
|
|
||||||
|
export interface BackupSpawn {
|
||||||
|
readonly slot: number;
|
||||||
|
readonly unit: string;
|
||||||
|
readonly backup: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function receiptKey(session: BattleSession, slot: number): string {
|
||||||
|
return `${session.sessionId}_${slot}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function recordDailyBackupSpawn(profile: BlkBlock, session: BattleSession, spawn: BackupSpawn): boolean {
|
||||||
|
return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === spawn.unit
|
||||||
|
&& recordDailySpare(profile, session.startedAtSec, receiptKey(session, spawn.slot));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Debit confirmed backup spawns from the lineup that the server sent at launch. */
|
||||||
|
export function consumeBattleSpares(
|
||||||
|
profile: BlkBlock, session: BattleSession, spawns: readonly BackupSpawn[], items: ItemCatalogue, techTree: TechTree,
|
||||||
|
): Readonly<Record<string, number>> {
|
||||||
|
const seenSlots = new Set<number>();
|
||||||
|
const consumed = new Map<string, number>();
|
||||||
|
for (const spawn of spawns) {
|
||||||
|
const { slot, unit, backup } = spawn;
|
||||||
|
if (session.spareSlots?.get(slot) !== unit || seenSlots.has(slot)) continue;
|
||||||
|
seenSlots.add(slot);
|
||||||
|
if (backup === DAILY_BACKUP) {
|
||||||
|
recordDailyBackupSpawn(profile, session, spawn);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (dailySparesLeft(profile, session.startedAtSec) > 0
|
||||||
|
|| usedDailySpare(profile, session.startedAtSec, receiptKey(session, slot))) continue;
|
||||||
|
if (backup !== VEHICLE_BACKUP && !applyUniversalSpares(profile, items, techTree, backup, unit, 1).ok) continue;
|
||||||
|
const owned = spareCount(profile, unit);
|
||||||
|
if (owned < 1) continue;
|
||||||
|
setSpareCount(profile, unit, owned - 1);
|
||||||
|
consumed.set(unit, (consumed.get(unit) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
return Object.fromEntries(consumed);
|
||||||
|
}
|
||||||
@@ -175,7 +175,8 @@ export function evaluateStreaks(definitions: readonly StreakDefinition[], facts:
|
|||||||
for (const time of facts.nuclearStrikes) award(def, time, 1);
|
for (const time of facts.nuclearStrikes) award(def, time, 1);
|
||||||
break;
|
break;
|
||||||
case 'firstKill': {
|
case 'firstKill': {
|
||||||
const first = facts.feed.find((k) => k.killerTeam !== k.victimTeam);
|
// Ignore non-player mission units (air defense SAM/AAA, NPCs) whose HUD feed killer id is -1.
|
||||||
|
const first = facts.feed.find((k) => k.killer >= 0 && k.killerTeam !== k.victimTeam);
|
||||||
if (first && first.killer === facts.localPlayerId) award(def, first.time, 1);
|
if (first && first.killer === facts.localPlayerId) award(def, first.time, 1);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ export interface BattleTuning {
|
|||||||
readonly strikeUcavSpawnScore: number;
|
readonly strikeUcavSpawnScore: number;
|
||||||
readonly tankBotRespawns: number;
|
readonly tankBotRespawns: number;
|
||||||
readonly airBotRespawns: number;
|
readonly airBotRespawns: number;
|
||||||
|
readonly nuclearEscalationStrategicBombers: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function readBattleTuning(reader: TuningReader): BattleTuning {
|
export function readBattleTuning(reader: TuningReader): BattleTuning {
|
||||||
@@ -66,5 +67,6 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
|
|||||||
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
|
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
|
||||||
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
|
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
|
||||||
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
|
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
|
||||||
|
nuclearEscalationStrategicBombers: reader.bool('nuclearEscalationStrategicBombers'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
/**
|
||||||
|
* Offline AI tank spawn ammunition selector:
|
||||||
|
* - Total carried rounds follow the vehicle's first-stage / autoloader ready rack, topped up
|
||||||
|
* when below the configured threshold (clamped to main gun capacity).
|
||||||
|
* - Primary shell prefers legal APFSDS, otherwise ranks anti-armor shells by 500 m penetration.
|
||||||
|
* - Secondary shell carries a small share of HE / HEAT / HESH when available for soft targets.
|
||||||
|
*/
|
||||||
|
import type { GroundAiLoadoutConfig } from '@wto/patcher';
|
||||||
|
import type { TankAmmoProfile, TankBotAmmoData, TankShellChoice } from '../game-data/datasets/tank-bot-ammo.ts';
|
||||||
|
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||||
|
import { vehicleTypeOfClass } from '../research/vehicle-types.ts';
|
||||||
|
|
||||||
|
export interface BotTankBulletSlot {
|
||||||
|
readonly modName: string;
|
||||||
|
readonly count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BotTankLoadout {
|
||||||
|
readonly weaponName: string;
|
||||||
|
readonly bullets: readonly BotTankBulletSlot[];
|
||||||
|
readonly modifications: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectBotTankLoadouts(
|
||||||
|
vehicles: readonly CatalogueVehicle[],
|
||||||
|
ammoData: TankBotAmmoData,
|
||||||
|
config: GroundAiLoadoutConfig,
|
||||||
|
): ReadonlyMap<string, BotTankLoadout> {
|
||||||
|
const result = new Map<string, BotTankLoadout>();
|
||||||
|
for (const vehicle of vehicles) {
|
||||||
|
if (vehicleTypeOfClass(vehicle.unitClass) !== 'Tank' || vehicle.unitClass === 'exp_SPAA') continue;
|
||||||
|
const profile = ammoData[vehicle.name];
|
||||||
|
if (!profile || profile.isBelt || profile.maxBullets <= 0) continue;
|
||||||
|
const loadout = chooseTankLoadout(profile, config);
|
||||||
|
if (loadout !== undefined) result.set(vehicle.name, loadout);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function chooseTankLoadout(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): BotTankLoadout | undefined {
|
||||||
|
const combatShells = profile.shells.filter((shell) => !isNonCombatShell(shell.bulletType));
|
||||||
|
if (combatShells.length === 0) return undefined;
|
||||||
|
|
||||||
|
const primary = pickPrimaryShell(combatShells);
|
||||||
|
if (!primary) return undefined;
|
||||||
|
const totalRounds = computeCarriedRounds(profile, config);
|
||||||
|
if (totalRounds <= 0) return undefined;
|
||||||
|
|
||||||
|
const secondary = pickSecondaryShell(combatShells, primary);
|
||||||
|
const bullets = splitRounds(primary, secondary, totalRounds, config);
|
||||||
|
const modSet = new Set<string>();
|
||||||
|
for (const chosen of [primary, ...(bullets.length > 1 && secondary ? [secondary] : [])]) {
|
||||||
|
if (chosen.modName) modSet.add(chosen.modName);
|
||||||
|
for (const req of chosen.requires) modSet.add(req);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
weaponName: profile.weaponName,
|
||||||
|
bullets,
|
||||||
|
modifications: [...modSet].sort(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeCarriedRounds(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): number {
|
||||||
|
const want = profile.readyRack >= config.lowReadyRackThreshold
|
||||||
|
? profile.readyRack
|
||||||
|
: config.topUpAmmoCount;
|
||||||
|
return Math.max(1, Math.min(want, profile.maxBullets));
|
||||||
|
}
|
||||||
|
|
||||||
|
function pickPrimaryShell(shells: readonly TankShellChoice[]): TankShellChoice | undefined {
|
||||||
|
const ranked = [...shells].sort((a, b) => compareAntiArmor(a, b));
|
||||||
|
return ranked[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareAntiArmor(a: TankShellChoice, b: TankShellChoice): number {
|
||||||
|
const tierA = antiArmorTier(a.bulletType);
|
||||||
|
const tierB = antiArmorTier(b.bulletType);
|
||||||
|
if (tierA !== tierB) return tierB - tierA;
|
||||||
|
const scoreA = a.pen500Mm + (isApheFamily(a.bulletType) ? 12 : 0);
|
||||||
|
const scoreB = b.pen500Mm + (isApheFamily(b.bulletType) ? 12 : 0);
|
||||||
|
if (scoreA !== scoreB) return scoreB - scoreA;
|
||||||
|
if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps;
|
||||||
|
return a.modName.localeCompare(b.modName);
|
||||||
|
}
|
||||||
|
|
||||||
|
function antiArmorTier(bulletType: string): number {
|
||||||
|
if (bulletType.includes('apds_fs')) return 5;
|
||||||
|
if (bulletType.includes('atgm')) return 4;
|
||||||
|
if (bulletType.includes('apds')) return 3;
|
||||||
|
if (bulletType.includes('heat') || isApheFamily(bulletType) || bulletType.startsWith('ap')) return 2;
|
||||||
|
if (bulletType.includes('hesh')) return 1;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pickSecondaryShell(shells: readonly TankShellChoice[], primary: TankShellChoice): TankShellChoice | undefined {
|
||||||
|
const candidates = shells.filter((shell) => shell.modName !== primary.modName && isSoftTargetShell(shell.bulletType));
|
||||||
|
if (candidates.length === 0) return undefined;
|
||||||
|
return [...candidates].sort((a, b) => {
|
||||||
|
const heA = a.bulletType.includes('he_frag') ? 2 : (a.bulletType.includes('hesh') ? 1 : 0);
|
||||||
|
const heB = b.bulletType.includes('he_frag') ? 2 : (b.bulletType.includes('hesh') ? 1 : 0);
|
||||||
|
if (heA !== heB) return heB - heA;
|
||||||
|
if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps;
|
||||||
|
return a.modName.localeCompare(b.modName);
|
||||||
|
})[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitRounds(
|
||||||
|
primary: TankShellChoice,
|
||||||
|
secondary: TankShellChoice | undefined,
|
||||||
|
totalRounds: number,
|
||||||
|
config: GroundAiLoadoutConfig,
|
||||||
|
): BotTankBulletSlot[] {
|
||||||
|
if (!secondary || config.primaryAmmoPct >= 100 || config.secondaryMinRounds <= 0 || totalRounds < config.secondaryMinRounds * 2 + 2) {
|
||||||
|
return [{ modName: primary.modName, count: totalRounds }];
|
||||||
|
}
|
||||||
|
const wantSec = Math.round((totalRounds * (100 - config.primaryAmmoPct)) / 100);
|
||||||
|
const secCount = Math.min(totalRounds - 1, Math.max(config.secondaryMinRounds, wantSec));
|
||||||
|
const priCount = totalRounds - secCount;
|
||||||
|
return [
|
||||||
|
{ modName: primary.modName, count: priCount },
|
||||||
|
{ modName: secondary.modName, count: secCount },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNonCombatShell(bulletType: string): boolean {
|
||||||
|
return bulletType.includes('smoke') || bulletType.includes('practice') || bulletType.includes('shrapnel');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSoftTargetShell(bulletType: string): boolean {
|
||||||
|
return bulletType.includes('he_frag') || bulletType.includes('hesh') || bulletType.includes('heat');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isApheFamily(bulletType: string): boolean {
|
||||||
|
return bulletType.includes('aphe') || bulletType.includes('apcbc') || bulletType.includes('apbc');
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue
|
|||||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||||
import type { ResearchRules } from '../../research/research-rules.ts';
|
import type { ResearchRules } from '../../research/research-rules.ts';
|
||||||
import type { StoreCatalogue } from '../../store/store-catalogue.ts';
|
import type { StoreCatalogue } from '../../store/store-catalogue.ts';
|
||||||
|
import type { TrainingCatalogue } from '../../training/training-completion.ts';
|
||||||
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
|
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
|
||||||
import type { CharActionHandler } from '../char-action.ts';
|
import type { CharActionHandler } from '../char-action.ts';
|
||||||
import { acceptEula } from './agreement-actions.ts';
|
import { acceptEula } from './agreement-actions.ts';
|
||||||
@@ -94,6 +95,7 @@ export interface ActionDependencies {
|
|||||||
readonly store: StoreCatalogue;
|
readonly store: StoreCatalogue;
|
||||||
readonly inventory: InventoryCatalogue;
|
readonly inventory: InventoryCatalogue;
|
||||||
readonly trophies: TrophyCatalogue;
|
readonly trophies: TrophyCatalogue;
|
||||||
|
readonly training?: TrainingCatalogue;
|
||||||
readonly clans?: ClanActionDependencies;
|
readonly clans?: ClanActionDependencies;
|
||||||
readonly cloudSettings?: CloudSettingsStore;
|
readonly cloudSettings?: CloudSettingsStore;
|
||||||
readonly battle?: BattleActionDependencies;
|
readonly battle?: BattleActionDependencies;
|
||||||
@@ -118,7 +120,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
|
|||||||
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
|
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
|
||||||
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
|
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
|
||||||
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
|
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
|
||||||
['cln_update', clientUpdateAction(deps.profiles, deps.accounts)],
|
['cln_update', clientUpdateAction(deps.profiles, deps.accounts, deps.training)],
|
||||||
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
|
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
|
||||||
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
|
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
|
||||||
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
|
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
|
||||||
|
|||||||
@@ -3,8 +3,10 @@
|
|||||||
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
|
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
|
||||||
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
|
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
|
||||||
*/
|
*/
|
||||||
|
import type { BattleSettlementContext } from '@wto/mods';
|
||||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||||
import { parseBattleReport } from '../../battle/battle-report.ts';
|
import { parseBattleReport } from '../../battle/battle-report.ts';
|
||||||
|
import { hasBattleResultLog } from '../../battle/battle-result-log.ts';
|
||||||
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
|
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
|
||||||
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
|
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
|
||||||
import type { BattleEconomy } from '../../battle/battle-economy.ts';
|
import type { BattleEconomy } from '../../battle/battle-economy.ts';
|
||||||
@@ -28,6 +30,7 @@ export interface BattleActionDependencies {
|
|||||||
readonly streaks: BattleStreaks;
|
readonly streaks: BattleStreaks;
|
||||||
/** Units whose lives and events are not settled (battle-support-planes.ts). */
|
/** Units whose lives and events are not settled (battle-support-planes.ts). */
|
||||||
readonly supportPlanes: ReadonlySet<string>;
|
readonly supportPlanes: ReadonlySet<string>;
|
||||||
|
readonly onAfterSettle?: (ctx: BattleSettlementContext) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FinishBattleContext {
|
export interface FinishBattleContext {
|
||||||
@@ -60,10 +63,19 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
|
|||||||
if (session.settled) {
|
if (session.settled) {
|
||||||
return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) };
|
return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) };
|
||||||
}
|
}
|
||||||
const updated = ctx.profiles.update(account.userId, (profile) => {
|
const updated = ctx.profiles.updateWhen(account.userId, (profile) => {
|
||||||
|
// The result log and expenses are written together. A retry can arrive after the profile
|
||||||
|
// was saved but before the session was marked settled.
|
||||||
|
if (hasBattleResultLog(profile, session.roomId)) return false;
|
||||||
settleBattle(profile, report, session, settlementDeps);
|
settleBattle(profile, report, session, settlementDeps);
|
||||||
|
battle.onAfterSettle?.({
|
||||||
|
userId: account.userId,
|
||||||
|
roomId: session.sessionId,
|
||||||
|
summary: { profile, report, session },
|
||||||
|
});
|
||||||
|
return true;
|
||||||
});
|
});
|
||||||
battle.sessions.markSettled(session.sessionId);
|
battle.sessions.markSettled(session.sessionId);
|
||||||
return { kind: 'data', blk: clientProfile(updated, account) };
|
return { kind: 'data', blk: clientProfile(updated ?? ctx.profiles.profileOf(account.userId), account) };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -2,19 +2,48 @@
|
|||||||
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
|
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
|
||||||
* triggered by `save_online_single_job` when the client marks seen user logs as disabled
|
* triggered by `save_online_single_job` when the client marks seen user logs as disabled
|
||||||
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
|
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
|
||||||
* auto-repair / auto-refill / auto-buy-modifications and map preferences. Answers the whole
|
* auto-repair / auto-refill / auto-buy-modifications and map preferences. On returning from
|
||||||
* updated profile.
|
* a stock training mission, the client also reports completion in `missionAwards` while
|
||||||
|
* `pveProgress` is empty. Answers the whole updated profile.
|
||||||
*/
|
*/
|
||||||
|
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
|
||||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||||
|
import { boolField, stringField } from '../../game-data/datasets/blk-fields.ts';
|
||||||
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
|
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
|
||||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||||
import { ACCEPTED } from '../../research/rule-outcome.ts';
|
import { ACCEPTED } from '../../research/rule-outcome.ts';
|
||||||
|
import type { TrainingCatalogue, TrainingCompletionReport } from '../../training/training-completion.ts';
|
||||||
import type { CharActionHandler } from '../char-action.ts';
|
import type { CharActionHandler } from '../char-action.ts';
|
||||||
import { ruleAction } from './rule-answer.ts';
|
import { ruleAction } from './rule-answer.ts';
|
||||||
|
|
||||||
export function clientUpdateAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
|
export function clientUpdateAction(
|
||||||
return ruleAction(profiles, accounts, (payload) => (profile) => {
|
profiles: PlayerProfiles,
|
||||||
applyClientProfileUpdate(profile, payload);
|
accounts: AccountStore,
|
||||||
return ACCEPTED;
|
training?: TrainingCatalogue,
|
||||||
|
): CharActionHandler {
|
||||||
|
return ruleAction(profiles, accounts, (payload) => {
|
||||||
|
const completion = training ? readTrainingCompletion(payload) : undefined;
|
||||||
|
return (profile) => {
|
||||||
|
applyClientProfileUpdate(profile, payload);
|
||||||
|
if (completion && training) training.applyCompletion(profile, completion);
|
||||||
|
return ACCEPTED;
|
||||||
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readTrainingCompletion(request: BlkBlock): TrainingCompletionReport | undefined {
|
||||||
|
const awards = findBlock(request, 'missionAwards');
|
||||||
|
if (!awards
|
||||||
|
|| stringField(awards, 'gameModeName') !== 'training'
|
||||||
|
|| boolField(awards, 'success') !== true
|
||||||
|
|| boolField(awards, 'early') !== false
|
||||||
|
|| boolField(awards, 'onlineGame') !== false) return undefined;
|
||||||
|
|
||||||
|
const chapter = stringField(awards, 'chapterName');
|
||||||
|
const mission = stringField(awards, 'missionName');
|
||||||
|
const difficulty = findParam(awards, 'difficulty')?.value;
|
||||||
|
if (!chapter || !mission || difficulty?.type !== 'int'
|
||||||
|
|| (difficulty.value !== 0 && difficulty.value !== 1 && difficulty.value !== 2)) return undefined;
|
||||||
|
|
||||||
|
return { chapter, mission, difficulty: difficulty.value };
|
||||||
|
}
|
||||||
@@ -13,6 +13,8 @@
|
|||||||
* default lets the client continue and reveal what it asks for next.
|
* default lets the client continue and reveal what it asks for next.
|
||||||
*/
|
*/
|
||||||
import { emptyBlock } from '@wto/blk';
|
import { emptyBlock } from '@wto/blk';
|
||||||
|
import type { ModCharRequest, ModCharResponse } from '@wto/mods';
|
||||||
|
import type { ServerModRuntime } from '../mods/server-mod-runtime.ts';
|
||||||
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
|
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
|
||||||
import type { CharActionHandler } from './char-action.ts';
|
import type { CharActionHandler } from './char-action.ts';
|
||||||
import { toResponse, type CharAnswer } from './char-answers.ts';
|
import { toResponse, type CharAnswer } from './char-answers.ts';
|
||||||
@@ -23,17 +25,26 @@ const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
|
|||||||
export class CharService implements Service {
|
export class CharService implements Service {
|
||||||
readonly name = 'char';
|
readonly name = 'char';
|
||||||
readonly #actions: ReadonlyMap<string, CharActionHandler>;
|
readonly #actions: ReadonlyMap<string, CharActionHandler>;
|
||||||
|
readonly #modRuntime: ServerModRuntime | undefined;
|
||||||
|
|
||||||
constructor(actions: ReadonlyMap<string, CharActionHandler>) {
|
constructor(actions: ReadonlyMap<string, CharActionHandler>, modRuntime?: ServerModRuntime) {
|
||||||
this.#actions = actions;
|
this.#actions = actions;
|
||||||
|
this.#modRuntime = modRuntime;
|
||||||
}
|
}
|
||||||
|
|
||||||
accepts(request: ServiceRequest): boolean {
|
accepts(request: ServiceRequest): boolean {
|
||||||
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
|
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
|
||||||
}
|
}
|
||||||
|
|
||||||
handle(request: ServiceRequest): ServiceResponse {
|
handle(request: ServiceRequest): ServiceResponse | Promise<ServiceResponse> {
|
||||||
const action = header(request, 'action') ?? '(no action header)';
|
const action = header(request, 'action') ?? '(no action header)';
|
||||||
|
if (this.#modRuntime?.hasCharOverride(action)) {
|
||||||
|
return this.#handleWithModOverride(action, request);
|
||||||
|
}
|
||||||
|
return this.#handleCore(action, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
#handleCore(action: string, request: ServiceRequest): ServiceResponse {
|
||||||
const payload = decodeRequestPayload(request.body);
|
const payload = decodeRequestPayload(request.body);
|
||||||
const handler = this.#actions.get(action);
|
const handler = this.#actions.get(action);
|
||||||
const answer: CharAnswer = handler
|
const answer: CharAnswer = handler
|
||||||
@@ -56,6 +67,46 @@ export class CharService implements Service {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async #handleWithModOverride(action: string, request: ServiceRequest): Promise<ServiceResponse> {
|
||||||
|
const headers: Record<string, string | undefined> = {};
|
||||||
|
for (const [key, value] of Object.entries(request.headers)) {
|
||||||
|
headers[key] = Array.isArray(value) ? value[0] : value;
|
||||||
|
}
|
||||||
|
const query: Record<string, string> = {};
|
||||||
|
for (const [key, value] of request.query.entries()) query[key] = value;
|
||||||
|
|
||||||
|
const modReq: ModCharRequest = {
|
||||||
|
action,
|
||||||
|
userId: header(request, 'uidhint') ?? '',
|
||||||
|
headers,
|
||||||
|
body: request.body,
|
||||||
|
query,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await this.#modRuntime!.dispatchCharOverride(action, modReq, async (nextReq): Promise<ModCharResponse> => {
|
||||||
|
const forwarded: ServiceRequest = { ...request, body: nextReq.body };
|
||||||
|
const coreResp = this.#handleCore(nextReq.action, forwarded);
|
||||||
|
return {
|
||||||
|
status: coreResp.status,
|
||||||
|
...(coreResp.headers ? { headers: coreResp.headers } : {}),
|
||||||
|
body: coreResp.body ?? '',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const responseHeaders: Record<string, string> = { ...(result.headers ?? {}) };
|
||||||
|
if (result.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
|
||||||
|
responseHeaders['content-type'] = result.contentType;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: result.status ?? 200,
|
||||||
|
headers: responseHeaders,
|
||||||
|
body: result.body,
|
||||||
|
logNotes: {
|
||||||
|
summary: `${action} [mod handler] -> ${result.status ?? 200}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function header(request: ServiceRequest, name: string): string | undefined {
|
function header(request: ServiceRequest, name: string): string | undefined {
|
||||||
|
|||||||
+23
-2
@@ -7,24 +7,45 @@
|
|||||||
* will start the service the same way. Stops on Ctrl+C.
|
* will start the service the same way. Stops on Ctrl+C.
|
||||||
*/
|
*/
|
||||||
import { parseArgs } from 'node:util';
|
import { parseArgs } from 'node:util';
|
||||||
|
import { discoverMods, type DiscoveredMod } from '@wto/mods';
|
||||||
import { LOOPBACK, startServer } from './server.ts';
|
import { LOOPBACK, startServer } from './server.ts';
|
||||||
|
|
||||||
|
function resolveCliMods(modsDir: string | undefined, modIds: readonly string[] | undefined): DiscoveredMod[] {
|
||||||
|
if (!modsDir || !modIds || modIds.length === 0) return [];
|
||||||
|
const discovered = discoverMods(modsDir);
|
||||||
|
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||||
|
return modIds.map((id) => {
|
||||||
|
const mod = byId.get(id);
|
||||||
|
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
|
||||||
|
return mod;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async function main(): Promise<number> {
|
async function main(): Promise<number> {
|
||||||
const { values } = parseArgs({
|
const { values } = parseArgs({
|
||||||
options: {
|
options: {
|
||||||
game: { type: 'string' },
|
game: { type: 'string' },
|
||||||
data: { type: 'string' },
|
data: { type: 'string' },
|
||||||
port: { type: 'string' },
|
port: { type: 'string' },
|
||||||
|
'mods-dir': { type: 'string' },
|
||||||
|
mod: { type: 'string', multiple: true },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const port = Number(values.port);
|
const port = Number(values.port);
|
||||||
if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) {
|
if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||||
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n>');
|
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n> [--mods-dir <dir> --mod <id>...]');
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
let service;
|
let service;
|
||||||
try {
|
try {
|
||||||
service = await startServer({ gameFolder: values.game, dataFolder: values.data, port, report: (line) => console.log(line) });
|
const mods = resolveCliMods(values['mods-dir'], values.mod);
|
||||||
|
service = await startServer({
|
||||||
|
gameFolder: values.game,
|
||||||
|
dataFolder: values.data,
|
||||||
|
port,
|
||||||
|
report: (line) => console.log(line),
|
||||||
|
...(mods.length > 0 ? { mods } : {}),
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const code = (error as NodeJS.ErrnoException).code;
|
const code = (error as NodeJS.ErrnoException).code;
|
||||||
console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error));
|
console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error));
|
||||||
|
|||||||
@@ -14,12 +14,14 @@
|
|||||||
* char.vromfs.bin config/wpcost.blk
|
* char.vromfs.bin config/wpcost.blk
|
||||||
* ucav_*_killstreak{ country:t ... }
|
* ucav_*_killstreak{ country:t ... }
|
||||||
* The strike UCAVs, one per country.
|
* The strike UCAVs, one per country.
|
||||||
|
* *_killstreak / nt_* with weapons.<preset>.totalNuclearYield:i
|
||||||
|
* Tactical (5 kt / 30 kt) and strategic (>= 1000 kt) nuclear carriers for Nuclear Escalation.
|
||||||
* char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical
|
* char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical
|
||||||
* Starting points and unit cost parameters for Ground Realistic Battles.
|
* Starting points and unit cost parameters for Ground Realistic Battles.
|
||||||
*/
|
*/
|
||||||
import type { BlkBlock } from '@wto/blk';
|
import type { BlkBlock } from '@wto/blk';
|
||||||
import { findParam } from '@wto/blk';
|
import { findParam } from '@wto/blk';
|
||||||
import { blockAt, numberField, stringField, stringList } from './blk-fields.ts';
|
import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts';
|
||||||
import type { Dataset } from './dataset.ts';
|
import type { Dataset } from './dataset.ts';
|
||||||
|
|
||||||
export interface SupportPlaneUnit {
|
export interface SupportPlaneUnit {
|
||||||
@@ -43,6 +45,18 @@ export interface StrikeUcav {
|
|||||||
readonly unitName: string;
|
readonly unitName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface NuclearCarrierWeapon {
|
||||||
|
readonly name: string;
|
||||||
|
readonly yieldKt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NuclearCarrierUnit {
|
||||||
|
readonly country: string;
|
||||||
|
readonly unitName: string;
|
||||||
|
readonly mrank: number;
|
||||||
|
readonly weapons: readonly NuclearCarrierWeapon[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface RandomSpawnUnit {
|
export interface RandomSpawnUnit {
|
||||||
readonly unitName: string;
|
readonly unitName: string;
|
||||||
readonly addModifications: readonly string[];
|
readonly addModifications: readonly string[];
|
||||||
@@ -76,22 +90,31 @@ export interface BattleSpawnRulesData {
|
|||||||
/** By event name (`missionSupportPlane` keys are game mode names). */
|
/** By event name (`missionSupportPlane` keys are game mode names). */
|
||||||
readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>;
|
readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>;
|
||||||
readonly strikeUcavs: readonly StrikeUcav[];
|
readonly strikeUcavs: readonly StrikeUcav[];
|
||||||
|
/** Killstreak nuclear carriers carrying 5 kt / 30 kt Nuclear Escalation presets. */
|
||||||
|
readonly nuclearEscalationTacticalCarriers: readonly NuclearCarrierUnit[];
|
||||||
|
/** Megaton-class strategic nuclear bombers (`nt_*` with totalNuclearYield >= 1000 kt). */
|
||||||
|
readonly nuclearEscalationStrategicBombers: readonly NuclearCarrierUnit[];
|
||||||
readonly spawnScore: SpawnScoreRules;
|
readonly spawnScore: SpawnScoreRules;
|
||||||
/** By event economic name, then country. */
|
/** By event economic name, then country. */
|
||||||
readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>;
|
readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
|
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
|
||||||
|
const KILLSTREAK_PATTERN = /_killstreak$/;
|
||||||
|
const STRATEGIC_BOMBER_PATTERN = /^nt_/;
|
||||||
|
const STRATEGIC_YIELD_MIN_KT = 1000;
|
||||||
|
|
||||||
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
|
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
|
||||||
id: 'battle-spawn-rules',
|
id: 'battle-spawn-rules',
|
||||||
version: 3,
|
version: 4,
|
||||||
extract: (source) => {
|
extract: (source) => {
|
||||||
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
|
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
|
||||||
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
|
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
|
||||||
return {
|
return {
|
||||||
supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')),
|
supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')),
|
||||||
strikeUcavs: extractStrikeUcavs(wpcost.blocks),
|
strikeUcavs: extractStrikeUcavs(wpcost.blocks),
|
||||||
|
nuclearEscalationTacticalCarriers: extractNuclearCarriers(wpcost.blocks, 'tactical'),
|
||||||
|
nuclearEscalationStrategicBombers: extractNuclearCarriers(wpcost.blocks, 'strategic'),
|
||||||
spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')),
|
spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')),
|
||||||
randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')),
|
randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')),
|
||||||
};
|
};
|
||||||
@@ -162,6 +185,38 @@ function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcav[] {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function extractNuclearCarriers(
|
||||||
|
wpcostBlocks: readonly BlkBlock[],
|
||||||
|
kind: 'tactical' | 'strategic',
|
||||||
|
): NuclearCarrierUnit[] {
|
||||||
|
const carriers: NuclearCarrierUnit[] = [];
|
||||||
|
for (const unitBlk of wpcostBlocks) {
|
||||||
|
const country = stringField(unitBlk, 'country') ?? '';
|
||||||
|
if (!country.startsWith('country_')) continue;
|
||||||
|
if (kind === 'tactical' && !KILLSTREAK_PATTERN.test(unitBlk.name)) continue;
|
||||||
|
if (kind === 'strategic' && !STRATEGIC_BOMBER_PATTERN.test(unitBlk.name)) continue;
|
||||||
|
const weaponsBlk = blockAt(unitBlk, 'weapons');
|
||||||
|
if (!weaponsBlk) continue;
|
||||||
|
const weapons: NuclearCarrierWeapon[] = [];
|
||||||
|
for (const weaponBlk of weaponsBlk.blocks) {
|
||||||
|
if (boolField(weaponBlk, 'isWeaponForCustomSlot') === true) continue;
|
||||||
|
if (boolField(weaponBlk, 'hideInGui') === true) continue;
|
||||||
|
if (weaponBlk.name.includes('without_countermeasures')) continue;
|
||||||
|
const yieldKt = numberField(weaponBlk, 'totalNuclearYield') ?? 0;
|
||||||
|
if (yieldKt <= 0) continue;
|
||||||
|
if (kind === 'tactical' && yieldKt >= STRATEGIC_YIELD_MIN_KT) continue;
|
||||||
|
if (kind === 'strategic' && yieldKt < STRATEGIC_YIELD_MIN_KT) continue;
|
||||||
|
weapons.push({ name: weaponBlk.name, yieldKt });
|
||||||
|
}
|
||||||
|
if (weapons.length === 0) continue;
|
||||||
|
weapons.sort((a, b) => a.yieldKt - b.yieldKt || a.name.localeCompare(b.name));
|
||||||
|
const mrank = numberField(unitBlk, 'economicRankHistorical') ?? numberField(unitBlk, 'economicRank') ?? 0;
|
||||||
|
carriers.push({ country, unitName: unitBlk.name, mrank, weapons });
|
||||||
|
}
|
||||||
|
carriers.sort((a, b) => a.country.localeCompare(b.country) || a.mrank - b.mrank || a.unitName.localeCompare(b.unitName));
|
||||||
|
return carriers;
|
||||||
|
}
|
||||||
|
|
||||||
function extractRandomSpawnUnits(
|
function extractRandomSpawnUnits(
|
||||||
root: BlkBlock | undefined,
|
root: BlkBlock | undefined,
|
||||||
): Record<string, Record<string, RandomSpawnGroup[]>> {
|
): Record<string, Record<string, RandomSpawnGroup[]>> {
|
||||||
|
|||||||
@@ -41,9 +41,13 @@ interface AirfieldLayoutData {
|
|||||||
readonly airfieldLayoutProblem?: string;
|
readonly airfieldLayoutProblem?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type GroundBattleMode = 'bttl' | 'conq' | 'dom';
|
||||||
|
|
||||||
export interface MissionHeader extends AirfieldLayoutData {
|
export interface MissionHeader extends AirfieldLayoutData {
|
||||||
readonly name: string;
|
readonly name: string;
|
||||||
readonly path: string;
|
readonly path: string;
|
||||||
|
/** Ground mission tactical layout derived from mislist category (or suffix fallback for events). */
|
||||||
|
readonly groundMode?: GroundBattleMode;
|
||||||
readonly level?: string;
|
readonly level?: string;
|
||||||
readonly type?: string;
|
readonly type?: string;
|
||||||
readonly environment?: string;
|
readonly environment?: string;
|
||||||
@@ -72,7 +76,7 @@ export interface MultiplayerMissions {
|
|||||||
|
|
||||||
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
|
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
|
||||||
id: 'multiplayer-missions',
|
id: 'multiplayer-missions',
|
||||||
version: 4,
|
version: 5,
|
||||||
extract(source: DatasetSource): MultiplayerMissions {
|
extract(source: DatasetSource): MultiplayerMissions {
|
||||||
const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION);
|
const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION);
|
||||||
if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`);
|
if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`);
|
||||||
@@ -82,6 +86,7 @@ export const multiplayerMissions: Dataset<MultiplayerMissions> = {
|
|||||||
missions: stringList(block, 'm'),
|
missions: stringList(block, 'm'),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const groundModeByMission = indexGroundModes(categories);
|
||||||
const paths = source.listFiles('mis.vromfs.bin');
|
const paths = source.listFiles('mis.vromfs.bin');
|
||||||
const pathByName = missionPathsByLowerName(paths);
|
const pathByName = missionPathsByLowerName(paths);
|
||||||
const knownPaths = new Set(paths);
|
const knownPaths = new Set(paths);
|
||||||
@@ -94,12 +99,34 @@ export const multiplayerMissions: Dataset<MultiplayerMissions> = {
|
|||||||
const document = source.readBlk('mis.vromfs.bin', path);
|
const document = source.readBlk('mis.vromfs.bin', path);
|
||||||
const airfields = path.startsWith(AIR_HISTORICAL_MISSION_FOLDER)
|
const airfields = path.startsWith(AIR_HISTORICAL_MISSION_FOLDER)
|
||||||
? readAirfieldLayouts(source, document, knownPaths, airfieldsByPath) : { airfieldLayouts: [] };
|
? readAirfieldLayouts(source, document, knownPaths, airfieldsByPath) : { airfieldLayouts: [] };
|
||||||
missions[name] = readHeader(name, path, document, airfields);
|
const groundMode = groundModeByMission.get(name) ?? groundModeFromName(name);
|
||||||
|
missions[name] = readHeader(name, path, document, airfields, groundMode);
|
||||||
}
|
}
|
||||||
return { categories, missions };
|
return { categories, missions };
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function indexGroundModes(categories: readonly MissionCategory[]): Map<string, GroundBattleMode> {
|
||||||
|
const byName = new Map<string, GroundBattleMode>();
|
||||||
|
for (const category of categories) {
|
||||||
|
const mode: GroundBattleMode | undefined =
|
||||||
|
category.name === 'air_ground_Bttl' ? 'bttl'
|
||||||
|
: category.name === 'air_ground_Conq' ? 'conq'
|
||||||
|
: category.name === 'air_ground_Dom' ? 'dom'
|
||||||
|
: undefined;
|
||||||
|
if (!mode) continue;
|
||||||
|
for (const name of category.missions) if (!byName.has(name)) byName.set(name, mode);
|
||||||
|
}
|
||||||
|
return byName;
|
||||||
|
}
|
||||||
|
|
||||||
|
function groundModeFromName(name: string): GroundBattleMode | undefined {
|
||||||
|
if (/_Bttl\d*$/i.test(name)) return 'bttl';
|
||||||
|
if (/_Conq\d*$/i.test(name)) return 'conq';
|
||||||
|
if (/_Dom\d*$/i.test(name)) return 'dom';
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
function missionPathsByLowerName(paths: readonly string[]): Map<string, string> {
|
function missionPathsByLowerName(paths: readonly string[]): Map<string, string> {
|
||||||
const byName = new Map<string, string>();
|
const byName = new Map<string, string>();
|
||||||
const repeated = new Set<string>();
|
const repeated = new Set<string>();
|
||||||
@@ -114,11 +141,12 @@ function missionPathsByLowerName(paths: readonly string[]): Map<string, string>
|
|||||||
}
|
}
|
||||||
|
|
||||||
function readHeader(
|
function readHeader(
|
||||||
name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData,
|
name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData, groundMode?: GroundBattleMode,
|
||||||
): MissionHeader {
|
): MissionHeader {
|
||||||
const settings = blockAt(document, 'mission_settings');
|
const settings = blockAt(document, 'mission_settings');
|
||||||
const mission = blockAt(settings, 'mission');
|
const mission = blockAt(settings, 'mission');
|
||||||
const optional = {
|
const optional = {
|
||||||
|
groundMode,
|
||||||
level: stringField(mission, 'level'),
|
level: stringField(mission, 'level'),
|
||||||
type: stringField(mission, 'type'),
|
type: stringField(mission, 'type'),
|
||||||
environment: stringField(mission, 'environment'),
|
environment: stringField(mission, 'environment'),
|
||||||
|
|||||||
@@ -0,0 +1,244 @@
|
|||||||
|
/**
|
||||||
|
* Dataset: primary cannon weapon name, capacity, first-stage/autoloader ready-rack count,
|
||||||
|
* and selectable ammunition groups (with penetration and prerequisite modifications) for
|
||||||
|
* every ground tank model in `aces.vromfs.bin` + `char.vromfs.bin`.
|
||||||
|
*/
|
||||||
|
import { findBlock, type BlkBlock } from '@wto/blk';
|
||||||
|
import type { Dataset, DatasetSource } from './dataset.ts';
|
||||||
|
import { boolField, numberField, stringField, stringList } from './blk-fields.ts';
|
||||||
|
|
||||||
|
const VEHICLE_ECONOMY = 'config/wpcost.blk';
|
||||||
|
const MODIFICATIONS_CONFIG = 'config/modifications.blk';
|
||||||
|
const TANK_MODELS_PREFIX = 'gamedata/units/tankmodels/';
|
||||||
|
|
||||||
|
export interface TankShellChoice {
|
||||||
|
/** Modification name expected by ChangeUnitReflection.bullets[i] (`""` for stock default). */
|
||||||
|
readonly modName: string;
|
||||||
|
readonly bulletType: string;
|
||||||
|
readonly speedMps: number;
|
||||||
|
/** Estimated normal penetration at 500 m (mm) for deterministic ranking. */
|
||||||
|
readonly pen500Mm: number;
|
||||||
|
/** Transitive prerequisite modifications needed to unlock this shell. */
|
||||||
|
readonly requires: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TankAmmoProfile {
|
||||||
|
readonly weaponName: string;
|
||||||
|
readonly maxBullets: number;
|
||||||
|
readonly isBelt: boolean;
|
||||||
|
/** Total firstStage / autoLoad / ammoLoadedInGun shell slots (excluding separate charges). */
|
||||||
|
readonly readyRack: number;
|
||||||
|
readonly shells: readonly TankShellChoice[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TankBotAmmoData = Readonly<Record<string, TankAmmoProfile>>;
|
||||||
|
|
||||||
|
interface GlobalModInfo {
|
||||||
|
readonly bulletMod?: string;
|
||||||
|
readonly requires: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface WeaponBulletMeta {
|
||||||
|
readonly bulletType: string;
|
||||||
|
readonly speedMps: number;
|
||||||
|
readonly pen500Mm: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const tankBotAmmo: Dataset<TankBotAmmoData> = {
|
||||||
|
id: 'tank-bot-ammo',
|
||||||
|
version: 2,
|
||||||
|
extract(source: DatasetSource): TankBotAmmoData {
|
||||||
|
const globalMods = readGlobalModInfo(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
|
||||||
|
const wpcost = source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY);
|
||||||
|
const acesPaths = new Set(source.listFiles('aces.vromfs.bin').map((p) => p.toLowerCase()));
|
||||||
|
const weaponCache = new Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>();
|
||||||
|
const out: Record<string, TankAmmoProfile> = {};
|
||||||
|
|
||||||
|
for (const vehicleBlk of wpcost.blocks) {
|
||||||
|
const unitPath = `${TANK_MODELS_PREFIX}${vehicleBlk.name.toLowerCase()}.blk`;
|
||||||
|
if (!acesPaths.has(unitPath)) continue;
|
||||||
|
const profile = extractTankProfile(source, acesPaths, weaponCache, globalMods, vehicleBlk, unitPath);
|
||||||
|
if (profile !== undefined) out[vehicleBlk.name] = profile;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function readGlobalModInfo(root: BlkBlock): ReadonlyMap<string, GlobalModInfo> {
|
||||||
|
const mods = findBlock(root, 'modifications');
|
||||||
|
const map = new Map<string, GlobalModInfo>();
|
||||||
|
for (const entry of mods?.blocks ?? []) {
|
||||||
|
const effects = findBlock(entry, 'effects');
|
||||||
|
const bulletMod = stringField(effects, 'additiveBulletMod') ?? stringField(effects, 'bulletMod');
|
||||||
|
map.set(entry.name, {
|
||||||
|
...(bulletMod !== undefined ? { bulletMod } : {}),
|
||||||
|
requires: stringList(entry, 'reqModification'),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractTankProfile(
|
||||||
|
source: DatasetSource,
|
||||||
|
acesPaths: ReadonlySet<string>,
|
||||||
|
weaponCache: Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>,
|
||||||
|
globalMods: ReadonlyMap<string, GlobalModInfo>,
|
||||||
|
wpcostVehicle: BlkBlock,
|
||||||
|
unitPath: string,
|
||||||
|
): TankAmmoProfile | undefined {
|
||||||
|
const unitBlk = source.readBlk('aces.vromfs.bin', unitPath);
|
||||||
|
const mainWeapon = findMainGunBlock(unitBlk);
|
||||||
|
if (!mainWeapon) return undefined;
|
||||||
|
const rawBlkPath = stringField(mainWeapon, 'blk');
|
||||||
|
const maxBullets = Math.trunc(numberField(mainWeapon, 'bullets') ?? 0);
|
||||||
|
if (!rawBlkPath || maxBullets <= 0) return undefined;
|
||||||
|
const lowerBlkPath = rawBlkPath.toLowerCase();
|
||||||
|
if (!acesPaths.has(lowerBlkPath)) return undefined;
|
||||||
|
|
||||||
|
const weaponName = basenameWithoutExt(rawBlkPath);
|
||||||
|
const weaponMeta = loadWeaponMeta(source, weaponCache, lowerBlkPath);
|
||||||
|
const readyRack = countReadyRackShells(unitBlk, stringField(mainWeapon, 'trigger') ?? 'gunner0');
|
||||||
|
const shells = collectSelectableShells(wpcostVehicle, unitBlk, globalMods, weaponMeta);
|
||||||
|
if (shells.length === 0) return undefined;
|
||||||
|
return { weaponName, maxBullets, isBelt: weaponMeta.isBelt, readyRack, shells };
|
||||||
|
}
|
||||||
|
|
||||||
|
function findMainGunBlock(unitBlk: BlkBlock): BlkBlock | undefined {
|
||||||
|
const common = findBlock(unitBlk, 'commonWeapons');
|
||||||
|
if (!common) return undefined;
|
||||||
|
return common.blocks.find((block) =>
|
||||||
|
stringField(block, 'trigger') === 'gunner0'
|
||||||
|
&& !(stringField(block, 'blk') ?? '').toLowerCase().includes('dummy_weapon'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function countReadyRackShells(unitBlk: BlkBlock, mainTrigger: string): number {
|
||||||
|
const stowages = findBlock(unitBlk, 'ammoStowages');
|
||||||
|
if (!stowages) return 0;
|
||||||
|
let total = 0;
|
||||||
|
for (const stow of stowages.blocks) {
|
||||||
|
const triggers = stringList(stow, 'weaponTrigger');
|
||||||
|
if (triggers.length > 0 && !triggers.includes(mainTrigger)) continue;
|
||||||
|
for (const cluster of stow.blocks) {
|
||||||
|
if (cluster.name !== 'shells') continue;
|
||||||
|
const isReady = boolField(cluster, 'firstStage') === true
|
||||||
|
|| boolField(cluster, 'autoLoad') === true
|
||||||
|
|| boolField(cluster, 'ammoLoadedInGun') === true;
|
||||||
|
if (!isReady) continue;
|
||||||
|
for (const slot of cluster.blocks) total += Math.max(0, Math.trunc(numberField(slot, 'count') ?? 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadWeaponMeta(
|
||||||
|
source: DatasetSource,
|
||||||
|
cache: Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>,
|
||||||
|
lowerPath: string,
|
||||||
|
) {
|
||||||
|
const cached = cache.get(lowerPath);
|
||||||
|
if (cached) return cached;
|
||||||
|
const blk = source.readBlk('aces.vromfs.bin', lowerPath);
|
||||||
|
const isBelt = boolField(blk, 'isBulletBelt') === true;
|
||||||
|
const defaultBlock = findBlock(blk, 'bullet');
|
||||||
|
const defaultBullet = defaultBlock ? parseBulletMeta(defaultBlock) : undefined;
|
||||||
|
const sets = new Map<string, WeaponBulletMeta>();
|
||||||
|
for (const child of blk.blocks) {
|
||||||
|
if (child.name === 'bullet') continue;
|
||||||
|
const subBullet = findBlock(child, 'bullet');
|
||||||
|
if (!subBullet) continue;
|
||||||
|
const meta = parseBulletMeta(subBullet);
|
||||||
|
if (meta) sets.set(child.name, meta);
|
||||||
|
}
|
||||||
|
const entry = { isBelt, ...(defaultBullet ? { defaultBullet } : {}), sets };
|
||||||
|
cache.set(lowerPath, entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBulletMeta(bullet: BlkBlock): WeaponBulletMeta | undefined {
|
||||||
|
const bulletType = (stringField(bullet, 'bulletType') ?? '').toLowerCase();
|
||||||
|
if (!bulletType) return undefined;
|
||||||
|
const speedMps = numberField(bullet, 'speed') ?? 0;
|
||||||
|
const pen500Mm = estimatePen500Mm(bullet, bulletType, speedMps);
|
||||||
|
return { bulletType, speedMps, pen500Mm };
|
||||||
|
}
|
||||||
|
|
||||||
|
function estimatePen500Mm(bullet: BlkBlock, bulletType: string, speedMps: number): number {
|
||||||
|
const cum = numberField(findBlock(bullet, 'cumulativeDamage'), 'armorPower');
|
||||||
|
const apBlock = findBlock(bullet, 'armorpower');
|
||||||
|
const ap500 = numberField(apBlock, 'ArmorPower500m') ?? numberField(apBlock, 'ArmorPower0m') ?? 0;
|
||||||
|
if (bulletType.includes('apds_fs')) {
|
||||||
|
const dmgBlock = findBlock(bullet, 'damage');
|
||||||
|
const kinetic = dmgBlock ? findBlock(dmgBlock, 'kinetic') : undefined;
|
||||||
|
const workLen = numberField(kinetic, 'lanzOdermattWorkingLength')
|
||||||
|
?? numberField(kinetic, 'WorkingLength')
|
||||||
|
?? numberField(kinetic, 'Length')
|
||||||
|
?? 0;
|
||||||
|
const density = numberField(kinetic, 'lanzOdermattDensity') ?? numberField(kinetic, 'Density') ?? 17000;
|
||||||
|
if (workLen > 0) return Math.max(ap500, Math.round(workLen * Math.sqrt(density / 7850) * (speedMps / 1700) * 0.85));
|
||||||
|
return Math.max(ap500, Math.round(speedMps * 0.24));
|
||||||
|
}
|
||||||
|
if (cum !== undefined && cum > ap500) return cum;
|
||||||
|
if (ap500 > 0) return ap500;
|
||||||
|
const mass = numberField(bullet, 'mass') ?? 0;
|
||||||
|
const cal = numberField(bullet, 'damageCaliber') ?? numberField(bullet, 'caliber') ?? 0;
|
||||||
|
if (mass > 0 && cal > 0 && speedMps > 100 && !bulletType.includes('he_') && !bulletType.includes('smoke')) {
|
||||||
|
return Math.round(0.0022 * Math.pow(mass, 0.55) * Math.pow(speedMps, 1.43) / Math.pow(cal * 1000, 0.65));
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectSelectableShells(
|
||||||
|
wpcostVehicle: BlkBlock,
|
||||||
|
unitBlk: BlkBlock,
|
||||||
|
globalMods: ReadonlyMap<string, GlobalModInfo>,
|
||||||
|
weaponMeta: { defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> },
|
||||||
|
): TankShellChoice[] {
|
||||||
|
const out: TankShellChoice[] = [];
|
||||||
|
if (weaponMeta.defaultBullet) {
|
||||||
|
out.push({ modName: '', ...weaponMeta.defaultBullet, requires: [] });
|
||||||
|
}
|
||||||
|
const wpModsBlock = findBlock(wpcostVehicle, 'modifications');
|
||||||
|
const unitModsBlock = findBlock(unitBlk, 'modifications');
|
||||||
|
const reqMap = new Map<string, readonly string[]>();
|
||||||
|
for (const mod of wpModsBlock?.blocks ?? []) reqMap.set(mod.name, stringList(mod, 'reqModification'));
|
||||||
|
|
||||||
|
for (const mod of wpModsBlock?.blocks ?? []) {
|
||||||
|
if (numberField(mod, 'ammoCount') === undefined) continue;
|
||||||
|
const unitMod = unitModsBlock ? findBlock(unitModsBlock, mod.name) : undefined;
|
||||||
|
const unitModEffects = unitMod ? findBlock(unitMod, 'effects') : undefined;
|
||||||
|
const setName = stringField(unitModEffects, 'additiveBulletMod')
|
||||||
|
?? stringField(unitModEffects, 'bulletMod')
|
||||||
|
?? globalMods.get(mod.name)?.bulletMod
|
||||||
|
?? mod.name;
|
||||||
|
const meta = weaponMeta.sets.get(setName);
|
||||||
|
if (!meta) continue;
|
||||||
|
out.push({
|
||||||
|
modName: mod.name,
|
||||||
|
...meta,
|
||||||
|
requires: collectTransitiveReqs(mod.name, reqMap, globalMods),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectTransitiveReqs(
|
||||||
|
modName: string,
|
||||||
|
reqMap: ReadonlyMap<string, readonly string[]>,
|
||||||
|
globalMods: ReadonlyMap<string, GlobalModInfo>,
|
||||||
|
): string[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const queue = [...(reqMap.get(modName) ?? []), ...(globalMods.get(modName)?.requires ?? [])];
|
||||||
|
while (queue.length > 0) {
|
||||||
|
const next = queue.pop()!;
|
||||||
|
if (!next || next === modName || seen.has(next)) continue;
|
||||||
|
seen.add(next);
|
||||||
|
for (const parent of reqMap.get(next) ?? []) queue.push(parent);
|
||||||
|
}
|
||||||
|
return [...seen].sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
function basenameWithoutExt(path: string): string {
|
||||||
|
const slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
|
||||||
|
const file = slash >= 0 ? path.slice(slash + 1) : path;
|
||||||
|
return file.endsWith('.blk') ? file.slice(0, -4) : file;
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
/**
|
||||||
|
* Dataset: stock training missions and their first-completion rewards from char.vromfs.bin:
|
||||||
|
* - config/mislist.blk ("training" block): chapter/mission full names accepted for progress;
|
||||||
|
* - config/pve_awards.blk ("training" block): per-mission decal, shared first-completion unlock,
|
||||||
|
* and per-difficulty Silver Lions rewards (`wpEarnedWinDiff0..2`);
|
||||||
|
* - config/unlocks.blk: decal unlock verification and `oneTimeAwardUnlock` Golden Eagles amount
|
||||||
|
* and mutually exclusive `char_unlocked` conditions.
|
||||||
|
*/
|
||||||
|
import { findParam, type BlkBlock } from '@wto/blk';
|
||||||
|
import { blockAt, boolField, stringField, stringList } from './blk-fields.ts';
|
||||||
|
import type { Dataset, DatasetSource } from './dataset.ts';
|
||||||
|
|
||||||
|
const CHAR_PACK = 'char.vromfs.bin';
|
||||||
|
const MISLIST = 'config/mislist.blk';
|
||||||
|
const PVE_AWARDS = 'config/pve_awards.blk';
|
||||||
|
const UNLOCKS = 'config/unlocks.blk';
|
||||||
|
const TRAINING_SECTION = 'training';
|
||||||
|
|
||||||
|
export interface TrainingFirstCompletionAward {
|
||||||
|
readonly id: string;
|
||||||
|
readonly goldenEagles: number;
|
||||||
|
readonly blockedBy: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrainingMissionEntry {
|
||||||
|
readonly fullName: string;
|
||||||
|
readonly decal?: string;
|
||||||
|
readonly firstCompletion?: TrainingFirstCompletionAward;
|
||||||
|
/** First-win Silver Lions rewards (`wpEarnedWinDiff0..2`) for arcade, realistic, simulator. */
|
||||||
|
readonly silverLionsByDifficulty: readonly [number, number, number];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrainingMissionsData {
|
||||||
|
readonly missions: readonly TrainingMissionEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const trainingMissions: Dataset<TrainingMissionsData> = {
|
||||||
|
id: 'training-missions',
|
||||||
|
version: 1,
|
||||||
|
extract(source: DatasetSource): TrainingMissionsData {
|
||||||
|
const misSection = blockAt(source.readBlk(CHAR_PACK, MISLIST), TRAINING_SECTION);
|
||||||
|
if (!misSection) throw new Error(`${MISLIST} has no "${TRAINING_SECTION}" block`);
|
||||||
|
const awardSection = blockAt(source.readBlk(CHAR_PACK, PVE_AWARDS), TRAINING_SECTION);
|
||||||
|
if (!awardSection) throw new Error(`${PVE_AWARDS} has no "${TRAINING_SECTION}" block`);
|
||||||
|
|
||||||
|
const awardsByMission = new Map<string, BlkBlock>(awardSection.blocks.map((entry) => [entry.name, entry]));
|
||||||
|
const unlocksById = new Map<string, BlkBlock>();
|
||||||
|
for (const entry of source.readBlk(CHAR_PACK, UNLOCKS).blocks) {
|
||||||
|
const id = stringField(entry, 'id');
|
||||||
|
if (id) unlocksById.set(id, entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const missions: TrainingMissionEntry[] = [];
|
||||||
|
for (const chapter of misSection.blocks) {
|
||||||
|
for (const mission of stringList(chapter, 'm')) {
|
||||||
|
const fullName = `${chapter.name}/${mission}`;
|
||||||
|
if (seen.has(fullName)) continue;
|
||||||
|
seen.add(fullName);
|
||||||
|
missions.push(buildMissionEntry(fullName, mission, awardsByMission.get(mission), unlocksById));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { missions };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildMissionEntry(
|
||||||
|
fullName: string,
|
||||||
|
mission: string,
|
||||||
|
award: BlkBlock | undefined,
|
||||||
|
unlocks: ReadonlyMap<string, BlkBlock>,
|
||||||
|
): TrainingMissionEntry {
|
||||||
|
const decalId = stringField(award, 'decal');
|
||||||
|
const decal = decalId && stringField(unlocks.get(decalId), 'type') === 'decal' ? decalId : undefined;
|
||||||
|
const firstCompletion = award ? readFirstCompletionAward(award, mission, unlocks) : undefined;
|
||||||
|
return {
|
||||||
|
fullName,
|
||||||
|
...(decal ? { decal } : {}),
|
||||||
|
...(firstCompletion ? { firstCompletion } : {}),
|
||||||
|
silverLionsByDifficulty: [
|
||||||
|
readWinSilverLions(award, 0),
|
||||||
|
readWinSilverLions(award, 1),
|
||||||
|
readWinSilverLions(award, 2),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function readFirstCompletionAward(
|
||||||
|
award: BlkBlock,
|
||||||
|
mission: string,
|
||||||
|
unlocks: ReadonlyMap<string, BlkBlock>,
|
||||||
|
): TrainingFirstCompletionAward | undefined {
|
||||||
|
const id = stringField(award, 'oneTimeAwardUnlock');
|
||||||
|
if (!id) return undefined;
|
||||||
|
const unlock = unlocks.get(id);
|
||||||
|
if (stringField(unlock, 'type') !== 'award') return undefined;
|
||||||
|
const amount = unlock && findParam(unlock, 'amount_gold')?.value;
|
||||||
|
const mode = blockAt(unlock, 'mode');
|
||||||
|
if (amount?.type !== 'int' || amount.value <= 0
|
||||||
|
|| stringField(mode, 'type') !== 'char_mission_list'
|
||||||
|
|| !stringList(mode, 'name').includes(mission)) return undefined;
|
||||||
|
|
||||||
|
const blocked = mode?.blocks.flatMap((condition) =>
|
||||||
|
condition.name === 'condition'
|
||||||
|
&& stringField(condition, 'type') === 'char_unlocked'
|
||||||
|
&& boolField(condition, 'positive') === false
|
||||||
|
? stringList(condition, 'unlock')
|
||||||
|
: []) ?? [];
|
||||||
|
const hideIfEarned = stringField(award, 'hideOneTimeAwardIfUnlockIsOpen');
|
||||||
|
if (hideIfEarned) blocked.push(hideIfEarned);
|
||||||
|
return { id, goldenEagles: amount.value, blockedBy: [...new Set(blocked)] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function readWinSilverLions(award: BlkBlock | undefined, difficulty: 0 | 1 | 2): number {
|
||||||
|
const value = award && findParam(award, `wpEarnedWinDiff${difficulty}`)?.value;
|
||||||
|
return value?.type === 'int' && value.value > 0 ? value.value : 0;
|
||||||
|
}
|
||||||
@@ -27,11 +27,14 @@ import type { Dataset } from './dataset.ts';
|
|||||||
import { shopEntriesByName } from './shop-tree.ts';
|
import { shopEntriesByName } from './shop-tree.ts';
|
||||||
|
|
||||||
const VEHICLE_ECONOMY = 'config/wpcost.blk';
|
const VEHICLE_ECONOMY = 'config/wpcost.blk';
|
||||||
|
const UNIT_TAGS = 'config/unittags.blk';
|
||||||
|
|
||||||
export interface CatalogueVehicle {
|
export interface CatalogueVehicle {
|
||||||
readonly name: string;
|
readonly name: string;
|
||||||
readonly country: string;
|
readonly country: string;
|
||||||
readonly unitClass: string;
|
readonly unitClass: string;
|
||||||
|
/** True when config/unittags.blk tags the vehicle with type_light_tank. */
|
||||||
|
readonly isLightTank?: boolean;
|
||||||
readonly rank: number;
|
readonly rank: number;
|
||||||
/** wpcost.blk reqAir; absent when empty or missing. */
|
/** wpcost.blk reqAir; absent when empty or missing. */
|
||||||
readonly requires?: string;
|
readonly requires?: string;
|
||||||
@@ -70,15 +73,27 @@ export interface CatalogueVehicle {
|
|||||||
|
|
||||||
export const vehicleCatalogue: Dataset<readonly CatalogueVehicle[]> = {
|
export const vehicleCatalogue: Dataset<readonly CatalogueVehicle[]> = {
|
||||||
id: 'vehicle-catalogue',
|
id: 'vehicle-catalogue',
|
||||||
version: 6,
|
version: 7,
|
||||||
extract: (source) => {
|
extract: (source) => {
|
||||||
const shopEntries = shopEntriesByName(source);
|
const shopEntries = shopEntriesByName(source);
|
||||||
const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index]));
|
const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index]));
|
||||||
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1));
|
const lightTanks = lightTankNames(source.readBlk('char.vromfs.bin', UNIT_TAGS));
|
||||||
|
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) =>
|
||||||
|
catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1, lightTanks.has(vehicle.name)),
|
||||||
|
);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number): CatalogueVehicle {
|
function lightTankNames(unitTagsRoot: BlkBlock): ReadonlySet<string> {
|
||||||
|
const names = new Set<string>();
|
||||||
|
for (const unit of unitTagsRoot.blocks) {
|
||||||
|
const tags = unit.blocks.find((block) => block.name === 'tags');
|
||||||
|
if (tags && boolField(tags, 'type_light_tank') === true) names.add(unit.name);
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number, isLightTank: boolean): CatalogueVehicle {
|
||||||
const requires = stringField(vehicle, 'reqAir');
|
const requires = stringField(vehicle, 'reqAir');
|
||||||
const researchType = stringField(vehicle, 'researchType');
|
const researchType = stringField(vehicle, 'researchType');
|
||||||
const requiredUnlock = stringField(shopEntry, 'reqUnlock');
|
const requiredUnlock = stringField(shopEntry, 'reqUnlock');
|
||||||
@@ -90,6 +105,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr
|
|||||||
name: vehicle.name,
|
name: vehicle.name,
|
||||||
country: stringField(vehicle, 'country') ?? '',
|
country: stringField(vehicle, 'country') ?? '',
|
||||||
unitClass: stringField(vehicle, 'unitClass') ?? '',
|
unitClass: stringField(vehicle, 'unitClass') ?? '',
|
||||||
|
...(isLightTank ? { isLightTank: true } : {}),
|
||||||
rank: numberField(vehicle, 'rank') ?? 0,
|
rank: numberField(vehicle, 'rank') ?? 0,
|
||||||
...(requires ? { requires } : {}),
|
...(requires ? { requires } : {}),
|
||||||
researchPoints: numberField(vehicle, 'reqExp') ?? 0,
|
researchPoints: numberField(vehicle, 'reqExp') ?? 0,
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ export interface GameModeDeclaration {
|
|||||||
* `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode).
|
* `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode).
|
||||||
*/
|
*/
|
||||||
readonly multiSlot?: boolean;
|
readonly multiSlot?: boolean;
|
||||||
|
/** Stock maxRespawns value when this mode specifies its own respawn count. */
|
||||||
|
readonly maxRespawns?: number;
|
||||||
|
/** Additional scalar settings the local host needs from this mode's missions. */
|
||||||
|
readonly missionRuleKeys?: readonly string[];
|
||||||
/** False for modes whose native weapon rules replace combat presets. Defaults to true. */
|
/** False for modes whose native weapon rules replace combat presets. Defaults to true. */
|
||||||
readonly allowBotAircraftLoadouts?: boolean;
|
readonly allowBotAircraftLoadouts?: boolean;
|
||||||
/** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */
|
/** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
* AB/RB get Enduring Confrontation; Ground AB and Air AB get none);
|
* 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`.
|
* - `queueEvent.nut` includes or excludes its `gameModeId` in `match.enqueue` `game_modes_list`.
|
||||||
*/
|
*/
|
||||||
|
import { UNLIMITED_RESPAWNS } from '../mode-definition.ts';
|
||||||
import type { GameModeDeclaration } from './game-mode-declaration.ts';
|
import type { GameModeDeclaration } from './game-mode-declaration.ts';
|
||||||
import {
|
import {
|
||||||
AIR_REALISTIC_MISSIONS,
|
AIR_REALISTIC_MISSIONS,
|
||||||
@@ -69,6 +70,15 @@ export const SUB_GAME_MODES: readonly GameModeDeclaration[] = [
|
|||||||
displayType: 'random_battle',
|
displayType: 'random_battle',
|
||||||
allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION },
|
allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION },
|
||||||
minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION,
|
minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION,
|
||||||
|
maxRespawns: UNLIMITED_RESPAWNS,
|
||||||
|
// mission_settings.mission in mis.vromfs.bin gamedata/missions/cta/planes/nuclear_escalation/.
|
||||||
|
missionRuleKeys: [
|
||||||
|
'customHUD', 'nuclearEscalationStage1', 'nuclearEscalationStage2', 'nuclearEscalationStage3',
|
||||||
|
'useSpawnDelay', 'afterRespawnDelaySec', 'overrideMaxActiveUnitsWeight', 'scheduleBasedGmUpdateMaxInterval',
|
||||||
|
'disableFallingTrees', 'alwaysSendAllyGMData', 'isAlwaysShowCollectiveDetectedUnits', 'useAIForCollectiveDetection',
|
||||||
|
'allowToChooseHUDIconPreset', 'showAIKilllog', 'showUnitTooltipOnMap', 'disableMfdForPrevgenConsoles',
|
||||||
|
'clientReplayMaxSizeMb', 'timeToLoseInstantDetection', 'showTacticalMapCellSize',
|
||||||
|
],
|
||||||
requiredClass: 'aircraft',
|
requiredClass: 'aircraft',
|
||||||
allowedClasses: ['aircraft'],
|
allowedClasses: ['aircraft'],
|
||||||
missions: NUCLEAR_ESCALATION_MISSIONS,
|
missions: NUCLEAR_ESCALATION_MISSIONS,
|
||||||
|
|||||||
@@ -41,8 +41,13 @@ export const MISSION_DIFFICULTY: Readonly<Record<ModeDifficulty, string>> = {
|
|||||||
simulator: 'hardcore',
|
simulator: 'hardcore',
|
||||||
};
|
};
|
||||||
|
|
||||||
// globals/missions/respawnCountModes.nut: RESPAWN_COUNT_MODE.SINGLE_SPAWN.
|
// globals/missions/respawnCountModes.nut: RESPAWN_COUNT_MODE.
|
||||||
export const SINGLE_SPAWN = 1;
|
export const SINGLE_SPAWN = 1;
|
||||||
|
export const UNLIMITED_RESPAWNS = -2;
|
||||||
|
|
||||||
|
export function modeMaxRespawns(mode: GameModeDeclaration): number | undefined {
|
||||||
|
return mode.maxRespawns ?? (mode.multiSlot === false ? SINGLE_SPAWN : undefined);
|
||||||
|
}
|
||||||
|
|
||||||
export type ModeDefinition = Readonly<Record<string, unknown>>;
|
export type ModeDefinition = Readonly<Record<string, unknown>>;
|
||||||
|
|
||||||
@@ -50,6 +55,7 @@ export function buildModeDefinition(mode: GameModeDeclaration, missions: readonl
|
|||||||
countries: readonly string[], missionRanks?: MissionRotationRanks): ModeDefinition {
|
countries: readonly string[], missionRanks?: MissionRotationRanks): ModeDefinition {
|
||||||
const minTeamSize = mode.teamSizeOverride?.min ?? 1;
|
const minTeamSize = mode.teamSizeOverride?.min ?? 1;
|
||||||
const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions);
|
const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions);
|
||||||
|
const maxRespawns = modeMaxRespawns(mode);
|
||||||
const team = {
|
const team = {
|
||||||
countries: [...countries],
|
countries: [...countries],
|
||||||
allowedCrafts: mode.allowedClasses.map((unitClass) => {
|
allowedCrafts: mode.allowedClasses.map((unitClass) => {
|
||||||
@@ -83,7 +89,7 @@ export function buildModeDefinition(mode: GameModeDeclaration, missions: readonl
|
|||||||
teamB: structuredClone(team),
|
teamB: structuredClone(team),
|
||||||
mission_decl: {
|
mission_decl: {
|
||||||
difficulty: MISSION_DIFFICULTY[mode.difficulty],
|
difficulty: MISSION_DIFFICULTY[mode.difficulty],
|
||||||
...(mode.multiSlot === false ? { maxRespawns: SINGLE_SPAWN } : {}),
|
...(maxRespawns === undefined ? {} : { maxRespawns }),
|
||||||
missions_list: Object.fromEntries(missions.map((mission) => {
|
missions_list: Object.fromEntries(missions.map((mission) => {
|
||||||
const ranges = missionRanks?.byMission.get(mission.name);
|
const ranges = missionRanks?.byMission.get(mission.name);
|
||||||
return [mission.name, ranges?.length === 1 ? { enableIf: ranges[0] } : {}];
|
return [mission.name, ranges?.length === 1 ? { enableIf: ranges[0] } : {}];
|
||||||
|
|||||||
@@ -11,5 +11,6 @@ export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails
|
|||||||
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
|
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
|
||||||
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
|
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
|
||||||
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
|
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
|
||||||
export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts';
|
export { loadGroundAiTuning, type GroundAiTuning } from './tuning/ground-ai-tuning.ts';
|
||||||
|
export { readLauncherTuning, writeLauncherTuning, type GroundAiTuningPatch, type LauncherTuningPatch } from './tuning/launcher-tuning.ts';
|
||||||
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
|
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
|
||||||
@@ -16,7 +16,6 @@ import type { BlkBlock, BlkValue } from '@wto/blk';
|
|||||||
import type { BannerParams } from '../battle/battle-economy.ts';
|
import type { BannerParams } from '../battle/battle-economy.ts';
|
||||||
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
|
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
|
||||||
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
|
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
|
||||||
import { SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
|
|
||||||
|
|
||||||
type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean];
|
type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean];
|
||||||
|
|
||||||
@@ -33,10 +32,16 @@ export interface BattleLaunchNotify extends Record<string, unknown> {
|
|||||||
readonly battle: Readonly<Record<string, unknown>>;
|
readonly battle: Readonly<Record<string, unknown>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BattleBackupAllowance {
|
||||||
|
readonly daily: number;
|
||||||
|
readonly vehicles: Readonly<Record<string, number>>;
|
||||||
|
}
|
||||||
|
|
||||||
export function battleLaunchNotify(
|
export function battleLaunchNotify(
|
||||||
plan: BattleLaunchPlan,
|
plan: BattleLaunchPlan,
|
||||||
awards: BannerParams,
|
awards: BannerParams,
|
||||||
scores: Readonly<Record<string, number>>,
|
scores: Readonly<Record<string, number>>,
|
||||||
|
backups?: BattleBackupAllowance,
|
||||||
): BattleLaunchNotify {
|
): BattleLaunchNotify {
|
||||||
return {
|
return {
|
||||||
from: 'wto_battle',
|
from: 'wto_battle',
|
||||||
@@ -52,18 +57,20 @@ export function battleLaunchNotify(
|
|||||||
mission: {
|
mission: {
|
||||||
name: plan.missionName,
|
name: plan.missionName,
|
||||||
difficulty: plan.difficulty,
|
difficulty: plan.difficulty,
|
||||||
...(plan.selectedSlot ? { maxRespawns: SINGLE_SPAWN } : {}),
|
...(plan.maxRespawns === undefined ? {} : { maxRespawns: plan.maxRespawns }),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
battle: {
|
battle: {
|
||||||
sessionId: plan.sessionId,
|
sessionId: plan.sessionId,
|
||||||
modeName: plan.modeName,
|
modeName: plan.modeName,
|
||||||
|
...(plan.modeTag ? { modeTag: plan.modeTag } : {}),
|
||||||
economicName: plan.economicName,
|
economicName: plan.economicName,
|
||||||
country: plan.country,
|
country: plan.country,
|
||||||
missionName: plan.missionName,
|
missionName: plan.missionName,
|
||||||
...(plan.selectedSlot ? { selectedSlot: plan.selectedSlot } : {}),
|
...(plan.selectedSlot ? { selectedSlot: plan.selectedSlot } : {}),
|
||||||
extraBattleSlots: plan.extraBattleSlots,
|
extraBattleSlots: plan.extraBattleSlots,
|
||||||
...(plan.spawnScore ? { spawnScore: plan.spawnScore } : {}),
|
...(plan.spawnScore ? { spawnScore: plan.spawnScore } : {}),
|
||||||
|
...(backups ? { backups } : {}),
|
||||||
awards,
|
awards,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
* "strike": time:f the local player's nuclear bomb exploded
|
* "strike": time:f the local player's nuclear bomb exploded
|
||||||
* answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] }
|
* answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] }
|
||||||
*/
|
*/
|
||||||
|
import type { BattleLiveFactContext } from '@wto/mods';
|
||||||
import type { BattleLiveLogs } from '../battle/battle-live-log.ts';
|
import type { BattleLiveLogs } from '../battle/battle-live-log.ts';
|
||||||
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
|
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
|
||||||
import type { BattleStreaks } from '../battle/battle-streaks.ts';
|
import type { BattleStreaks } from '../battle/battle-streaks.ts';
|
||||||
@@ -23,6 +24,7 @@ export interface BattleLiveDependencies {
|
|||||||
readonly streaks: BattleStreaks;
|
readonly streaks: BattleStreaks;
|
||||||
/** Units whose lives and events earn no awards (battle-support-planes.ts). */
|
/** Units whose lives and events earn no awards (battle-support-planes.ts). */
|
||||||
readonly supportPlanes: ReadonlySet<string>;
|
readonly supportPlanes: ReadonlySet<string>;
|
||||||
|
readonly onLiveFact?: (ctx: BattleLiveFactContext) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> {
|
export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> {
|
||||||
@@ -34,6 +36,11 @@ export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string,
|
|||||||
if (!session || session.settled) return { streaks: [] };
|
if (!session || session.settled) return { streaks: [] };
|
||||||
const log = deps.liveLogs.of(session.sessionId);
|
const log = deps.liveLogs.of(session.sessionId);
|
||||||
if (!recordFact(log, p)) return { streaks: [] };
|
if (!recordFact(log, p)) return { streaks: [] };
|
||||||
|
deps.onLiveFact?.({
|
||||||
|
userId: userId!,
|
||||||
|
roomId: session.sessionId,
|
||||||
|
fact: p as Record<string, unknown>,
|
||||||
|
});
|
||||||
const awarded = deps.streaks.evaluate({
|
const awarded = deps.streaks.evaluate({
|
||||||
...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes),
|
...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes),
|
||||||
feed: log.feed,
|
feed: log.feed,
|
||||||
|
|||||||
@@ -5,16 +5,21 @@
|
|||||||
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
|
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
|
||||||
* - `match.check_reconnect`
|
* - `match.check_reconnect`
|
||||||
*/
|
*/
|
||||||
|
import type { BlkBlock } from '@wto/blk';
|
||||||
|
import type { BattleMatchmakeContext } from '@wto/mods';
|
||||||
import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts';
|
import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts';
|
||||||
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
|
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
|
||||||
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
|
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
|
||||||
import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts';
|
import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts';
|
||||||
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
|
import type { BattleSession, BattleSessionStore } from '../battle/battle-session-store.ts';
|
||||||
|
import { DAILY_BACKUP, recordDailyBackupSpawn } from '../battle/battle-spares.ts';
|
||||||
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
||||||
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
|
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
|
||||||
|
import { dailySparesLeft } from '../profile/profile-daily-spares.ts';
|
||||||
import { vehicleMrankDelta } from '../profile/profile-hangar.ts';
|
import { vehicleMrankDelta } from '../profile/profile-hangar.ts';
|
||||||
|
import { spareCount } from '../profile/profile-vehicle-state.ts';
|
||||||
import type { PlayerProfiles } from '../profile/player-profiles.ts';
|
import type { PlayerProfiles } from '../profile/player-profiles.ts';
|
||||||
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
|
import { battleLaunchNotify, type BattleBackupAllowance, type BattleLaunchNotify } from './battle-launch-notify.ts';
|
||||||
import type { MatchingRequestHandler } from './matching-requests.ts';
|
import type { MatchingRequestHandler } from './matching-requests.ts';
|
||||||
|
|
||||||
export interface BattleQueueDependencies {
|
export interface BattleQueueDependencies {
|
||||||
@@ -24,6 +29,7 @@ export interface BattleQueueDependencies {
|
|||||||
readonly sessions: BattleSessionStore;
|
readonly sessions: BattleSessionStore;
|
||||||
readonly economy: BattleEconomy;
|
readonly economy: BattleEconomy;
|
||||||
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
|
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
|
||||||
|
readonly onBeforeMatchmake?: (ctx: BattleMatchmakeContext) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
|
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
|
||||||
@@ -36,6 +42,18 @@ export function battleQueueRequests(deps: BattleQueueDependencies): Array<[strin
|
|||||||
return {};
|
return {};
|
||||||
}],
|
}],
|
||||||
['match.check_reconnect', () => ({})],
|
['match.check_reconnect', () => ({})],
|
||||||
|
['wto_battle.daily_spare', ({ params }, connection) => {
|
||||||
|
const userId = connection.authenticatedUserId();
|
||||||
|
if (!userId) return { error: 'AUTH_REQ_ERROR' };
|
||||||
|
const { sessionId, slot, unit } = params;
|
||||||
|
if (typeof sessionId !== 'string' || typeof slot !== 'number' || typeof unit !== 'string') {
|
||||||
|
return { error: 'BAD_PARAMS' };
|
||||||
|
}
|
||||||
|
const battle = deps.sessions.findForUser(sessionId, userId);
|
||||||
|
if (!battle || battle.settled || battle.spareSlots?.get(slot) !== unit) return { error: 'BAD_PARAMS' };
|
||||||
|
deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit, backup: DAILY_BACKUP }));
|
||||||
|
return {};
|
||||||
|
}],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,6 +103,11 @@ function handleEnqueue(
|
|||||||
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
|
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
|
||||||
const idInCountry = playerEntry.selectedSlot;
|
const idInCountry = playerEntry.selectedSlot;
|
||||||
const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry);
|
const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry);
|
||||||
|
deps.onBeforeMatchmake?.({
|
||||||
|
userId,
|
||||||
|
eventName: modes[0]!.declaration.name,
|
||||||
|
request: params as Record<string, unknown>,
|
||||||
|
});
|
||||||
const outcome = deps.matchmaker.enqueue({
|
const outcome = deps.matchmaker.enqueue({
|
||||||
userId,
|
userId,
|
||||||
mode: modes[0]!,
|
mode: modes[0]!,
|
||||||
@@ -106,15 +129,31 @@ function handleEnqueue(
|
|||||||
...(launch.selectedSlot ? [launch.selectedSlot.unitName] : slotVehicles),
|
...(launch.selectedSlot ? [launch.selectedSlot.unitName] : slotVehicles),
|
||||||
...launch.extraBattleSlots.map((slot) => slot.unitName),
|
...launch.extraBattleSlots.map((slot) => slot.unitName),
|
||||||
]);
|
]);
|
||||||
const awards = deps.economy.bannerParams(playerVehicles, economyDifficulty(modes[0]!.declaration.difficulty));
|
|
||||||
setImmediate(() => {
|
setImmediate(() => {
|
||||||
if (!deps.sessions.isPending(userId, launch.sessionId)) return;
|
if (!deps.sessions.isPending(userId, launch.sessionId)) return;
|
||||||
deps.sessions.clearPending(userId, launch.sessionId);
|
deps.sessions.clearPending(userId, launch.sessionId);
|
||||||
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards, deps.economy.missionScores()));
|
const battle = deps.sessions.findForUser(launch.sessionId, userId);
|
||||||
|
if (!battle) return;
|
||||||
|
const awards = deps.economy.bannerParams(playerVehicles, economyDifficulty(battle.difficulty), battle.modeName);
|
||||||
|
const backups = launch.allowSpares ? configureBattleBackups(battle, profile) : undefined;
|
||||||
|
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards, deps.economy.missionScores(battle.modeName), backups));
|
||||||
});
|
});
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function configureBattleBackups(battle: BattleSession, profile: BlkBlock): BattleBackupAllowance {
|
||||||
|
const slots = new Map<number, string>();
|
||||||
|
for (let slot = 0; slot < MAX_BATTLE_CREW_SLOTS; slot++) {
|
||||||
|
const unit = crewSlotVehicleOfCountry(profile, battle.country, slot);
|
||||||
|
if (unit) slots.set(slot, unit);
|
||||||
|
}
|
||||||
|
battle.spareSlots = slots;
|
||||||
|
return {
|
||||||
|
daily: dailySparesLeft(profile, battle.startedAtSec),
|
||||||
|
vehicles: Object.fromEntries([...slots.values()].map((unit) => [unit, spareCount(profile, unit)])),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] {
|
function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] {
|
||||||
if (!Array.isArray(rawCrafts)) return [];
|
if (!Array.isArray(rawCrafts)) return [];
|
||||||
return rawCrafts.flatMap((craft): CraftRankEntry[] => {
|
return rawCrafts.flatMap((craft): CraftRankEntry[] => {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import { moduleResearchTarget, setModuleResearchTarget } from '../profile/profil
|
|||||||
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
||||||
import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
|
import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
|
||||||
import { currentModuleStatus } from './module-state.ts';
|
import { currentModuleStatus } from './module-state.ts';
|
||||||
import { ModuleStatus } from './module-status.ts';
|
import { ModuleStatus, vehicleModuleState } from './module-status.ts';
|
||||||
|
|
||||||
export interface ModificationOrder {
|
export interface ModificationOrder {
|
||||||
readonly vehicle: string;
|
readonly vehicle: string;
|
||||||
@@ -48,8 +48,9 @@ export function buyModification(profile: BlkBlock, catalogue: EquipmentCatalogue
|
|||||||
export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome {
|
export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome {
|
||||||
const equipment = catalogue.vehicle(vehicle);
|
const equipment = catalogue.vehicle(vehicle);
|
||||||
if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS');
|
if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS');
|
||||||
|
const { statuses } = vehicleModuleState(profile, equipment);
|
||||||
const purchases = equipment.modifications.flatMap((modification) => {
|
const purchases = equipment.modifications.flatMap((modification) => {
|
||||||
const purchase = buyAllEntry(profile, vehicle, modification, catalogue, outright);
|
const purchase = buyAllEntry(profile, vehicle, modification, statuses.get(modification.name), outright);
|
||||||
return purchase ? [{ modification, purchase }] : [];
|
return purchase ? [{ modification, purchase }] : [];
|
||||||
});
|
});
|
||||||
const price = purchases.reduce<Price>((sum, { purchase }) => ({
|
const price = purchases.reduce<Price>((sum, { purchase }) => ({
|
||||||
@@ -114,17 +115,24 @@ function outrightPurchase(profile: BlkBlock, vehicle: string, modification: Modi
|
|||||||
/**
|
/**
|
||||||
* One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost):
|
* One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost):
|
||||||
* skip what is at its maximum; with forceOpen every modification starts at its outright price
|
* skip what is at its maximum; with forceOpen every modification starts at its outright price
|
||||||
* (whatever its status); a buyable one (canBuyMod) with a non-zero price takes its own price
|
* (whatever its status); a buyable or researched one (canBuyMod || isModStatusResearched) with a
|
||||||
* instead, and is skipped altogether when counted or priced in golden eagles.
|
* non-zero price takes its own price instead, and is skipped altogether when counted or priced in
|
||||||
|
* golden eagles.
|
||||||
*/
|
*/
|
||||||
function buyAllEntry(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue, outright: boolean): Purchase | undefined {
|
function buyAllEntry(
|
||||||
|
profile: BlkBlock,
|
||||||
|
vehicle: string,
|
||||||
|
modification: ModificationFacts,
|
||||||
|
status: ModuleStatus | undefined,
|
||||||
|
outright: boolean,
|
||||||
|
): Purchase | undefined {
|
||||||
const record = modificationRecord(profile, vehicle, modification.name);
|
const record = modificationRecord(profile, vehicle, modification.name);
|
||||||
const maxAmount = Math.max(1, modification.maxCount);
|
const maxAmount = Math.max(1, modification.maxCount);
|
||||||
if ((record?.count ?? 0) >= maxAmount) return undefined;
|
if ((record?.count ?? 0) >= maxAmount) return undefined;
|
||||||
let purchase: Purchase | undefined;
|
let purchase: Purchase | undefined;
|
||||||
const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0;
|
const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0;
|
||||||
if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 };
|
if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 };
|
||||||
const buyable = record !== undefined || currentModuleStatus(profile, catalogue, vehicle, modification.name) === ModuleStatus.CAN_BUY;
|
const buyable = record !== undefined || status === ModuleStatus.CAN_BUY || status === ModuleStatus.RESEARCHED;
|
||||||
if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) {
|
if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) {
|
||||||
if (isCounted(modification) || modification.goldenEagles > 0) return undefined;
|
if (isCounted(modification) || modification.goldenEagles > 0) return undefined;
|
||||||
purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 };
|
purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 };
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ import { moduleResearchPoints } from '../profile/profile-module-research.ts';
|
|||||||
import { countsForTier, isResearchable } from './equipment-catalogue.ts';
|
import { countsForTier, isResearchable } from './equipment-catalogue.ts';
|
||||||
import type { ProfileEquipmentIndex } from './profile-equipment-index.ts';
|
import type { ProfileEquipmentIndex } from './profile-equipment-index.ts';
|
||||||
|
|
||||||
/** shopItemConsts ES_ITEM_STATUS_*; the same values as the vehicle statuses. */
|
/** shopItemConsts ES_ITEM_STATUS_* (aces.exe 2.61.0.58 0x17e2894..0x17e294b); same values as VehicleStatus. */
|
||||||
export const ModuleStatus = {
|
export const ModuleStatus = {
|
||||||
LOCKED: 1,
|
LOCKED: 1,
|
||||||
CAN_RESEARCH: 2,
|
CAN_RESEARCH: 2,
|
||||||
CAN_BUY: 8,
|
CAN_BUY: 8,
|
||||||
|
RESEARCHED: 0x40,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus];
|
export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus];
|
||||||
@@ -32,10 +33,11 @@ export function vehicleModuleState(
|
|||||||
index?: ProfileEquipmentIndex,
|
index?: ProfileEquipmentIndex,
|
||||||
): VehicleModuleState {
|
): VehicleModuleState {
|
||||||
const openTier = openTierOf(profile, equipment, index);
|
const openTier = openTierOf(profile, equipment, index);
|
||||||
|
const byName = new Map(equipment.modifications.map((mod) => [mod.name, mod]));
|
||||||
const statuses = new Map<string, ModuleStatus>();
|
const statuses = new Map<string, ModuleStatus>();
|
||||||
for (const modification of equipment.modifications) {
|
for (const modification of equipment.modifications) {
|
||||||
if (isOwned(profile, equipment.vehicle, modification.name, index)) continue;
|
if (isOwned(profile, equipment.vehicle, modification.name, index)) continue;
|
||||||
statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, index));
|
statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, byName, index));
|
||||||
}
|
}
|
||||||
return { openTier, statuses };
|
return { openTier, statuses };
|
||||||
}
|
}
|
||||||
@@ -80,16 +82,38 @@ function openTierOf(profile: BlkBlock, equipment: VehicleEquipment, index?: Prof
|
|||||||
return tier;
|
return tier;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function arePrerequisitesResearched(
|
||||||
|
profile: BlkBlock,
|
||||||
|
vehicle: string,
|
||||||
|
requires: readonly string[],
|
||||||
|
byName: ReadonlyMap<string, ModificationFacts>,
|
||||||
|
index?: ProfileEquipmentIndex,
|
||||||
|
): boolean {
|
||||||
|
return requires.every((required) => {
|
||||||
|
if (isOwned(profile, vehicle, required, index)) return true;
|
||||||
|
const mod = byName.get(required);
|
||||||
|
return mod !== undefined && isResearchable(mod) && isModuleResearched(profile, vehicle, mod, index);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function statusOf(
|
function statusOf(
|
||||||
profile: BlkBlock,
|
profile: BlkBlock,
|
||||||
vehicle: string,
|
vehicle: string,
|
||||||
modification: ModificationFacts,
|
modification: ModificationFacts,
|
||||||
openTier: number,
|
openTier: number,
|
||||||
|
byName: ReadonlyMap<string, ModificationFacts>,
|
||||||
index?: ProfileEquipmentIndex,
|
index?: ProfileEquipmentIndex,
|
||||||
): ModuleStatus {
|
): ModuleStatus {
|
||||||
if (isResearchable(modification)) {
|
if (isResearchable(modification)) {
|
||||||
if (modification.tier > openTier) return ModuleStatus.LOCKED;
|
if (modification.tier > openTier) return ModuleStatus.LOCKED;
|
||||||
return isModuleResearched(profile, vehicle, modification, index) ? ModuleStatus.CAN_BUY : ModuleStatus.CAN_RESEARCH;
|
if (isModuleResearched(profile, vehicle, modification, index)) {
|
||||||
|
return arePrerequisitesOwned(profile, vehicle, modification.requires, index)
|
||||||
|
? ModuleStatus.CAN_BUY
|
||||||
|
: ModuleStatus.RESEARCHED;
|
||||||
|
}
|
||||||
|
return arePrerequisitesResearched(profile, vehicle, modification.requires, byName, index)
|
||||||
|
? ModuleStatus.CAN_RESEARCH
|
||||||
|
: ModuleStatus.LOCKED;
|
||||||
}
|
}
|
||||||
return arePrerequisitesOwned(profile, vehicle, modification.requires, index) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED;
|
return arePrerequisitesOwned(profile, vehicle, modification.requires, index) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED;
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,12 @@
|
|||||||
* carry 30,000+ flat sub-blocks; indexing once drops refresh cost from O(N^2) to O(N).
|
* carry 30,000+ flat sub-blocks; indexing once drops refresh cost from O(N^2) to O(N).
|
||||||
*/
|
*/
|
||||||
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
||||||
import { recordName, type ModificationRecord } from '../profile/profile-modifications.ts';
|
import {
|
||||||
|
allModificationBlocks,
|
||||||
|
MAX_MODIFICATION_BLOCK_ENTRIES,
|
||||||
|
recordName,
|
||||||
|
type ModificationRecord,
|
||||||
|
} from '../profile/profile-modifications.ts';
|
||||||
import type { WeaponRecord } from '../profile/profile-weapons.ts';
|
import type { WeaponRecord } from '../profile/profile-weapons.ts';
|
||||||
|
|
||||||
const HANGAR = 'hangar';
|
const HANGAR = 'hangar';
|
||||||
@@ -21,7 +26,7 @@ export class ProfileEquipmentIndex {
|
|||||||
readonly #weapons = new Map<string, BlkBlock>();
|
readonly #weapons = new Map<string, BlkBlock>();
|
||||||
readonly #modsResearch = new Map<string, BlkBlock>();
|
readonly #modsResearch = new Map<string, BlkBlock>();
|
||||||
readonly #removedResearch = new Set<string>();
|
readonly #removedResearch = new Set<string>();
|
||||||
#modificationsBlock: BlkBlock | undefined;
|
readonly #modificationsBlocks: BlkBlock[];
|
||||||
#weaponsBlock: BlkBlock | undefined;
|
#weaponsBlock: BlkBlock | undefined;
|
||||||
#modsResearchBlock: BlkBlock | undefined;
|
#modsResearchBlock: BlkBlock | undefined;
|
||||||
|
|
||||||
@@ -30,9 +35,9 @@ export class ProfileEquipmentIndex {
|
|||||||
const hangar = findBlock(profile, HANGAR);
|
const hangar = findBlock(profile, HANGAR);
|
||||||
if (hangar) for (const entry of hangar.blocks) this.#hangar.set(entry.name, entry);
|
if (hangar) for (const entry of hangar.blocks) this.#hangar.set(entry.name, entry);
|
||||||
|
|
||||||
this.#modificationsBlock = findBlock(profile, MODIFICATIONS);
|
this.#modificationsBlocks = allModificationBlocks(profile);
|
||||||
if (this.#modificationsBlock) {
|
for (const chunk of this.#modificationsBlocks) {
|
||||||
for (const entry of this.#modificationsBlock.blocks) this.#modifications.set(entry.name, entry);
|
for (const entry of chunk.blocks) this.#modifications.set(entry.name, entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.#weaponsBlock = findBlock(profile, WEAPONS);
|
this.#weaponsBlock = findBlock(profile, WEAPONS);
|
||||||
@@ -103,14 +108,32 @@ export class ProfileEquipmentIndex {
|
|||||||
const key = recordName(vehicle, modification);
|
const key = recordName(vehicle, modification);
|
||||||
let block = this.#modifications.get(key);
|
let block = this.#modifications.get(key);
|
||||||
if (!block) {
|
if (!block) {
|
||||||
this.#modificationsBlock ??= ensureBlock(this.#profile, MODIFICATIONS);
|
|
||||||
block = { name: key, params: [], blocks: [] };
|
block = { name: key, params: [], blocks: [] };
|
||||||
this.#modificationsBlock.blocks.push(block);
|
this.#appendModificationBlock(block);
|
||||||
this.#modifications.set(key, block);
|
this.#modifications.set(key, block);
|
||||||
}
|
}
|
||||||
block.params = orderedModParams(record);
|
block.params = orderedModParams(record);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#appendModificationBlock(entry: BlkBlock): void {
|
||||||
|
for (let index = this.#modificationsBlocks.length - 1; index >= 0; index--) {
|
||||||
|
const chunk = this.#modificationsBlocks[index]!;
|
||||||
|
if (chunk.blocks.length < MAX_MODIFICATION_BLOCK_ENTRIES) {
|
||||||
|
chunk.blocks.push(entry);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const nextChunk: BlkBlock = { name: MODIFICATIONS, params: [], blocks: [entry] };
|
||||||
|
const lastChunk = this.#modificationsBlocks[this.#modificationsBlocks.length - 1];
|
||||||
|
if (lastChunk) {
|
||||||
|
const insertAt = this.#profile.blocks.lastIndexOf(lastChunk) + 1;
|
||||||
|
this.#profile.blocks.splice(insertAt, 0, nextChunk);
|
||||||
|
} else {
|
||||||
|
this.#profile.blocks.push(nextChunk);
|
||||||
|
}
|
||||||
|
this.#modificationsBlocks.push(nextChunk);
|
||||||
|
}
|
||||||
|
|
||||||
weaponRecord(vehicle: string, weapon: string): WeaponRecord | undefined {
|
weaponRecord(vehicle: string, weapon: string): WeaponRecord | undefined {
|
||||||
const block = this.#weapons.get(`${vehicle}_${weapon}`);
|
const block = this.#weapons.get(`${vehicle}_${weapon}`);
|
||||||
if (!block) return undefined;
|
if (!block) return undefined;
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
*/
|
*/
|
||||||
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
|
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
|
||||||
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
|
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
|
||||||
import { recordName } from '../profile/profile-modifications.ts';
|
import { allModificationBlocks, appendModificationEntry, recordName } from '../profile/profile-modifications.ts';
|
||||||
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
|
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
|
||||||
|
|
||||||
export interface SupportPlaneModification {
|
export interface SupportPlaneModification {
|
||||||
@@ -31,7 +31,10 @@ export interface SupportUnitEquipmentGrants {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function supportPlaneModifications(
|
export function supportPlaneModifications(
|
||||||
rules: Pick<BattleSpawnRulesData, 'supportPlanes' | 'strikeUcavs'>,
|
rules: Pick<
|
||||||
|
BattleSpawnRulesData,
|
||||||
|
'supportPlanes' | 'strikeUcavs' | 'nuclearEscalationTacticalCarriers' | 'nuclearEscalationStrategicBombers'
|
||||||
|
>,
|
||||||
catalogue: EquipmentCatalogue,
|
catalogue: EquipmentCatalogue,
|
||||||
): SupportUnitEquipmentGrants {
|
): SupportUnitEquipmentGrants {
|
||||||
const seenMods = new Set<string>();
|
const seenMods = new Set<string>();
|
||||||
@@ -53,21 +56,34 @@ export function supportPlaneModifications(
|
|||||||
weapons.push({ vehicle, weapon, count: Math.max(1, count) });
|
weapons.push({ vehicle, weapon, count: Math.max(1, count) });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const grantWeaponPreset = (unitName: string, weapon: string): void => {
|
||||||
|
const facts = catalogue.weapon(unitName, weapon);
|
||||||
|
addWeapon(unitName, weapon, facts?.maxCount ?? 1);
|
||||||
|
for (const modification of facts?.requires ?? []) addMod(unitName, modification);
|
||||||
|
for (const container of facts?.sumWeapons ?? []) {
|
||||||
|
const containerFacts = catalogue.weapon(unitName, container);
|
||||||
|
addWeapon(unitName, container, containerFacts?.maxCount ?? 1);
|
||||||
|
for (const modification of containerFacts?.requires ?? []) addMod(unitName, modification);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
for (const presets of Object.values(rules.supportPlanes)) {
|
for (const presets of Object.values(rules.supportPlanes)) {
|
||||||
for (const preset of presets) {
|
for (const preset of presets) {
|
||||||
for (const { unitName, weapon } of Object.values(preset.units)) {
|
for (const { unitName, weapon } of Object.values(preset.units)) {
|
||||||
const facts = catalogue.weapon(unitName, weapon);
|
grantWeaponPreset(unitName, weapon);
|
||||||
addWeapon(unitName, weapon, facts?.maxCount ?? 1);
|
|
||||||
for (const modification of facts?.requires ?? []) addMod(unitName, modification);
|
|
||||||
for (const container of facts?.sumWeapons ?? []) {
|
|
||||||
const containerFacts = catalogue.weapon(unitName, container);
|
|
||||||
addWeapon(unitName, container, containerFacts?.maxCount ?? 1);
|
|
||||||
for (const modification of containerFacts?.requires ?? []) addMod(unitName, modification);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const carrier of [
|
||||||
|
...rules.nuclearEscalationTacticalCarriers,
|
||||||
|
...rules.nuclearEscalationStrategicBombers,
|
||||||
|
]) {
|
||||||
|
for (const weapon of carrier.weapons) {
|
||||||
|
grantWeaponPreset(carrier.unitName, weapon.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (const ucav of rules.strikeUcavs) {
|
for (const ucav of rules.strikeUcavs) {
|
||||||
const vehicle = catalogue.vehicle(ucav.unitName);
|
const vehicle = catalogue.vehicle(ucav.unitName);
|
||||||
if (!vehicle) continue;
|
if (!vehicle) continue;
|
||||||
@@ -82,13 +98,14 @@ export function supportPlaneModifications(
|
|||||||
|
|
||||||
export function grantSupportPlaneModifications(profile: BlkBlock, grants: SupportUnitEquipmentGrants): void {
|
export function grantSupportPlaneModifications(profile: BlkBlock, grants: SupportUnitEquipmentGrants): void {
|
||||||
if (grants.modifications.length > 0) {
|
if (grants.modifications.length > 0) {
|
||||||
let modsBlock = findBlock(profile, 'modifications');
|
const existing = new Set<string>();
|
||||||
const existing = new Set((modsBlock?.blocks ?? []).map((entry) => entry.name));
|
for (const chunk of allModificationBlocks(profile)) {
|
||||||
|
for (const entry of chunk.blocks) existing.add(entry.name);
|
||||||
|
}
|
||||||
for (const { vehicle, modification } of grants.modifications) {
|
for (const { vehicle, modification } of grants.modifications) {
|
||||||
const key = recordName(vehicle, modification);
|
const key = recordName(vehicle, modification);
|
||||||
if (existing.has(key)) continue;
|
if (existing.has(key)) continue;
|
||||||
modsBlock ??= ensureBlock(profile, 'modifications');
|
appendModificationEntry(profile, { name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] });
|
||||||
modsBlock.blocks.push({ name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] });
|
|
||||||
existing.add(key);
|
existing.add(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
/**
|
||||||
|
* HTTP router service that exposes mod-registered routes under `/mods/<modId>/...`
|
||||||
|
* so mods can provide custom APIs or embedded-browser pages without touching core routes.
|
||||||
|
*/
|
||||||
|
import type { ModHttpHandler, ModHttpRequest } from '@wto/mods';
|
||||||
|
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
|
||||||
|
|
||||||
|
export interface RegisteredModHttpRoute {
|
||||||
|
readonly modId: string;
|
||||||
|
/** Full normalized path prefix or exact path under `/mods/<modId>/...`. */
|
||||||
|
readonly pattern: string;
|
||||||
|
readonly isWildcard: boolean;
|
||||||
|
readonly prefix: string;
|
||||||
|
readonly handler: ModHttpHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ModHttpService implements Service {
|
||||||
|
readonly name = 'mods-http';
|
||||||
|
readonly #routes: readonly RegisteredModHttpRoute[];
|
||||||
|
|
||||||
|
constructor(routes: readonly RegisteredModHttpRoute[]) {
|
||||||
|
this.#routes = routes;
|
||||||
|
}
|
||||||
|
|
||||||
|
accepts(request: ServiceRequest): boolean {
|
||||||
|
if (request.originalHost !== undefined) return false;
|
||||||
|
return this.#match(request.path) !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
async handle(request: ServiceRequest): Promise<ServiceResponse> {
|
||||||
|
const matched = this.#match(request.path);
|
||||||
|
if (!matched) {
|
||||||
|
return { status: 404, body: 'mod route not found' };
|
||||||
|
}
|
||||||
|
const headers: Record<string, string | undefined> = {};
|
||||||
|
for (const [key, value] of Object.entries(request.headers)) {
|
||||||
|
headers[key] = Array.isArray(value) ? value[0] : value;
|
||||||
|
}
|
||||||
|
const query: Record<string, string> = {};
|
||||||
|
for (const [key, value] of request.query.entries()) query[key] = value;
|
||||||
|
|
||||||
|
const modReq: ModHttpRequest = {
|
||||||
|
method: request.method,
|
||||||
|
path: request.path,
|
||||||
|
query,
|
||||||
|
headers,
|
||||||
|
body: request.body,
|
||||||
|
};
|
||||||
|
const answer = await matched.handler(modReq);
|
||||||
|
const responseHeaders: Record<string, string> = { ...(answer.headers ?? {}) };
|
||||||
|
if (answer.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
|
||||||
|
responseHeaders['content-type'] = answer.contentType;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: answer.status ?? 200,
|
||||||
|
headers: responseHeaders,
|
||||||
|
body: answer.body,
|
||||||
|
logNotes: { summary: `mod:${matched.modId} ${request.method} ${request.path}` },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#match(path: string): RegisteredModHttpRoute | undefined {
|
||||||
|
for (const route of this.#routes) {
|
||||||
|
if (route.isWildcard) {
|
||||||
|
if (path.startsWith(route.prefix)) return route;
|
||||||
|
} else if (path === route.pattern) {
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildModHttpRoute(modId: string, subPath: string, handler: ModHttpHandler): RegisteredModHttpRoute {
|
||||||
|
const cleaned = subPath.startsWith('/') ? subPath : `/${subPath}`;
|
||||||
|
const full = `/mods/${modId}${cleaned === '/' ? '' : cleaned}`;
|
||||||
|
if (full.endsWith('/*')) {
|
||||||
|
const prefix = full.slice(0, -1); // keeps trailing '/'
|
||||||
|
return { modId, pattern: full, isWildcard: true, prefix, handler };
|
||||||
|
}
|
||||||
|
return { modId, pattern: full, isWildcard: false, prefix: full, handler };
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* Isolated JSON storage for server mods:
|
||||||
|
* - per-player files under `<dataFolder>/saves/<userId>/mods/<safeModId>.json`
|
||||||
|
* - shared mod state under `<dataFolder>/mods-data/<safeModId>.json`
|
||||||
|
*
|
||||||
|
* Keeping mod state outside `profile.blk` guarantees uninstalling a mod never corrupts stock saves.
|
||||||
|
*/
|
||||||
|
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import type { ModPlayerStorage, ModStorageApi } from '@wto/mods';
|
||||||
|
import { writeFileAtomic } from '../storage/atomic-file.ts';
|
||||||
|
|
||||||
|
export function createModStorage(dataFolder: string, modId: string): ModStorageApi {
|
||||||
|
const safeMod = sanitizeSegment(modId);
|
||||||
|
return {
|
||||||
|
forPlayer(userId: string): ModPlayerStorage {
|
||||||
|
const safeUser = sanitizeSegment(userId);
|
||||||
|
const filePath = join(dataFolder, 'saves', safeUser, 'mods', `${safeMod}.json`);
|
||||||
|
return createJsonFileStorage(filePath);
|
||||||
|
},
|
||||||
|
shared(): ModPlayerStorage {
|
||||||
|
const filePath = join(dataFolder, 'mods-data', `${safeMod}.json`);
|
||||||
|
return createJsonFileStorage(filePath);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createJsonFileStorage(filePath: string): ModPlayerStorage {
|
||||||
|
return {
|
||||||
|
read<T = unknown>(): T | undefined {
|
||||||
|
if (!existsSync(filePath)) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(readFileSync(filePath, 'utf8')) as T;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
write(value: unknown): void {
|
||||||
|
writeFileAtomic(filePath, JSON.stringify(value, null, 2));
|
||||||
|
},
|
||||||
|
remove(): void {
|
||||||
|
try {
|
||||||
|
rmSync(filePath, { force: true });
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeSegment(raw: string): string {
|
||||||
|
const cleaned = raw.replace(/[^A-Za-z0-9._-]/g, '_');
|
||||||
|
if (!cleaned || cleaned === '.' || cleaned === '..') {
|
||||||
|
throw new Error(`invalid storage path segment "${raw}"`);
|
||||||
|
}
|
||||||
|
return cleaned;
|
||||||
|
}
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
/**
|
||||||
|
* Experimental server-side JS/TS mod runtime.
|
||||||
|
*
|
||||||
|
* Loads each enabled mod's server script entry (`.ts`, `.mjs`, or `.js` via Node 24's built-in
|
||||||
|
* TypeScript stripping and ESM dynamic import), injects an isolated `WtoServerModContext`, and
|
||||||
|
* coordinates lifecycle hooks, profile/battle hooks, char/matching wrappers, and `/mods/<id>/*`
|
||||||
|
* HTTP routes.
|
||||||
|
*/
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import type { BlkBlock } from '@wto/blk';
|
||||||
|
import {
|
||||||
|
MOD_API_VERSION,
|
||||||
|
type BattleFilterMissionsContext,
|
||||||
|
type BattleLiveFactContext,
|
||||||
|
type BattleMatchmakeContext,
|
||||||
|
type BattleMissionCandidate,
|
||||||
|
type BattleSettlementContext,
|
||||||
|
type DiscoveredMod,
|
||||||
|
type ModCharHandler,
|
||||||
|
type ModCharRequest,
|
||||||
|
type ModCharResponse,
|
||||||
|
type ModCharWrapper,
|
||||||
|
type ModHttpHandler,
|
||||||
|
type ModMatchingHandler,
|
||||||
|
type ModMatchingRequest,
|
||||||
|
type ModMatchingWrapper,
|
||||||
|
type ServerModCataloguesView,
|
||||||
|
type ServerModDatasetsView,
|
||||||
|
type WtoServerMod,
|
||||||
|
type WtoServerModContext,
|
||||||
|
} from '@wto/mods';
|
||||||
|
import type { MatchingRequestHandler, MatchingRequestTable } from '../matching/matching-requests.ts';
|
||||||
|
import { buildModHttpRoute, ModHttpService, type RegisteredModHttpRoute } from './mod-http-service.ts';
|
||||||
|
import { createModStorage } from './mod-storage.ts';
|
||||||
|
|
||||||
|
interface RuntimeInitOptions {
|
||||||
|
readonly mods: readonly DiscoveredMod[];
|
||||||
|
readonly gameFolder: string;
|
||||||
|
readonly dataFolder: string;
|
||||||
|
readonly port: number;
|
||||||
|
readonly report: (line: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScopedHandler<T> {
|
||||||
|
readonly modId: string;
|
||||||
|
readonly fn: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServerModRuntime {
|
||||||
|
readonly #report: (line: string) => void;
|
||||||
|
readonly #loadedModIds: string[] = [];
|
||||||
|
readonly #onDatasetsLoaded: ScopedHandler<(datasets: ServerModDatasetsView) => void | Promise<void>>[] = [];
|
||||||
|
readonly #onCataloguesReady: ScopedHandler<(catalogues: ServerModCataloguesView) => void | Promise<void>>[] = [];
|
||||||
|
readonly #onServerListening: ScopedHandler<(info: { readonly port: number }) => void | Promise<void>>[] = [];
|
||||||
|
readonly #onServerClosing: ScopedHandler<() => void | Promise<void>>[] = [];
|
||||||
|
readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = [];
|
||||||
|
readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = [];
|
||||||
|
readonly #onFilterMissions: ScopedHandler<(ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void>[] = [];
|
||||||
|
readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = [];
|
||||||
|
readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = [];
|
||||||
|
readonly #charHandlers = new Map<string, ScopedHandler<ModCharHandler>>();
|
||||||
|
readonly #charWrappers = new Map<string, ScopedHandler<ModCharWrapper>[]>();
|
||||||
|
readonly #matchingHandlers = new Map<string, ScopedHandler<ModMatchingHandler>>();
|
||||||
|
readonly #matchingWrappers = new Map<string, ScopedHandler<ModMatchingWrapper>[]>();
|
||||||
|
readonly #httpRoutes: RegisteredModHttpRoute[] = [];
|
||||||
|
|
||||||
|
private constructor(report: (line: string) => void) {
|
||||||
|
this.#report = report;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async load(options: RuntimeInitOptions): Promise<ServerModRuntime> {
|
||||||
|
const runtime = new ServerModRuntime(options.report);
|
||||||
|
const scriptMods = options.mods.filter((mod) => mod.content.serverEntry !== undefined);
|
||||||
|
if (scriptMods.length === 0) return runtime;
|
||||||
|
|
||||||
|
const cacheBust = Date.now();
|
||||||
|
for (const mod of scriptMods) {
|
||||||
|
const entryRel = mod.content.serverEntry!;
|
||||||
|
const entryAbs = join(mod.rootDir, ...entryRel.split('/'));
|
||||||
|
const modId = mod.manifest.id;
|
||||||
|
const url = `${pathToFileURL(entryAbs).href}?wto_mod=${cacheBust}`;
|
||||||
|
|
||||||
|
let loadedModule: Record<string, unknown>;
|
||||||
|
try {
|
||||||
|
loadedModule = (await import(url)) as Record<string, unknown>;
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Failed to load server mod "${modId}" (${entryRel}): ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const modExport = resolveModExport(loadedModule);
|
||||||
|
if (!modExport) {
|
||||||
|
throw new Error(
|
||||||
|
`Server mod "${modId}" (${entryRel}) must export default { setup(ctx) { ... } } or named setup(ctx)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ctx = runtime.#createContext(mod, options);
|
||||||
|
try {
|
||||||
|
await modExport.setup(ctx);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Server mod "${modId}" setup() failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
runtime.#loadedModIds.push(modId);
|
||||||
|
options.report(`mod ${modId}: server script loaded (${entryRel})`);
|
||||||
|
}
|
||||||
|
return runtime;
|
||||||
|
}
|
||||||
|
|
||||||
|
get loadedModIds(): readonly string[] {
|
||||||
|
return this.#loadedModIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
async runDatasetsLoaded(view: ServerModDatasetsView): Promise<void> {
|
||||||
|
for (const { modId, fn } of this.#onDatasetsLoaded) {
|
||||||
|
try {
|
||||||
|
await fn(view);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Server mod "${modId}" onDatasetsLoaded failed: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async runCataloguesReady(view: ServerModCataloguesView): Promise<void> {
|
||||||
|
for (const { modId, fn } of this.#onCataloguesReady) {
|
||||||
|
try {
|
||||||
|
await fn(view);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Server mod "${modId}" onCataloguesReady failed: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async runServerListening(port: number): Promise<void> {
|
||||||
|
for (const { modId, fn } of this.#onServerListening) {
|
||||||
|
try {
|
||||||
|
await fn({ port });
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] onServerListening error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async runServerClosing(): Promise<void> {
|
||||||
|
for (const { modId, fn } of [...this.#onServerClosing].reverse()) {
|
||||||
|
try {
|
||||||
|
await fn();
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] onServerClosing error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runProfileRefresh(profile: BlkBlock, userId: string): void {
|
||||||
|
for (const { modId, fn } of this.#onProfileRefresh) {
|
||||||
|
try {
|
||||||
|
fn(profile, userId);
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] profile.onRefresh error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runBattleBeforeMatchmake(ctx: BattleMatchmakeContext): void {
|
||||||
|
for (const { modId, fn } of this.#onBeforeMatchmake) {
|
||||||
|
try {
|
||||||
|
fn(ctx);
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] battle.onBeforeMatchmake error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runBattleFilterMissions<T extends BattleMissionCandidate>(
|
||||||
|
ctx: Omit<BattleFilterMissionsContext, 'missions'> & { readonly missions: readonly T[] },
|
||||||
|
): readonly T[] {
|
||||||
|
if (this.#onFilterMissions.length === 0) return ctx.missions;
|
||||||
|
let current: readonly T[] = ctx.missions;
|
||||||
|
for (const { modId, fn } of this.#onFilterMissions) {
|
||||||
|
try {
|
||||||
|
const next = fn({ ...ctx, missions: current });
|
||||||
|
if (Array.isArray(next)) {
|
||||||
|
const allowed = new Set(next.map((item) => item.name));
|
||||||
|
const filtered = current.filter((item) => allowed.has(item.name));
|
||||||
|
if (filtered.length > 0) {
|
||||||
|
current = filtered;
|
||||||
|
} else {
|
||||||
|
this.#report(`[mod:${modId}] battle.onFilterMissions returned 0 matching candidates for ${ctx.modeName}; keeping previous pool`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] battle.onFilterMissions error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
runBattleLiveFact(ctx: BattleLiveFactContext): void {
|
||||||
|
for (const { modId, fn } of this.#onLiveFact) {
|
||||||
|
try {
|
||||||
|
fn(ctx);
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] battle.onLiveFact error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runBattleAfterSettle(ctx: BattleSettlementContext): void {
|
||||||
|
for (const { modId, fn } of this.#onAfterSettle) {
|
||||||
|
try {
|
||||||
|
fn(ctx);
|
||||||
|
} catch (error) {
|
||||||
|
this.#report(`[mod:${modId}] battle.onAfterSettle error: ${formatError(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hasCharOverride(action: string): boolean {
|
||||||
|
return this.#charHandlers.has(action) || this.#charWrappers.has(action);
|
||||||
|
}
|
||||||
|
|
||||||
|
async dispatchCharOverride(
|
||||||
|
action: string,
|
||||||
|
request: ModCharRequest,
|
||||||
|
baseDispatch: (req: ModCharRequest) => Promise<ModCharResponse>,
|
||||||
|
): Promise<ModCharResponse> {
|
||||||
|
const custom = this.#charHandlers.get(action);
|
||||||
|
const terminal: (req: ModCharRequest) => Promise<ModCharResponse> = custom
|
||||||
|
? async (req) => await custom.fn(req)
|
||||||
|
: baseDispatch;
|
||||||
|
|
||||||
|
const wrappers = this.#charWrappers.get(action);
|
||||||
|
if (!wrappers || wrappers.length === 0) return terminal(request);
|
||||||
|
|
||||||
|
let chain = terminal;
|
||||||
|
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
|
||||||
|
const wrapper = wrappers[i]!.fn;
|
||||||
|
const next = chain;
|
||||||
|
chain = async (req) => await wrapper(req, next);
|
||||||
|
}
|
||||||
|
return chain(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
applyMatchingRoutes(baseTable: MatchingRequestTable): MatchingRequestTable {
|
||||||
|
if (this.#matchingHandlers.size === 0 && this.#matchingWrappers.size === 0) {
|
||||||
|
return baseTable;
|
||||||
|
}
|
||||||
|
const merged = new Map<string, MatchingRequestHandler>(baseTable);
|
||||||
|
|
||||||
|
for (const [method, custom] of this.#matchingHandlers) {
|
||||||
|
merged.set(method, (request, session) => custom.fn({
|
||||||
|
method,
|
||||||
|
params: request.params,
|
||||||
|
userId: session.authenticatedUserId(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [method, wrappers] of this.#matchingWrappers) {
|
||||||
|
const original = merged.get(method);
|
||||||
|
merged.set(method, (request, session) => {
|
||||||
|
const baseFn = (req: ModMatchingRequest): Record<string, unknown> => (
|
||||||
|
original ? original({ ...request, params: req.params }, session) : {}
|
||||||
|
);
|
||||||
|
let chain = baseFn;
|
||||||
|
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
|
||||||
|
const wrap = wrappers[i]!.fn;
|
||||||
|
const next = chain;
|
||||||
|
chain = (req) => wrap(req, next);
|
||||||
|
}
|
||||||
|
return chain({
|
||||||
|
method,
|
||||||
|
params: request.params,
|
||||||
|
userId: session.authenticatedUserId(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
httpService(): ModHttpService {
|
||||||
|
return new ModHttpService(this.#httpRoutes);
|
||||||
|
}
|
||||||
|
|
||||||
|
#createContext(mod: DiscoveredMod, options: RuntimeInitOptions): WtoServerModContext {
|
||||||
|
const modId = mod.manifest.id;
|
||||||
|
return {
|
||||||
|
apiVersion: MOD_API_VERSION,
|
||||||
|
manifest: mod.manifest,
|
||||||
|
modDir: mod.rootDir,
|
||||||
|
gameFolder: options.gameFolder,
|
||||||
|
dataFolder: options.dataFolder,
|
||||||
|
port: options.port,
|
||||||
|
logger: {
|
||||||
|
info: (message) => options.report(`[mod:${modId}] ${message}`),
|
||||||
|
warn: (message) => options.report(`[mod:${modId}] WARN: ${message}`),
|
||||||
|
error: (message) => options.report(`[mod:${modId}] ERROR: ${message}`),
|
||||||
|
},
|
||||||
|
storage: createModStorage(options.dataFolder, modId),
|
||||||
|
hooks: {
|
||||||
|
onDatasetsLoaded: (fn) => { this.#onDatasetsLoaded.push({ modId, fn }); },
|
||||||
|
onCataloguesReady: (fn) => { this.#onCataloguesReady.push({ modId, fn }); },
|
||||||
|
onServerListening: (fn) => { this.#onServerListening.push({ modId, fn }); },
|
||||||
|
onServerClosing: (fn) => { this.#onServerClosing.push({ modId, fn }); },
|
||||||
|
profile: {
|
||||||
|
onRefresh: (fn) => { this.#onProfileRefresh.push({ modId, fn }); },
|
||||||
|
},
|
||||||
|
battle: {
|
||||||
|
onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); },
|
||||||
|
onFilterMissions: (fn) => { this.#onFilterMissions.push({ modId, fn }); },
|
||||||
|
onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); },
|
||||||
|
onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
routes: {
|
||||||
|
char: {
|
||||||
|
register: (action, fn) => { this.#charHandlers.set(action, { modId, fn }); },
|
||||||
|
wrap: (action, fn) => {
|
||||||
|
const list = this.#charWrappers.get(action) ?? [];
|
||||||
|
list.push({ modId, fn });
|
||||||
|
this.#charWrappers.set(action, list);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
matching: {
|
||||||
|
register: (method, fn) => { this.#matchingHandlers.set(method, { modId, fn }); },
|
||||||
|
wrap: (method, fn) => {
|
||||||
|
const list = this.#matchingWrappers.get(method) ?? [];
|
||||||
|
list.push({ modId, fn });
|
||||||
|
this.#matchingWrappers.set(method, list);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
register: (subPath: string, handler: ModHttpHandler) => {
|
||||||
|
this.#httpRoutes.push(buildModHttpRoute(modId, subPath, handler));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveModExport(mod: Record<string, unknown>): WtoServerMod | undefined {
|
||||||
|
const def = mod.default;
|
||||||
|
if (def && typeof def === 'object' && typeof (def as Record<string, unknown>).setup === 'function') {
|
||||||
|
return def as WtoServerMod;
|
||||||
|
}
|
||||||
|
if (typeof def === 'function') {
|
||||||
|
return { setup: def as WtoServerMod['setup'] };
|
||||||
|
}
|
||||||
|
if (typeof mod.setup === 'function') {
|
||||||
|
return { setup: mod.setup as WtoServerMod['setup'] };
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatError(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.stack ?? error.message : String(error);
|
||||||
|
}
|
||||||
@@ -11,15 +11,18 @@
|
|||||||
import { setParam, type BlkBlock } from '@wto/blk';
|
import { setParam, type BlkBlock } from '@wto/blk';
|
||||||
import type { Account } from '../accounts/account-store.ts';
|
import type { Account } from '../accounts/account-store.ts';
|
||||||
import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts';
|
import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts';
|
||||||
|
import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts';
|
||||||
import { clearStoreCart } from './profile-store-cart.ts';
|
import { clearStoreCart } from './profile-store-cart.ts';
|
||||||
|
import { clientHangarSpares } from './profile-vehicle-state.ts';
|
||||||
import { serverTimeNow } from './server-time.ts';
|
import { serverTimeNow } from './server-time.ts';
|
||||||
|
|
||||||
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
|
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
|
||||||
// Shallow-copy only the top-level lists; child blocks are never mutated here.
|
// Clone the hangar entries whose spare count has a different wire representation.
|
||||||
const profile: BlkBlock = {
|
const profile: BlkBlock = {
|
||||||
name: saved.name,
|
name: saved.name,
|
||||||
params: [...saved.params],
|
params: [...saved.params],
|
||||||
blocks: [...saved.blocks],
|
blocks: saved.blocks.filter((block) => block.name !== DAILY_SPARES_BLOCK)
|
||||||
|
.map((block) => block.name === 'hangar' ? clientHangarSpares(block) : block),
|
||||||
};
|
};
|
||||||
clearStoreCart(profile);
|
clearStoreCart(profile);
|
||||||
const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON;
|
const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON;
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
|
||||||
|
|
||||||
|
export const DAILY_SPARES_BLOCK = 'wtoDailySpares';
|
||||||
|
|
||||||
|
// Stock quota from the Spearhead release notes and aces.exe 2.61.0.58 at 0x967a8d.
|
||||||
|
const FREE_SPARES_PER_DAY = 5;
|
||||||
|
const DAY_SECONDS = 24 * 60 * 60;
|
||||||
|
|
||||||
|
function utcDay(seconds: number): string {
|
||||||
|
return String(Math.floor(seconds / DAY_SECONDS));
|
||||||
|
}
|
||||||
|
|
||||||
|
function dayOf(profile: BlkBlock, startedAtSec: number): BlkBlock | undefined {
|
||||||
|
const ledger = findBlock(profile, DAILY_SPARES_BLOCK);
|
||||||
|
return ledger && findBlock(ledger, utcDay(startedAtSec));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dailySparesLeft(profile: BlkBlock, startedAtSec: number): number {
|
||||||
|
return Math.max(0, FREE_SPARES_PER_DAY - (dayOf(profile, startedAtSec)?.params.length ?? 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usedDailySpare(profile: BlkBlock, startedAtSec: number, key: string): boolean {
|
||||||
|
const day = dayOf(profile, startedAtSec);
|
||||||
|
return day !== undefined && findParam(day, key) !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One receipt per room and crew slot, shared by the live and settlement writes. */
|
||||||
|
export function recordDailySpare(profile: BlkBlock, startedAtSec: number, key: string): boolean {
|
||||||
|
if (usedDailySpare(profile, startedAtSec, key) || dailySparesLeft(profile, startedAtSec) === 0) return false;
|
||||||
|
const day = ensureBlock(ensureBlock(profile, DAILY_SPARES_BLOCK), utcDay(startedAtSec));
|
||||||
|
setParam(day, key, { type: 'bool', value: true });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -17,12 +17,20 @@
|
|||||||
* script function get_mission_progress (0x179c900 -> 0xebad60) looks up. It returns the
|
* script function get_mission_progress (0x179c900 -> 0xebad60) looks up. It returns the
|
||||||
* highest difficulty completed (0, 1, 2), or 3 or more when there is none.
|
* highest difficulty completed (0, 1, 2), or 3 or more when there is none.
|
||||||
*/
|
*/
|
||||||
import { ensureBlock, setParam, type BlkBlock } from '@wto/blk';
|
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
|
||||||
|
|
||||||
const PVE_PROGRESS = 'pveProgress';
|
const PVE_PROGRESS = 'pveProgress';
|
||||||
const MISSIONS = 'missions';
|
const MISSIONS = 'missions';
|
||||||
const DIFFICULTIES = [0, 1, 2] as const;
|
const DIFFICULTIES = [0, 1, 2] as const;
|
||||||
|
|
||||||
|
export function hasCompletedMissionDifficulty(profile: BlkBlock, fullMissionName: string, difficulty: 0 | 1 | 2): boolean {
|
||||||
|
const pve = findBlock(profile, PVE_PROGRESS);
|
||||||
|
const missions = pve && findBlock(pve, MISSIONS);
|
||||||
|
const mission = missions && findBlock(missions, fullMissionName);
|
||||||
|
const flag = mission && findParam(mission, `diff_${difficulty}`)?.value;
|
||||||
|
return flag?.type === 'bool' && flag.value;
|
||||||
|
}
|
||||||
|
|
||||||
/** Record the mission as completed on every difficulty up to and including `highest` (0, 1 or 2). */
|
/** Record the mission as completed on every difficulty up to and including `highest` (0, 1 or 2). */
|
||||||
export function recordMissionCompleted(profile: BlkBlock, fullMissionName: string, highest: 0 | 1 | 2): void {
|
export function recordMissionCompleted(profile: BlkBlock, fullMissionName: string, highest: 0 | 1 | 2): void {
|
||||||
const entry = ensureBlock(ensureBlock(ensureBlock(profile, PVE_PROGRESS), MISSIONS), fullMissionName);
|
const entry = ensureBlock(ensureBlock(ensureBlock(profile, PVE_PROGRESS), MISSIONS), fullMissionName);
|
||||||
|
|||||||
@@ -12,11 +12,19 @@
|
|||||||
* the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole:
|
* the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole:
|
||||||
* wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i
|
* wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i
|
||||||
* Absent values are left out; enabled is only written when false (the default is enabled).
|
* Absent values are left out; enabled is only written when false (the default is enabled).
|
||||||
|
*
|
||||||
|
* Dagor's binary DataBlock stores child block counts in a uint16 (65,535 max). Because the full
|
||||||
|
* vehicle catalogue exceeds 65,535 modifications, aces.exe splits modifications across up to 3
|
||||||
|
* sibling top-level `modifications` blocks of at most 65,535 entries each (2.61.0.37 0x938fae..0x9397e6,
|
||||||
|
* 2.61.0.58 0x93ba70 / 0x93bb53). All readers and writers here span every sibling block.
|
||||||
*/
|
*/
|
||||||
import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk';
|
import type { BlkBlock, BlkParam } from '@wto/blk';
|
||||||
|
|
||||||
const MODIFICATIONS = 'modifications';
|
const MODIFICATIONS = 'modifications';
|
||||||
|
|
||||||
|
/** Maximum entries per `modifications` DataBlock (uint16 child count limit in aces.exe 0x939000 / 0x93ba70). */
|
||||||
|
export const MAX_MODIFICATION_BLOCK_ENTRIES = 0xffff;
|
||||||
|
|
||||||
export interface ModificationRecord {
|
export interface ModificationRecord {
|
||||||
readonly silverLionsSpent: number;
|
readonly silverLionsSpent: number;
|
||||||
readonly goldenEaglesSpent: number;
|
readonly goldenEaglesSpent: number;
|
||||||
@@ -29,9 +37,66 @@ export function recordName(vehicle: string, modification: string): string {
|
|||||||
return `${vehicle}_${modification}`;
|
return `${vehicle}_${modification}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every top-level `modifications` chunk in the profile, in document order. */
|
||||||
|
export function allModificationBlocks(profile: BlkBlock): BlkBlock[] {
|
||||||
|
return profile.blocks.filter((block) => block.name === MODIFICATIONS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Append a new modification entry to a chunk with spare capacity, opening a sibling chunk when full. */
|
||||||
|
export function appendModificationEntry(profile: BlkBlock, entry: BlkBlock): void {
|
||||||
|
const chunks = allModificationBlocks(profile);
|
||||||
|
for (let index = chunks.length - 1; index >= 0; index--) {
|
||||||
|
const chunk = chunks[index]!;
|
||||||
|
if (chunk.blocks.length < MAX_MODIFICATION_BLOCK_ENTRIES) {
|
||||||
|
chunk.blocks.push(entry);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const nextChunk: BlkBlock = { name: MODIFICATIONS, params: [], blocks: [entry] };
|
||||||
|
const lastChunk = chunks[chunks.length - 1];
|
||||||
|
if (lastChunk) {
|
||||||
|
const insertAt = profile.blocks.lastIndexOf(lastChunk) + 1;
|
||||||
|
profile.blocks.splice(insertAt, 0, nextChunk);
|
||||||
|
} else {
|
||||||
|
profile.blocks.push(nextChunk);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ensure every top-level `modifications` chunk stays within the 65,535-child DataBlock limit. */
|
||||||
|
export function normalizeModificationBlocks(profile: BlkBlock): void {
|
||||||
|
const chunks = allModificationBlocks(profile);
|
||||||
|
if (chunks.length === 0) return;
|
||||||
|
const needsRebalance = chunks.some((chunk) => chunk.blocks.length > MAX_MODIFICATION_BLOCK_ENTRIES)
|
||||||
|
|| (chunks.length > 1 && chunks.some((chunk) => chunk.blocks.length === 0));
|
||||||
|
if (!needsRebalance) return;
|
||||||
|
|
||||||
|
const firstIndex = profile.blocks.findIndex((block) => block.name === MODIFICATIONS);
|
||||||
|
const entries = chunks.flatMap((chunk) => chunk.blocks);
|
||||||
|
profile.blocks = profile.blocks.filter((block) => block.name !== MODIFICATIONS);
|
||||||
|
if (entries.length === 0) return;
|
||||||
|
|
||||||
|
const rebuilt: BlkBlock[] = [];
|
||||||
|
for (let offset = 0; offset < entries.length; offset += MAX_MODIFICATION_BLOCK_ENTRIES) {
|
||||||
|
rebuilt.push({
|
||||||
|
name: MODIFICATIONS,
|
||||||
|
params: [],
|
||||||
|
blocks: entries.slice(offset, offset + MAX_MODIFICATION_BLOCK_ENTRIES),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
profile.blocks.splice(Math.max(0, firstIndex), 0, ...rebuilt);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findModificationEntry(profile: BlkBlock, key: string): BlkBlock | undefined {
|
||||||
|
for (const chunk of profile.blocks) {
|
||||||
|
if (chunk.name !== MODIFICATIONS) continue;
|
||||||
|
const found = chunk.blocks.find((entry) => entry.name === key);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined {
|
export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined {
|
||||||
const block = findBlock(profile, MODIFICATIONS);
|
const record = findModificationEntry(profile, recordName(vehicle, modification));
|
||||||
const record = block && findBlock(block, recordName(vehicle, modification));
|
|
||||||
if (!record) return undefined;
|
if (!record) return undefined;
|
||||||
return {
|
return {
|
||||||
silverLionsSpent: intOf(record, 'wpSpent'),
|
silverLionsSpent: intOf(record, 'wpSpent'),
|
||||||
@@ -42,12 +107,17 @@ export function modificationRecord(profile: BlkBlock, vehicle: string, modificat
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean {
|
export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean {
|
||||||
return modificationRecord(profile, vehicle, modification) !== undefined;
|
return findModificationEntry(profile, recordName(vehicle, modification)) !== undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void {
|
export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void {
|
||||||
const block = ensureBlock(ensureBlock(profile, MODIFICATIONS), recordName(vehicle, modification));
|
const key = recordName(vehicle, modification);
|
||||||
block.params = orderedParams(record);
|
const existing = findModificationEntry(profile, key);
|
||||||
|
if (existing) {
|
||||||
|
existing.params = orderedParams(record);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
appendModificationEntry(profile, { name: key, params: orderedParams(record), blocks: [] });
|
||||||
}
|
}
|
||||||
|
|
||||||
function orderedParams(record: ModificationRecord): BlkParam[] {
|
function orderedParams(record: ModificationRecord): BlkParam[] {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
* investMode:t the modification being researched, empty = none (AircraftInfo+0x100)
|
* investMode:t the modification being researched, empty = none (AircraftInfo+0x100)
|
||||||
* investModePrev:t the modification whose research just finished (+0x108)
|
* investModePrev:t the modification whose research just finished (+0x108)
|
||||||
* tierNumber:i the highest open modification tier (script is_tier_available)
|
* tierNumber:i the highest open modification tier (script is_tier_available)
|
||||||
* spareAircraftsCount:i spares the player has for this vehicle
|
* spareAircraftsCount:i owned spares in the saved profile, encoded as a negative i64 on the wire
|
||||||
* excessExp:i64 banked modification research points (+0x70)
|
* excessExp:i64 banked modification research points (+0x70)
|
||||||
* freeRepairs:i64 free repairs used (0x941cef; shop_get_free_repairs_used at 0x17a4b80)
|
* freeRepairs:i64 free repairs used (0x941cef; shop_get_free_repairs_used at 0x17a4b80)
|
||||||
*/
|
*/
|
||||||
@@ -55,6 +55,19 @@ export function setSpareCount(profile: BlkBlock, vehicle: string, count: number)
|
|||||||
if (entry) setParam(entry, SPARES, { type: 'int', value: count });
|
if (entry) setParam(entry, SPARES, { type: 'int', value: count });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** SpareAircraftStat reads i64 and clears positive values. The getter negates the stat
|
||||||
|
* (aces.exe 2.61.0.58 0x9447bb, 0x94f7ab, 0x17abe70). */
|
||||||
|
export function clientHangarSpares(hangar: BlkBlock): BlkBlock {
|
||||||
|
const blocks = hangar.blocks.map((vehicle) => {
|
||||||
|
const count = findParam(vehicle, SPARES)?.value;
|
||||||
|
if (count?.type !== 'int') return vehicle;
|
||||||
|
const clientVehicle = { ...vehicle, params: [...vehicle.params] };
|
||||||
|
setParam(clientVehicle, SPARES, { type: 'int64', value: -BigInt(count.value) });
|
||||||
|
return clientVehicle;
|
||||||
|
});
|
||||||
|
return { ...hangar, blocks };
|
||||||
|
}
|
||||||
|
|
||||||
/** Uses one free repair on an owned vehicle if it still has an allowance. */
|
/** Uses one free repair on an owned vehicle if it still has an allowance. */
|
||||||
export function consumeFreeRepair(profile: BlkBlock, vehicle: string, allowance: number): boolean {
|
export function consumeFreeRepair(profile: BlkBlock, vehicle: string, allowance: number): boolean {
|
||||||
const entry = vehicleEntry(profile, vehicle);
|
const entry = vehicleEntry(profile, vehicle);
|
||||||
|
|||||||
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user