diff --git a/dev-docs.html b/dev-docs.html index 08faa51..d1958ca 100644 --- a/dev-docs.html +++ b/dev-docs.html @@ -4,7 +4,7 @@ WTOffline · 开发者文档与 PR 规范 - + @@ -60,265 +60,1345 @@ 返回 WTOffline 主页 Back to WTOffline Home -
DEVELOPER DOCUMENTATION
+
DEVELOPER HANDBOOK

- 开发者文档与贡献规范 - Developer Docs & Contribution Standards + 开发者手册(全 5 章) + Developer Handbook (5 Chapters)

- - 面向核心代码贡献者、版本适配者与使用 AI 辅助开发的协作者。写清架构分层、动态补丁做法、常见实现陷阱与提交前检查命令,让每一笔 PR 既解决根因又经得起后续版本演进。 - - - For core contributors, client version adapters, and AI-assisted PR authors. Covers repository layering, dynamic patching, common implementation pitfalls, and required verification commands. - + 与仓库 dev-docs/ 1:1 同源生成的完整手册:从核心黑话翻译、服务端完整请求走读、EXE 逐字节拆解与 Native 6 文件接线,到 AI 辅助开发约束提示词与流量日志排错法。 + Compiled 1:1 from repository dev-docs/: plain-language glossary, end-to-end server action trace, 57-byte EXE patch anatomy, 6-file Native C wiring, AI coding assistant prompt, and traffic-log debugging.

-
- - -
-

- 1. 常见实现陷阱与工程红线(含 AI 辅助开发对照) - 1. Common Implementation Pitfalls (Including AI-Assisted PRs) -

-
- - 欢迎使用 AI 辅助定位根因。借助 AI 阅读反汇编、分析协议和定位 bug 非常高效;但真正提交代码前,请按下面 7 条正反对照逐项收口实现——也可以直接把本节作为约束交给你的 AI 助手。 - - - AI-assisted root-cause analysis is welcome. Before opening a PR, review the implementation itself against the 7 engineering guardrails below—feel free to pass this section directly to your AI coding assistant as constraints. - +
+
+

01 · 导览、核心术语词典与任务入口

+

欢迎参与 WTOffline 开发。本目录面向项目贡献者、客户端新版本适配者,以及使用 AI 编程工具辅助逆向定位与编写代码的协作者。无论你之前是否接触过 Dagor 引擎或《战争雷霆》客户端内部结构,都可以按本指南一步步上手。

+

如果你只是想制作载具属性魔改、自定义地图池、全新 3D 载具模型或服务端脚本模组:你完全不需要修改 WTOffline 核心源码,请直接阅读 模组开发文档(mod-dev-docs) 或访问 在线模组文档。

+
+

第一次来,建议按什么顺序读?

+

不要一上来就啃二进制补丁字段或反汇编地址。按下面三步顺读,大约 15–20 分钟就能建立完整的全局认知:

+
  1. 开发理念、架构分层与工程规范(必读第一站):搞清楚启动器、单端口本地模拟服务器(apps/server)与进程内网络/对局桥接库(wto_ws.dll)是如何协同工作的;顺着一个真实的 cln_set_researchable 动作看懂服务端四层代码怎么流转;掌握「三类数值放哪里」「好代码 vs 坏代码」真实对比,以及可直接复制给 AI 编程助手的工程约束提示词。
  2. 补丁编写与新版本适配指南:当确认本地服务器与原版配置确实无法解决问题、必须修改客户端时,按这篇手把手教程拆包查看原版文件、用 tools/re/cli.py 反汇编定位,并对照完整无省略的 GUI(patches/gui/)、EXE(patches/exe/)和 Native(patches/native/ + native/wto-net/)真实案例编写跨版本自适应补丁。
  3. 环境搭建、流量调试与提交自查:配齐本地开发环境,学会直接阅读 <数据目录>/logs/ 下自动解码的明文 BLK 流量日志快速抓 Bug,按改动类型运行对应的必跑检查命令,并对照 PR 模板 提交高质量改动。
+
+

核心概念与术语词典

+

在阅读后续文档或翻阅源码时,你会频繁遇到以下专有名词。这里用大白话一次性讲透:

+

1. vromfs.bin(Dagor 虚拟只读归档包)

+

《战争雷霆》不会把成千上万个零散脚本和配置文件直接摊在硬盘上,而是打包进若干个 .vromfs.bin 归档文件中。它在结构上分两层:外层是带简单异或混淆的 Zstandard(zstd)压缩容器、内部镜像 MD5 与末尾 256 字节签名;内层是文件表(全小写相对路径、偏移量、可选 SHA-1 摘要,以及可选的共享键名表 nm 与 .dict 压缩字典)。项目中的 @wto/vromfs(readArchive / getFile / putFile / writeArchive)负责无损读写这些归档包。

+

不同归档包各司其职,查数据时按下面这张表找最快:

+
归档包路径(相对于游戏根目录)里面装什么核心内容WTOffline 哪里会用到它
char.vromfs.bin科技树排布(config/shop.blk)、载具价格/研发点/修车费/改装件(config/wpcost.blk)、全局经济与分房公式(config/warpoints.blk、config/rank.blk)、初始档案模板(config/default_user.blk)、任务列表与成就解锁(config/mislist.blk、config/pve_awards.blk、config/unlocks.blk)、涂装/贴花/挂件/道具定义(config/skins.blk、config/decals.blk、config/attachable.blk、config/items.blk)以及 config/network.blkpackages/patcher 构建副本时改写服务地址与隐藏载具可见性;apps/server 启动时从中提取绝大部分静态经济与科技树数据集
aces.vromfs.bin局内玩法与连杀支援规则(config/gameplay.blk)、界面与礼包 GUID 映射(config/gui.blk)、工坊配方(config/workshop.blk)以及全部载具的气动/损伤/武器预设模型(gamedata/flightmodels/…、gamedata/units/…)packages/patcher 写入本地商店礼包 GUID;apps/server 提取对局出生规则、礼包映射与载具武器预设
gui.vromfs.bin客户端全部机库、弹窗、商店、战后结算与 HUD 界面的 Quirrel 脚本(scripts/**/*.nut)与布局模板(.blk / .css)patches/gui/ 在构建副本时对少数客户端界面脚本做精确片段替换
mis.vromfs.bin多人对战与单人任务的地图逻辑、出生点区域、战区与胜利条件定义(gamedata/missions/**/*.blk)apps/server 启动时扫描提取多人任务目录(multiplayer-missions 数据集),用于匹配开局
lang.vromfs.bin分号分隔的多语言本地化词条表(lang/units.csv、lang/menu.csv、lang/unlocks_achievements.csv 等)apps/server 提取载具、国家与物品的多语言显示名称,供本地网页商店、交易所和启动器展示
ui/atlases.vromfs.bin科技树载具剪影与阵营国旗等矢量图标(gameuiskin/*.svg)apps/server 按需提取金币车/礼包车/市场车图标与国旗(web-icons 数据集)供游戏内嵌网页商店渲染
ui/images.vromfs.bin界面位图插画、礼包封面与飞行员头像贴图(images/**)apps/server 为内嵌网页商店展示商品封面,并为启动器存档页渲染玩家头像
+

2. BLK / DataBlock(Dagor 树状键值与块数据格式)

+

BLK(引擎 C++ 类名为 DataBlock)是贯穿整个游戏的通用配置与通信载体,结构类似「带严格值类型的树状 JSON」:每个节点既可以挂载带类型的参数(如整数 :i、浮点 :r、字符串 :t、布尔 :b、三维向量 :p3、矩阵 :m 等),也可以嵌套任意多层同名或异名子块。在 WTOffline 中你会见到它的四种形态,全部由 @wto/blk(decodeBlk、encodeBlk、formatBlkText、parseBlkText)统一处理:

+
  • 归档包内的紧凑二进制 BLK:char.vromfs.bin 与 aces.vromfs.bin 里的 .blk 通常将键名抽离到包内共享键名表 nm(甚至配合 .dict 字典做二次 zstd 压缩),解码时需传入 SharedNameContext;
  • char 协议单包二进制 BLK:HTTP 响应体首字节带压缩标记(例如 0x69 即 'i' 表示未压缩二进制 BLK,另有 zlib / zstd 标记),后面紧跟自包含二进制 BLK;
  • PBBD 批处理流:客户端上传云端键位与设置(cln_bulk_set_gblk)时使用的多段二进制容器(魔数 "PBBD"),每段内嵌独立 BLK 块;
  • 本地存档自包含二进制 BLK:<数据目录>/saves/<userId>/profile.blk 直接用 encodeBlk() 落盘,完整保留每个字段的原始值类型,避免整数与浮点数混淆导致客户端解析异常。
+

3. 本地模拟的四大 Gaijin 后端服务

+

原版联网客户端并不是只跟一台服务器通信,而是同时访问多套职责不同的后端服务。apps/server 在本机 127.0.0.1:<端口> 上把这四大核心服务全部接管并模拟:

+
  • yuplay2(登录与权益服务,login/、store/):处理客户端启动时的账号密码表单登录(POST /login.php),签发本地会话凭据与 userId,并提供商店礼包与激活码相关的 Web 接口;
  • char(角色档案服务器 Character Server,char/):机库阶段最核心的请求入口(原域名 char-*.warthunder.com)。客户端通过 HTTP 请求头 action 指明动作名(如 cln_get_user_stat、cln_buy_aircraft、cln_set_researchable、cln_update),通过 uidhint 指明当前账号,请求与响应主体以二进制 BLK 为主,负责完整玩家档案下发、科技树研发、买车买改装、乘员组训练、联队、云端键位设置及战后经济结算;
  • matching(匹配与开局二进制长连接服务,matching/):基于 TCP 的自定义二进制长连接协议(首字节固定为 0x01,9 字节包头 + LZ4 压缩负载,握手后启用流加密)。负责向客户端下发可用游戏模式列表、接收排队与小队状态,并在匹配成功时向客户端下发完整的对局启动参数(地图、天气、AI 名单、自定义计分参数等);
  • inventory(外部物品库与交易所服务,inventory/):模拟 inventory-proxy-*.gaijin.net/char 接口(动作名如 GetInventory、GetItemDefsClient、GetItemPrices、GetItemDefChances、ExchangeItems)。与 char 不同,客户端 charsq 模块直接将响应解析为 UTF-8 JSON,且要求关键响应附带 RSA 内容签名;用于驱动补给箱开箱、载具兑换券、工坊合成与本地模拟交易所。
+

4. LocalMP(为什么既要有 apps/server,又必须有 wto_ws.dll?)

+

初看代码库时最容易产生的疑问是:既然已经用 Node.js 写了本地服务器 apps/server,为什么还要用 C 写一个 native/wto-net/(编译为 wto_ws.dll)注入进游戏进程?

+

原因在于《战争雷霆》客户端与专用对局服务器(Dedicated Server)的代码裁剪边界:

+
  • 原版零售客户端 aces.exe 内部其实保留了一套名为 LocalMP(本地多人主机,mp_is_host == 1 && mp_is_local_mp == 1) 的局内会话模式,能够在本机直接跑完整的物理引擎、弹道解算、损伤模型与 AI 驾驶逻辑,因此 WTOffline 不需要重写整套游戏物理服务器;
  • 但是,Gaijin 在编译零售版 aces.exe 时,把原本只在云端专用对局服务器上运行的大量「对局裁判(Host Referee)」处理逻辑裁掉了——包括:响应玩家选车与挂载弹药并生成实体、允许 BotSystem 刷出 AI 载具、判定击杀/助攻/占点并往记分牌加分、陆战街机连杀空中支援事件生成、核弹落地直接判胜,以及过滤本不该发给受害者之外玩家的炮管/炮闩受损提示;
  • 因此两套组件分工明确、缺一不可:apps/server 负责对局之外的一切(登录、机库养成、商店市场、排队拼装任务配置、战后发银狮/研发点与存档持久化);而 wto_ws.dll 在对局进行期间通过 MinHook 挂载在 aces.exe 进程内,一方面把所有硬编码外网 Socket 连接重定向回 127.0.0.1,另一方面通过 local_mp_* 模块把被客户端裁掉的局内主机裁判逻辑原原本本补齐。
+

5. Quirrel (.nut) 与 sq.exe 字节码编译器

+

gui.vromfs.bin 中的 .nut 文件使用的是 Gaijin 基于 Squirrel 深度定制的强词法作用域脚本语言 Quirrel。客户端在玩家点击登录、进入机库前会一次性编译加载大批 .nut 脚本。

+

为什么修改 patches/gui/ 后不能只靠肉眼或普通语法树(AST)检查,而需要用对应提交版本的原生编译器 sq.exe 跑 wtotools check-gui?因为 Quirrel 的 compilestring 字节码编译阶段会执行严格的词法绑定检查:

+
  • 如果你在 replace.nut 里声明了一个 local 变量,恰好与该文件顶部 from ... import * 通配导入的某个全局常量重名;
  • 或者在函数尚未定义/绑定前做了前向调用;
  • 或者把 Quirrel 保留字(最典型的坑是 base)当成了普通变量名;
+

普通语法检查器都会放行,但真进游戏时 Quirrel 虚拟机就会直接中断模块加载,导致客户端永远卡死在登录后的「正在加载…」转圈界面。wtotools check-gui 会在内存中打上所有 GUI 补丁并逐个调用 sq.exe 编译字节码,把这类致命隐患在提交前 100% 拦住。

+

6. RVA、虚拟地址(VA)与进程运行时指针

+

在看 patches/exe/、patches/native/ 或使用逆向工具时,务必分清这三种地址表示:

+
  • VA(Virtual Address,静态虚拟地址):Ghidra 或 IDA 打开 64 位 Windows 程序 aces.exe 时,默认镜像基址(ImageBase)是 0x140000000,因此反编译器里显示的函数地址往往长这样:0x1412657a0;
  • RVA(Relative Virtual Address,相对虚拟地址):减去镜像基址后的纯偏移,即 RVA = VA - ImageBase(例如 0x1412657a0 - 0x140000000 = 0x12657a0)。因为 Windows 的 ASLR(地址空间布局随机化)每次启动游戏都会把 aces.exe 加载到不同的内存基址,仓库内所有补丁注释、tools/re/cli.py 参数以及生成的 win64/wto_ws.cfg 一律使用 RVA;
  • 运行时绝对指针(Runtime Pointer):游戏启动后,wto_ws.dll(见 native/wto-net/src/local_mp_values.c)通过 (uint8_t *)GetModuleHandleW(NULL) + rva 把 wto_ws.cfg 里的 RVA 换算成当次进程内的真实内存地址存入 g_lmp。
+

7. features 功能标签与三条「核心安全锁」(ESSENTIAL_FEATURES)

+

每个 patches/exe/**/patch.jsonc、patches/gui/**/patch.jsonc 和 patches/native/*.jsonc 都包含一个 features 字符串数组,标签以功能分组字母 A-..K- 开头(例如 "G-Store"、"K-AI opponents and teammates"、"K-Kill, assist and capture scoring")。当游戏刚发布小版本更新、个别非关键补丁暂时失配时,启动器依靠这些标签清晰告知玩家「当前版本哪一项具体子功能暂不可用」,其余功能仍可正常游玩。

+

但其中有 3 个定义在 packages/patcher/src/essential-features.ts(ESSENTIAL_FEATURES)中的硬阻断安全标签例外:

+
  1. A-Offline startup:离线副本能否启动的根基(例如跳过修改后 .vromfs.bin 的官方签名校验);
  2. A-Isolation from the official game:与官方正版客户端的完全隔离(将用户配置存档改到独立 WTOffline 目录、注册表改到 Software\WTOffline、剥离反作弊启动器与崩溃上报);
  3. A-No Gaijin connections:彻底阻断连向 Gaijin 官方服务器(例如将导入表 WS2_32.dll 替换为 wto_ws.dll 并在加载时强制挂载网络重定向钩子)。
+

只要带有上述任一标签的补丁未能成功定位和应用,blockingFailures() 就会终止副本构建与启动,防止离线客户端触碰玩家的线上正版数据或直连官方服务器,从而保护玩家的线上账号安全。

+
+

按你想做的事,直接定位代码目录

+
你想做什么具体源码子目录对口参考章节
新增或修复机库动作路由(买车、研发、乘员、联队、贴花、战后结算等 char 接口)apps/server/src/char/actions/(协议适配)+ apps/server/src/<领域>/(纯业务规则,如 research/、modifications/、crew/、battle/)架构分层与真实动作追踪
修改玩家档案字段读写、新号初始资产或存档落盘格式apps/server/src/profile/、apps/server/src/saves/、apps/server/src/storage/存档层与原子写盘规范
从游戏原版数据包提取新的载具/经济/任务/本地化静态数据apps/server/src/game-data/datasets/三类数值与缓存数据集
调整离线版默认倍率、商店定价、补给箱权重、AI 重生数或上限参数apps/server/tuning/*.jsonc + apps/server/src/tuning/ + 各领域 *-tuning.ts三类数值放哪里
修改本地内嵌网页商店、模拟交易所或服务器脚本模组运行时apps/server/src/store/、apps/server/src/inventory/、apps/server/src/web-ui/、apps/server/src/mods/服务器目录全景图
修改桌面启动器界面、安装向导、存档管理页、模组管理页或更新器apps/launcher/src/检查命令清单
修改离线副本构建管线、归档包改写、BLK 编解码、EXE 补丁引擎或模组加载器packages/patcher/、packages/blk/、packages/vromfs/、packages/exepatch/、packages/mods/仓库级单向依赖约定
修改游戏内界面弹窗、按钮或结算页脚本(Quirrel .nut)patches/gui/<领域>/<名称>/GUI 补丁完整范例
修改 aces.exe 机器码分支或只读常量字符串patches/exe/<领域>/<名称>/EXE 补丁 57 字节逐指令拆解
编写或修复 wto_ws.dll 局内 LocalMP 原生裁判钩子patches/native/<模块>.jsonc + native/wto-net/src/Native 模块 6 文件串联教程
协助适配刚发布的《战争雷霆》客户端小版本更新patches/versions/、scripts/record-game-version.ts适配新版本客户端四步流程
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
维度Area推荐做法Preferred Practice避免做法Avoid
定位与偏移Locating & OffsetsDOexe 与 native 一律通过 patches/exe/、patches/native/ 的 signature / string_ref / within 动态捕获地址、跳转目标与结构体偏移。Resolve addresses, jump targets, and struct offsets dynamically via signature, string_ref, or within captures in patches/.AVOID在 C/TS 代码里硬编码 RVA、结构体偏移、函数地址或 _ReturnAddress(游戏一个小补丁就会全断)。Hardcoding RVAs, struct offsets, raw function pointers, or _ReturnAddress checks in C or TypeScript.
改动分层LayeringDO先看本地服务器协议、任务根字段或原版配置能否解决;严守协议层 / 规则层 / 存档层 / 数据层职责,修改档案先写盘再回复。Solve in the local server or stock config first; keep protocol, rules, persistence, and datasets separate, and write saves before replying.AVOID用客户端补丁绕开本该由服务端处理的问题;在协议处理器里堆大段规则;先回成功再写盘。Adding client hacks for server-solvable issues, mixing game rules into protocol handlers, or replying before persistence.
静态数据与数值Static Data & TuningDO载具、任务、奖励、出生点等原版数据通过缓存 datasets/ 从玩家游戏文件读取;离线自定参数放进 apps/server/tuning/*.jsonc 并做启动校验。Read stock vehicle, mission, reward, and spawn data from player archives via cached datasets/; put offline defaults in tuning/*.jsonc with startup validation.AVOID在源码里手抄原版表、写死兜底坐标或散落魔法数字。Copying stock tables into source code, hardcoding fallback coordinates, or scattering magic constants.
复用与粒度Reuse & ModularityDO复用 local_mp_core 等公共站点与现有工具;共享库 packages/* 通过参数收配置;文件接近 300 行、函数接近 50 行时拆分职责。Reuse shared native sites (local_mp_core) and helpers; pass paths/config into packages/*; split files near 300 lines or functions near 50 lines.AVOID重复挂钩同一原生函数;让 packages/* 反向读取 apps/*;把多项职责塞进单个大文件或大函数。Duplicating hooks on the same symbol, reading apps/* from packages/*, or growing monolithic handlers.
编译器兼容ToolchainsDONative C 必须用 MSVC native/wto-net/build.ps1 编过且 0 警告;TS 兼容 Node 24 原生类型剥离(erasableSyntaxOnly)。Build native C cleanly with MSVC native/wto-net/build.ps1 (zero warnings); keep TS compatible with Node 24 erasable syntax.AVOID引入 GCC 专属扩展(如 typeof / 语句表达式)或未在 MSVC 编过的 C 代码。Relying on GCC-only extensions or submitting C edits without an MSVC build check.
校验与验收VerificationDO按变动运行 typecheck、check-patches、完整 check-gui(Quirrel 字节码检查)与临时副本构建,如实标注待实机验收项。Run the applicable typecheck, check-patches, full check-gui (Quirrel bytecode check), and temporary copy build; honestly mark pending in-game checks.AVOID只跑模拟单测就宣称实机无误;跳过 check-gui;在未实机验收前提交 patches/versions/*.jsonc。Treating mock tests as in-game verification, skipping check-gui, or committing patches/versions/*.jsonc before live acceptance.
范围与纪律Scope & HygieneDO一笔 PR 专注单一目标,使用英文约定式提交与英文代码注释,Co-authored-by 只留给实际协作的人类开发者。Keep one goal per PR, use English conventional commits and English comments, and reserve Co-authored-by for human collaborators.AVOID夹带无关重构或格式改动、暴露个人本机绝对路径、给 AI 助手加 Co-authored-by。Mixing unrelated refactors, leaking personal paths, or adding AI tools in Co-authored-by.
+
+

01 · Overview, Core Glossary & Task Map

+

Welcome to WTOffline development. This directory is written for project contributors, client build adapters, and collaborators using AI coding assistants to reverse-engineer, investigate, and fix issues. Even if you have never worked with the Dagor Engine or War Thunder internals before, these guides walk you through every layer from first principles.

+

Just want to create vehicle stat tweaks, custom map pools, standalone 3D vehicles, or server script mods? You do not need to modify WTOffline's core source code at all—head straight to the Mod Development Docs (mod-dev-docs) or the online Mod Docs.

+
+ +

Do not jump straight into raw byte patterns or disassembly offsets on your first visit. Reading the three core guides in this order builds the full mental model in 15–20 minutes:

+
  1. Design Philosophy, Architecture & Engineering Rules (Start here): Understand how the launcher, single-port local server (apps/server), and in-process Winsock/LocalMP bridge (wto_ws.dll) fit together; trace one real cln_set_researchable request end-to-end across all four server layers; learn where the three categories of numbers belong; review four real Good vs. Bad code comparisons; and grab the copy-paste prompt block for AI coding assistants.
  2. Patch Authoring & Version Adaptation Guide: Once you have confirmed that the local server and stock configuration genuinely cannot solve an issue, follow step-by-step instructions to unpack stock archives, disassemble aces.exe with tools/re/cli.py, and study un-elided real patches across patches/gui/, patches/exe/, and patches/native/ + native/wto-net/.
  3. Environment Setup, Traffic Debugging & PR Guide: Set up the Windows x64 toolchain, inspect auto-decoded readable BLK payloads under <data-dir>/logs/ to pinpoint bugs in minutes, run the required verification commands for your change type, and fill out the PR template.
+
+

Core Concepts & Glossary

+

You will encounter these War Thunder and WTOffline terms throughout the codebase and documentation. Here is what each one means in plain language:

+

1. vromfs.bin (Dagor Virtual Read-Only File System Archive)

+

Instead of shipping tens of thousands of loose scripts and config files on disk, War Thunder bundles them into .vromfs.bin archives. Each archive has two layers: an outer container (Zstandard compression with lightweight XOR obfuscation, an MD5 digest of the inner image, and a 256-byte signature tail) and an inner image (a lowercase relative path table, byte offsets, optional SHA-1 digests, plus an optional shared name map nm and .dict zstd dictionary). @wto/vromfs (readArchive, getFile, putFile, writeArchive) reads and repacks these archives losslessly.

+

Use this lookup table whenever you need to find where a stock script, config, or asset lives:

+
Archive path (relative to game root)What it storesHow WTOffline uses it
char.vromfs.binTech-tree layout (config/shop.blk), per-vehicle prices, RP, repair costs, and modifications (config/wpcost.blk), global economy and BR formulas (config/warpoints.blk, config/rank.blk), new-account profile template (config/default_user.blk), mission lists and unlock definitions (config/mislist.blk, config/pve_awards.blk, config/unlocks.blk), camos/decals/decorators/classic items (config/skins.blk, config/decals.blk, config/attachable.blk, config/items.blk), and config/network.blkpackages/patcher rewrites backend URLs and hidden-vehicle visibility during copy builds; apps/server extracts most economy, tech-tree, unlock, and mission datasets from it at startup
aces.vromfs.binMatch gameplay and killstreak rules (config/gameplay.blk), UI config and store bundle GUID mappings (config/gui.blk), workshop recipes (config/workshop.blk), and all vehicle flight/damage/weapon preset files (gamedata/flightmodels/…, gamedata/units/…)packages/patcher injects offline store bundle GUIDs; apps/server extracts spawn rules, bundle mappings, and weapon presets
gui.vromfs.binAll in-game hangar, modal, store, debriefing, and HUD Quirrel scripts (scripts/**/*.nut) and layout templates (.blk / .css)patches/gui/ applies minimal surgical text replacements to UI scripts when building the offline copy
mis.vromfs.binMultiplayer and single-player mission logic, spawn zones, capture points, and victory rules (gamedata/missions/**/*.blk)apps/server scans it at startup (multiplayer-missions dataset) to build matchmaking mission definitions
lang.vromfs.binSemicolon-separated localization CSV tables (lang/units.csv, lang/menu.csv, lang/unlocks_achievements.csv, etc.)apps/server extracts localized vehicle, country, and item names for the in-game web store, marketplace, and launcher
ui/atlases.vromfs.binTech-tree vehicle silhouettes and country flags in SVG format (gameuiskin/*.svg)apps/server extracts icons for gift/premium/market vehicles and flags (web-icons dataset) for the local web store and marketplace
ui/images.vromfs.binUI raster artwork, bundle cover images, and pilot avatar textures (images/**)apps/server serves store/marketplace item artwork and renders player profile icons for the launcher's saves page
+

2. BLK / DataBlock (Dagor Typed Hierarchical Data Format)

+

BLK (named DataBlock in Dagor Engine C++ code) is the typed tree format used everywhere in War Thunder for configs, network payloads, and player profiles. Think of it as a tree of named blocks and typed key-value parameters (:i integers, :r floats, :t strings, :b booleans, :p3 3D vectors, :m matrices, etc.). You will encounter four binary/wire representations in WTOffline, all handled by @wto/blk (decodeBlk, encodeBlk, formatBlkText, parseBlkText):

+
  • Slimmed binary BLK inside .vromfs.bin: .blk files inside char.vromfs.bin and aces.vromfs.bin strip repeated key names into the archive's shared name map nm (and may compress payloads with an archive .dict zstd dictionary), decoded by passing SharedNameContext to decodeBlk;
  • Framed binary BLK on char HTTP exchanges: Single-document HTTP payloads prefixed with a 1-byte compression marker (e.g., 0x69 / 'i' for uncompressed binary BLK, or zlib/zstd markers);
  • PBBD batch streams: Multi-chunk binary streams (magic "PBBD") used by online_storage (cln_bulk_set_gblk) when uploading keybindings and cloud settings, where each chunk carries an embedded BLK block;
  • Self-contained binary BLK on disk: Player profiles saved at <data>/saves/<userId>/profile.blk via encodeBlk(), preserving every parameter's exact scalar/vector type so the game client never misinterprets ints as floats or vice versa.
+

3. The Four Gaijin Backend Services Emulated Locally

+

A live War Thunder client talks to several distinct backend services rather than a single monolithic API. apps/server emulates all four locally on a single 127.0.0.1:<port> listener:

+
  • yuplay2 (Login & Entitlement APIs, login/, store/): Handles form-encoded credential sign-in (POST /login.php), issues local session tokens and userIds, and serves store/redeem-code web endpoints;
  • char (Character Server, char/): The primary hangar RPC service (char-*.warthunder.com). Requests specify the operation via the action HTTP header (such as cln_get_user_stat, cln_buy_aircraft, cln_set_researchable, cln_update) and identify the player via uidhint, exchanging binary BLK payloads for full profile sync, tech-tree research, vehicle/modification/crew purchases, squadrons, cloud settings, and post-battle settlement;
  • matching (Binary Matchmaking & Session RPC, matching/): A persistent binary TCP protocol (first byte 0x01, 9-byte header + LZ4-compressed frame, stream-encrypted after handshake) that serves game-mode lists, manages queues and squad state, and dispatches complete battle launch configurations (map, weather, AI bot rosters, customScoreParams, etc.);
  • inventory (External Inventory & Marketplace Service, inventory/): Emulates inventory-proxy-*.gaijin.net/char (GetInventory, GetItemDefsClient, GetItemPrices, GetItemDefChances, ExchangeItems). Unlike char, the client's charsq subsystem parses raw HTTP bodies directly as UTF-8 JSON and verifies RSA content signatures—powering supply chests, vehicle coupons, workshop crafting, and the simulated marketplace.
+

4. LocalMP (Why WTOffline Needs Both apps/server AND wto_ws.dll)

+

A natural question for newcomers is: If apps/server already emulates Gaijin's backend in TypeScript, why do we also compile native/wto-net/ into wto_ws.dll and load it inside aces.exe?

+

The answer comes down to what Gaijin kept vs. stripped in the retail game client:

+
  • Retail aces.exe still contains an in-process LocalMP session mode (mp_is_host == 1 && mp_is_local_mp == 1) capable of running full physics, ballistics, damage models, and AI piloting/driving locally—meaning WTOffline does not have to reimplement a Dedicated Server physics engine from scratch;
  • However, when building retail aces.exe, Gaijin compiled out many Dedicated Server battle referee handlers that normally run only in the cloud during live matches: spawning player vehicles and weapon loadouts on selection, granting BotSystem permission to spawn AI vehicles, awarding kill/assist/capture scoreboard points, running Ground Arcade killstreak air events, triggering nuclear instant victories, and filtering barrel/breech/part-damage HUD notices so enemy hits are not misdelivered to the local player;
  • Consequently, the two halves have a crisp boundary: apps/server owns everything before and after a battle (login, hangar progression, economy, store/market, matchmaking setup, post-battle Silver Lions/RP settlement, and atomic save persistence), while wto_ws.dll hooks aces.exe in-process via MinHook—redirecting hardcoded outbound Winsock traffic to 127.0.0.1 and restoring stripped host-side referee logic during live LocalMP battles via modular local_mp_* bridges.
+

5. Quirrel (.nut) & the sq.exe Bytecode Compiler

+

UI scripts inside gui.vromfs.bin (.nut files) are written in Quirrel, Gaijin's Squirrel-derived scripting language with strict lexical scoping. When logging into the hangar, the client preloads and compiles UI script modules en masse.

+

Why is running wtotools check-gui with the matching sq.exe compiler mandatory whenever you touch patches/gui/, instead of eyeballing diffs or running an AST-only syntax check? Because Quirrel's compilestring bytecode compiler enforces lexical binding rules that AST parsers ignore:

+
  • Declaring a local identifier that collides with a constant imported via from ... import * at the top of the file;
  • Referencing an unbound local/module function before its declaration;
  • Using a Quirrel reserved keyword (most notoriously base) as a variable name.
+

Any of those mistakes looks syntactically innocent on paper, yet aborts module compilation inside the game client and freezes login indefinitely on the "Loading..." spinner. wtotools check-gui applies every GUI patch in memory and compiles each modified .nut file to Quirrel bytecode via sq.exe, catching 100% of lexical and constant-binding errors before commit.

+

6. RVA vs. Virtual Address (VA) vs. Runtime Pointer

+

Keep these three address forms straight whenever you read disassembly or write patches/:

+
  • VA (Virtual Address): When you open 64-bit aces.exe in Ghidra or IDA, the default PE ImageBase is 0x140000000, so addresses appear as 0x1412657a0;
  • RVA (Relative Virtual Address): Offset from the image base, i.e., RVA = VA - ImageBase (0x1412657a0 - 0x140000000 = 0x12657a0). Because Windows ASLR loads aces.exe at a fresh random base address on every launch, every patches/ comment, tools/re/cli.py argument, and win64/wto_ws.cfg entry uses RVAs exclusively;
  • Runtime Pointer: When the game starts, wto_ws.dll (native/wto-net/src/local_mp_values.c) adds the live module base (uint8_t *)GetModuleHandleW(NULL) + rva and stores the resulting process pointer in g_lmp.
+

7. features Tags & the Three Essential Safety Locks (ESSENTIAL_FEATURES)

+

Every definition in patches/exe/**/patch.jsonc, patches/gui/**/patch.jsonc, and patches/native/*.jsonc lists one or more features tags prefixed by inventory category (A- through K-, such as "G-Store", "K-AI opponents and teammates", or "K-Kill, assist and capture scoring"). If a minor client update breaks an optional patch, the launcher uses these tags to show the player exactly which non-essential gameplay feature is degraded while still letting them play.

+

Three tags defined in packages/patcher/src/essential-features.ts (ESSENTIAL_FEATURES) are hard-blocking safety locks:

+
  1. A-Offline startup: Required for the offline copy to boot at all (e.g., bypassing .vromfs.bin pack signature checks so modified archives load);
  2. A-Isolation from the official game: Keeps the offline copy completely separate from the official client (redirecting user saves/settings to WTOffline, registry keys to Software\WTOffline, and disabling the anti-cheat launcher and crash reporter);
  3. A-No Gaijin connections: Guarantees zero traffic reaches Gaijin's live servers (e.g., rewriting the PE import descriptor from WS2_32.dll to wto_ws.dll and enforcing Winsock redirection hooks on attach).
+

If any patch carrying one of these three tags fails to resolve, blockingFailures() immediately aborts copy installation and launch—protecting the player's official online installation and account from ever being touched.

+
+

Jump Straight to Your Task

+
What you want to doSpecific codebase directoriesPrimary reference
Add or fix hangar actions (research, purchases, crews, squadrons, decals, post-battle settlement, etc.)apps/server/src/char/actions/ (wire handlers) + apps/server/src/<domain>/ (pure rules: research/, modifications/, crew/, battle/, etc.)Server Layers & Action Walkthrough
Change player profile fields, new-account defaults, or save persistence / format upgradesapps/server/src/profile/, apps/server/src/saves/, apps/server/src/storage/Persistence & Atomic Writes
Extract new static vehicle, economy, mission, or localization data from stock archivesapps/server/src/game-data/datasets/Three Categories of Values
Adjust offline reward multipliers, store prices, supply-chest weights, AI respawn counts, or limitsapps/server/tuning/*.jsonc + apps/server/src/tuning/ + <domain>/*-tuning.tsThree Categories of Values
Work on the in-game web store, simulated marketplace, or server script mod runtimeapps/server/src/store/, apps/server/src/inventory/, apps/server/src/web-ui/, apps/server/src/mods/Server Directory Map
Change the desktop launcher UI, install wizard, saves manager, mods page, or auto-updaterapps/launcher/src/Required Check Commands
Modify copy building, archive patching, BLK/vromfs codecs, EXE patch engine, or mod loaderpackages/patcher/, packages/blk/, packages/vromfs/, packages/exepatch/, packages/mods/Workspace Dependency Rule
Patch in-game UI modals, buttons, or debriefing Quirrel scripts (.nut)patches/gui/<domain>/<name>/GUI Patches Full Example
Patch machine instructions or constant .rdata strings in aces.exepatches/exe/<domain>/<name>/EXE Patch 57-Byte Anatomy
Write or fix wto_ws.dll in-process LocalMP battle host hookspatches/native/<module>.jsonc + native/wto-net/src/Native Modules 6-File Wiring
Adapt WTOffline to a newly released minor War Thunder client buildpatches/versions/, scripts/record-game-version.tsAdapting a New Client Build
-
- - -
-

- 2. 架构与代码分层 - 2. Architecture & Code Layering -

-

- WTOffline 采用与 SPT 类似的「本地模拟服务器 + 最小客户端补丁」路线:把客户端的所有联网请求重定向至 127.0.0.1,让原生游戏逻辑照常运行。只有在本地服务器和原版配置确实无法满足时,才向客户端新增补丁。 - WTOffline redirects all client network requests to 127.0.0.1 and emulates online services locally so stock client logic runs naturally. Client patches are added only when the local server and stock configuration cannot solve a behavior. -

-
- - - - - - - - - - - - - - - -
目录Path职责Responsibility
apps/server本地服务器:内部严格拆分为协议层、规则层、存档层与数据集提取层(src/game-data/datasets/)。Local server: strictly split into protocol, rules, persistence, and game-data extraction (src/game-data/datasets/).
apps/launcherElectron 安装器与启动器(React):副本管理、存档编辑、数值覆盖、模组管理与签名更新。Electron installer and launcher (React): copies, saves, tuning overrides, mods, and signed updates.
packages/*共享库(blk、vromfs、exepatch、jsonc、patcher、mods)。依赖只能从 apps/* 指向 packages/*。Shared libraries (blk, vromfs, exepatch, jsonc, patcher, mods). Dependencies flow strictly from apps/* to packages/*.
patches/补丁集根目录:exe/、gui/、native/ 定义与 versions/ 核对记录。Patch set root: exe/, gui/, native/ definitions and versions/ verification records.
native/wto-netwto_ws.dll C 源码:网络重定向钩子与 local_mp_*.c 本地主机对局桥接模块。wto_ws.dll C source: socket redirection hooks and local_mp_*.c local host battle modules.
scripts/ · tools/副本构建脚本、版本记录脚本,以及 Python 补丁核对工具 wtotools。Copy build and version record scripts, plus the Python wtotools patch verifier.
+ -
- 隔离与只读原则:原版游戏目录一律只读使用;启动调试游戏只能在 Steam 库之外的独立副本和断网/隔离环境进行,使用本地账号,严禁把修改后的文件写回线上客户端。 - Isolation & Read-Only Source: Always treat your stock game folder as read-only. Launch test sessions only from a separate offline copy outside your Steam library with verified network/data isolation and a local account. + + +
+
+

02 · 架构原理、真实目录分层与好坏代码对比

+

这篇文档不只罗列「能做什么、不能做什么」,而是先把 WTOffline 为什么这样分层、客户端与本地服务器各自承担什么角色 彻底讲透。只要底层运行模型在脑子里立住了,项目里的每一条工程规范都是自然而然的推论。

+
+

1. 先建立全景图:WTOffline 到底是怎么跑起来的?

+

WTOffline 采用与《逃离塔科夫》单机版(SPT)一脉相承的本地模拟架构:不推翻重写游戏引擎,而是让原版客户端相信自己正连着完整的线上后端,把它的全部网络请求收口到本机 127.0.0.1 的模拟服务器,并仅在进程内补齐客户端被裁剪掉的局内主机裁判函数。

+
text
玩家在启动器点击「启动游戏」
+  │
+  ├─ 1. 桌面启动器(apps/launcher)调用构建引擎(packages/patcher)
+  │     └─ 以「严格只读」方式读取玩家的官方原版客户端目录,向独立离线副本目录生成:
+  │        ├─ char.vromfs.bin / aces.vromfs.bin:改写 network.blk 服务地址 -> 127.0.0.1:<端口>,注入本地商店礼包 GUID
+  │        ├─ gui.vromfs.bin:应用 patches/gui/(仅修补本地服务器无法覆盖的极少数界面脚本点)
+  │        ├─ win64/aces.exe:应用 patches/exe/(跳过包验签、隔离存档与注册表、禁用反作弊、把导入表 WS2_32.dll 改为 wto_ws.dll)
+  │        └─ win64/wto_ws.dll + win64/wto_ws.cfg:按 patches/native/*.jsonc 动态解析函数 RVA 与结构体偏移写入配置文件
+  │
+  ├─ 2. 本地模拟服务器(apps/server,仅绑定 127.0.0.1:<端口> 单端口监听)
+  │     ├─ 启动阶段:通过 DatasetCache 从游戏归档包提取静态事实(科技树、价格、改装件、任务、多语言词条),加载 tuning/*.jsonc
+  │     └─ 运行阶段:port-listener.ts 按每个 TCP 连接的首批字节自动分流多协议:
+  │        ├─ 首字节 0x01                       ──▶ MatchingService(9 字节头 + LZ4 压缩帧,握手后流加密)
+  │        ├─ 明文 PASS/NICK/USER/CAP/PING       ──▶ IrcServer(机库与小队聊天)
+  │        ├─ 首字节 0x16(TLS ClientHello)     ──▶ 本地证书 TLSSocket 解密后再二次分流至 IrcServer 或 HTTP
+  │        └─ 其余全部明文连接                   ──▶ HTTP 服务器(yuplay2 登录、char 二进制 BLK 档案、inventory 签名 JSON、内嵌网页商店)
+  │                                                  (注:HTTP WebSocket upgrade 请求会被记录日志后直接 socket.destroy() 拒绝)
+  │
+  └─ 3. 隔离离线副本(win64/aces.exe + win64/wto_ws.dll)
+        ├─ 进程加载时(DllMain):wto_ws.dll 通过 wto_ws.def 把全部 Winsock 导出(含序号导出)转发至系统 ws2_32.dll,
+        │  同时用 MinHook 挂钩系统 ws2_32.dll 的域名解析与连接函数;若任一网络钩子安装失败,DllMain 直接返回 FALSE 终止启动!
+        ├─ 机库阶段:登录、拉取档案、科技树研发、买车买改装、乘员训练、开箱、逛商店,全部走原版协议由 apps/server 处理并原子落盘
+        └─ 对局阶段:MatchingService 下发任务参数使客户端以 LocalMP 本地主机开局;
+           wto_ws.dll 校验 PE 指纹匹配后启用 local_mp_* 模块,在进程内补齐选车出生、AI 刷出、击杀助攻占点计分、
+           陆战街机空中支援、核弹判胜与受损提示过滤;战后由客户端经 cln_update 回传 apps/server 结算银狮/研发点并落盘
+

1.1 单端口多协议分流细节(apps/server/src/transport/)

+

客户端内部既有读取 config/network.blk 的模块,也有把域名、端口甚至 https:// 写死在二进制常量里的模块。为了不占用一串本地端口,本地服务器在 apps/server/src/transport/port-listener.ts 中用单个 TCP 监听端口接住所有流量,在 socket.once('data', ...) 窥探首批字节后原样退回缓冲区(socket.unshift)并精准派发:

+
  1. 匹配二进制协议(首字节 0x01):匹配 startsMatchingPacket(first) 后交由 MatchingService 处理(9 字节小端包头 + LZ4 数据块,见 matching/matching-frame.ts);
  2. 明文 IRC 握手:首行以 PASS、NICK、USER、CAP 或 PING 开头时交由 IrcServer 处理;
  3. TLS 加密连接(首字节 0x16):使用本地动态生成的自签名证书建立 TLSSocket 解密,再窥探解密后的首包字节——若是 TLS 承载的 IRC 握手则交由 IrcServer,否则派发给 HTTP 服务器;
  4. 常规 HTTP 连接:其余连接直接进入 http-listener.ts 的 createHttpServer,由 Router 按原始目标域名(originalHost)和路径分发给 login、char、inventory、store、downloadable-content 等服务。注意:WTOffline 不使用 WebSocket——客户端偶然发起的 HTTP upgrade 请求会在 http-listener.ts 中记入流量日志(WebSocket ... (refused))并立即调用 socket.destroy() 断开。
+

1.2 wto_ws.dll 是如何在零外联风险下接管网络的?

+

在 patches/exe/online/network-hook-library/patch.jsonc 中,补丁将 aces.exe 只读数据段(.rdata)导入描述符引用的字符串 "WS2_32.dll\0"(57 53 32 5f 33 32 2e 64 6c 6c 00,共 11 字节)原位替换为等长的 "wto_ws.dll\0"(77 74 6f 5f 77 73 2e 64 6c 6c 00,同样 11 字节):

+
  • Windows 加载器启动 aces.exe 时会自动加载同目录下的 win64/wto_ws.dll,由 native/wto-net/src/wto_ws.def 将客户端导入的全部 Winsock API(包含 31 个按 @序号 导入的函数)无缝转发给系统 ws2_32.dll;
  • 在 native/wto-net/src/dll_main.c 的 DllMain(DLL_PROCESS_ATTACH) 中,DLL 读取同目录 wto_ws.cfg,通过 MinHook 直接挂钩系统 ws2_32.dll 本身的域名解析与连接/数据报函数(这样进程内所有模块的网络调用都会经过重定向,而不只是主程序);
  • 安全熔断:如果 MH_Initialize、install_resolver_hooks、install_connection_hooks 或 MH_ApplyQueued 中任何一步失败,DllMain 会记录日志并直接返回 FALSE,让 Windows 加载器中止启动游戏进程,避免游戏在未挂钩状态下连接外网。
+

1.3 基本设计原则

+

遇到功能缺失或 Bug 时,先评估能否在 apps/server 或通过下发原版配置字段解决。
能通过修正服务端协议响应、补齐下发给客户端的任务 BLK 字段、或读取原版静态配置解决的问题,优先在服务端解决,不新增 .nut 界面脚本或 aces.exe / wto_ws.dll 客户端补丁。客户端补丁留给原版客户端确实缺少对应通路的场景——因为游戏每次小版本更新都会重排二进制代码,而服务端协议与配置字段跨版本稳定得多。

+
+

2. 仓库依赖约定与 apps/server 真实代码地图

+

2.1 仓库级单向依赖约定

+
text
apps/launcher  ──┐
+                 ├──▶  packages/*  (@wto/blk · @wto/vromfs · @wto/jsonc · @wto/exepatch · @wto/patcher · @wto/mods)
+apps/server    ──┘
+
  • 依赖方向单向朝下:应用层 apps/* 可以导入共享包 packages/*(开发脚本 scripts/* 可组合两者),packages/* 不应反向导入、引用或硬编码读取 apps/* 下的代码或配置文件。
  • 当共享包需要补丁集目录、数据目录、端口或礼包列表时,一律由上层调用方通过函数参数显式传入。
+

2.2 本地服务器 apps/server/src/ 四层目录全景图

+

注意:apps/server/src/ 下并没有一个笼统的 rules/ 文件夹——业务规则是按游戏业务领域拆分成独立目录的。动手写代码前请对照下面这张真实目录表放对位置:

+
职责分层apps/server/src/ 下的真实子目录这一层负责什么应避免放在这一层的内容
1. 传输与协议层(Transport & Protocol)transport/(单端口分流、HTTP 路由、TLS 证书)、traffic-log/(流量落盘)、login/(yuplay2 登录与会话凭据)、char/(含 char-service.ts、pbbd-stream.ts、char/actions/*-actions.ts 与路由总表 char/actions/action-table.ts)、matching/(LZ4 帧、流加密与排队 RPC)、inventory/(外部物品库与 RSA 内容签名)、store/(礼包与激活码路由)、chat/(IRC 服务端)、cloud-settings/、downloadable-content/、web-ui/(内嵌商店/市场页面渲染)、mods/(服务端模组运行时)解码线上传输格式(表单、JSON、压缩标记二进制 BLK、PBBD 流、LZ4 帧),提取并校验请求参数,调用对应领域规则,再把结果编码回客户端期待的原版响应格式避免在 *-actions.ts 里堆砌几百行扣钱、算研发点或改档案树的业务逻辑;不要绕过 PlayerProfiles / SaveStore 直接读写磁盘文件
2. 领域规则层(Domain Rules)battle/(开局配置与战后经济结算)、research/(科技树状态、选定研发、自由研发点兑换)、modifications/(改装件、弹链、备用载具、自定义挂载)、crew/(乘员组槽位与技能加点)、items/(加成卡、赌注、折扣券)、repair/(战损折算与免费修车时间)、clans/(联队管理与联队载具研发)、decor/(涂装、贴花、3D 挂件)、unlocks/(成就、头衔、阶段解锁)、player-card/(头像、资料卡展柜)、training/(新手教程首通奖励)、game-modes/纯业务逻辑:接收内存中的档案 BlkBlock、已加载的静态数据集与可调参数,校验前置条件,计算并更新档案状态,返回明确的成功或拒绝错误码(如 RuleOutcome)零网络、零磁盘 I/O:不导入 node:http、node:net 或 node:fs,也不要感知外层是 HTTP 还是匹配长连接
3. 档案与持久化层(Profile & Persistence)profile/(player-profiles.ts 及按领域拆分的 profile-*.ts 档案节点读写器、派生状态刷新器)、saves/(save-store.ts 账号存档读写、save-upgrades.ts 版本演进)、accounts/(本地多账号密码与隔离)、storage/(atomic-file.ts 原子落盘)封装档案 BLK 树的底层字段读写,管理多账号目录隔离(<data>/saves/<userId>/),维护存档 formatVersion,并通过临时文件 + fsync + 原子重命名保证断电不坏档不掺杂具体购买价格或研发公式;任何修改档案的动作必须在磁盘原子写入完成后才能向客户端返回成功响应
4. 静态数据集与可调配置层(Datasets & Tuning)game-data/(game-files.ts、game-pack.ts、datasets/*.ts、datasets/dataset-cache.ts)、仓库默认配置 apps/server/tuning/*.jsonc + 加载校验器 src/tuning/(tuning-loader.ts、tuning-reader.ts、limits-tuning.ts、launcher-tuning.ts)+ 各领域 <领域>/*-tuning.ts启动时从玩家原版 .vromfs.bin 提取静态事实并按包时间戳 + 内部文件 SHA-1 缓存到 <data>/cache/datasets/;按「仓库默认 → 已启用模组 → 玩家 <data>/tuning/ 覆盖」三层合并 JSONC 并做严格类型与范围校验不要凭空编造原版数据;必填字段缺失时应明确报错停止启动,避免用隐式假默认值掩盖问题
+

模块粒度与复用准则:

+
  • 当单个源文件接近 300 行 或单个函数接近 50 行 时,主动检查是否把协议拆包、档案树遍历和业务公式塞进了同一个文件,及时按上表拆开;
  • 动手前先搜现有公共基础设施(如 char/actions/rule-answer.ts、profile/profile-*.ts、modifications/equipment-catalogue.ts、web-ui/ 公共组件、native 侧的 local_mp_core),尽量复用而不是重复实现。
+
+

2.3 跟着真实代码走一遍:cln_set_researchable 是怎么穿透四层的?

+

光看分层表还不够直观。下面我们顺着玩家在科技树点击「研发此载具」时触发的真实动作 cln_set_researchable,逐文件看一遍标准请求流(你在写任何新 char 动作时直接照这个模板写即可):

+
  1. 客户端发包 → 协议入口解码(apps/server/src/char/char-service.ts) 客户端向 char-*.warthunder.com 发送 HTTP POST,请求头带 action: cln_set_researchable 与 uidhint: <userId>,请求体是带压缩标记的二进制 BLK(包含 unit:t = "us_m4a1_1942_sherman" 与 type:i = 0)。CharService.#handleCore 调用 decodeRequestPayload(request.body)(char/char-payload.ts)把二进制负载解码为 BlkBlock(同时生成可读文本供流量日志记录),然后从 char/actions/action-table.ts 注册表里查出对应的处理器 setResearchable。
  2. 协议动作适配与参数提取(apps/server/src/char/actions/research-actions.ts) setResearchable 本身只有十几行:它使用公共包装器 ruleAction(char/actions/rule-answer.ts),通过 stringParam(payload, 'unit') 和 intParam(payload, 'type')(char/actions/payload-params.ts)做基础类型提取。如果缺字段就返回 undefined(由 ruleAction 统一回 !ERROR:BAD_PARAMS);参数齐全则返回一个闭包: (profile) => chooseResearchTarget(profile, rules, vehicle, type)。
  3. 加载档案与执行纯领域规则(apps/server/src/research/research-progress.ts) ruleAction 校验完账号后调用 profiles.updateWhen(account.userId, ...)(profile/player-profiles.ts),由 SaveStore.loadProfile 从 <data>/saves/<userId>/profile.blk 读出当前档案并交给纯规则函数 chooseResearchTarget: +
    • 先从启动期提取好的科技树数据集 rules.techTree.vehicle(vehicleName) 查找该载具并核对 typeId;
    • 调用 currentStatus(profile, rules, vehicleName) 确认该载具在玩家当前档案下确实处于 VehicleStatus.CAN_RESEARCH 状态;若尚未解锁前置车或已拥有,则返回 refused('NOT_AVAILABLE')({ ok: false, refusal: 'NOT_AVAILABLE' }),updateWhen 看到 false 不触碰磁盘,ruleAction 向客户端回复纯文本 !ERROR:NOT_AVAILABLE;
    • 校验通过后,调用 profile/profile-research-targets.ts 的访问器写入新研发目标、清空刚完成研发弹窗标记,返回 ACCEPTED({ ok: true })。
  4. 先原子落盘,再回包给客户端(profile/player-profiles.ts → saves/save-store.ts → storage/atomic-file.ts) updateWhen 收到 true 后,先运行 #refresh(profile, userId) 同步档案内的派生状态(解锁阶段、头衔、联队同步等),随即调用 SaveStore.saveProfile(userId, profile)。saveProfile 使用 writeFileAtomic 先在同目录写出临时文件 profile.blk.<pid>.<rand>.tmp、调用 fsyncSync(fd) 刷入物理磁盘、再原位 renameSync 覆盖目标文件并更新 save.json。只有在磁盘写入彻底成功后,ruleAction 才调用 clientProfile(profile, account) 组装客户端视图,由 toResponse(char/char-answers.ts)加上 0x69 标记编码成二进制 BLK 返回 HTTP 200。
+

2.4 存档结构演进规则(saves/save-upgrades.ts)

+
  • 领域规则只面向「当前最新版」存档结构编程:避免在 research/、modifications/、battle/ 等业务代码里散落兼容旧测试字段的 if/else 分支;
  • 当正式版本演进确实改变了 profile.blk 的存储结构时,统一在档案升级链(saves/save-upgrades.ts 的 SaveUpgrades)中追加一步升级函数(steps[n] 负责把 formatVersion 从 n + 1 原地升级到 n + 2)。SaveStore.loadProfile 打开旧版存档时会按顺序跑完升级步骤并立即以最新 formatVersion 原子回写磁盘。仍在同一分支开发调试、尚未发布的草稿改动无需写迁移代码。
+
+

3. 三类数值放哪里(保持边界清晰)

+

在代码审查中,最常见的返工原因就是把不同性质的数字混写在了业务逻辑里。写下任何一个字面量前,先问它属于下面哪一类:

+
数值类别典型例子唯一正确的存放位置常见错误示范
① 协议与引擎固定常量匹配/局内消息号(如 LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u)、PBBD 魔数(0x44424250)、Dagor 容器布局(dag::Vector 偏移、FastNameMap 移位)、状态位掩码定义为具名常量放在对应协议或头文件中,并用英文注释写明一手来源(目标客户端版本号 + RVA,或 DagorEngine 公开源码 文件路径)在函数中间裸写 if (msgId == 61488) 或 if (status == 64) 且没有任何来源注释
② 原版游戏包里本来就有的静态事实载具购买银狮/金鹰价、研发点需求、分房权重、维修费、改装件树、多人地图列表、新手教程首通奖励、连杀支援出生高度/距离/速度在 apps/server/src/game-data/datasets/ 编写 Dataset<T>,服务启动时经 DatasetCache 从玩家原版 .vromfs.bin 动态读取并缓存在 <data>/cache/datasets/<id>.json;若原版文件缺失必填块/字段,直接 throw new Error(...) 明确报错停止把某一个客户端版本的载具表、奖励金额或出生坐标手抄成 TS/C 常量表;或者读不到原版字段时悄悄 ?? 10000 填个假默认值蒙混过关
③ 离线版自己决定的可调参数银狮/研发点收益倍率、新账号初始货币、本地商店礼包定价、补给箱掉落权重、AI 机器人重生次数、单次请求数量上限、玩法开关仓库默认值放进 apps/server/tuning/<领域>.jsonc,在对应 <领域>/*-tuning.ts 用 TuningReader 做启动期类型与上下界校验;运行期由 tuning-loader.ts 自动按「仓库默认 → 已启用模组覆盖 → 玩家 <data>/tuning/<领域>.jsonc 覆盖」合并把 const RP_MULTIPLIER = 3.0 或硬上限直接写死在结算函数内部,导致玩家和模组作者无法通过 tuning/ 调参
+
+

4. 好代码 vs 坏代码:4 组来自真实仓库的代码对比

+

下面所有正面代码全部取自仓库内的真实文件与真实符号,提交前请逐条对照自查。

+

对比 1:Native C 钩子 —— g_lmp 动态捕获与外层作用域标志 vs 硬编码偏移与 _ReturnAddress()

+

客户端只要发一个小版本更新(例如 2.61.0.37 → 2.61.0.58),函数 RVA 会整体漂移,C++ 类成员偏移也会随着字段增删而移动(例如 gameplay 里的连杀规则表偏移就会跨版本变化)。

+
c
// ❌ 坏写法:硬编码 RVA、硬编码结构体偏移 +0x3798、用 _ReturnAddress() 猜调用栈
+//           只要游戏发一个小补丁,轻则功能静默失效,重则当场非法内存访问崩溃!
+static void __fastcall bad_hook_send_unit_respawn(uint8_t *unit, const void *spawn)
+{
+    uintptr_t base = (uintptr_t)GetModuleHandleW(NULL);
+    if ((uintptr_t)_ReturnAddress() != base + 0x1281280)
+        return;
+    const uint8_t *gameplay = *(const uint8_t *const *)(base + 0x7bad2f0);
+    const uint8_t *rules = *(const uint8_t *const *)(gameplay + 0x3798);
+    /* ... */
+}
+
c
// ✅ 好写法(真实代码:native/wto-net/src/local_mp_air_events.c + local_mp_offsets.h + local_mp_values.h):
+//    1. 所有函数地址与结构体偏移均在 patches/native/local_mp_air_events.jsonc 动态捕获写入 wto_ws.cfg,
+//       运行时由 local_mp_values.c 填入全局 extern LmpValues g_lmp(LMP_GP_OFF_KS_RULES 展开为 g_lmp.gp_ks_rules);
+//    2. 用外层函数钩子 + 线程局部标志(__declspec(thread))精确界定调用上下文,彻底告别脆弱的 _ReturnAddress()。
+static SwitchPlayerUnitFn orig_switch_player_unit;
+static __declspec(thread) int g_in_air_event_switch;
+
+static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air)
+{
+    int previous = g_in_air_event_switch;
+
+    if (to_air != 0 && ground_arcade_air_events_enabled())
+        g_in_air_event_switch = 1;
+    orig_switch_player_unit(event_mgr, participant, to_air);
+    g_in_air_event_switch = previous;
+}
+
+// 读取连杀规则表时全部走 g_lmp 动态解析值,跨小版本自动适配:
+const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL;
+const uint8_t *rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
+uint32_t rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
+

对比 2:原版静态数据 —— DatasetCache 提取与纯领域目录消费 vs 在业务里手抄常量表

+
ts
// ❌ 坏写法:把某一个版本的新手教程首通银狮/金鹰奖励硬编码成服务端字典
+const TUTORIAL_REWARDS: Record<string, { silverLions: number; goldenEagles: number }> = {
+  'tutorialB_fighter': { silverLions: 5000, goldenEagles: 100 },
+  'tutorialB_assaulter': { silverLions: 5000, goldenEagles: 0 },
+};
+
ts
// ✅ 好写法(真实代码:apps/server/src/game-data/datasets/training-missions.ts
+//                    + apps/server/src/training/training-completion.ts):
+//    1. 在 datasets/ 定义带版本号的 Dataset,从玩家原版 char.vromfs.bin 的
+//       config/mislist.blk、config/pve_awards.blk、config/unlocks.blk 提取真实配置;缺失必填块立即抛错。
+export const trainingMissions: Dataset<TrainingMissionsData> = {
+  id: 'training-missions',
+  version: 1,
+  extract(source: DatasetSource): TrainingMissionsData {
+    const misSection = blockAt(source.readBlk('char.vromfs.bin', 'config/mislist.blk'), 'training');
+    if (!misSection) throw new Error('config/mislist.blk has no "training" block');
+    const awardSection = blockAt(source.readBlk('char.vromfs.bin', 'config/pve_awards.blk'), 'training');
+    if (!awardSection) throw new Error('config/pve_awards.blk has no "training" block');
+    // ... 组装 missions 列表并返回纯数据对象
+    return { missions };
+  },
+};
+
+//    2. 启动时通过 DatasetCache 加载(包未变直接命中缓存),交由纯领域类 TrainingCatalogue 执行幂等发奖:
+const trainingCatalogue = new TrainingCatalogue(datasets.load(trainingMissions));
+trainingCatalogue.applyCompletion(profile, { chapter, mission, difficulty });
+

对比 3:找准修复层级与严格遵守工具链语法(MSVC C 与 Node 24 原生 TS)

+

(A)先查原版读取逻辑,别急着动刀写客户端补丁

+
  • ❌ 坏思路:发现多载具出击模式下 AI 机器人死一次就不再重生,立刻去反汇编 BotSystem 准备写 patches/exe/ 强改内存计数器。
  • ✅ 好思路:先看 MissionSettings::load 是怎么读任务配置的——结果发现原版客户端本来就会读取任务 BLK 根节点的 numBotRespawns 与 numTankBotRespawns,只是服务端组装匹配开局配置时漏填了这两个根字段。在 apps/server 补上几行配置下发即可解决,零客户端补丁、跨版本永久免疫失效。
+

(B)MSVC C 编译规范与 Node 24 原生 TypeScript 语法规范

+
  • Native C(native/wto-net/):由 native/wto-net/build.ps1 调用 Visual Studio cl.exe 以 /W4 编译,要求零编译警告。校验自定义结构体大小与成员偏移时使用 <windows.h> 的编译期断言 C_ASSERT(sizeof(LocalMpAirSpawn) == 0x48);,线程局部存储使用 __declspec(thread),内存对齐使用 __declspec(align(16));避免使用 __attribute__((...))、零长数组、可变长数组(VLA)或 void * 算术运算等 GCC/Clang 专属扩展。
  • TypeScript(tsconfig.json):Node.js 24 直接剥离类型运行 .ts 源码,仓库开启了 erasableSyntaxOnly: true、verbatimModuleSyntax: true、allowImportingTsExtensions: true 与 exactOptionalPropertyTypes: true:
+
ts
// ❌ 坏写法:省略 .ts 后缀、值导入混用纯类型、使用 enum 或构造函数参数属性(Node 24 类型剥离与 tsc 均会报错!)
+import { SaveStore, SaveUpgrades } from '../saves/save-store';
+export enum ResearchState { Locked = 0, Available = 1 }
+export class Handler {
+  constructor(private readonly saves: SaveStore) {}
+}
+
ts
// ✅ 好写法:相对路径一律写明 .ts 扩展名;纯类型必须用 import type;用 as const 对象或联合类型代替 enum;用 #私有字段
+import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
+import { writeFileAtomic } from '../storage/atomic-file.ts';
+import type { SaveUpgrades } from './save-upgrades.ts';
+
+export const VehicleStatus = {
+  CAN_RESEARCH: 2,
+  OWNED: 4,
+} as const;
+

对比 4:工程验证 —— 跑真实工具链检查 vs 写几百行假 Mock 单元测试

+
  • ❌ 坏写法:改了 patches/gui/ 只肉眼扫一眼 .nut 缩进,或者自己造一套模拟客户端行为的 300 行 Mock 单测跑绿就宣称「测试全部通过」——结果真进游戏时因为 Quirrel 词法作用域冲突卡死在登录界面,或者 patch.jsonc 多写了一个非法键在构建副本时直接抛 DefinitionError。
  • ✅ 好写法:按改动范围老老实实运行真实检查工具(npm run typecheck、wtotools check-patches、带 sq.exe 的完整 wtotools check-gui、native\wto-net\build.ps1、scripts/build-game-copy.ts),并在 PR 描述中如实把「已在命令行跑过的检查」与「尚待在隔离副本进游戏实机验收的步骤」分开写清楚。
+
+

5. 使用 AI 编程助手协作指南(含一键复制约束提示词)

+

我们非常鼓励你使用 Claude Code、Codex、Cursor 等 AI 工具协助阅读反汇编、梳理 .nut 界面调用链、核对 BLK 字段以及快速定位协议差异。

+

但 AI 如果事先不知道 WTOffline 的工程边界,很容易顺手写出硬编码 RVA、在 patches/gui/**/patch.jsonc 里误加 requires 字段、漏写 .ts 导入后缀、用 enum 语法或生成一大堆无意义的 Mock 测试。在让 AI 动手修改任何文件之前,请先把下面这段完整提示词发给它:

+
text
我正在为 WTOffline 仓库开发改动。在编写或修改代码前,请遵循以下项目规范(写任何符号、结构体字段、CLI 参数前先读取仓库真实源文件核实):
+
+1. 修复层级优先顺序:先查原版一手依据(玩家只读原版 .vromfs.bin、gui.vromfs.bin 里的 .nut 脚本、DagorEngine 公开源码)。凡是能在本地服务器(apps/server)协议响应、任务配置字段或静态数据集里解决的问题,不要新增 patches/gui/、patches/exe/ 或 native/wto-net/ 客户端补丁。
+2. 动态定位,不硬编码地址与偏移:不要在 C 或 TS 代码里写死 exe 函数地址、RVA、C++ 结构体偏移或 _ReturnAddress() 调用栈判断。所有原生地址与偏移通过 patches/exe/ 或 patches/native/*.jsonc 的 signature / string_ref / within 动态捕获写入 wto_ws.cfg,C 侧通过 extern LmpValues g_lmp(local_mp_values.h / local_mp_offsets.h)读取,并用外层钩子 + __declspec(thread) 标志替代返回地址检查。带尾随立即数的 rip-relative 指令捕获 rel32 时需显式指定 "end"(指令总字节长度)。
+3. 三类数值严格归位:原版游戏自带数值(载具价格、研发点、奖励、任务、出生参数)必须通过 apps/server/src/game-data/datasets/(DatasetCache)从原版归档提取,缺必填字段直接抛错;离线版自定参数与开关统一放入 apps/server/tuning/*.jsonc 并在对应 *-tuning.ts 做启动校验;协议/引擎常量写英文注释注明客户端版本 RVA 或 DagorEngine 源码路径。
+4. 分层与依赖方向:packages/* 不导入或读取 apps/*。apps/server/src/ 内区分传输协议层(char/actions/ 等)、领域规则层(research/、battle/、modifications/ 等纯逻辑目录,无 rules/ 目录,零网络零磁盘 I/O)、档案持久化层(profile/、saves/、storage/atomic-file.ts —— 改档动作先原子写盘成功再回包);存档兼容升级统一通过 saves/save-upgrades.ts 的 formatVersion 步骤处理,不在业务规则里散落旧版兼容分支。单文件接近 300 行或函数接近 50 行时主动拆分。
+5. 严格语法与 Schema 约束:
+   - TypeScript 运行在 Node 24 原生类型剥离模式(erasableSyntaxOnly + verbatimModuleSyntax + allowImportingTsExtensions):所有相对导入必须带显式 `.ts` 后缀,纯类型必须用 `import type`,禁止使用 `enum`、`namespace` 和构造函数参数属性。
+   - Native C 必须通过 MSVC `native/wto-net/build.ps1`(/W4 零警告),使用 `C_ASSERT` 做编译期布局检查,禁止 GCC 扩展;新增 `.c` 文件需同步加入 `build.ps1` 的 `$sources`。
+   - 补丁 JSONC 严格校检未知键:特别是 `patches/gui/**/patch.jsonc` 顶层只允许 `id`、`title`、`features`、`variants`(不要写 `requires`,否则会抛出 DefinitionError)。
+6. 真实工具验证:不要编写庞大的模拟(mock)单元测试套件。按改动运行真实检查命令(`npm run typecheck`、`wtotools check-patches`、带 `--sq` 的完整 `wtotools check-gui`、`native/wto-net/build.ps1`、`scripts/build-game-copy.ts`),并如实区分已跑过的命令与待隔离副本实机验收项。
+7. 提交规范:一笔 PR 只聚焦单一目标;代码注释、补丁 `title`/头部三行说明与约定式提交消息统一使用英文;不把 AI 写入 Co-authored-by;在隔离副本实机进游戏验收前不提交 `patches/versions/*.jsonc`。
+
+

6. 隔离安全与资产边界

+
  1. 官方原版客户端目录保持只读:无论是拆包查 .blk、跑 tools/re/cli.py 反汇编、wtotools 核对补丁还是构建游戏副本,原版目录都只作为只读输入源,不要向 Steam 或官方启动器安装目录写入、覆盖或残留文件。
  2. 仅在独立隔离副本中运行测试:实机运行客户端必须在 Steam 库目录之外的独立离线副本中进行,并确保三大核心安全锁(ESSENTIAL_FEATURES)全部生效——所有联网请求经 wto_ws.dll 收口至 127.0.0.1、本地配置落入独立 WTOffline 用户目录与 Software\WTOffline 注册表路径、反作弊与崩溃上报已剥离,且只使用离线本地账号登录。
  3. 代码仓库不包含受版权保护资产与隐私信息:不要将 .vromfs.bin、aces.exe、解包出的原版 .nut / .blk 完整文件、真实玩家存档、本机绝对路径或未脱敏日志提交进 Git 仓库。
-
+
+

02 · Architecture, Real Directory Map & Code Patterns

+

Rather than handing you a dry list of dos and don'ts, this guide first explains how WTOffline actually works under the hood and why its layers are separated the way they are. Once that architecture clicks, every engineering rule follows naturally.

+
+

1. End-to-End Architecture: How WTOffline Works

+

WTOffline uses the same core philosophy as Single Player Tarkov (SPT): do not rewrite the game engine—keep the retail client running its native code paths, redirect all network traffic to a local emulation server on 127.0.0.1, and hook aces.exe in-process only where retail builds stripped Dedicated Server battle handlers.

+
text
Player clicks "Launch" in the Launcher
+  │
+  ├─ 1. Desktop Launcher (apps/launcher) invokes Copy Builder (packages/patcher)
+  │     └─ Reads the player's official stock install STRICTLY READ-ONLY and writes an isolated copy:
+  │        ├─ char.vromfs.bin / aces.vromfs.bin: rewrite network.blk endpoints -> 127.0.0.1:<port>, inject store bundle GUIDs
+  │        ├─ gui.vromfs.bin: apply patches/gui/ (surgical UI script edits only where server responses cannot suffice)
+  │        ├─ win64/aces.exe: apply patches/exe/ (bypass pack signature checks, isolate user dir & registry, disable anti-cheat,
+  │        │                  rewrite PE import name "WS2_32.dll\0" -> "wto_ws.dll\0")
+  │        └─ win64/wto_ws.dll + win64/wto_ws.cfg: resolve patches/native/*.jsonc RVAs & struct offsets into wto_ws.cfg
+  │
+  ├─ 2. Local Emulation Server (apps/server, bound strictly to 127.0.0.1:<port>)
+  │     ├─ Startup: DatasetCache extracts static facts from stock .vromfs.bin archives; tuning-loader merges tuning/*.jsonc
+  │     └─ Runtime: transport/port-listener.ts peeks at the first bytes of every TCP socket on that single port:
+  │        ├─ First byte 0x01                     ──▶ MatchingService (9-byte header + LZ4 frames, encrypted after handshake)
+  │        ├─ Plaintext PASS/NICK/USER/CAP/PING   ──▶ IrcServer (hangar & squad chat)
+  │        ├─ First byte 0x16 (TLS ClientHello)   ──▶ Local-cert TLSSocket decrypts, then routes to IrcServer or HTTP
+  │        └─ Everything else                     ──▶ HTTP server (yuplay2 login, char binary BLK RPC, signed inventory JSON, web store)
+  │                                                   (Note: HTTP WebSocket `upgrade` requests are logged and explicitly refused via socket.destroy()!)
+  │
+  └─ 3. Isolated Offline Client Copy (win64/aces.exe + win64/wto_ws.dll)
+        ├─ Process attach (DllMain): wto_ws.dll forwards all Winsock exports (including 31 ordinal imports) via wto_ws.def
+        │  to system ws2_32.dll and installs MinHook detours on ws2_32's resolver/connect APIs; if ANY network hook fails,
+        │  DllMain returns FALSE so Windows immediately aborts launch before a single packet can go online!
+        ├─ Hangar phase: sign-in, profile load, tech-tree research, purchases, crews, chests, and store all run over stock
+        │  protocols against apps/server with atomic disk persistence
+        └─ Battle phase: MatchingService launches a LocalMP host session; after verifying PE headers against wto_ws.cfg,
+           wto_ws.dll activates local_mp_* modules to restore stripped host handlers (vehicle/loadout spawn, AI bot spawn,
+           kill/assist/capture scoring, Ground Arcade air events, nuclear instant win, damage-notice filtering), and post-battle
+           results return to apps/server via cln_update for reward settlement and save persistence
+

1.1 Single-Port Protocol Multiplexing (apps/server/src/transport/)

+

Because some client subsystems read URLs from config/network.blk while others use compiled-in hostnames, ports, and https:// URLs, apps/server/src/transport/port-listener.ts multiplexes every protocol over one 127.0.0.1 TCP port. On each incoming connection, socket.once('data', ...) inspects the initial bytes, pushes them back with socket.unshift(first), and hands the socket to the matching protocol handler:

+
  1. Matching binary RPC (first[0] === 0x01): Matched by startsMatchingPacket(first) (matching/matching-frame.ts — 9-byte little-endian header + LZ4 block) and handed to MatchingService;
  2. Plaintext IRC handshake: Connections starting with PASS, NICK, USER, CAP, or PING (startsIrcHandshake) go straight to IrcServer;
  3. TLS ClientHello (first[0] === 0x16): Wrapped in a TLSSocket using the local certificate, after which the first decrypted bytes are inspected again—routing TLS-wrapped IRC handshakes to IrcServer and all other decrypted streams to the HTTP server;
  4. Plaintext HTTP: All remaining connections go to createHttpServer (transport/http-listener.ts), where Router dispatches requests by originalHost and path across login, char, inventory, store, downloadable-content, etc. Note on WebSockets: WTOffline does not use WebSockets—any HTTP upgrade request hits server.on('upgrade', ...) in http-listener.ts, which logs WebSocket <host><path> (refused) in the traffic log and immediately closes the socket with socket.destroy().
+

1.2 How wto_ws.dll Intercepts All Outbound Traffic Safely

+

patches/exe/online/network-hook-library/patch.jsonc locates the 11-byte import descriptor name "WS2_32.dll\0" (57 53 32 5f 33 32 2e 64 6c 6c 00) in aces.exe's .rdata section and overwrites it in place with "wto_ws.dll\0" (77 74 6f 5f 77 73 2e 64 6c 6c 00, also 11 bytes):

+ +

1.3 The Golden Priority Rule

+

Before touching any client file, always ask: "Can apps/server or stock mission/config fields solve this?"
If a bug or feature can be implemented by returning the right server payload, populating a stock BLK field in the mission launch config, or extracting stock archive data, never add a .nut, aces.exe, or wto_ws.dll patch. Client patches are strictly a last resort when retail aces.exe or gui.vromfs.bin genuinely lacks the path—because minor game updates frequently shift binary code while wire protocols and BLK schemas remain stable across builds.

+
+

2. Workspace Dependency Rule & Real apps/server Directory Map

+

2.1 One-Way Workspace Dependency Rule

+
text
apps/launcher  ──┐
+                 ├──▶  packages/*  (@wto/blk · @wto/vromfs · @wto/jsonc · @wto/exepatch · @wto/patcher · @wto/mods)
+apps/server    ──┘
+ +

2.2 Complete apps/server/src/ Four-Layer Directory Map

+

Note that there is NO monolithic rules/ folder in apps/server/src/—domain rules live in dedicated per-domain directories. Use this map to place every file in the right layer:

+
LayerReal directories under apps/server/src/What belongs hereWhat must NOT go here
1. Transport & Protocoltransport/ (single-port listener, HTTP router, TLS cert), traffic-log/ (JSONL + decoded body logger), login/ (yuplay2 sign-in & session tokens), char/ (char-service.ts, pbbd-stream.ts, char/actions/*-actions.ts, and char/actions/action-table.ts), matching/ (LZ4 framing, stream cipher, queue/battle RPC), inventory/ (external inventory & RSA content signing), store/ (bundle & redeem-code endpoints), chat/ (IRC server), cloud-settings/, downloadable-content/, web-ui/ (in-game store & market HTML/CSS), mods/ (server mod runtime)Decode wire payloads (HTML forms, JSON, marker-prefixed binary BLK, PBBD streams, LZ4 packets), validate request parameters, invoke domain rules, and serialize results back into stock wire formatsDo not write multi-hundred-line currency, research, or profile-mutation logic inside *-actions.ts; never read or write save files directly bypassing PlayerProfiles / SaveStore
2. Domain Rulesbattle/ (mission setup & post-battle economy settlement), research/ (tech-tree state, target selection, free-RP conversion), modifications/ (modules, ammo belts, spares, custom weapon presets), crew/ (slots & skill progression), items/ (boosters, wagers, discounts), repair/ (battle damage & timed free repair), clans/ (squadrons & squadron vehicle RP), decor/ (skins, decals, 3D attachables), unlocks/ (streaks, titles, progression unlocks), player-card/ (pilot icons & showcases), training/ (tutorial completion rewards), game-modes/Pure domain logic: take an in-memory profile BlkBlock, loaded datasets, and validated tuning; verify preconditions; mutate or compute the next state; return an explicit RuleOutcome (ACCEPTED or refused('CODE'))Zero network or filesystem I/O: never import node:http, node:net, or node:fs, and keep domain logic agnostic of HTTP headers or sockets
3. Profile & Persistenceprofile/ (player-profiles.ts plus focused profile-*.ts BLK accessors and derived-state refresh), saves/ (save-store.ts & save-upgrades.ts formatVersion), accounts/ (multi-account credentials & isolation), storage/ (atomic-file.ts writeFileAtomic)Encapsulate typed BlkBlock profile accessors, isolate per-account saves under <data>/saves/<userId>/, run ordered formatVersion upgrades, and guarantee crash-safe writes via temp file + fsync + atomic renameDo not embed shop pricing or research formulas here; every profile mutation must finish writing to disk before replying to the client
4. Datasets & Tuninggame-data/ (game-files.ts, game-pack.ts, datasets/*.ts, datasets/dataset-cache.ts), shipped defaults in apps/server/tuning/*.jsonc + loader/validators in src/tuning/ (tuning-loader.ts, tuning-reader.ts, limits-tuning.ts, launcher-tuning.ts) + per-domain <domain>/*-tuning.tsExtract static facts from stock .vromfs.bin archives at startup (cached in <data>/cache/datasets/<id>.json by pack size/mtime and inner file SHA-1 digests), and merge/validate JSONC tuning across shipped defaults -> enabled mods -> player <data>/tuning/ overridesNever invent stock game numbers; if a required stock block or field is missing, throw an explicit error at startup instead of silently substituting a fake default
+

File granularity & reuse:

+ +
+

2.3 End-to-End Walkthrough of One Real Action: cln_set_researchable

+

To see how those four layers collaborate in practice, let's trace what happens when a player clicks "Research" on a vehicle in the tech tree and the client sends cln_set_researchable (use this exact pattern whenever you add a new profile-mutating char action):

+
  1. Wire Arrival & Payload Decoding (apps/server/src/char/char-service.ts) The client sends an HTTP POST to char-*.warthunder.com with headers action: cln_set_researchable and uidhint: <userId>, carrying a marker-prefixed binary BLK body (unit:t = "us_m4a1_1942_sherman", type:i = 0). CharService.#handleCore calls decodeRequestPayload(request.body) (char/char-payload.ts) to decode the BlkBlock (and format readable BLK text for the traffic log), then looks up 'cln_set_researchable' in char/actions/action-table.ts to invoke setResearchable.
  2. Protocol Adapter & Parameter Extraction (apps/server/src/char/actions/research-actions.ts) setResearchable is a thin 14-line adapter built on ruleAction (char/actions/rule-answer.ts). It extracts unit and type (or mod for module research) using stringParam and intParam (char/actions/payload-params.ts). Missing parameters return undefined (which ruleAction turns into !ERROR:BAD_PARAMS); valid parameters return a pure rule closure: (profile) => chooseResearchTarget(profile, rules, vehicle, type).
  3. Profile Load & Pure Domain Rule (apps/server/src/research/research-progress.ts) After resolving the account via withAccount, ruleAction calls profiles.updateWhen(account.userId, ...) (profile/player-profiles.ts), which loads <data>/saves/<userId>/profile.blk through SaveStore.loadProfile and passes the BlkBlock into chooseResearchTarget: +
    • Looks up the vehicle in the startup-extracted tech-tree dataset via rules.techTree.vehicle(vehicleName) and verifies vehicleTypeById(typeId) === vehicle.type;
    • Verifies currentStatus(profile, rules, vehicleName) === VehicleStatus.CAN_RESEARCH. If the vehicle is locked or already owned, it returns refused('NOT_AVAILABLE') ({ ok: false, refusal: 'NOT_AVAILABLE' })—causing updateWhen to return undefined without touching the disk and ruleAction to reply !ERROR:NOT_AVAILABLE;
    • Otherwise, updates the active target and clears any pending finished-research prompt via profile/profile-research-targets.ts, returning ACCEPTED ({ ok: true }).
  4. Atomic Disk Persistence BEFORE Replying (profile/player-profiles.ts -> saves/save-store.ts -> storage/atomic-file.ts) When the closure accepts, PlayerProfiles.updateWhen runs #refresh(profile, userId) to bring derived profile state (unlocked ranks, statuses, clan sync, earned unlocks) up to date, then calls SaveStore.saveProfile(userId, profile). saveProfile calls writeFileAtomic (storage/atomic-file.ts), which writes profile.blk.<pid>.<rand>.tmp, flushes hardware buffers via fsyncSync(fd), and atomically renameSyncs it over profile.blk (with Windows transient-lock retries) before updating save.json. Only after both atomic writes succeed does ruleAction project clientProfile(profile, account) and toResponse (char/char-answers.ts) send HTTP 200 (0x69 uncompressed marker + binary BLK) back to aces.exe.
+

2.4 Save Schema Upgrades (saves/save-upgrades.ts)

+ +
+

3. Three Categories of Values (Keep Boundaries Clear)

+

Every number or constant in WTOffline belongs to exactly one of three categories:

+
CategoryConcrete examplesWhere it MUST liveAnti-pattern to avoid
1. Protocol & engine constantsWire/MPI message IDs (LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u), PBBD magic (0x44424250), Dagor container layouts (dag::Vector offsets, FastNameMap shifts), bitmasksNamed constants in the relevant protocol module or header, with an English comment citing the primary source (client version + RVA, or DagorEngine open-source file path)Bare magic numbers like if (msgId == 61488) or if (st == 64) with zero provenance comment
2. Stock game factsVehicle SL/GE prices, RP requirements, battle ratings, repair costs, modification trees, mission lists, tutorial first-win rewards, killstreak spawn altitude/distance/speedExtracted from the player's read-only .vromfs.bin archives at startup via apps/server/src/game-data/datasets/ (Dataset<T>) and cached in <data>/cache/datasets/<id>.json by DatasetCache. Throw an explicit Error if a required block/field is missingCopying a table of vehicle costs, tutorial rewards, or spawn coordinates from one client build into TS/C code, or silently falling back to ?? 10000 when a lookup fails
3. Offline tuning & defaultsSL/RP reward multipliers, new-profile starting balances, local store bundle prices, supply-chest drop weights, AI bot respawn counts, request caps, gameplay togglesShipped defaults in apps/server/tuning/<domain>.jsonc, validated for type and bounds at startup via TuningReader in <domain>/*-tuning.ts, and merged by tuning-loader.ts across shipped defaults -> enabled mod overrides -> player <data>/tuning/<domain>.jsonc overridesHardcoding const RP_MULTIPLIER = 3.0 or arbitrary caps inside a settlement function where players and mods cannot override them
+
+

4. Good vs. Bad Code: 4 Real Codebase Comparisons

+

Every "✅ Good" snippet below uses the exact symbols and files from this repository. Check your changes against all four before opening a PR.

+

Comparison 1: Native C Hooks — g_lmp Dynamic Captures & Scoped TLS Flags vs. Hardcoded Offsets & _ReturnAddress()

+

Whenever War Thunder ships a minor patch (e.g., 2.61.0.37 -> 2.61.0.58), function RVAs shift across .text and C++ class member offsets move whenever fields are added or reordered.

+
c
// ❌ BAD: Hardcoded RVAs, hardcoded struct offset (+0x3798), and brittle _ReturnAddress() caller check.
+//         The very next minor game update will silently break the feature or crash the client!
+static void __fastcall bad_hook_send_unit_respawn(uint8_t *unit, const void *spawn)
+{
+    uintptr_t base = (uintptr_t)GetModuleHandleW(NULL);
+    if ((uintptr_t)_ReturnAddress() != base + 0x1281280)
+        return;
+    const uint8_t *gameplay = *(const uint8_t *const *)(base + 0x7bad2f0);
+    const uint8_t *rules = *(const uint8_t *const *)(gameplay + 0x3798);
+    /* ... */
+}
+
c
// ✅ GOOD (Real code: native/wto-net/src/local_mp_air_events.c + local_mp_offsets.h + local_mp_values.h):
+//    1. Every RVA and struct offset is dynamically captured in patches/native/local_mp_air_events.jsonc,
+//       written to wto_ws.cfg, and loaded into extern LmpValues g_lmp (LMP_GP_OFF_KS_RULES -> g_lmp.gp_ks_rules);
+//    2. An outer detour + thread-local flag (__declspec(thread)) scopes the call cleanly without _ReturnAddress().
+static SwitchPlayerUnitFn orig_switch_player_unit;
+static __declspec(thread) int g_in_air_event_switch;
 
-          
-          
-

- 3. 三类数值与数据来源 - 3. Three Categories of Values & Data Sources -

-
- - - - - - - - - - - - - - - - - - - - - -
数值类别Category放置位置与要求Where It Belongs
协议常量Protocol constants包头长度、消息枚举、编码魔数等保留在代码中,并用英文注释注明版本和出处(优先引用 DagorEngine 公开源码 或目标构建)。Header sizes, message enums, and encoding magic stay in code with English comments citing the build or DagorEngine public source.
游戏文件已有数据Stock game data载具、价格、改装件、任务、奖励表等在启动时通过 apps/server/src/game-data/datasets/ 从玩家原版文件提取并缓存;缺必需字段时明确报错,不悄悄塞入编造的默认值。Vehicles, prices, modifications, missions, and reward tables are extracted from the player's stock files via apps/server/src/game-data/datasets/. Report missing required fields and fail instead of substituting invented defaults.
离线版自定数值Offline tuning defaults倍率、商店定价、箱子权重、上限、开关等统一放进 apps/server/tuning/*.jsonc,并在启动时做完整类型与范围校验;用户目录同名文件可按字段覆盖。Multipliers, store prices, crate weights, limits, and toggles live in apps/server/tuning/*.jsonc with startup schema validation and per-client overrides.
+static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air) +{ + int previous = g_in_air_event_switch; + + if (to_air != 0 && ground_arcade_air_events_enabled()) + g_in_air_event_switch = 1; + orig_switch_player_unit(event_mgr, participant, to_air); + g_in_air_event_switch = previous; +} + +// Struct offsets come from g_lmp, surviving minor client updates automatically: +const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL; +const uint8_t *rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES); +uint32_t rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
+

Comparison 2: Stock Game Data — DatasetCache Extraction + Pure Catalogue vs. Hardcoded TS Maps

+
ts
// ❌ BAD: Hardcoding tutorial mission rewards from one client build directly in server code
+const TUTORIAL_REWARDS: Record<string, { silverLions: number; goldenEagles: number }> = {
+  'tutorialB_fighter': { silverLions: 5000, goldenEagles: 100 },
+  'tutorialB_assaulter': { silverLions: 5000, goldenEagles: 0 },
+};
+
ts
// ✅ GOOD (Real code: apps/server/src/game-data/datasets/training-missions.ts
+//                    + apps/server/src/training/training-completion.ts):
+//    1. Define a versioned Dataset<T> that extracts stock data from char.vromfs.bin
+//       (config/mislist.blk, config/pve_awards.blk, config/unlocks.blk) and throws if required blocks are missing.
+export const trainingMissions: Dataset<TrainingMissionsData> = {
+  id: 'training-missions',
+  version: 1,
+  extract(source: DatasetSource): TrainingMissionsData {
+    const misSection = blockAt(source.readBlk('char.vromfs.bin', 'config/mislist.blk'), 'training');
+    if (!misSection) throw new Error('config/mislist.blk has no "training" block');
+    const awardSection = blockAt(source.readBlk('char.vromfs.bin', 'config/pve_awards.blk'), 'training');
+    if (!awardSection) throw new Error('config/pve_awards.blk has no "training" block');
+    // ... build and return { missions }
+    return { missions };
+  },
+};
+
+//    2. Load through DatasetCache at startup and pass pure data into TrainingCatalogue:
+const trainingCatalogue = new TrainingCatalogue(datasets.load(trainingMissions));
+trainingCatalogue.applyCompletion(profile, { chapter, mission, difficulty });
+

Comparison 3: Fixing at the Right Layer & Toolchain Discipline (MSVC C & Node 24 TypeScript)

+

(A) Check stock loader fields before writing a client patch

+ +

(B) MSVC C rules & Node 24 native TypeScript rules

+ +
ts
// ❌ BAD: Extensionless relative import, value-importing a type, using `enum`, and constructor parameter properties
+import { SaveStore, SaveUpgrades } from '../saves/save-store';
+export enum ResearchState { Locked = 0, Available = 1 }
+export class Handler {
+  constructor(private readonly saves: SaveStore) {}
+}
+
ts
// ✅ GOOD: Explicit `.ts` extension on all relative imports, `import type` for types, `as const` objects instead of `enum`, and `#private` fields
+import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
+import { writeFileAtomic } from '../storage/atomic-file.ts';
+import type { SaveUpgrades } from './save-upgrades.ts';
+
+export const VehicleStatus = {
+  CAN_RESEARCH: 2,
+  OWNED: 4,
+} as const;
+

Comparison 4: Real Verification vs. Mock Test Suites

+ +
+

5. Working Effectively with AI Coding Assistants (Copy-Paste Prompt Block)

+

Using AI assistants (Claude Code, Codex, Cursor, etc.) to read disassembly, trace .nut UI call chains, inspect BLK schemas, and pinpoint protocol mismatches is warmly welcomed.

+

However, without explicit project context, AI tools frequently invent hardcoded RVAs, add an invalid requires field to patches/gui/**/patch.jsonc, omit .ts import extensions, write enum declarations, or generate bloated mock test suites. Paste the constraint block below into your AI session before asking it to write or edit code:

+
text
I am preparing a change for the WTOffline repository. Before writing any code, always read the real source files to verify symbols, struct fields, and CLI flags, and follow these engineering rules strictly:
+
+1. Layer priority: Ground every change in primary sources (read-only stock .vromfs.bin archives, gui.vromfs.bin .nut scripts, DagorEngine open-source code). Solve issues in apps/server protocol answers, mission BLK fields, or stock datasets before adding any client patch under patches/gui/, patches/exe/, or native/wto-net/.
+2. Zero hardcoded addresses or offsets: Never hardcode function RVAs, global addresses, C++ struct offsets, or _ReturnAddress() caller checks in C or TS. Capture all native symbols and offsets dynamically via patches/exe/ or patches/native/*.jsonc (signature / string_ref / within) into wto_ws.cfg, read them in C exclusively through `extern LmpValues g_lmp` (local_mp_values.h / local_mp_offsets.h), and replace caller checks with an outer hook + `__declspec(thread)` flag. When capturing a `rel32` from an instruction that has trailing immediate bytes after disp32, always pass `"end"` set to the full instruction byte length.
+3. Three value categories: Extract stock game numbers (vehicle prices, RP, rewards, missions, spawn params) from stock archives via `apps/server/src/game-data/datasets/` (`DatasetCache`), throwing explicitly if required fields are missing. Put offline defaults/multipliers/toggles in `apps/server/tuning/*.jsonc` validated via `*-tuning.ts`. Keep protocol/engine constants in code with English comments citing the client build RVA or DagorEngine source path.
+4. Layer & dependency rules: `packages/*` must never import or read from `apps/*`. Inside `apps/server/src/`, keep transport/protocol (`char/actions/`, etc.), pure domain rules (`research/`, `battle/`, `modifications/`, etc. — note there is NO `rules/` folder; zero network/disk I/O in domain modules), and profile/persistence (`profile/`, `saves/`, `storage/atomic-file.ts` — always persist atomically to disk BEFORE replying) cleanly separated. Handle save schema evolution only via `formatVersion` steps in `saves/save-upgrades.ts`, never ad-hoc legacy branches in domain rules. Split files near 300 lines or functions near 50 lines.
+5. Strict toolchain & schema rules:
+   - TypeScript runs on Node 24 native type-stripping (`erasableSyntaxOnly`, `verbatimModuleSyntax`, `allowImportingTsExtensions`): include explicit `.ts` extensions on all relative imports, use `import type` for type-only imports, and never use `enum`, `namespace`, or constructor parameter properties.
+   - Native C must compile cleanly with MSVC `native/wto-net/build.ps1` (`/W4`, zero warnings), using `C_ASSERT` for layout checks and zero GCC extensions; register any new `.c` file in `build.ps1`'s `$sources` list.
+   - Patch JSONC files reject unknown keys: in particular, `patches/gui/**/patch.jsonc` allows ONLY `id`, `title`, `features`, and `variants` at top level (adding `requires` throws `DefinitionError`!).
+6. Real verification: Do not add large mock unit test suites. Run the applicable real checks (`npm run typecheck`, `wtotools check-patches`, full `wtotools check-gui` with `--sq`, `native/wto-net/build.ps1`, `scripts/build-game-copy.ts`) and clearly separate executed CLI checks from pending isolated in-game acceptance steps.
+7. PR hygiene: Keep one focused goal per PR; write code comments, patch `title`/3-line header comments, and conventional commit messages in English; never list AI tools in `Co-authored-by`; and never commit `patches/versions/*.jsonc` before live in-game verification in an isolated copy.
+
+

6. Isolation & Asset Boundaries (Non-Negotiable)

+
  1. Keep the official stock installation strictly read-only: Unpacking archives, running tools/re/cli.py, checking patches with wtotools, and building game copies must only ever read the stock client folder—never write, modify, or drop files inside a Steam or official launcher installation.
  2. Test exclusively in an isolated offline copy: Run the patched client only from a separate directory outside your Steam library, with all three ESSENTIAL_FEATURES safety locks active—all network calls redirected to 127.0.0.1 by wto_ws.dll, user files isolated under WTOffline, registry state under Software\WTOffline, anti-cheat and crash reporting disabled, and signed in only with a local offline account.
  3. Zero copyrighted assets or private data in Git: Never commit .vromfs.bin packs, aces.exe, full extracted stock .nut / .blk files, personal player saves, machine-specific paths, or unredacted logs to the repository.
- +
+ ← 上一章← Previous01 · 导览、术语词典与入口地图01 · Overview, Glossary & Map + +
+ - -
-

- 4. 补丁体系与动态定位规范 - 4. Patch System & Dynamic Locating -

-

- 每处客户端改动独立成文件/目录,并在头部用英文注释写明三件事:改了什么、为什么本地服务器或配置做不到、不打会有什么后果。所有补丁加载器都采用严格字段校验,分析证据写在注释或 PR 里。 - Keep one behavior per patch definition, with English top comments explaining what changes, why the local server/config is insufficient, and what breaks without it. Loaders reject unknown fields, so put evidence in comments or the PR. -

- -
+
+
+

03 · 补丁编写、逐字节拆解与 Native 完整接线

+

这篇手册面向需要修改客户端(Quirrel 界面脚本、aces.exe 二进制指令、或 wto_ws.dll 局内 LocalMP 原生裁判模块)以及协助适配游戏新版本的开发者。

+

动手前的第一道自检:请先阅读 开发规范第 1 节,确认问题确实无法通过修改 apps/server 协议响应或下发原版任务/配置 BLK 字段解决。只有原版客户端真正缺失对应通路时,才编写客户端补丁。

+
+

1. 第 0 步:只读拆包、查看二进制 BLK、反汇编定位与选型

+

请将原版客户端目录视为只读,不要直接修改其中的文件。利用仓库自带的 @wto/vromfs、@wto/blk 和 Python 静态分析工具 tools/re/cli.py,你可以在内存中直接查看原版脚本、配置与反汇编代码。

+

1.1 一行命令读取原版 .vromfs.bin 中的 .nut 脚本或解码二进制 .blk

+

无需安装第三方解包器,在仓库根目录运行下面这段 Node.js 脚本(把 <原版目录> 换成你的官方客户端路径,只读不写):

+
powershell
# 示例 A:列出 gui.vromfs.bin 中匹配关键字的脚本路径,并直接打印某个 .nut 原文
+node --input-type=module -e "
+import { readFileSync } from 'node:fs';
+import { getFile, readArchive } from '@wto/vromfs';
+const archive = readArchive(readFileSync(String.raw`<原版目录>\gui.vromfs.bin`));
+console.log([...archive.files.keys()].filter((p) => p.includes('tutorial')));
+console.log(Buffer.from(getFile(archive, 'scripts/tutorials/nexttutorialhandler.nut')).toString('utf8'));
+"
 
-          
-          
-

- 5. 环境准备与对应检查命令 - 5. Environment Setup & Check Commands -

-

- 环境要求:Windows x64、Node.js 24+、Visual Studio / Build Tools(含 x64 C++ 工具,用于编译 wto_ws.dll)、Python 3.12+(仅 wtotools 需要),以及一份只读的原版游戏客户端。 - Requirements: Windows x64, Node.js 24+, Visual Studio / Build Tools with x64 C++ tools (for wto_ws.dll), Python 3.12+ (for wtotools), and a read-only stock client folder. -

-
-
- PowerShell · Checks - -
-
# TypeScript & Launcher build
-npm run typecheck
-npm run typecheck --workspace "@wto/launcher"
-npm run build --workspace "@wto/launcher"
+# 示例 B:读取 char.vromfs.bin(或 aces.vromfs.bin)里的紧凑二进制 .blk 并格式化为可读文本
+# (自动加载包内共享键名表 nm 与可选的 .dict 压缩字典)
+node --input-type=module -e "
+import { readFileSync } from 'node:fs';
+import { decodeBlk, formatBlkText, parseSharedNameMap } from '@wto/blk';
+import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs';
+const archive = readArchive(readFileSync(String.raw`<原版目录>\char.vromfs.bin`));
+const dictionary = [...archive.files.entries()].find(([p]) => p.endsWith('.dict'))?.[1];
+const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
+const blk = decodeBlk(getFile(archive, 'config/pve_awards.blk'), { names, dictionary });
+console.log(formatBlkText(blk).slice(0, 2000));
+"
+

1.2 使用 tools/re/cli.py 对 aces.exe 做只读静态逆向定位

+

先按 环境准备 初始化 .venv(pip install -e ./tools)。随后即可直接在命令行查字符串交叉引用、查调用者、反汇编函数(注意:所有地址参数均为十六进制 RVA,且务必显式传入 --exe "<原版目录>\win64\aces.exe"):

+
powershell
# 1. 查找固定英文字符串在 .rdata 中的 RVA,以及所有通过 rip-relative lea 引用它的代码位置与所属函数
+.\.venv\Scripts\python.exe tools\re\cli.py find-string "customScoreParams" --exe "<原版目录>\win64\aces.exe"
 
-# Native DLL build (MSVC x64, must compile cleanly)
+# 2. 查找所有以 rip-relative 方式读写某个全局变量 RVA 的指令
+.\.venv\Scripts\python.exe tools\re\cli.py xref 0x7bad2f0 --exe "<原版目录>\win64\aces.exe"
+
+# 3. 查找所有直接 call 或 jmp 到目标函数 RVA 的调用点
+.\.venv\Scripts\python.exe tools\re\cli.py callers 0x5445270 --exe "<原版目录>\win64\aces.exe"
+
+# 4. 反汇编指定 RVA(默认打印 40 条指令,带字符串和调用注释;可传 --count、--end 或 --function 反汇编整函数)
+.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x11b2c14 --count 20 --exe "<原版目录>\win64\aces.exe"
+.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x126d762 --function --exe "<原版目录>\win64\aces.exe"
+

1.3 选对客户端修改方式与通用编写规范

+
你要改什么代码放哪里真实参考例子
修改机库/弹窗/结算界面脚本(Quirrel .nut)patches/gui/<领域>/<名称>/patches/gui/tutorials/immediate-save-skip-tutorial/
改写 aces.exe 内寥寥几条跳转/比较指令或 .rdata 固定字符串patches/exe/<领域>/<名称>/patches/exe/battle/allow-local-host-bot-spawns/
用 C 语言写 MinHook 钩子补齐 LocalMP 局内裁判逻辑(wto_ws.dll)patches/native/<模块>.jsonc + native/wto-net/src/<模块>.cpatches/native/local_mp_scores.jsonc
改写 network.blk、shop.blk、gui.blk 等数据包静态配置packages/patcher/src/(不放 patches/)packages/patcher/src/char-pack.ts、main-pack.ts
+

所有 patches/ 定义共享的四条基本约定:

+
  1. 一处独立行为对应一个目录/模块,不在同一个补丁里顺手塞两件不相关的改动;
  2. patch.jsonc / <模块>.jsonc 顶部必须写三行英文注释: +
    • 第 1 行:这个补丁具体改了什么;
    • 第 2 行(Why the client: / Why the exe:):为什么本地服务器或原版配置解决不了;
    • 第 3 行(Without it:):如果不打这个补丁,玩家会遇到什么具体现象。
  3. title 与 features 统一写英文(注:仓库内个别早期补丁保留了中文 title 历史遗留,所有新增补丁请一律使用清晰的英文 title),并优先复用现有的 A-..K- 功能标签(见 核心概念词典第 7 节);
  4. 唯一命中校验:无论多少个 variants,对任意一个客户端版本必须且只能有恰好 1 个 variant 命中(且单次定位全局唯一命中 1 处);0 命中或多处命中都会被补丁引擎安全拒绝,避免误写。
+
+

2. GUI 补丁(patches/gui/)—— 完整三文件实例与严格 Schema 校验

+

2.1 看一个完整的真实 GUI 补丁:tutorials/immediate-save-skip-tutorial

+

在原版 scripts/tutorials/nexttutorialhandler.nut 中,当玩家弹出「是否参加新手教程」询问框并勾选「不再询问」时,脚本调用 saveLocalByAccount(skipTutorialBitmaskId, skipTutorial) 时没传第 3 个参数,默认走延迟 60 秒防抖的 saveProfile()——如果玩家勾选后在 60 秒内重启或崩溃退出,设置根本没发到服务端落盘,下次进机库弹窗又会冒出来。服务端无法替客户端缩短前端自己的 60 秒定时器,因此需要补上第 3 个回调参数 @() save_profile(false) 立即保存。

+

该补丁目录 patches/gui/tutorials/immediate-save-skip-tutorial/ 下共有 3 个文件,完整内容如下:

+

① patch.jsonc(注:此早期补丁保留了中文 title,你编写新补丁时请将 title 写为英文,如 "Save tutorial opt-out immediately after ticking 'do not ask again'"):

+
jsonc
// Save the tutorial opt-out immediately via save_profile(false).
+// Why the client: the stock callback waits 60 s before writing or sending anything to the service.
+// Without it: a crash within 60 s of ticking "do not ask again" brings the tutorial prompt back.
+{
+  "id": "tutorials/immediate-save-skip-tutorial",
+  "title": "新手教程询问窗勾选「不再询问」后立即落盘保存",
+  "features": [
+    "A-Tutorials"
+  ],
+  "variants": [
+    {
+      "written_for": "2.61.0.37",
+      "file": "scripts/tutorials/nexttutorialhandler.nut",
+      "edits": [
+        {
+          "find": "find.nut",
+          "replace": "replace.nut"
+        }
+      ]
+    }
+  ]
+}
+

② find.nut(原版脚本中最小且在目标文件内唯一出现 1 次的原文,保留原始 4 空格缩进):

+
squirrel
    skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
+    saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)
+  }
+

③ replace.nut(替换后的脚本片段):

+
squirrel
    skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
+    saveLocalByAccount(skipTutorialBitmaskId, skipTutorial, @() save_profile(false))
+  }
+

2.2 gui-patch-definition.ts 严格 Schema 白名单与编写细节(极易踩坑!)

+

packages/patcher/src/gui-patch-definition.ts 会调用 rejectUnknownKeys 对每一层字段做严格白名单检查,多写任何一个未定义字段都会直接抛出 DefinitionError:

+
  • 顶层只允许 4 个键:"id"、"title"、"features"、"variants"。 +

    特别警告:GUI 的 patch.jsonc 没有 "requires" 字段! 不要把 EXE 补丁里的 "requires": [] 复制到 patches/gui/ 里,否则加载器会当场抛错拒绝构建!

  • variants[] 元素只允许 3 个键:"written_for"、"file"、"edits"。其中 "file" 必须是 gui.vromfs.bin 内部全小写、以 / 分隔且不带前导 / 的相对路径(例如 "scripts/tutorials/nexttutorialhandler.nut",注意原版归档内文件名全被转为小写!)。
  • edits[] 元素只允许 2 个键:"find"、"replace",值必须是同一补丁目录下的纯文件名(不允许包含 / 或 \ 子路径)。
  • 换行与唯一匹配规则:读取 .nut 片段时会自动剥离 UTF-8 BOM、将 \r\n 归一化为 \n,并去掉文件末尾的单个终止换行符(因此 Git 自动换行转换不会破坏匹配);find.nut 的内容在目标脚本里必须精确出现 1 次(0 次或 ≥2 次均报错)。
  • 本地服务地址占位符:如果 replace.nut 里需要拼出本地服务器地址,直接写 {{LOCAL_ENDPOINT}},构建副本时 gui-pack.ts 会自动替换成 127.0.0.1:<实际端口>。
  • 跨版本演进:如果新版本游戏修改了附近代码导致 find.nut 不再命中,切勿直接覆盖旧片段破坏老版本兼容性——新建 find-58.nut 与 replace-58.nut,在 variants 数组里追加一条 "written_for": "<新版本号>" 的记录即可。
  • 必跑 sq.exe 字节码检查:只要改过任何 patches/gui/ 文件,提交前必须运行: +
    powershell
    .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
    +

    它会把补丁打在内存里的原版脚本上并调用 sq.exe 执行 compilestring 字节码编译,精准拦截与顶部 from ... import * 词法重名、未绑定函数前向引用以及误用 base 等保留字导致的进机库无限卡加载 Bug。

+
+

3. EXE 补丁(patches/exe/)—— 57 字节完整逐指令解剖与进阶参考

+

当需要改动 aces.exe 内部某条分支判断或常量字符串时,我们使用 @wto/exepatch 的声明式补丁格式,做到零硬编码地址、跨小版本自动重定位。

+

3.1 完整无省略实例:patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc

+

在 LocalMP 对局中,原版 BotSystem::changeUnit 在通过出生点检查后,会检查全局变量 g_multiplayer 是否为空(cmp qword ptr [rip + disp32], 0):单机试驾时 g_multiplayer == NULL,直接 jz 跳去调用 Unit::changeAircraft 刷出 AI;一旦处于 LocalMP 多人会话(g_multiplayer != NULL),零售客户端因为裁掉了专用服务器的脚本刷怪许可,落入后续分支只会打印 "spawn denied by scripts",导致整场对局一辆 AI 载具都刷不出来。

+

下面是仓库中 patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc 的一字不差完整原文(pattern 共 57 字节,无任何省略号):

+
jsonc
// Let BotSystem::changeUnit spawn the AI players' vehicles on a LocalMP host (0x11b2c3a: the g_multiplayer
+// null guard becomes a jump to the Unit::changeAircraft call at 0x11b314e).
+// Why the exe: the build drops the dedicated server's script spawn permission, so with a multiplayer
+// session the function only logs "spawn denied by scripts"; non-host sessions already return at its start.
+// Without it: no AI vehicle ever spawns in a LocalMP battle.
+{
+  "id": "battle/allow-local-host-bot-spawns",
+  "title": "Let BotSystem spawn AI vehicles on a LocalMP host",
+  "features": [
+    "K-AI opponents and teammates"
+  ],
+  "requires": [],
+  "variants": [
+    // Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010)
+    // to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards.
+    // 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a).
+    // spawn_call: where the null guard's jz goes (the Unit::changeAircraft call); the edit jumps there
+    // unconditionally. The guard's rip displacement differs between builds, so it is a wildcard.
+    {
+      "written_for": "2.61.0.37",
+      "locate": {
+        "method": "signature",
+        "section": ".text",
+        "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20",
+        "captures": {
+          "spawn_call": {
+            "offset": 48,
+            "type": "rel32"
+          }
+        }
+      },
+      "edit": {
+        "offset": 38,
+        "asm": [
+          "jmp {spawn_call}",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop"
+        ],
+        "bytes": "e9 ?? ?? ?? ?? 90 90 90 90 90 90 90 90 90",
+        "expect_original": "48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??",
+        "fixups": [
+          {
+            "at": 1,
+            "type": "rel32",
+            "target": "spawn_call"
+          }
+        ]
+      }
+    }
+  ]
+}
+

3.2 +0..+56 全部 57 字节逐指令拆解表

+

为什么 edit.offset 是 38?为什么 spawn_call 的 offset 是 48?为什么 fixups[0].at 又是 1?把这 57 个字节按 x86-64 指令逐条摊开,一眼就彻底明白了(以 2.61.0.37 命中起点 site = 0x11b2c14 为例):

+
相对 site 偏移长度pattern 中的十六进制字节对应的 x86-64 反汇编指令在补丁中扮演的角色
+0 .. +67 B48 8b 05 ?? ?? ?? ??mov rax, qword ptr [rip + disp32]前置上下文锚点;?? 通配随版本变化的全局变量 RIP 位移
+7 .. +137 B48 8b 88 e0 03 00 00mov rcx, qword ptr [rax + 0x3e0]前置上下文锚点
+14 .. +185 B48 8b 5c 24 20mov rbx, qword ptr [rsp + 0x20]前置上下文锚点
+19 .. +213 B48 89 damov rdx, rbx前置上下文锚点
+22 .. +243 B4d 89 f0mov r8, r14前置上下文锚点
+25 .. +295 Be8 ?? ?? ?? ??call rel32(出生点检查函数)前置上下文锚点;?? 通配被调函数相对距离
+30 .. +312 B84 c0test al, al前置上下文锚点
+32 .. +376 B0f 84 ?? ?? ?? ??jz rel32(无可用出生点则提前返回)前置上下文锚点;确保我们不会覆盖到前面的合法返回分支
+38 .. +458 B48 83 3d ?? ?? ?? ?? 00cmp qword ptr [rip + disp32], 0被改写区第 1 条指令(起点 edit.offset = 38):原版 g_multiplayer == 0 判空检查
+46 .. +516 B0f 84 ?? ?? ?? ??jz rel32(跳向 Unit::changeAircraft)被改写区第 2 条指令:操作码 0f 84 占 +46..+47,4 字节 rel32 位移位于 +48..+51,由 captures.spawn_call(offset: 48)动态读出跳转目标 RVA!
+52 .. +565 B48 8b 54 24 20mov rdx, qword ptr [rsp + 0x20]后置上下文锚点:锁死指令边界,确认 +51 之后紧跟预期的下一条指令
+

从上面这张表可以提炼出编写任何 EXE 补丁的 5 个核心要点:

+
  1. 首尾锚点保证 .text 全局唯一命中:单靠 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??(判空后条件跳转)在整个 aces.exe 里会撞上成百上千处;加上前后 +0..+37 与 +52..+56 的寄存器与调用序列后,80 MB 代码段里就只剩这唯一 1 处命中。
  2. edit.offset: 38 精准对齐被替换指令首字节:只改写 +38..+51 这两条指令(8 + 6 = 14 字节),前后的上下文锚点纹丝不动。
  3. captures.spawn_call 动态抠出跳转目的地:原 jz rel32 的 4 字节有符号位移位于 site + 48..51,未传 end 时默认指令结尾为 offset + 4 = 52,因此补丁引擎自动算出目标 RVA = site + 52 + disp32(在 2.61.0.37 上即 0x11b2c14 + 52 + disp32 = 0x11b314e)。哪怕下个版本目标函数挪到了别的地址,只要相对跳转还在,捕获出的目标就永远准确!
  4. expect_original、bytes 与 asm 三重互锁:expect_original(8 + 6 = 14 字节)与写入的 bytes(5 字节 e9 ?? ?? ?? ?? 无条件跳转 + 9 个 90 nop = 14 字节)长度必须严丝合缝相等;运行 wtotools check-patches 时还会调用汇编器把 asm 编译成机器码与 bytes 逐字节比对,杜绝手算机器码出错。
  5. 务必分清两套偏移基准点(新手头号易混点!): +
    • edit.offset(38)和 locate.captures.*.offset(48)都是从 locate 匹配起点 site(+0)开始算的;
    • 而 edit.fixups[].at(1)和 edit.fixups[].end(默认 at + 4 = 5)是从 edit.bytes 的第 0 字节(即 site + edit.offset = site + 38)开始算的!因为 bytes 第 0 字节是 e9(jmp 操作码),紧跟其后的 4 个 ?? 洞口就在 at: 1,回填位移公式为 spawn_call - ((site + 38) + 5)。
+

3.3 EXE 与 Native 定位进阶参考(必读防坑指南)

+
(1)rel32 捕获的 "end" 陷阱:带尾随立即数的 RIP 相对寻址指令!
+

x86-64 CPU 计算 [rip + disp32] 内存地址时,基准点永远是整条指令结束处(下一条指令的首地址),而不是 disp32 这 4 个字节结束的位置!

+
  • 对于 mov rax, [rip + disp32](48 8b 05 ?? ?? ?? ??,共 7 字节)或 jz rel32(0f 84 ?? ?? ?? ??,共 6 字节),disp32 恰好位于指令最末尾,所以默认的 end = offset + 4 刚好等于指令结尾,无需写 "end"。
  • 但如果指令在 disp32 后面还跟着立即数操作数,默认 end 就会算错地址!例如单条指令: c6 05 ?? ?? ?? ?? 00 —— mov byte ptr [rip + disp32], 0(整条指令共 7 字节:c6 05 占 0..1,disp32 占 2..5,末尾立即数 00 占第 6 字节,指令在偏移 7 处结束)。如果你只写 { "offset": 2, "type": "rel32" },默认 end 会取 2 + 4 = 6,算出来的全局变量 RVA 就会偏小 1 个字节!此时必须显式加上 "end": 7: +
    jsonc
    "captures": {
    +  "some_flag": { "offset": 2, "type": "rel32", "end": 7 }
    +}
    +

    仓库真实范例见 patches/native/local_mp_core.jsonc 的 disabled_slots_mask 站点:31 c0(+0..+1)后面紧跟 48 83 3d ?? ?? ?? ?? 00(+2..+9,cmp qword ptr [rip + disp32], 0),disp32 在 offset: 5,末尾还有 1 字节立即数 00(+9),因此显式声明了 "multiplayer": { "offset": 5, "type": "rel32", "end": 10 }。

+
(2)captures 支持的全部 7 种数值类型(packages/exepatch/src/captures.ts)
+
type字节宽度读取语义典型用途
"rel32"4 B(小端有符号)计算并返回 site + end + int32(即目标 RVA)捕获 call、jmp/jcc 跳转目标或 [rip + disp32] 全局变量地址
"u8"1 B(无符号)原样读取 0..255捕获短位移成员偏移(如 [r8 + 0x61] 中的 0x61)
"u16"2 B(小端无符号)原样读取 0..65535捕获 16 位消息号或协议常量(如 MPI 消息 ID)
"u32"4 B(小端无符号)原样读取 32 位无符号整数捕获常规 C++ 结构体大偏移(如 [rax + 0x6d8] 中的 0x6d8)或元素步长
"i8"1 B(有符号)原样读取 -128..127捕获带负号的单字节指针偏置(如循环步进指针向回偏移 -0x10)
"i16"2 B(小端有符号)原样读取 -32768..32767捕获 16 位有符号位移
"i32"4 B(小端有符号)原样读取 32 位有符号整数捕获可能为负数的 32 位有符号结构体/栈位移
+
(3)改写 .rdata 只读字符串的 "data" 写法
+

当你在 .rdata 数据段替换等长 ASCII 字符串(而不是改 .text 汇编指令)时,在 edit 中用 "data" 代替 "asm"(真实范例见 patches/exe/online/network-hook-library/patch.jsonc):

+
jsonc
"edit": {
+  "offset": 0,
+  "data": {
+    "encoding": "ascii",
+    "text": "wto_ws.dll"
+  },
+  "bytes": "77 74 6f 5f 77 73 2e 64 6c 6c 00",
+  "expect_original": "57 53 32 5f 33 32 2e 64 6c 6c 00"
+}
+

注意:bytes 与 expect_original 都包含末尾的 C 字符串终止零字节 00(共 11 字节),wtotools check-patches 会自动核对 "text" 的 ASCII 编码加终止零与 "bytes" 完全一致。

+
+

4. Native 模块(patches/native/ + native/wto-net/)—— 三种定位器与 6 文件完整串联教程

+

当需要在 wto_ws.dll 中用 C 语言挂载 MinHook 钩子或调用引擎内部函数时,不要在 C 源码里写死十六进制地址或游戏结构体偏移常量——所有值都由 patches/native/<模块>.jsonc 定位,经 wto_ws.cfg 传入 C 侧全局结构体 g_lmp。

+

4.1 三种代码定位方法详解(signature / string_ref / within)

+
  1. "method": "signature":在指定段(默认 ".text",可通过 "section" 覆盖)搜索全局唯一命中的字节特征码,支持 captures。
  2. "method": "string_ref"(packages/exepatch/src/locate/string-ref.ts,最抗编译器重排与小版本更新的利器!):先在 ".rdata"(或指定 "section")中找到以 \0 结尾的 UTF-8 字符串,再检索 .text 中所有加载该字符串地址的 7 字节 RIP 相对 lea 指令(48 8d / 4c 8d)。它共有 3 种工作模式: +
    • 模式 A(默认 "target": "reference",不带 "pattern"):直接返回那条 7 字节 lea 指令本身的 RVA(可校验字节长度为 7);
    • 模式 B("target": "function"):通过 PE 异常表(.pdata)反查包含该 lea 引用的外层函数起始 RVA 并去重返回(注意:此模式可校验字节长度为 0,不能直接在它上面挂 captures,专门用来定位函数入口供 MinHook 挂钩或作为下方 within 的父锚点!);
    • 模式 C("pattern" + "lea_at",此时 "target" 必须保持默认 "reference"):围绕字符串 lea 匹配一段局部指令序列,要求加载该字符串的 7 字节 lea 恰好位于 pattern 内部偏移 lea_at 处,返回 pattern 起点 RVA——这样就能顺手用 captures 把紧挨着字符串引用的结构体字段偏移抠出来!(例如通过字段名 "kills" 直接抠出 MPlayer 里的击杀计数字段偏移)。
  3. "method": "within"(packages/exepatch/src/locate/within.ts):在同一个或被 requires 依赖的模块中已经先行定位好的站点 "in" 所属函数的 .pdata [begin, end) 范围内搜索 "pattern"。因为在单个函数内部搜索,哪怕只有一两条指令的短特征码也能唯一命中,彻底避免全程序撞码。
+

4.2 跟着 local_mp_scores 走完从 JSONC 到 C 落地的全部 6 个文件

+

假设我们要实现 LocalMP 局内记分牌分值读取模块 local_mp_scores(本地服务器把各事件得分写进任务配置的 customScoreParams 子块,客户端 MissionSettings::load 会把它拷进 MissionSettings 结构体内部某偏移处,但客户端自己从不读它;我们的 C 模块需要调用引擎的 DataBlock::getReal 从该偏移处读出分值)。看看这 6 个真实文件是怎么严丝合缝串起来的:

+
第 1 步:编写定位定义 patches/native/local_mp_scores.jsonc
+

文件名必须与 "module" 字段完全同名。由于我们要复用 local_mp_core.jsonc 里已经用 "string_ref"("string": "customScoreParams", "target": "function")定位好的函数 "mission_settings_load",在 "requires" 中声明 "local_mp_core":

+
jsonc
// Score table of a LocalMP battle (native/wto-net/src/local_mp_scores.c): the local server puts it
+// in the mission's customScoreParams; the host reads it there.
+// Without it: kills, assists and captures score nothing.
+{
+  "module": "local_mp_scores",
+  "features": [
+    "K-Kill, assist and capture scoring"
+  ],
+  "requires": [
+    "local_mp_core"
+  ],
+  "sites": {
+    // DataBlock::getReal wrapper.
+    // 2.61.0.37: 0x5445270
+    "datablock_get_real": {
+      "variants": [
+        {
+          "written_for": "2.61.0.37",
+          "locate": {
+            "method": "signature",
+            "pattern": "48 83 ec 28 f3 0f 11 54 24 24 4c 8d 44 24 24 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc 56 57 53 48 83 ec 30 48 89 d7 48 89 ce 48 8d 15"
+          }
+        }
+      ]
+    },
+    // MissionSettings customScoreParams copy.
+    // 2.61.0.37: 0x126d762 (lea rcx, [rax + 0x6d8]; mov eax, dword ptr [r13 + 0x10]; cmp eax, -1; ...)
+    "mission_score_params": {
+      "variants": [
+        {
+          "written_for": "2.61.0.37",
+          "locate": {
+            "method": "within",
+            "in": "mission_settings_load",
+            "pattern": "48 8d 88 ?? ?? ?? ?? 41 8b 45 10 83 f8 ff 74 ?? 45 0f b7 45 0e 46 8d 0c 00 31 d2 44 39 c8 0f 8d ?? ?? ?? ?? ff c7 4d 8b 4d 00 45 8b 51 5c 4d 01 d1 49 81 c1 90 00 00 00 41 bb ff ff ff 3f 45 31 d2 66 66 66 66 2e 0f 1f 84 00 00 00 00 00 42 8d 34 10 48 c1 e6 05 41 8b 5c 31 08 44 21 db 39 fb 74 ?? 41 ff c2 45 39 d0 75 ?? eb ?? 41 0f b7 45 0e 31 d2 85 c0 74 ?? ff c7 4d 8b 4d 18 4d 8b 01 45 8b 49 08 44 8d 14 c5 00 00 00 00 45 29 d1 41 ba ff ff ff 3f 45 31 db 66 0f 1f 44 00 00 4b 8b 34 08 8b 76 08 44 21 d6 39 fe 74 ?? 41 ff c3 49 83 c1 08 44 39 d8 75 ?? eb ?? 49 01 f1 31 d2 45 39 c2 49 0f 42 d1 eb ?? 41 39 c3 73 ?? 44 89 c8 49 8b 14 00 eb ?? 31 d2 48 85 d2 49 0f 44 d6 31 f6 45 31 c0 e8 ?? ?? ?? ?? 49 8b 5d 00 bf ff ff ff ff 48 85 db 74 ?? 48 8d 0d ?? ?? ?? ?? ba 16 00 00 00",
+            "captures": {
+              "custom_score_params": {
+                "offset": 3,
+                "type": "u32"
+              }
+            }
+          }
+        }
+      ]
+    }
+  }
+}
+

看 mission_score_params 首条指令 48 8d 88 ?? ?? ?? ??(lea rcx, [rax + disp32]):前 3 字节是 48 8d 88,第 3..6 字节就是 MissionSettings 里的结构体偏移,因此 "offset": 3, "type": "u32" 直接把 0x6d8 抠了出来!

+
第 2 步:构建器自动生成 <离线副本>/win64/wto_ws.cfg(packages/patcher/src/native/)
+

构建副本时,native-resolve.ts 与 native-settings.ts 会把当前 aces.exe 的 PE 头指纹连同所有已就绪模块的 <站点> 与 <站点>.<捕获名> 写入 win64/wto_ws.cfg:

+
ini
port=27015
+exe.time_date_stamp=0x67e5a1b2
+exe.size_of_image=0x83f4000
+native.datablock_get_real=0x5445270
+native.mission_score_params=0x126d762
+native.mission_score_params.custom_score_params=0x6d8
+
第 3 步:在 native/wto-net/src/local_mp_values.h 声明 LmpValues 字段
+

地址一律声明为 uint8_t *,无符号偏移/大小声明为 size_t(有符号位移声明为 ptrdiff_t):

+
c
typedef struct LmpValues {
+    /* ... 其他模块字段 ... */
+
+    /* local_mp_scores */
+    uint8_t *datablock_get_real;
+    size_t mis_custom_score_params;
+} LmpValues;
+
+extern LmpValues g_lmp;
+
第 4 步:在 native/wto-net/src/local_mp_values.c 绑定 SPECS[] 映射表
+

local_mp_values.c 通过三个宏把 wto_ws.cfg 里的键名映射到 g_lmp 的成员:

+
  • A(module, name, field)(LMP_ADDRESS):读取 RVA 后自动加上当次进程基址 (uint8_t *)GetModuleHandleW(NULL) + value,存成可直接调用的运行时指针;
  • O(module, name, field)(LMP_OFFSET):存为无符号 size_t 结构体偏移或步长;
  • S(module, name, field)(LMP_SIGNED):存为有符号 ptrdiff_t 位移;
  • 如果某个复合偏移需要由两个捕获值相加减(客户端没有单独访问它的指令),则写在同文件的 derive_values() 中。
+
c
#define SCORES "local_mp_scores"
+
+static const LmpValueSpec SPECS[] = {
+    /* ... */
+    A(SCORES, "datablock_get_real", datablock_get_real),
+    O(SCORES, "mission_score_params.custom_score_params", mis_custom_score_params),
+    /* ... */
+};
+
第 5 步:在 native/wto-net/src/local_mp_offsets.h 定义可读偏移宏
+
c
#define LMP_MIS_OFF_CUSTOM_SCORE_PARAMS (g_lmp.mis_custom_score_params)
+
第 6 步:实现 local_mp_scores.c、注册到 local_mp_core.c 并加入 build.ps1
+
  • 在 local_mp_scores.c 中只读取 g_lmp 与 local_mp_core 导出的公共指针: +
    c
    typedef float (__fastcall *DataBlockGetRealFn)(const void *blk, const char *name, float def);
    +static DataBlockGetRealFn fn_datablock_get_real;
    +
    +float local_mp_score_param(const char *key)
    +{
    +    if (fn_datablock_get_real == NULL || g_local_mp_mission_settings == NULL || key == NULL)
    +        return 0.0f;
    +    return fn_datablock_get_real(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_SCORE_PARAMS, key, 0.0f);
    +}
    +
    +int install_local_mp_score_reader(void)
    +{
    +    fn_datablock_get_real = (DataBlockGetRealFn)g_lmp.datablock_get_real;
    +    return 1;
    +}
  • 在 local_mp_core.c 中,启动时 install_local_mp_hooks() 会先用 config_native_matches_executable() 核对当前运行中 aces.exe 的 PE TimeDateStamp 与 SizeOfImage 是否与 wto_ws.cfg 完全一致(不一致则整套 LocalMP 桥接器安全关闭),然后按依赖顺序遍历 MODULES[] 数组,对每个模块先跑 lmp_values_load(MODULES[i].name) 确认值一个不少,再调用安装函数并在最后统一 MH_ApplyQueued()。
  • 如果新增了一个全新的 .c 源文件:除了在 local_mp_internal.h 声明安装函数并加入 local_mp_core.c 的 MODULES[],还必须把该 .c 文件路径加进 native/wto-net/build.ps1 的 $sources 数组!
  • 多模块共享钩子:如果两个模块都需要拦截或调用同一个引擎函数(例如 Unit::onEvent 同时被 local_mp_damage_notifications 和 local_mp_air_events 使用),请把站点放进 local_mp_core.jsonc 统一解析分发,避免在两个模块里用 MinHook 重复挂钩同一个目标地址。
+
+

5. 适配新版本客户端(标准四步流程)

+

每当《战争雷霆》发布小版本更新(例如 2.61.0.37 → 2.61.0.58)时,按下面四步跟进适配:

+
  1. 对只读原版客户端运行版本核对脚本: +
    powershell
     node scripts/record-game-version.ts --game "<原版目录>"
    +

    该脚本会只读扫描原版客户端,一次性跑完所有 patches/exe/、patches/gui/ 和 patches/native/ 的定位测试。如果三条核心安全锁(ESSENTIAL_FEATURES)中有补丁失效,脚本会直接拒绝生成版本记录并列出阻断项;若核心安全锁全部命中,则会写出 patches/versions/<版本号>.jsonc 并打印所有 unavailable(暂不可用)的非关键补丁/模块。

  2. 排查失配项并追加新 variant: 打开失配的补丁或原生站点,用第 1 节的 Node 拆包脚本或 tools/re/cli.py(优先用 find-string 找不变的字符串锚点!)查看新版本原版文件发生了什么变化。保留原有旧版本的 variant 不动,在 variants 数组中追加一条 "written_for": "<新版本号>" 的新写法。
  3. 跑完完整工具链核对: 重新运行 record-game-version.ts 确认 unavailable 清零,并依次跑通: +
    • .\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<原版目录>\win64\aces.exe"
    • .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
    • 若改了 native/wto-net/,运行 powershell -NoProfile -File .\native\wto-net\build.ps1
    • 用临时输出目录跑一遍 node scripts/build-game-copy.ts 确认副本完整生成。
  4. 隔离副本实机进游戏验收后再提交 patches/versions/<版本号>.jsonc: 启动器依赖 patches/versions/<版本号>.jsonc 向玩家展示「该客户端版本已核对通过」。请在隔离副本里实际登录进机库并完成一局 LocalMP 对局验收后,再提交 patches/versions/<版本号>.jsonc,不要仅凭命令行脚本通过就直接入库。
+

新建补丁时可直接复制空白脚手架模板:dev-docs/templates/gui/、dev-docs/templates/exe/、dev-docs/templates/native/。

+
+
+

03 · Patch Authoring, Byte Anatomy & Full Native Wiring

+

This handbook covers authoring client patches (Quirrel UI scripts, aces.exe machine-code/data patches, and wto_ws.dll LocalMP native modules) and adapting WTOffline to new War Thunder client builds.

+

Check first before touching the client: Read Development Rules — Section 1 and verify that the issue genuinely cannot be solved in apps/server or via stock mission/config BLK fields. Client patches are strictly for code paths that retail client builds omit or hardcode.

+
+

1. Step 0: Unpacking Stock Archives, Reading Binary BLK, Disassembling aces.exe, and Choosing a Patch Type

+

Never modify any file inside your official stock installation. Using @wto/vromfs, @wto/blk, and tools/re/cli.py, you can inspect every stock script, binary .blk, and aces.exe function purely in memory.

+

1.1 Inspect .nut Scripts or Binary .blk Files Inside Stock .vromfs.bin Archives

+

Run these one-liners from the repository root (replacing <stock-dir> with your read-only official War Thunder path):

+
powershell
# Example A: List matching .nut paths inside gui.vromfs.bin and print a stock Quirrel script
+node --input-type=module -e "
+import { readFileSync } from 'node:fs';
+import { getFile, readArchive } from '@wto/vromfs';
+const archive = readArchive(readFileSync(String.raw`<stock-dir>\gui.vromfs.bin`));
+console.log([...archive.files.keys()].filter((p) => p.includes('tutorial')));
+console.log(Buffer.from(getFile(archive, 'scripts/tutorials/nexttutorialhandler.nut')).toString('utf8'));
+"
+
+# Example B: Decode a slimmed binary .blk from char.vromfs.bin (or aces.vromfs.bin) as readable text
+# (automatically loads the archive's shared name map `nm` and optional `.dict` zstd dictionary)
+node --input-type=module -e "
+import { readFileSync } from 'node:fs';
+import { decodeBlk, formatBlkText, parseSharedNameMap } from '@wto/blk';
+import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs';
+const archive = readArchive(readFileSync(String.raw`<stock-dir>\char.vromfs.bin`));
+const dictionary = [...archive.files.entries()].find(([p]) => p.endsWith('.dict'))?.[1];
+const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
+const blk = decodeBlk(getFile(archive, 'config/pve_awards.blk'), { names, dictionary });
+console.log(formatBlkText(blk).slice(0, 2000));
+"
+

1.2 Static Reverse Engineering on aces.exe with tools/re/cli.py

+

Once your .venv is installed (pip install -e ./tools; see Environment Setup), use tools/re/cli.py to locate strings, cross-references, callers, and disassembly (all addresses are hex RVAs, and always pass --exe "<stock-dir>\win64\aces.exe" explicitly):

+
powershell
# 1. Find where a C string lives in .rdata and every rip-relative `lea` instruction + function referencing it
+.\.venv\Scripts\python.exe tools\re\cli.py find-string "customScoreParams" --exe "<stock-dir>\win64\aces.exe"
+
+# 2. Find every instruction with a rip-relative reference to a target RVA (e.g., a global pointer)
+.\.venv\Scripts\python.exe tools\re\cli.py xref 0x7bad2f0 --exe "<stock-dir>\win64\aces.exe"
+
+# 3. Find every direct `call` or `jmp` targeting a function RVA
+.\.venv\Scripts\python.exe tools\re\cli.py callers 0x5445270 --exe "<stock-dir>\win64\aces.exe"
+
+# 4. Disassemble an RVA with string and call annotations (defaults to 40 instructions; supports --count, --end, or --function)
+.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x11b2c14 --count 20 --exe "<stock-dir>\win64\aces.exe"
+.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x126d762 --function --exe "<stock-dir>\win64\aces.exe"
+

1.3 Choosing the Right Patch Type & Universal Conventions

+
What needs changingWhere it belongsReal codebase example
Hangar, modal, store, or debriefing UI scripts (Quirrel .nut)patches/gui/<domain>/<name>/patches/gui/tutorials/immediate-save-skip-tutorial/
A few machine instructions or a constant .rdata string in aces.exepatches/exe/<domain>/<name>/patches/exe/battle/allow-local-host-bot-spawns/
In-process C hooks restoring LocalMP battle host logic (wto_ws.dll)patches/native/<module>.jsonc + native/wto-net/src/<module>.cpatches/native/local_mp_scores.jsonc
Static archive config rewrites (network.blk, shop.blk, gui.blk)packages/patcher/src/ (not under patches/)packages/patcher/src/char-pack.ts, main-pack.ts
+

Four universal rules across all patches/ definitions:

+
  1. One behavior per directory/module—never bundle unrelated fixes into a single patch definition.
  2. Start every patch.jsonc / <module>.jsonc with a 3-line English comment: +
    • Line 1: What the patch changes;
    • Line 2 (Why the client: / Why the exe:): Why the local server or stock config cannot provide it;
    • Line 3 (Without it:): What breaks for the player if this patch is missing.
  3. Write title and features in English (note: a few early historical patches still carry Chinese title strings, but all new patches must write title in English), reusing existing A-..K- inventory tags (Glossary — Section 7).
  4. Exact single-variant, single-site match: On any given client build, exactly one variant must apply, and its locator must hit exactly one site; zero hits or multiple hits fail safely rather than corrupting the output copy.
+
+

2. GUI Patches (patches/gui/) — Full 3-File Example & Strict Schema Rules

+

2.1 Complete Real Example: tutorials/immediate-save-skip-tutorial

+

In stock scripts/tutorials/nexttutorialhandler.nut, when a player ticks "Do not ask me again" on the tutorial prompt, the script calls saveLocalByAccount(skipTutorialBitmaskId, skipTutorial) with no third argument. That falls back to saveProfile(), which waits on a 60-second debounce timer before sending anything to the server—so closing or crashing within 60 seconds loses the opt-out and brings the prompt back on next login. Because apps/server cannot speed up a client-side timer before a request is ever sent, this patch passes @() save_profile(false) as the immediate-save callback.

+

Here are all three files in patches/gui/tutorials/immediate-save-skip-tutorial/ verbatim (note: this early patch kept a Chinese title, whereas new patches should use an English title such as "Save tutorial opt-out immediately after ticking 'do not ask again'"):

+

1. patch.jsonc:

+
jsonc
// Save the tutorial opt-out immediately via save_profile(false).
+// Why the client: the stock callback waits 60 s before writing or sending anything to the service.
+// Without it: a crash within 60 s of ticking "do not ask again" brings the tutorial prompt back.
+{
+  "id": "tutorials/immediate-save-skip-tutorial",
+  "title": "新手教程询问窗勾选「不再询问」后立即落盘保存",
+  "features": [
+    "A-Tutorials"
+  ],
+  "variants": [
+    {
+      "written_for": "2.61.0.37",
+      "file": "scripts/tutorials/nexttutorialhandler.nut",
+      "edits": [
+        {
+          "find": "find.nut",
+          "replace": "replace.nut"
+        }
+      ]
+    }
+  ]
+}
+

2. find.nut (the smallest verbatim stock snippet occurring exactly once in the target .nut file, preserving exact indentation):

+
squirrel
    skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
+    saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)
+  }
+

3. replace.nut (the replacement text):

+
squirrel
    skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
+    saveLocalByAccount(skipTutorialBitmaskId, skipTutorial, @() save_profile(false))
+  }
+

2.2 Strict gui-patch-definition.ts Schema Whitelist & Authoring Rules

+

packages/patcher/src/gui-patch-definition.ts calls rejectUnknownKeys at every level—any extra property immediately throws DefinitionError:

+
  • Top-level keys are strictly id, title, features, variants. +

    Watch out: GUI patch.jsonc does NOT have a requires key! Do not copy "requires": [] from an EXE patch into patches/gui/, or loadGuiPatches will throw DefinitionError!

  • variants[] keys are strictly written_for, file, edits. file must be the exact lowercase, /-separated relative path inside gui.vromfs.bin without a leading slash (e.g., "scripts/tutorials/nexttutorialhandler.nut"—archive paths are all lowercased!).
  • edits[] keys are strictly find, replace, naming plain filenames directly inside the patch folder (no / or \ subdirectories).
  • Line endings & exact-once matching: readFragment strips any UTF-8 BOM, normalizes \r\n to \n, and removes a single trailing newline at EOF (so Git autocrlf never breaks patches). find.nut must match exactly once in the target script.
  • {{LOCAL_ENDPOINT}} placeholder: Whenever replacement Quirrel code needs the local server address, write {{LOCAL_ENDPOINT}}; gui-pack.ts expands it to 127.0.0.1:<port> during copy builds.
  • Adding a variant for a newer build: Never edit an existing find.nut in a way that breaks older supported builds—create find-58.nut / replace-58.nut and append a new entry to variants.
  • Mandatory sq.exe bytecode check: Every change under patches/gui/ must pass: +
    powershell
    .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
    +

    check-gui applies all GUI patches in memory and runs sq.exe (compilestring) on every patched .nut script, catching lexical binding clashes with top-of-file from ... import * imports, unbound forward calls, and reserved keywords like base that otherwise hang the client forever on "Loading...".

+
+

3. EXE Patches (patches/exe/) — Full 57-Byte Anatomy & Reference

+

When modifying instructions or constant data inside aces.exe, @wto/exepatch lets you express edits with zero hardcoded addresses so patches survive minor game updates automatically.

+

3.1 Un-Elided Real Example: patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc

+

In BotSystem::changeUnit, after verifying a valid spawn point, stock aces.exe checks whether g_multiplayer is null (cmp qword ptr [rip + disp32], 0): in single-player test flights (g_multiplayer == NULL), jz jumps straight to the Unit::changeAircraft call to spawn the AI unit; in a LocalMP session (g_multiplayer != NULL), because retail aces.exe strips the Dedicated Server's script spawn permission, execution falls through to "spawn denied by scripts" and no AI vehicle ever spawns.

+

Here is the complete, un-elided patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc (all 57 pattern bytes, zero ...):

+
jsonc
// Let BotSystem::changeUnit spawn the AI players' vehicles on a LocalMP host (0x11b2c3a: the g_multiplayer
+// null guard becomes a jump to the Unit::changeAircraft call at 0x11b314e).
+// Why the exe: the build drops the dedicated server's script spawn permission, so with a multiplayer
+// session the function only logs "spawn denied by scripts"; non-host sessions already return at its start.
+// Without it: no AI vehicle ever spawns in a LocalMP battle.
+{
+  "id": "battle/allow-local-host-bot-spawns",
+  "title": "Let BotSystem spawn AI vehicles on a LocalMP host",
+  "features": [
+    "K-AI opponents and teammates"
+  ],
+  "requires": [],
+  "variants": [
+    // Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010)
+    // to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards.
+    // 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a).
+    // spawn_call: where the null guard's jz goes (the Unit::changeAircraft call); the edit jumps there
+    // unconditionally. The guard's rip displacement differs between builds, so it is a wildcard.
+    {
+      "written_for": "2.61.0.37",
+      "locate": {
+        "method": "signature",
+        "section": ".text",
+        "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20",
+        "captures": {
+          "spawn_call": {
+            "offset": 48,
+            "type": "rel32"
+          }
+        }
+      },
+      "edit": {
+        "offset": 38,
+        "asm": [
+          "jmp {spawn_call}",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop",
+          "nop"
+        ],
+        "bytes": "e9 ?? ?? ?? ?? 90 90 90 90 90 90 90 90 90",
+        "expect_original": "48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??",
+        "fixups": [
+          {
+            "at": 1,
+            "type": "rel32",
+            "target": "spawn_call"
+          }
+        ]
+      }
+    }
+  ]
+}
+

3.2 Instruction-by-Instruction Breakdown (+0..+56, All 57 Bytes)

+

Breaking down every byte from the match start site (0x11b2c14 on 2.61.0.37) makes every offset number self-evident:

+
Offset from siteSizeHex bytes in patternx86-64 instructionRole in this patch
+0 .. +67 B48 8b 05 ?? ?? ?? ??mov rax, qword ptr [rip + disp32]Leading context anchor (?? masks build-varying RIP displacement)
+7 .. +137 B48 8b 88 e0 03 00 00mov rcx, qword ptr [rax + 0x3e0]Leading context anchor
+14 .. +185 B48 8b 5c 24 20mov rbx, qword ptr [rsp + 0x20]Leading context anchor
+19 .. +213 B48 89 damov rdx, rbxLeading context anchor
+22 .. +243 B4d 89 f0mov r8, r14Leading context anchor
+25 .. +295 Be8 ?? ?? ?? ??call rel32 (spawn-point check)Leading context anchor (?? masks call displacement)
+30 .. +312 B84 c0test al, alLeading context anchor
+32 .. +376 B0f 84 ?? ?? ?? ??jz rel32 (early-out if spawn check failed)Leading context anchor (kept intact!)
+38 .. +458 B48 83 3d ?? ?? ?? ?? 00cmp qword ptr [rip + disp32], 0Edited instruction #1 (edit.offset = 38): the g_multiplayer null guard
+46 .. +516 B0f 84 ?? ?? ?? ??jz rel32 (to Unit::changeAircraft call)Edited instruction #2: 2-byte opcode 0f 84 (+46..+47) + 4-byte rel32 at +48..+51, captured as spawn_call (offset: 48)!
+52 .. +565 B48 8b 54 24 20mov rdx, qword ptr [rsp + 0x20]Trailing context anchor verifying exact instruction boundary after +51
+

Notice the five key mechanics working together here:

+
  1. Surrounding anchors guarantee a unique hit: 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? alone appears hundreds of times across .text, whereas anchoring +0..+37 before it and +52..+56 after it narrows 80 MB of code down to a single unambiguous hit.
  2. edit.offset: 38 leaves the anchors untouched: Only the 14 bytes at +38..+51 are overwritten.
  3. captures.spawn_call (offset: 48, type: "rel32") resolves the jump target dynamically: The jz instruction's 4-byte displacement sits at +48..+51, so default end = 48 + 4 = 52, yielding target RVA = site + 52 + disp32 (0x11b314e on 2.61.0.37). Even when future builds shift Unit::changeAircraft, the captured RVA updates automatically.
  4. Exact 14-byte parity & asm verification: expect_original is 8 + 6 = 14 bytes and bytes is 5 (e9 ?? ?? ?? ??) + 9 (90 NOPs) = 14 bytes. Running wtotools check-patches assembles asm and verifies byte-for-byte agreement with bytes.
  5. Crucial offset base distinction (most common beginner mistake!): +
    • edit.offset (38) and locate.captures.*.offset (48) count from site (+0 of locate.pattern);
    • edit.fixups[].at (1) and edit.fixups[].end (default at + 4 = 5) count from byte 0 of edit.bytes (site + 38), right after the e9 opcode!
+

3.3 Reference: The rel32 "end" Trap, All 7 Capture Types & .rdata Edits

+
(1) The rel32 "end" Trap (Instructions with Trailing Immediate Bytes!)
+

On x86-64, RIP-relative addressing always adds disp32 to the address of the next instruction (where the current instruction ends), NOT where the 4-byte disp32 ends!

+
  • For mov rax, [rip + disp32] (48 8b 05 ?? ?? ?? ??, 7 B) or jz rel32 (0f 84 ?? ?? ?? ??, 6 B), disp32 is at the very end of the instruction, so the default end = offset + 4 matches the instruction end automatically.
  • However, when an instruction has trailing immediate byte(s) after disp32, omitting "end" resolves the wrong address! Take c6 05 ?? ?? ?? ?? 00 (mov byte ptr [rip + disp32], 0): the instruction is 7 bytes total (c6 05 at 0..1, disp32 at 2..5, trailing immediate 00 at 6, ending at 7). Writing { "offset": 2, "type": "rel32" } defaults end to 2 + 4 = 6, landing 1 byte before the real global variable! You must pass "end": 7: +
    jsonc
    "captures": {
    +  "some_flag": { "offset": 2, "type": "rel32", "end": 7 }
    +}
    +

    For a real example in the repo, see disabled_slots_mask.multiplayer in patches/native/local_mp_core.jsonc: after 31 c0 (+0..+1), 48 83 3d ?? ?? ?? ?? 00 (cmp qword ptr [rip + disp32], 0) spans +2..+9 with disp32 at offset: 5 and trailing 00 at +9, so it specifies "end": 10.

+
(2) All 7 Capture Types (packages/exepatch/src/captures.ts)
+
typeWidthHow it is readTypical use
"rel32"4 B (signed LE)Computes target RVA = site + end + int32Target of call, jmp/jcc, or [rip + disp32] global variable
"u8"1 B (unsigned)Raw 0..255Compact 8-bit struct field offset (e.g., [r8 + 0x61])
"u16"2 B (unsigned LE)Raw 0..6553516-bit wire/MPI message IDs
"u32"4 B (unsigned LE)Raw 32-bit unsigned integerStandard C++ struct member offsets (e.g., [rax + 0x6d8]) or array strides
"i8"1 B (signed)Raw -128..127Signed 1-byte pointer biases in loop iterators
"i16"2 B (signed LE)Raw -32768..32767Signed 16-bit displacements
"i32"4 B (signed LE)Raw 32-bit signed integerSigned 32-bit stack or struct displacements
+
(3) Constant String / Data Edits in .rdata
+

When replacing a fixed-length string in .rdata instead of assembly instructions, use "data" in place of "asm" (real example: patches/exe/online/network-hook-library/patch.jsonc):

+
jsonc
"edit": {
+  "offset": 0,
+  "data": {
+    "encoding": "ascii",
+    "text": "wto_ws.dll"
+  },
+  "bytes": "77 74 6f 5f 77 73 2e 64 6c 6c 00",
+  "expect_original": "57 53 32 5f 33 32 2e 64 6c 6c 00"
+}
+

Both bytes and expect_original include the terminating 00 byte (11 bytes total), and wtotools check-patches verifies that data encodes identically to bytes.

+
+

4. Native Modules (patches/native/ + native/wto-net/) — Locators & Complete 6-File Wiring Walkthrough

+

When writing MinHook detours or calling engine functions in wto_ws.dll, never put a single build-specific RVA or game struct offset in C code. Instead, declare sites in patches/native/<module>.jsonc, let the patcher emit resolved hex values into win64/wto_ws.cfg, and read them in C from extern LmpValues g_lmp.

+

4.1 All Three Locate Methods (signature, string_ref, within)

+
  1. "method": "signature": Scans ".text" (or a specified "section") for a unique byte pattern, supporting captures.
  2. "method": "string_ref" (packages/exepatch/src/locate/string-ref.ts — most resilient across compiler codegen shifts!): Finds UTF-8 string + \0 in ".rdata" (or "section") and locates 7-byte RIP-relative lea (48 8d / 4c 8d) instructions loading that string in .text. Supports three modes: +
    • Mode A ("target": "reference", default without "pattern"): Returns the RVA of the 7-byte lea instruction itself (checked length = 7 bytes);
    • Mode B ("target": "function"): Looks up the enclosing function's start RVA in the PE .pdata exception directory (checked length = 0, so no direct captures—ideal for locating function entry points to hook or use as within anchors);
    • Mode C ("pattern" + "lea_at", with default "target": "reference"): Matches pattern around the string reference where the 7-byte lea sits at byte offset lea_at, returning the pattern start RVA so captures can read adjacent struct offsets right next to the string reference!
  3. "method": "within" (packages/exepatch/src/locate/within.ts): Searches pattern strictly within the [begin, end) PE .pdata bounds of an already-resolved site named in "in" (from an earlier site in the same module or a requires module), allowing short field-access patterns to match uniquely inside one function.
+

4.2 Complete 6-File Wiring Walkthrough: local_mp_scores

+

Here is how local_mp_scores (which reads per-event scoreboard points placed by apps/server into MissionSettings.customScoreParams) connects end-to-end across all 6 real files:

+
File 1: patches/native/local_mp_scores.jsonc
+

The filename must match "module". Because "mission_settings_load" is already resolved via string_ref ("string": "customScoreParams", "target": "function") in local_mp_core.jsonc, "local_mp_scores" lists "local_mp_core" in "requires" and searches inside "mission_settings_load" using "within":

+
jsonc
// Score table of a LocalMP battle (native/wto-net/src/local_mp_scores.c): the local server puts it
+// in the mission's customScoreParams; the host reads it there.
+// Without it: kills, assists and captures score nothing.
+{
+  "module": "local_mp_scores",
+  "features": [
+    "K-Kill, assist and capture scoring"
+  ],
+  "requires": [
+    "local_mp_core"
+  ],
+  "sites": {
+    // DataBlock::getReal wrapper.
+    // 2.61.0.37: 0x5445270
+    "datablock_get_real": {
+      "variants": [
+        {
+          "written_for": "2.61.0.37",
+          "locate": {
+            "method": "signature",
+            "pattern": "48 83 ec 28 f3 0f 11 54 24 24 4c 8d 44 24 24 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc 56 57 53 48 83 ec 30 48 89 d7 48 89 ce 48 8d 15"
+          }
+        }
+      ]
+    },
+    // MissionSettings customScoreParams copy.
+    // 2.61.0.37: 0x126d762 (lea rcx, [rax + 0x6d8]; mov eax, dword ptr [r13 + 0x10]; cmp eax, -1; ...)
+    "mission_score_params": {
+      "variants": [
+        {
+          "written_for": "2.61.0.37",
+          "locate": {
+            "method": "within",
+            "in": "mission_settings_load",
+            "pattern": "48 8d 88 ?? ?? ?? ?? 41 8b 45 10 83 f8 ff 74 ?? 45 0f b7 45 0e 46 8d 0c 00 31 d2 44 39 c8 0f 8d ?? ?? ?? ?? ff c7 4d 8b 4d 00 45 8b 51 5c 4d 01 d1 49 81 c1 90 00 00 00 41 bb ff ff ff 3f 45 31 d2 66 66 66 66 2e 0f 1f 84 00 00 00 00 00 42 8d 34 10 48 c1 e6 05 41 8b 5c 31 08 44 21 db 39 fb 74 ?? 41 ff c2 45 39 d0 75 ?? eb ?? 41 0f b7 45 0e 31 d2 85 c0 74 ?? ff c7 4d 8b 4d 18 4d 8b 01 45 8b 49 08 44 8d 14 c5 00 00 00 00 45 29 d1 41 ba ff ff ff 3f 45 31 db 66 0f 1f 44 00 00 4b 8b 34 08 8b 76 08 44 21 d6 39 fe 74 ?? 41 ff c3 49 83 c1 08 44 39 d8 75 ?? eb ?? 49 01 f1 31 d2 45 39 c2 49 0f 42 d1 eb ?? 41 39 c3 73 ?? 44 89 c8 49 8b 14 00 eb ?? 31 d2 48 85 d2 49 0f 44 d6 31 f6 45 31 c0 e8 ?? ?? ?? ?? 49 8b 5d 00 bf ff ff ff ff 48 85 db 74 ?? 48 8d 0d ?? ?? ?? ?? ba 16 00 00 00",
+            "captures": {
+              "custom_score_params": {
+                "offset": 3,
+                "type": "u32"
+              }
+            }
+          }
+        }
+      ]
+    }
+  }
+}
+

In 48 8d 88 ?? ?? ?? ?? (lea rcx, [rax + disp32]), bytes 0..2 are 48 8d 88 and bytes 3..6 hold the struct offset (0x6d8 on 2.61.0.37), captured via "offset": 3, "type": "u32".

+
File 2: Generated <copy>/win64/wto_ws.cfg (packages/patcher/src/native/native-settings.ts)
+

During copy builds, the patcher writes the executable's PE identity stamps alongside <site> and <site>.<capture> entries for all completely resolved modules:

+
ini
port=27015
+exe.time_date_stamp=0x67e5a1b2
+exe.size_of_image=0x83f4000
+native.datablock_get_real=0x5445270
+native.mission_score_params=0x126d762
+native.mission_score_params.custom_score_params=0x6d8
+
File 3: native/wto-net/src/local_mp_values.h
+

Add pointer (uint8_t *), unsigned offset (size_t), or signed displacement (ptrdiff_t) fields to struct LmpValues:

+
c
typedef struct LmpValues {
+    /* ... other modules ... */
+
+    /* local_mp_scores */
+    uint8_t *datablock_get_real;
+    size_t mis_custom_score_params;
+} LmpValues;
+
+extern LmpValues g_lmp;
+
File 4: native/wto-net/src/local_mp_values.c
+

Wire the wto_ws.cfg keys into SPECS[] using the three storage macros:

+
  • A(module, name, field) (LMP_ADDRESS): computes (uint8_t *)GetModuleHandleW(NULL) + rva and stores the live process pointer;
  • O(module, name, field) (LMP_OFFSET): stores an unsigned size_t struct offset or stride;
  • S(module, name, field) (LMP_SIGNED): stores a signed ptrdiff_t displacement;
  • Use derive_values() in the same file when a relative offset must be computed from two captured values (e.g., subtracting econ_change_req from an outer econ_req_* offset).
+
c
#define SCORES "local_mp_scores"
+
+static const LmpValueSpec SPECS[] = {
+    /* ... */
+    A(SCORES, "datablock_get_real", datablock_get_real),
+    O(SCORES, "mission_score_params.custom_score_params", mis_custom_score_params),
+    /* ... */
+};
+
File 5: native/wto-net/src/local_mp_offsets.h
+

Expose a descriptive macro backed by g_lmp:

+
c
#define LMP_MIS_OFF_CUSTOM_SCORE_PARAMS (g_lmp.mis_custom_score_params)
+
File 6: local_mp_scores.c, local_mp_core.c & native/wto-net/build.ps1
+
  • Consume the resolved function and offset in local_mp_scores.c: +
    c
    typedef float (__fastcall *DataBlockGetRealFn)(const void *blk, const char *name, float def);
    +static DataBlockGetRealFn fn_datablock_get_real;
    +
    +float local_mp_score_param(const char *key)
    +{
    +    if (fn_datablock_get_real == NULL || g_local_mp_mission_settings == NULL || key == NULL)
    +        return 0.0f;
    +    return fn_datablock_get_real(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_SCORE_PARAMS, key, 0.0f);
    +}
    +
    +int install_local_mp_score_reader(void)
    +{
    +    fn_datablock_get_real = (DataBlockGetRealFn)g_lmp.datablock_get_real;
    +    return 1;
    +}
  • In local_mp_core.c, install_local_mp_hooks() first calls config_native_matches_executable() to verify that the running aces.exe's PE TimeDateStamp and SizeOfImage match wto_ws.cfg (disabling the entire LocalMP bridge if wto_ws.cfg came from a different build), loads local_mp_core, iterates MODULES[] in dependency order ({ "local_mp_scores", install_local_mp_score_reader }) calling lmp_values_load(MODULES[i].name) before install(), and enables all queued hooks in one pass via MH_ApplyQueued().
  • Adding a brand-new .c file: Declare its installer in local_mp_internal.h, register it in MODULES[] (local_mp_core.c), and add the .c file to $sources in native/wto-net/build.ps1.
  • Sharing common engine hooks: When two modules need the same target function (e.g., unit_on_event shared by local_mp_damage_notifications and local_mp_air_events), define and dispatch it once in local_mp_core rather than calling MH_CreateHook twice on the same address.
+
+

5. Adapting a New Client Build (4-Step Workflow)

+

When War Thunder releases a minor client update (e.g., 2.61.0.37 -> 2.61.0.58), follow these four steps:

+
  1. Run the build recorder against your read-only stock client: +
    powershell
     node scripts/record-game-version.ts --game "<stock-dir>"
    +

    record-game-version.ts tests every patches/exe/, patches/gui/, and patches/native/ definition without modifying the stock folder. If any essential safety patch (ESSENTIAL_FEATURES) fails, it refuses to write a record and prints the blocking failures; otherwise it writes patches/versions/<version>.jsonc and lists any unavailable optional patches/modules.

  2. Add new variants only for failing patches/sites: Inspect the updated .nut script or aces.exe function using the Step 0 Node snippet or tools/re/cli.py (prefer find-string anchors!). Keep existing variants untouched so earlier builds continue working, and append a new variant with "written_for": "<new-version>".
  3. Run the full verification suite: Re-run record-game-version.ts to confirm zero unavailable items, then run: +
    • .\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-dir>\win64\aces.exe"
    • .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
    • powershell -NoProfile -File .\native\wto-net\build.ps1 (if any C file changed)
    • node scripts/build-game-copy.ts into a temporary copy directory to confirm clean assembly.
  4. Verify live in-game inside an isolated copy BEFORE committing patches/versions/<version>.jsonc: The launcher relies on patches/versions/<version>.jsonc to badge a client build as verified. Boot the isolated copy, sign into the hangar, and play through a LocalMP battle before committing patches/versions/<version>.jsonc rather than relying on CLI checks alone.
+

Starter templates for new patches live under dev-docs/templates/gui/, dev-docs/templates/exe/, and dev-docs/templates/native/.

+
+ +
+ +
+
+

04 · 环境搭建、本地流量日志排错与检查命令

+

这篇指南带你从零搭好本地开发环境、用内置的自动解码流量日志快速定位机库与对局问题,并在发起 Pull Request 前跑通对应的真实工程检查。

+
+

1. 开发环境准备

+

你需要一台 Windows x64 电脑,并安装以下基础工具:

+
  1. Node.js 24+:仓库内的 CLI 脚本与 apps/server 直接以 Node 24 原生类型剥离模式运行 .ts 源码(Node 20/22 旧版本会因 .ts 扩展名或模块解析报错)。
  2. Visual Studio 2022 或 Build Tools(勾选「使用 C++ 的桌面开发」x64 工具链与 CMake):用于通过 cl.exe 编译 native/wto-net/(生成 wto_ws.dll),以及一次性编译 Quirrel 字节码检查器 sq.exe。
  3. Python 3.12+:用于运行补丁校验器 wtotools、静态逆向工具 tools/re/cli.py 与客户端 .clog 日志解密命令。
  4. 一份玩家本人合法持有的官方原版客户端(严格保持只读),以及在 Steam 游戏库目录之外单独准备的离线副本目录与本地服务器数据目录。
+

首次克隆仓库后,在仓库根目录依次执行:

+
powershell
# 1. 安装工作区依赖
+npm install
+
+# 2. 编译进程内网络重定向与 LocalMP 桥接库 -> build\native\wto_ws.dll
 powershell -NoProfile -File .\native\wto-net\build.ps1
 
-# Exe & GUI patch checks (against read-only stock client)
-.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-dir>\win64\aces.exe"
-.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
+# 3. 下载桌面启动器所需的 Electron 二进制运行时
+node node_modules/electron/install.js
 
-# Temporary isolated copy build check
-node scripts/build-game-copy.ts --game "<stock-dir>" --out "<temp-out-dir>" --data "<temp-data-dir>" --port 27015
+# 4. 初始化 Python 虚拟环境并安装本地补丁/逆向工具包 wtotools +python -m venv .venv +.\.venv\Scripts\python.exe -m pip install -e ./tools
+

如果你想脱离桌面启动器,直接从命令行快速构建一份离线副本并以前台模式启动本地服务器查看实时输出(注意:--game 在构建时传只读原版目录、启动服务器时传离线副本目录,两条命令的 --data 与 --port 必须完全一致):

+
powershell
node scripts/build-game-copy.ts --game "<原版目录>" --out "<离线副本目录>" --data "<独立数据目录>" --port 27015
+node apps/server/src/cli.ts --game "<离线副本目录>" --data "<独立数据目录>" --port 27015
+
+

2. 怎么调试与查日志(排查 Bug 最快的路径)

+

排查机库动作报错、购买失败、匹配卡住或对局计分异常时,千万不要靠盲猜客户端发了什么包。WTOffline 在四处关键节点都留有可直接阅读的诊断日志:

+

2.1 本地服务器流量日志:<数据目录>/logs/<启动时间戳>/(第一站!)

+

每次启动 apps/server,TrafficLog(apps/server/src/traffic-log/traffic-log.ts)都会在 <数据目录>/logs/ 下新建一个带 ISO 时间戳的会话文件夹,里面包含两部分:

+
  1. requests.jsonl(全量请求索引流) 每行是一条 JSON 记录,按全局递增序号 id 记录每一次 HTTP 交互(kind: "http")、每一条匹配服双向消息(kind: "matching")、被拒绝的 WebSocket 升级请求(kind: "websocket")以及连接开关事件: +
    • 一秒定位未实现接口:直接在 requests.jsonl 中搜索 "unhandled":true(或看终端输出末尾带 [UNHANDLED] 标记的行),就能立刻抓出客户端刚发了哪个尚未挂载处理器的 char 动作、yuplay2 路径或 matching 消息!
    • 每条记录中的 files 字段直接指明该次请求与响应对应的负载文件名。
  2. bodies/ 子目录(自动解码的可读明文负载!) 每个序号 id(补零至 6 位,如 000042)按需生成以下文件: +
    • 000042.req.bin / 000042.resp.bin:原始线上传输字节(登录表单中的密码字段会自动脱敏);
    • 000042.req.txt / 000042.resp.txt:自动解包并格式化好的可读明文 BLK 文本(无论是带 0x69 / zlib / zstd 标记的 char 二进制 BLK,还是 cln_bulk_set_gblk 上传的 PBBD 多段批处理流,都会自动转成缩进清晰的文本 BLK!)或 UTF-8 JSON 文本——你无需手写任何解包脚本,直接用编辑器打开 .txt 就能看清每一个字段与类型;
    • 000042.matching-in.json / 000042.matching-out.json:解密并解压后的匹配长连接双向 RPC 消息(in 为客户端发来,out 为本地服务器下发)。
+

2.2 其余三类配套诊断日志

+
  • 进程内钩子与 LocalMP 日志:<离线副本目录>/win64/wto_ws.log 由 wto_ws.dll 每次启动游戏时重写。记录本地服务器端口号、每一次域名拦截与 Socket 连接重定向结果、wto_ws.cfg 与当前 aces.exe 的 PE 头校验结果,以及 11 个 local_mp_* 模块中哪些成功安装、哪些因缺少 wto_ws.cfg 键值被优雅跳过(并打印缺失的具体键名)。排查局内不刷 AI、选车无响应、记分牌为 0 或连杀飞机异常时先看这里。
  • 游戏引擎客户端日志:<离线副本目录>/.game_logs/*.clog Dagor 引擎原生日志,记录 Quirrel 脚本编译/运行期报错、进机库卡死在「正在加载…」的具体栈信息、任务脚本报错与资源缺失。由于 .clog 是二进制异或加密格式,直接用 tools/re/cli.py 解密成纯文本再查阅: +
    powershell
    .\.venv\Scripts\python.exe tools\re\cli.py decrypt-clog "<离线副本目录>\.game_logs\<最新文件>.clog" --out "<临时目录>\game.clog.txt"
  • 桌面启动器日志:launcher.log 在启动器界面打开「设置 → 诊断 → 打开日志目录」即可查看,记录副本构建、补丁包校验、子进程启停与更新器状态。
+
+

3. 提交前必跑的工程检查命令(按改动范围对照执行)

+

WTOffline 不要求也不提倡编写庞大的模拟(Mock)单元测试套件,而是要求你按实际触碰的代码目录,跑通下面对应的真实编译器、补丁字节核对与 Quirrel 字节码检查;最终交互体验则在独立隔离副本中进游戏实机验收。

+
你修改了哪里提交前必须跑通的检查
共享库 packages/*、本地服务器 apps/server 或 scripts/*根目录 npm run typecheck;若动了服务端启动逻辑或 tuning/*.jsonc,用临时数据目录启动一次 apps/server/src/cli.ts 确认数据集提取与配置校验零报错
桌面启动器 apps/launcher启动器 typecheck + electron-vite build;若增改了界面多语言词条,确认 en.json 与 zh-CN.json 键名完全对齐
patches/exe/(任何 patch.jsonc)wtotools check-patches(验证特征码唯一命中、expect_original 匹配,且 asm/data 编译结果与 bytes 逐字节一致)
patches/gui/(任何 patch.jsonc 或 .nut 片段)完整 wtotools check-gui(调用 sq.exe 执行 compilestring 词法作用域与字节码编译检查) + 临时副本构建确认 gui-patch-definition.ts Schema 无未知键报错
native/wto-net/ 或 patches/native/MSVC nativewto-netbuild.ps1(/W4 零警告)+ 临时目录 scripts/build-game-copy.ts 确认所有原生站点全部解析就绪
适配客户端新版本(patches/versions/)scripts/record-game-version.ts + 上述全部适用检查 + 在隔离副本中实机登录进机库并完成 LocalMP 对局验收后,方可提交 patches/versions/<版本号>.jsonc
+

常用检查命令汇总(均在仓库根目录执行,将尖括号替换为你的本地路径):

+
powershell
# 1. TypeScript 类型与语法剥离约束检查(校验 .ts 后缀、import type、erasableSyntaxOnly 等)
+npm run typecheck
+npm run typecheck --workspace "@wto/launcher"
+npm run build --workspace "@wto/launcher"
+
+# 2. EXE 与 GUI 补丁核对(输入源必须是只读原版客户端目录!)
+.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<原版目录>\win64\aces.exe"
+.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
+
+# 3. Native DLL 编译(MSVC /W4 零警告)与完整离线副本试构建
+powershell -NoProfile -File .\native\wto-net\build.ps1
+node scripts/build-game-copy.ts --game "<原版目录>" --out "<临时副本目录>" --data "<临时数据目录>" --port 27015
+
+# 4. 客户端版本适配记录核对
+node scripts/record-game-version.ts --game "<原版目录>"
+

一次性编译 Quirrel 字节码检查器 sq.exe(注意 --sq 路径参数!)

+

check-gui 需要调用与《战争雷霆》客户端同代的官方 Quirrel 编译器(固定在 Quirrel 仓库提交 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)。使用 Visual Studio 2022 C++ 工具链与 CMake 编译一次即可长期复用:

+
powershell
git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source
+git -C build/quirrel-source checkout --detach 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
+cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64
+cmake --build build/quirrel-cli --config Release --target sq
+

关于 --sq 参数的重要说明:wtotools check-gui 在不传 --sq 时的默认查找路径是 build/quirrel-check/sq.exe(见 tools/src/wtotools/cli/gui_commands.py),而上面这条 Visual Studio CMake 多配置构建命令会把可执行文件生成在 build\quirrel-cli\bin\Release\sq.exe。因此运行 check-gui 时请像上方命令一样显式传入 --sq "build\quirrel-cli\bin\Release\sq.exe"(或者手动把生成的 sq.exe 复制一份到 build\quirrel-check\sq.exe)。

+
+

4. 提交消息规范与 PR 自查清单

+
  • 一笔 PR 只聚焦一个清晰目标:不要在修某个结算 Bug 的 PR 里顺手重排无关目录或大面积格式化其他文件。
  • 全英文约定式提交(Conventional Commits)与英文注释: +
    • 提交标题格式:type(scope): concise summary(例如 fix(battle): credit Ground Arcade air event kills from AI victims、feat(launcher): show missing optional patch features;仓库级工程或文档改动用 repo 或 docs);
    • 若包含破坏性变更,在 scope 后加 ! 并在正文末尾附上 BREAKING CHANGE: 说明;
    • 代码注释、补丁顶部三行说明、补丁 title 与 Git 提交消息正文统一使用英文;
    • Co-authored-by 尾注仅用于署名实际参与协作的人类开发者,不要填写 AI 模型或编程工具。
  • 发起 PR 前最后 5 项自检: +
    1. 对照 开发规范第 4 节:零硬编码 RVA/结构体偏移/_ReturnAddress()、零手抄游戏静态数值、零越层 I/O;
    2. 核对语法与 Schema 细节:TS 相对导入全部带 .ts 后缀且遵守 erasableSyntaxOnly;补丁 JSONC 无多余未知键(特别是 patches/gui/**/patch.jsonc 未误写 requires);带尾随立即数的 rel32 捕获已显式填写 "end";
    3. 涉及货币、研发、库存或存档改动时,确认所有修改均通过 PlayerProfiles / SaveStore 先完成原子写盘再向客户端返回响应,且多账号目录严格隔离;
    4. 通读一遍 git diff,确认没有带入任何本机个人路径、原版游戏文件、解包产物、测试存档或未脱敏日志;
    5. 完整填写 PR 模板,如实列出实际运行过的命令与输出结论,并把「已在隔离副本实机验收的界面步骤」与「尚待维护者实机验收的步骤」明确区分开。
-

- 说明:项目注重「语法 / 类型 / 补丁编译 / 可运行性检查 + 隔离副本人工实机验收」,不要求编写庞大脆弱的模拟测试套件;请把实际执行过的命令与客户端版本号如实填入 PR。 - Note: Focus on typecheck, patch compilation, build, and runnable startup checks plus human in-game verification on an isolated copy rather than large mock test suites. Record the exact commands and client builds actually run in your PR. -

- +
+

04 · Setup, Traffic Log Debugging & Check Commands

+

This guide walks you through setting up a Windows x64 development environment, diagnosing bugs rapidly with auto-decoded local traffic logs, and running the required verification checks before opening a Pull Request.

+
+

1. Environment Setup

+

You need a Windows x64 machine with:

+
  1. Node.js 24+: Repository CLI scripts and apps/server execute .ts files directly via Node 24's native type-stripping (older Node 20/22 releases will fail on .ts import specifiers).
  2. Visual Studio 2022 or Build Tools (with "Desktop development with C++" x64 tools & CMake): Used by native/wto-net/build.ps1 (cl.exe) to build wto_ws.dll and once to compile the Quirrel bytecode checker sq.exe.
  3. Python 3.12+: Used for the patch verifier (wtotools), static disassembler (tools/re/cli.py), and .clog log decryptor.
  4. Your own legitimate stock War Thunder installation (kept strictly read-only), plus a separate offline copy folder and server data folder located outside any Steam library directory.
+

After cloning the repository, bootstrap everything from the repo root:

+
powershell
# 1. Install npm workspace dependencies
+npm install
 
-          
-          
-

- 6. 提交信息与 PR 提交流程 - 6. Commit Messages & PR Workflow -

-
    -
  • 英文约定式提交English Conventional Commits:格式为 type(scope): description(如 fix(battle): ...、feat(launcher): ...,仓库级用 repo);正文写明改动原因、一手证据和验证状态,代码注释统一用英文。Use type(scope): description (e.g., fix(battle): ..., feat(launcher): ..., or repo); document rationale, evidence, and verification in the body, with English code comments.
  • -
  • 如实填写 PR 模板Complete the PR Template:逐项勾选自查表,写清目标客户端版本、一手依据(脚本路径、游戏配置或 DagorEngine 源码)、实际运行的检查命令,以及待实机验证的操作入口和预期现象。Check every self-check item, list the target build and primary evidence, report executed checks honestly, and write clear in-game acceptance steps.
  • -
  • 只传最小自有代码No Game Assets or Player Data:切勿提交任何原版游戏文件、解包产物、玩家存档或未脱敏日志。Never commit stock game files, extracted archives, player saves, or unredacted personal logs.
  • -
+# 2. Compile the Winsock redirector & LocalMP host bridge -> build\native\wto_ws.dll +powershell -NoProfile -File .\native\wto-net\build.ps1 + +# 3. Download the Electron runtime binary for the desktop launcher +node node_modules/electron/install.js + +# 4. Create the Python virtual environment and install `wtotools` in editable mode +python -m venv .venv +.\.venv\Scripts\python.exe -m pip install -e ./tools
+

To build an offline game copy and run the local server directly from the terminal without the desktop launcher (note: pass the read-only stock folder to build-game-copy.ts --game, pass the offline copy folder to cli.ts --game, and keep --data and --port identical across both commands):

+
powershell
node scripts/build-game-copy.ts --game "<stock-dir>" --out "<copy-dir>" --data "<data-dir>" --port 27015
+node apps/server/src/cli.ts --game "<copy-dir>" --data "<data-dir>" --port 27015
+
+

2. Traffic Log Debugging & Diagnostic Logs

+

Never guess what payload the game client sent or why a hangar action failed—WTOffline records human-readable diagnostics across four log locations:

+

2.1 Local Server Traffic Logs: <data-dir>/logs/<ISO-timestamp>/ (Check Here First!)

+

Every time apps/server starts, TrafficLog (apps/server/src/traffic-log/traffic-log.ts) creates a timestamped session folder under <data-dir>/logs/ containing:

+
  1. requests.jsonl (Indexed Exchange Log) One JSON line per HTTP request/response (kind: "http"), matching message (kind: "matching"), refused WebSocket upgrade (kind: "websocket"), or TCP connection open/close, numbered sequentially by id: +
    • Spot missing endpoints instantly: Search requests.jsonl for "unhandled":true (or look for [UNHANDLED] in the server console) to immediately see any unimplemented char action, yuplay2 endpoint, or matching RPC!
    • Each entry's files object points directly to its corresponding payload files inside bodies/.
  2. bodies/ Subdirectory (Auto-Decoded Readable BLK & JSON Payloads!) Numbered by zero-padded sequence ID (e.g., 000042.*): +
    • 000042.req.bin / 000042.resp.bin: Raw wire bytes (with sign-in passwords automatically redacted);
    • 000042.req.txt / 000042.resp.txt: Automatically unpacked and formatted readable BLK text (covering 0x69/zlib/zstd-framed char binary BLK payloads as well as multi-chunk PBBD streams on cln_bulk_set_gblk!) or UTF-8 JSON/form text—open any .txt file directly in your editor to inspect exact block trees and parameter types without manual decoding;
    • 000042.matching-in.json / 000042.matching-out.json: Decrypted, LZ4-decompressed inbound (in) and outbound (out) matching binary RPC messages.
+

2.2 The Other Three Diagnostic Logs

+
  • Native Hook & LocalMP Log: <copy-dir>/win64/wto_ws.log Rewritten on every client launch by wto_ws.dll. Logs the active local port, every locally answered hostname and redirected/refused socket, whether wto_ws.cfg matched the running aces.exe PE TimeDateStamp / SizeOfImage, and which of the 11 local_mp_* modules installed vs. were skipped (naming the exact missing wto_ws.cfg key when skipped), plus live battle referee events.
  • Dagor Client Log: <copy-dir>/.game_logs/*.clog Records Quirrel script compilation/runtime errors, exact call stacks behind "Loading..." login hangs, mission errors, and missing assets. Because .clog files are XOR-encrypted binary logs, decrypt them to plain text with tools/re/cli.py: +
    powershell
    .\.venv\Scripts\python.exe tools\re\cli.py decrypt-clog "<copy-dir>\.game_logs\<latest>.clog" --out "<temp-dir>\game.clog.txt"
  • Desktop Launcher Log: launcher.log Accessible from Launcher Settings -> Diagnostics -> Open log folder, covering copy builds, patch-pack checks, server process lifecycle, and updater activity.
+
+

3. Required Checks Before Submitting

+

WTOffline does not require or encourage large mock unit test suites. Instead, run the real compiler, binary-patch, and Quirrel bytecode verifiers matching the files you touched, followed by live acceptance in an isolated game copy:

+
What you changedRequired checks before opening a PR
packages/*, apps/server, or scripts/*Root npm run typecheck; if you touched server startup or tuning/*.jsonc, boot apps/server/src/cli.ts against a temporary data folder to confirm clean dataset extraction and tuning validation
apps/launcherLauncher typecheck + electron-vite build; if you edited UI strings, verify en.json and zh-CN.json locale key parity
patches/exe/ (any patch.jsonc)wtotools check-patches (verifies unique signature hits, expect_original bytes, and exact byte-for-byte agreement between asm/data and bytes)
patches/gui/ (any patch.jsonc or .nut fragment)Full wtotools check-gui using sq.exe compilestring (required) + a temporary copy build to confirm zero unknown schema keys in gui-patch-definition.ts
native/wto-net/ or patches/native/MSVC nativewto-netbuild.ps1 (/W4, zero warnings) + temporary scripts/build-game-copy.ts run confirming every native module resolves cleanly
Adapting a new client build (patches/versions/)scripts/record-game-version.ts + all applicable checks above + live in-game verification in an isolated copy (hangar login + LocalMP battle) before committing patches/versions/<version>.jsonc
+

Complete command reference (run from the repository root, substituting bracketed paths):

+
powershell
# 1. TypeScript typecheck & Node 24 erasable-syntax checks (.ts extensions, import type, etc.)
+npm run typecheck
+npm run typecheck --workspace "@wto/launcher"
+npm run build --workspace "@wto/launcher"
+
+# 2. EXE & GUI patch verification (always point at your READ-ONLY stock folder!)
+.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-dir>\win64\aces.exe"
+.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
+
+# 3. Native DLL build (MSVC /W4 zero warnings) & temporary offline copy build
+powershell -NoProfile -File .\native\wto-net\build.ps1
+node scripts/build-game-copy.ts --game "<stock-dir>" --out "<temp-copy-dir>" --data "<temp-data-dir>" --port 27015
+
+# 4. Client build compatibility record
+node scripts/record-game-version.ts --game "<stock-dir>"
+

One-Time Build of the Quirrel Bytecode Compiler sq.exe (Note the --sq Flag!)

+

check-gui requires the official Quirrel compiler pinned to the revision matching War Thunder's client VM (Quirrel commit 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe). Build it once with Visual Studio 2022 C++ tools and CMake:

+
powershell
git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source
+git -C build/quirrel-source checkout --detach 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
+cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64
+cmake --build build/quirrel-cli --config Release --target sq
+

Important note on --sq: wtotools check-gui defaults --sq to build/quirrel-check/sq.exe (tools/src/wtotools/cli/gui_commands.py), whereas the multi-config Visual Studio CMake build above outputs build\quirrel-cli\bin\Release\sq.exe. Always pass --sq "build\quirrel-cli\bin\Release\sq.exe" explicitly as shown in the command block above (or copy sq.exe to build\quirrel-check\sq.exe).

+
+

4. Commit Conventions & Pre-PR Checklist

+
  • One focused goal per PR: Avoid mixing unrelated refactors or repo-wide formatting into a bugfix or feature PR.
  • English Conventional Commits & English code comments: +
    • Format commit titles as type(scope): concise summary (e.g., fix(battle): credit Ground Arcade air event kills from AI victims, feat(launcher): show missing optional patch features; use repo or docs for repository-level or documentation changes);
    • Mark breaking changes with ! after the scope and a BREAKING CHANGE: footer;
    • Write all code comments, 3-line patch header comments, patch title fields, and commit bodies in English;
    • Reserve Co-authored-by trailers strictly for human collaborators—never list AI models or coding tools.
  • Final 5-point self-check before opening a PR: +
    1. Check against Development Rules — Section 4: zero hardcoded RVAs, struct offsets, or _ReturnAddress() checks; zero hardcoded stock game numbers; zero cross-layer I/O;
    2. Verify syntax & schema discipline: explicit .ts extensions on relative imports, import type for types, no enum/namespace/parameter properties; strict patch JSONC keys (no requires in patches/gui/**/patch.jsonc, explicit "end" on rel32 captures with trailing immediates);
    3. For currency, research, inventory, or profile mutations, verify changes persist atomically via PlayerProfiles / SaveStore before replying to the client, with strict per-account isolation;
    4. Review git diff to ensure zero personal machine paths, copyrighted game files, extracted stock scripts, personal saves, or unredacted logs slipped in;
    5. Fill out the PR template completely, recording exact commands run and clearly separating observed in-game checks from pending in-game acceptance steps.
+
+ +
+ +
+
+

05 · Pull Request 标准模板与自查清单

+

提交 PR 时请直接复制下方模板,逐项勾选 Self-check 并如实填写实际运行过的检查命令与待实机验收步骤:

+
markdown
## Change
+
+<!-- Describe the player-visible result and the single focused goal of this PR. -->
+
+## Reason and evidence
+
+<!-- Give the target client build (e.g. 2.61.0.37) and cite the primary source: stock archive file, .nut script, RVA, or DagorEngine source path. -->
+<!-- For any client patch (patches/gui, patches/exe, native/wto-net), explain why apps/server or stock BLK configuration cannot solve it. -->
+<!-- For tuning changes (apps/server/tuning/*.jsonc), record the rationale, bounds, and units of the new defaults. -->
+
+## Client compatibility
+
+<!-- List the tested/affected client builds and any added patch variants or patches/versions/<version>.jsonc updates. -->
+<!-- Reminder: never commit patches/versions/<version>.jsonc until live isolated in-game acceptance is complete. -->
+
+## Self-check
+
+- [ ] No hardcoded addresses, RVAs, C++ struct offsets, or `_ReturnAddress()` checks (all native values resolved dynamically into `g_lmp` via `patches/`, with explicit `"end"` on `rel32` captures that have trailing immediate bytes)
+- [ ] No hardcoded stock game numbers or silent fallback defaults (extracted from stock archives via `game-data/datasets/` or validated in `tuning/*.jsonc`)
+- [ ] Layer & persistence rules preserved (`packages/*` never imports `apps/*`; domain modules stay free of network/disk I/O; profile mutations persist atomically via `PlayerProfiles` / `SaveStore` before replying)
+- [ ] Toolchain & schema rules met (explicit `.ts` extensions on relative imports, `import type` for types, no `enum`/`namespace`/parameter properties; strict patch JSONC keys—e.g., no `requires` in `patches/gui/**/patch.jsonc`; new `.c` files added to `native/wto-net/build.ps1`)
+- [ ] Focused on one goal, English comments / patch `title` / conventional commit message used, no AI `Co-authored-by` trailers, and no personal paths, game assets, or unredacted logs in `git diff`
+- [ ] Every command listed in **Checks run** was actually executed (including `wtotools check-gui --sq ...` for `patches/gui/` and MSVC `native/wto-net/build.ps1` with zero warnings for `native/`)
+
+## Checks run
+
+| Command or check | Client build (if relevant) | Result |
+| --- | --- | --- |
+| | | |
+
+## In-game acceptance
+
+<!-- Give the exact screen or entry point, the action to perform, and the expected result in an isolated offline copy. -->
+<!-- Clearly state what was observed in-game, or explicitly mark steps that are still pending live verification. -->
+
+
+

05 · Pull Request Template & Self-Check

+

Copy the template below when opening a PR, check every Self-check box, and honestly record executed checks alongside pending in-game verification steps:

+
markdown
## Change
+
+<!-- Describe the player-visible result and the single focused goal of this PR. -->
+
+## Reason and evidence
+
+<!-- Give the target client build (e.g. 2.61.0.37) and cite the primary source: stock archive file, .nut script, RVA, or DagorEngine source path. -->
+<!-- For any client patch (patches/gui, patches/exe, native/wto-net), explain why apps/server or stock BLK configuration cannot solve it. -->
+<!-- For tuning changes (apps/server/tuning/*.jsonc), record the rationale, bounds, and units of the new defaults. -->
+
+## Client compatibility
+
+<!-- List the tested/affected client builds and any added patch variants or patches/versions/<version>.jsonc updates. -->
+<!-- Reminder: never commit patches/versions/<version>.jsonc until live isolated in-game acceptance is complete. -->
+
+## Self-check
+
+- [ ] No hardcoded addresses, RVAs, C++ struct offsets, or `_ReturnAddress()` checks (all native values resolved dynamically into `g_lmp` via `patches/`, with explicit `"end"` on `rel32` captures that have trailing immediate bytes)
+- [ ] No hardcoded stock game numbers or silent fallback defaults (extracted from stock archives via `game-data/datasets/` or validated in `tuning/*.jsonc`)
+- [ ] Layer & persistence rules preserved (`packages/*` never imports `apps/*`; domain modules stay free of network/disk I/O; profile mutations persist atomically via `PlayerProfiles` / `SaveStore` before replying)
+- [ ] Toolchain & schema rules met (explicit `.ts` extensions on relative imports, `import type` for types, no `enum`/`namespace`/parameter properties; strict patch JSONC keys—e.g., no `requires` in `patches/gui/**/patch.jsonc`; new `.c` files added to `native/wto-net/build.ps1`)
+- [ ] Focused on one goal, English comments / patch `title` / conventional commit message used, no AI `Co-authored-by` trailers, and no personal paths, game assets, or unredacted logs in `git diff`
+- [ ] Every command listed in **Checks run** was actually executed (including `wtotools check-gui --sq ...` for `patches/gui/` and MSVC `native/wto-net/build.ps1` with zero warnings for `native/`)
+
+## Checks run
+
+| Command or check | Client build (if relevant) | Result |
+| --- | --- | --- |
+| | | |
+
+## In-game acceptance
+
+<!-- Give the exact screen or entry point, the action to perform, and the expected result in an isolated offline copy. -->
+<!-- Clearly state what was observed in-game, or explicitly mark steps that are still pending live verification. -->
+
+
- - + +
diff --git a/mod-docs.html b/mod-docs.html index f38f057..0c8a535 100644 --- a/mod-docs.html +++ b/mod-docs.html @@ -3,8 +3,8 @@ - WTOffline · 模组制作文档 - + WTOffline · 模组制作完整手册 + @@ -60,302 +60,1834 @@ 返回 WTOffline 主页 Back to WTOffline Home -
MOD AUTHORING GUIDE · API 0.1-EXPERIMENTAL
+
MOD AUTHORING HANDBOOK · API 0.1-EXPERIMENTAL

- 模组制作文档 - Mod Authoring Documentation + 模组制作完整手册(全 7 章) + Mod Authoring Handbook (7 Chapters)

- - WTOffline 采用添加式、按加载顺序逐层叠加的模组架构:支持零代码数值覆盖、客户端数据包增量补丁、自定义 3D 模型载具、原生 GUI 扩展与服务端 JS/TS 脚本,关掉模组自动还原不污染原版。 - - - WTOffline uses an additive, load-order-layered mod system supporting code-free tuning overlays, incremental client archive patches, custom 3D vehicles, native UI extensions, and Node 24 JS/TS server scripts—cleanly reverted when disabled. - + 面向模组创作者的完整在线手册:从解包查看原版文件、5 分钟入门、BLK/CSV 增量补丁、自定义 3D 载具、GUI/EXE 补丁到服务端零代码调参与全栈脚本案例,中英双语零删减呈现。 + The complete unabridged 7-chapter handbook for mod authors—from inspecting stock archives and 5-minute quick start to BLK/CSV patches, custom 3D vehicles, GUI/EXE hooks, tuning overlays, and full-stack server scripts.

-
+
+ 启动器首次初始化已自动释放 3 套可运行官方模板,也可直接在线查阅源码: + The launcher seeds 3 runnable official templates on first run—browse them online anytime: +
+ + 查看官方模组模板源码 ↗ + Official Mod Templates ↗ + +
- - -
-

- 1. 快速入门与清单规范(mod.jsonc) - 1. Quick Start & Manifest (mod.jsonc) -

-
- - 实验期声明(api_version: "0.1-experimental"):WTOffline 处于早期开发阶段,服务端脚本接口、钩子契约和声明式 exe 补丁格式可能随本体演进调整,现阶段不承诺向后兼容。 - - - Experimental Notice (api_version: "0.1-experimental"): WTOffline is in early development. Server script APIs, hook contracts, and declarative exe patch formats may change across releases without backwards compatibility. - -
-

- 启动游戏前,启动器从纯净备份(wtoffline/stock/)出发,先应用核心离线补丁,再按玩家在「模组」页排好的顺序叠加各模组(越靠下优先级越高)。全局模组仓库默认在 %APPDATA%\WTOffline Launcher\mods,可在启动器内自由修改。 - Before launch, the launcher starts from the clean stock backup (wtoffline/stock/), applies core offline patches, and layers enabled mods in order (lower items win). The default mod repository is %APPDATA%\WTOffline Launcher\mods and can be moved in the launcher. -

- -

最小模组示例(5 分钟上手)Minimal Mod Example (5-Minute Start)

-
-
- my-first-mod/mod.jsonc - -
-
{
-  "format": 1,
-  "id": "demo.my-first-mod",
-  "name": { "zh-CN": "我的第一个模组", "en": "My First Mod" },
-  "version": "0.1.0",
-  "author": "YourName",
-  "description": {
-    "zh-CN": "把对局银狮和研发点倍率调整为 2 倍。",
-    "en": "Doubles Silver Lions and Research Points battle rewards."
+          
+
+

01 · 快速入门与清单规范

+

适用版本:format: 1 · api_version: "0.1-experimental"(实验期接口,随本体开发可能调整)

+

1. 核心思路:添加式叠加架构

+

WTOffline 采用添加式、按加载顺序逐层叠加的模组架构。模组通过增量补丁与新增文件作用于客户端与服务端,不支持直接整包替换原版 .vromfs.bin 归档文件:

+
  1. 启动游戏前,启动器从纯净原版备份(<游戏副本>/wtoffline/stock/)出发,先应用离线版核心补丁,再按玩家在「模组」页排好的顺序,依次叠加所有已启用模组的客户端补丁与新增文件;
  2. 大体积 3D 模型和贴图包通过 Windows NTFS 目录联接点(Junction) 跨盘零拷贝挂载;
  3. 本地服务器启动时自动读取叠加后的客户端数据包,再按同一顺序合并各模组的 server/tuning/*.jsonc 并加载 server/index.ts 脚本;
  4. 关掉模组或切换预设时,启动器自动拆除联接点并从 wtoffline/stock/ 还原原版文件,不破坏客户端本体。
+
  • 全局模组仓库:默认位于 %APPDATA%\WTOffline Launcher\mods(可在启动器「模组 › 预设与仓库」修改到任意硬盘)。
  • 首次启动自带 3 个官方模板:启动器首次初始化全局 mods/ 目录时,会自动放入 example-vehicle-tweak(零代码改车与译名)、example-server-script(服务端 TS 脚本最小示例)和 official-map-selector(原生 DaGui 弹窗 + 服务端选图全栈模组)三个现成模组(默认未勾选)。点击「模组 › 打开模组目录」即可直接阅读源码或复制改造!
  • 每客户端独立配置:模组开关、加载顺序和命名预设分别保存在各自客户端的数据目录 <数据目录>/mods-config.json 中。
+
+

2. 前置准备:如何解包与查阅原版游戏数据

+

在动手改载具属性、挂科技树或写界面补丁之前,你需要先知道原版游戏里的内部载具 ID(例如美系初始轻坦 M2A4 的内部 ID 是 us_m2a4,M1A2 SEP V2 是 us_m1a2_sep2_abrams)以及原版文件的目录结构。

+

2.1 原版核心归档文件在哪里?

+

在你的《战争雷霆》客户端目录(以及离线副本目录)下,核心数据存放在以下 .vromfs.bin 虚拟文件系统包中:

+
原版包路径(相对于客户端根目录)里面的核心内容
char.vromfs.bin科技树排布(config/shop.blk)、载具价格/研发点/权重/改装件(config/wpcost.blk)、载具分类标签(config/unittags.blk)、道具与解锁配置
aces.vromfs.bin坦克模型与装甲参数(gamedata/units/tankmodels/*.blk)、飞机气动(gamedata/flightmodels/*.blk)、舰船、炮弹与导弹参数(gamedata/weapons/...)
gui.vromfs.bin客户端全部界面逻辑脚本(scripts/**/*.nut)、界面模板(gui/**/*.tpl)与样式表(gui/**/*.css)
lang.vromfs.bin多语言本地化词条表(lang/units.csv 载具名、lang/menu.csv 界面文本、lang/units_weaponry.csv 武器弹药名)
ui/atlases.vromfs.bin科技树与商店使用的载具剪影图标(gameuiskin/<载具id>_ico.svg)
ui/images.vromfs.bin资料卡与乘员槽位载具大图(units/<载具id>.ddsx)
+

备份目录说明:<游戏副本>/wtoffline/stock/ 是启动器用来重建和还原纯净客户端的原版备份目录,请按只读方式对待,不要手动修改或覆盖其中的文件,以免影响关闭模组后的自动还原。所有模组改动都放在 mods/<你的模组>/ 下即可。

+

2.2 查阅与解包原版数据的方法

+

你可以根据自己的习惯,直接从本机原版客户端查阅 .blk、.csv 和 .nut 文件:

+
  1. 使用社区解包工具在本地查阅: 将客户端里的 char.vromfs.bin、aces.vromfs.bin、gui.vromfs.bin 等归档复制到单独的临时工作文件夹(不要在游戏目录原地解包),使用常见的 .vromfs.bin / .blk 社区解包工具提取目录并将二进制 .blk 转为可读文本,即可查找任意载具的内部 ID、科技树路径和字段名。
  2. 用 WTOffline 仓库自带库直接读取(适合拉取了源码仓库的开发者): 如果你在本地克隆了 WTOffline 仓库,可以直接在仓库根目录用 Node 24 调用内置的 @wto/vromfs 与 @wto/blk 读取任意原版包内的二进制 .blk 并打印为标准文本 BLK:
+
js
import { readFileSync } from 'node:fs';
+import { getFile, NAME_MAP_PATH, readArchive } from './packages/vromfs/src/index.ts';
+import { decodeBlk, formatBlkText, parseSharedNameMap } from './packages/blk/src/index.ts';
+const ar = readArchive(readFileSync('C:/WarThunder/char.vromfs.bin'));
+const dict = [...ar.files.entries()].find(([k]) => k.endsWith('.dict'))?.[1];
+console.log(formatBlkText(decodeBlk(getFile(ar, 'config/wpcost.blk'), { names: ar.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(ar, NAME_MAP_PATH), dict).names : [], dictionary: dict })));
+
+

3. 5 分钟做出你的第一个模组

+
  1. 在启动器里打开 「模组 › 打开模组目录」(你会看到里面已经有 3 个官方示例模组可供参考);
  2. 在里面新建文件夹 my-first-mod;
  3. 创建清单文件 my-first-mod/mod.jsonc:
+
jsonc
{
+  "format": 1,
+  "id": "demo.my-first-mod",
+  "name": {
+    "zh-CN": "我的第一个模组",
+    "en": "My First Mod"
   },
-  "api_version": "0.1-experimental",
-  "game_versions": ["2.61.0.*"]
-}
+ "version": "0.1.0", + "author": "YourName", + "description": { + "zh-CN": "把对局银狮和研发点倍率调整为 2 倍。", + "en": "Doubles Silver Lions and Research Points battle rewards." + }, + "api_version": "0.1-experimental", + "game_versions": ["2.61.0.*"] +}
+
  1. 创建 my-first-mod/server/tuning/battle.jsonc:
+
jsonc
{
+  "rewardMultiplierSilverLions": 2.0,
+  "rewardMultiplierResearchPoints": 2.0
+}
+
  1. 切回启动器窗口(页面获得焦点时会自动刷新,也可点击「刷新」),勾选启用你的模组并点击「启动游戏」即可生效。
+
+

4. 完整标准目录结构

+

按需创建你实际用到的子目录,未用到的部分完全不必建立:

+
text
<mod-folder>/
+├─ mod.jsonc                          # 必需:模组清单
+├─ server/                            # 可选:服务端部分
+│  ├─ tuning/                         #   可调数值增量覆盖(*.jsonc)
+│  └─ index.ts (或 index.mjs / .js)   #   服务端脚本入口(默认自动探测)
+└─ client/                            # 可选:客户端部分
+   ├─ packs/                          #   .vromfs.bin 数据包增量叠加
+   │  ├─ char.vromfs.bin/
+   │  ├─ aces.vromfs.bin/
+   │  ├─ gui.vromfs.bin/
+   │  ├─ lang.vromfs.bin/
+   │  ├─ mis.vromfs.bin/
+   │  ├─ game.vromfs.bin/
+   │  ├─ ui/atlases.vromfs.bin/
+   │  └─ ui/images.vromfs.bin/
+   ├─ addon/                          #   3D 模型与贴图扩展包(res/*.grp, res/*.dxp.bin)
+   ├─ gui-patches/                    #   GUI 脚本/模板/样式增量补丁(与本体 patches/gui 同格式)
+   ├─ exe-patches/                    #   声明式 exe 补丁(与本体 patches/exe 同格式)
+   ├─ files/                          #   可选:大型整合包附带的配套涂装/瞄具/音效/任务
+   └─ config-blk.patch.jsonc          #   可选:游戏根目录 config.blk 的增量补丁
+
+

5. mod.jsonc 全字段参考

+

清单元数据解析采用严格白名单校验,写错字段名或出现未定义字段会被直接拒绝,并在启动器报错区显示具体原因。

+
字段必填类型说明
format是1清单格式版本号,目前固定为整数 1
id是string全局唯一模组 ID,匹配 /^[a-z0-9][a-z0-9._-]{0,63}$/(仅小写字母、数字、.、_、-,首字符须为字母或数字,最长 64 位;推荐 <作者>.<模组名>)
name是string | { [lang]: string }展示名称,支持单字符串或按语言代码映射(如 zh-CN、en)
version是string模组版本号(推荐语义化版本,如 0.1.0)
author是string作者或制作组名称
description否string | { [lang]: string }模组简介,支持单字符串或多语言对象
api_version是string目标接口标识,当前固定填 "0.1-experimental"
game_versions否string[]声明适配的游戏版本通配符列表(如 ["2.61.0.*"]);与客户端版本不符时仅发出警告,不强行阻断启动
requires否string[]前置依赖模组 ID 列表:缺失或未启用时作为阻塞错误阻止启动;同时约束加载顺序(若排在前置模组上方会触发 dependency-order 顺序警告,并参与启动器「按依赖自动排序」)
conflicts否string[]已知互斥模组 ID 列表;同时启用时作为阻塞错误阻止启动
load_after否string[]建议排在这些可选模组 ID 之后(越靠下越晚加载、优先级越高);不强制要求对方启用,若同时启用则参与顺序提示与「按依赖自动排序」
load_before否string[]建议排在这些可选模组 ID 之前;同样参与顺序提示与「按依赖自动排序」
server否{ entry?: string, tuning?: string }显式覆盖服务端入口文件(相对路径,不得含 ..)和 tuning 目录路径(默认自动探测 server/index.{ts,mjs,js} 与 server/tuning)
+
+

6. 启动器自动计算的能力与风险徽标(多徽标叠加)

+

启动器扫描模组目录后会自动计算并展示能力徽标。徽标是多选累加(非互斥)的——例如同时包含数据包修改与服务端脚本的模组会同时显示 data 和 script 两个徽标,而 official-map-selector 会同时显示 data、gui、script 三个徽标:

+ +
+

7. 排序规则与冲突检测

+
-
-
- my-first-mod/server/tuning/battle.jsonc - -
-
{
-  "rewardMultiplierSilverLions": 2.0,
-  "rewardMultiplierResearchPoints": 2.0
-}
+
+

01 · Quick Start & Manifest Reference

+

Target Spec: format: 1 · api_version: "0.1-experimental" (experimental API; subject to breaking changes as core development progresses)

+

1. Core Concept: Additive Overlay Architecture

+

WTOffline uses a stackable, load-order additive mod architecture. Mods supply incremental patches and added files to the client and server, and do not replace whole stock .vromfs.bin archives:

+
  1. Before launching the game, the launcher starts from clean stock backups (<copy>/wtoffline/stock/), applies core offline patches first, and then layers every enabled mod's client patches and added files in the exact order shown on the Mods page;
  2. Large 3D model and texture addons mount across drives with zero file copying via Windows NTFS Directory Junctions;
  3. When the local server starts, it automatically extracts static game data from the overlaid client packs, merges each mod's server/tuning/*.jsonc in the same order, and loads server/index.ts scripts;
  4. When you disable a mod or switch presets, the launcher automatically unmounts junctions and restores clean files from wtoffline/stock/ without corrupting the client copy.
+ +
+

2. Prerequisite: How to Unpack & Inspect Stock Game Files

+

Before tweaking vehicle stats, wiring tech-tree entries, or patching UI scripts, you need to look up stock internal vehicle IDs (for example, the US reserve light tank M2A4 is us_m2a4, and the M1A2 SEP V2 is us_m1a2_sep2_abrams) and stock file paths.

+

2.1 Where Stock Archives Live in the Game Client

+

Inside your War Thunder client folder (and offline copy folder), stock game data lives inside .vromfs.bin virtual filesystem archives:

+
Stock Archive Path (relative to client root)Key Contents Inside
char.vromfs.binTech-tree layout (config/shop.blk), vehicle prices/RP/BR/modifications (config/wpcost.blk), unit classification tags (config/unittags.blk), items, and unlocks
aces.vromfs.binTank models & armor (gamedata/units/tankmodels/*.blk), aircraft flight models (gamedata/flightmodels/*.blk), ships, shells, and missiles (gamedata/weapons/...)
gui.vromfs.binAll client UI Quirrel scripts (scripts/**/*.nut), Handyman templates (gui/**/*.tpl), and DaGui stylesheets (gui/**/*.css)
lang.vromfs.binLocalization tables (lang/units.csv vehicle names, lang/menu.csv UI strings, lang/units_weaponry.csv weapons & ammo names)
ui/atlases.vromfs.binTech-tree and local web store vehicle silhouette icons (gameuiskin/<unit_id>_ico.svg)
ui/images.vromfs.binStat-card and crew-slot vehicle portraits (units/<unit_id>.ddsx)
+

Note on the backup folder: Treat <copy>/wtoffline/stock/ as read-only. The launcher relies on wtoffline/stock/ to rebuild overlays and restore clean files when mods are disabled; modifying files inside stock/ can prevent automatic restoration. Place all mod changes under mods/<your-mod>/.

+

2.2 Practical Ways to Inspect Stock Files

+

You can inspect stock .blk, .csv, and .nut files directly from your own local game installation:

+
  1. Local unpacking with community tools: Copy char.vromfs.bin, aces.vromfs.bin, or gui.vromfs.bin from your client into a separate scratch folder (avoid unpacking in-place inside the game directory) and use standard community .vromfs.bin / .blk unpacking tools to extract readable text .blk and .nut files, vehicle IDs, and tech-tree paths.
  2. 5-line Node 24 snippet using @wto/vromfs + @wto/blk (if you cloned the WTOffline repo): If you have the WTOffline repository checked out locally, run Node 24 from the repo root to decode any binary .blk straight out of a .vromfs.bin archive and print formatted text BLK:
+
js
import { readFileSync } from 'node:fs';
+import { getFile, NAME_MAP_PATH, readArchive } from './packages/vromfs/src/index.ts';
+import { decodeBlk, formatBlkText, parseSharedNameMap } from './packages/blk/src/index.ts';
+const ar = readArchive(readFileSync('C:/WarThunder/char.vromfs.bin'));
+const dict = [...ar.files.entries()].find(([k]) => k.endsWith('.dict'))?.[1];
+console.log(formatBlkText(decodeBlk(getFile(ar, 'config/wpcost.blk'), { names: ar.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(ar, NAME_MAP_PATH), dict).names : [], dictionary: dict })));
+
+

3. Build Your First Mod in 5 Minutes

+
  1. Open Mods › Open mods folder in the launcher (you will already see the 3 official template folders inside for reference);
  2. Create a new folder named my-first-mod;
  3. Create the manifest file my-first-mod/mod.jsonc:
+
jsonc
{
+  "format": 1,
+  "id": "demo.my-first-mod",
+  "name": {
+    "zh-CN": "我的第一个模组",
+    "en": "My First Mod"
+  },
+  "version": "0.1.0",
+  "author": "YourName",
+  "description": {
+    "zh-CN": "把对局银狮和研发点倍率调整为 2 倍。",
+    "en": "Doubles Silver Lions and Research Points battle rewards."
+  },
+  "api_version": "0.1-experimental",
+  "game_versions": ["2.61.0.*"]
+}
+
  1. Create my-first-mod/server/tuning/battle.jsonc:
+
jsonc
{
+  "rewardMultiplierSilverLions": 2.0,
+  "rewardMultiplierResearchPoints": 2.0
+}
+
  1. Switch back to the launcher window (the Mods page refreshes automatically on focus, or click Refresh), enable your mod, and click Launch.
+
+

4. Complete Standard Folder Layout

+

Create only the subdirectories your mod actually uses—unused folders can be omitted completely:

+
text
<mod-folder>/
+├─ mod.jsonc                          # Required: mod manifest
+├─ server/                            # Optional: server-side extensions
+│  ├─ tuning/                         #   incremental tuning overlays (*.jsonc)
+│  └─ index.ts (or index.mjs / .js)   #   server script entry (auto-detected by default)
+└─ client/                            # Optional: client-side extensions
+   ├─ packs/                          #   .vromfs.bin archive overlays
+   │  ├─ char.vromfs.bin/
+   │  ├─ aces.vromfs.bin/
+   │  ├─ gui.vromfs.bin/
+   │  ├─ lang.vromfs.bin/
+   │  ├─ mis.vromfs.bin/
+   │  ├─ game.vromfs.bin/
+   │  ├─ ui/atlases.vromfs.bin/
+   │  └─ ui/images.vromfs.bin/
+   ├─ addon/                          #   3D model & texture addon (res/*.grp, res/*.dxp.bin)
+   ├─ gui-patches/                    #   incremental GUI script/tpl/css patches (same format as patches/gui)
+   ├─ exe-patches/                    #   declarative exe patches (same format as patches/exe)
+   ├─ files/                          #   optional companion skins/sights/sounds/missions
+   └─ config-blk.patch.jsonc          #   optional root config.blk incremental patch
+
+

5. Full mod.jsonc Schema Reference

+

Manifest parsing enforces strict whitelist validation: typos or unknown keys are rejected immediately with a detailed error message on the Launcher Mods page.

+
FieldRequiredTypeDescription
formatYes1Manifest schema version, currently fixed to integer 1
idYesstringGlobally unique mod ID matching /^[a-z0-9][a-z0-9._-]{0,63}$/ (lowercase letters, digits, ., _, -; must start with letter/digit; max 64 chars; <author>.<mod-name> recommended)
nameYesstring | { [lang]: string }Display name as a plain string or locale map (e.g. zh-CN, en)
versionYesstringMod version string (SemVer such as 0.1.0 recommended)
authorYesstringAuthor or team name
descriptionNostring | { [lang]: string }Short summary as a plain string or locale map
api_versionYesstringTarget API version tag, currently fixed to "0.1-experimental"
game_versionsNostring[]Supported game build wildcards (e.g. ["2.61.0.*"]); mismatches emit a warning without blocking launch
requiresNostring[]Required dependency mod IDs: missing or disabled dependencies raise a blocking error; also enforces load order (emits a dependency-order warning if placed above its dependency and participates in Auto-Sort)
conflictsNostring[]Mutually incompatible mod IDs; enabling both raises a blocking error
load_afterNostring[]Optional mods this mod should load after (lower in the list = higher priority); does not require them to be enabled, and participates in order hints & Auto-Sort
load_beforeNostring[]Optional mods this mod should load before; also participates in order hints & Auto-Sort
serverNo{ entry?: string, tuning?: string }Explicit relative paths (no ..) overriding default auto-detection of server/index.{ts,mjs,js} and server/tuning
+
+

6. Automatically Computed Capability & Risk Badges (Additive Multi-Badge)

+

After scanning each mod folder, the launcher computes capability badges automatically. Badges are additive, not mutually exclusive—for example, a mod with pack overlays and a server script displays both data and script, while official-map-selector displays data, gui, and script:

+ +
+

7. Load Order Rules & Conflict Detection

+
- -

完整标准目录结构(按需创建)Standard Folder Layout (Create Only What You Use)

-
-
Layout
-
<mod-folder>/
-├─ mod.jsonc                        # Required manifest (strict whitelist schema)
-├─ server/                          # Optional server extensions
-│  ├─ tuning/*.jsonc                #   Code-free tuning overlays
-│  └─ index.ts (or .mjs / .js)      #   Server script entry (auto-detected)
-└─ client/                          # Optional client overlays
-   ├─ packs/<archive>.vromfs.bin/   #   Incremental BLK/CSV patches or added files
-   ├─ addon/res/                    #   3D models (.grp) & textures (.dxp.bin)
-   ├─ gui-patches/<patch>/          #   Incremental Quirrel UI script patches
-   ├─ exe-patches/<patch>/          #   Declarative signature-based exe patches
-   ├─ files/                        #   Bundled skins/sights/sound packs
-   └─ config-blk.patch.jsonc        #   Incremental patch for root config.blk
+ + -

清单字段与能力徽标Key Manifest Fields & Risk Badges

- - - - -
-

- 2. 客户端数据包与 BLK / CSV 增量补丁 - 2. Client Archives & Incremental BLK / CSV Patching -

-

- 支持叠加 8 个数据包:char.vromfs.bin、aces.vromfs.bin、gui.vromfs.bin、lang.vromfs.bin、mis.vromfs.bin、game.vromfs.bin、ui/atlases.vromfs.bin、ui/images.vromfs.bin。服务端启动时直接读取叠加后的包,新增或改动的载具价格、科技树与权重会自动同步生效。 - Eight archives support additive overlays: char, aces, gui, lang, mis, game, ui/atlases, and ui/images. The local server reads the overlaid archives at startup, automatically picking up edited vehicle trees, costs, and BRs. -

-
    -
  • <path>.patch.jsonc:保留类型的 BLK 增量补丁,支持全部 7 种操作:setParam、addParam、removeParam、upsertBlock、addBlock(支持 before/after)、removeBlock 与 cloneBlock;路径支持 range[0] 下标寻址。Type-preserving BLK patch supporting all 7 operations: setParam, addParam, removeParam, upsertBlock, addBlock (with before/after), removeBlock, and cloneBlock, with indexed paths like range[0].
  • -
  • <path>.patch.csv:按第 1 列词条键增量合并本地化表(更新已有键或追加新键),绝不整表覆写。Merges localization entries by first-column key without replacing the whole table.
  • -
  • 其余新增文件Added files:文本 .blk 自动编译为二进制 BLK;.svg / .ddsx / .nut / .tpl 原样写入。Text .blk files are compiled to binary BLK automatically; .svg, .ddsx, .nut, and .tpl are embedded as-is.
  • -
-
- - -
-

- 3. 添加全新 3D 模型与贴图载具 - 3. Adding Custom 3D Vehicle Models & Textures -

-

- 把 CDK 导出的 .grp 模型与 .dxp.bin 贴图放入 client/addon/res/。启动器自动通过 Windows NTFS 目录联接点(Junction)挂载到 content/pkg_user/<modId>——支持跨盘、免管理员、零额外磁盘空间、约 1 毫秒完成,关闭模组即拆除。 - Place CDK-exported .grp models and .dxp.bin textures under client/addon/res/. The launcher mounts them to content/pkg_user/<modId> via a zero-copy cross-drive NTFS Junction (no admin required, removed cleanly on disable). -

-
    -
  1. 模型与贴图:放入 client/addon/res/<unit_id>.grp 与 .dxp.bin;Model & textures: place .grp and .dxp.bin in client/addon/res/.
  2. -
  3. 物理与武器配置:放进 client/packs/aces.vromfs.bin/gamedata/units/.../<unit_id>.blk;Unit config: add gamedata/units/.../<unit_id>.blk under client/packs/aces.vromfs.bin/.
  4. -
  5. 经济与科技树:用 .patch.jsonc 修改 wpcost.blk(推荐 cloneBlock)、shop.blk 与 unittags.blk(若带 gift:t="msi_notebook",构建器自动为其登记本地商店 GUID);Economy & tree: patch wpcost.blk (cloneBlock is fastest), shop.blk, and unittags.blk; setting gift:t="msi_notebook" auto-registers a local store GUID.
  6. -
  7. 译名与图标:用 units.csv.patch.csv 加中英文名,图标放入全小写路径 ui/atlases.vromfs.bin/gameuiskin/<unit_id>_ico.svg。Localization & icons: add names via units.csv.patch.csv and lowercase gameuiskin/<unit_id>_ico.svg.
  8. -
-
- 原生目录保护:普通独立涂装、瞄具与单人任务照旧放进 UserSkins/、UserSights/ 即可;大型整合包附带资源可放 client/files/,若与玩家已有原生文件撞名会自动跳过,绝不覆盖。 - Native file protection: Standalone skins/sights belong in UserSkins/ and UserSights/. Bundled assets in client/files/ never overwrite existing player files. -
-
- - -
-

- 4. 客户端 GUI 补丁与声明式 EXE 补丁 - 4. Client GUI Patches & Declarative EXE Patches -

-
    -
  • 界面扩展最佳实践UI Extension Pattern:大块逻辑写成独立 .nut / .tpl / .css 放进 client/packs/gui.vromfs.bin/,再在 client/gui-patches/ 用几行最小增量补丁挂载入口按钮;每条 find 必须唯一命中,否则整条跳过。Place new modals/logic as standalone .nut/.tpl/.css files in client/packs/gui.vromfs.bin/, and keep client/gui-patches/ minimal to hook entry buttons. Every find fragment must match exactly once.
  • -
  • 必做 Quirrel 字节码检查Mandatory Quirrel Bytecode Check:局部变量与 from ... import * 重名、前向引用或误用保留字(如 base)会导致进机库卡死在「正在加载」;务必用 sq.exe 的 compilestring 完整编译检查。Lexical scope clashes, forward references, or reserved words like base freeze login on loading. Always validate with sq.exe using compilestring.
  • -
  • 声明式 EXE 补丁与隔离红线Declarative EXE Patches & Isolation Lock:复用 @wto/exepatch 的特征码格式放入 client/exe-patches/,严禁分发改过的 aces.exe;任何企图触碰离线核心隔离补丁字节区段的模组都会被直接拒绝。Use @wto/exepatch signature patches in client/exe-patches/—never redistribute patched aces.exe. Patches overlapping protected core isolation bytes are rejected.
  • -
-
- - -
-

- 5. 服务端零代码数值叠加(server/tuning/) - 5. Code-Free Server Tuning Overlays -

-

- 12 份配置文件均可叠加:battle、battle-economy、store、marketplace、trophies、supply-chests、recycling、redeem-codes、new-profile、research、clans、limits。合并优先级:内置默认 < 模组(按排序) < 玩家在启动器「数值」页的手动覆盖。 - All 12 tuning files are overlayable (battle, battle-economy, store, marketplace, trophies, supply-chests, recycling, redeem-codes, new-profile, research, clans, limits). Precedence: defaults < enabled mods in order < player overrides. -

-

- 数组字段支持 $listOps(append、prepend、upsertBy、removeBy),让多个模组往礼包/兑换码/奖池追加条目时互不覆盖: - Array fields support $listOps (append, prepend, upsertBy, removeBy) so multiple mods can extend packs, codes, or pools without clobbering each other: -

-
-
- server/tuning/store.jsonc · $listOps - -
-
{
-  "multiVehiclePacks": {
-    "$listOps": [
-      { "op": "upsertBy", "key": "id", "item": { "id": "wto_pack_two_fronts", "priceGjn": 19.99 } }
+          
+
+

02 · 客户端数据包与 BLK 增量补丁

+

绝大多数《战争雷霆》数据模组(调整载具性能、炮弹穿深、导弹机动、科技树排布、银狮/研发点价格、分房权重、本地化译名、载具图标)都落在游戏的 .vromfs.bin 数据包中。本章讲解如何以完全可叠加、多模组互不顶掉的方式修改这些数据包,并在章末带你从零克隆出一辆能在美系科技树看到并直接试驾的独立新坦克。

+
+

1. 先懂概念:什么是 BLK?它为什么和 JSON 不一样?

+

Dagor 引擎使用自研的 BLK(DataBlock) 格式存储几乎所有游戏配置(在数据包内编译为紧凑二进制,解包后可读为文本 .blk)。初看很像 JSON,但它有三个关键差异:

+
  1. 每个参数都带显式静态类型后缀:例如 :i(32 位整数)、:r(单精度浮点)、:t(字符串)、:b(布尔 yes/no);把 :r 误写成 :i 会导致引擎读不到小数参数;
  2. 同一个块内允许出现多个同名参数:例如 slaveUnit:t="launcher_a" 下面紧跟第二行 slaveUnit:t="launcher_b"(如果直接转成普通 JSON 对象,前一行就会被后一行覆盖丢失!);
  3. 同一个父块下允许并列多个同名子块:最典型的就是科技树 shop.blk,每个陆军/空军分支下并列着好几个同名的 range { ... } 子块。
+

对比下面这段 8 行原版文本 .blk(节选自 wpcost.blk 的 us_m2a4)与对应的 .blk.patch.jsonc 增量补丁,你立刻就能看懂两者的对应关系:

+
blk
// 原版可读文本 BLK(char.vromfs.bin -> config/wpcost.blk 节选)
+us_m2a4 {
+  value:i = 0
+  rank:i = 1
+  economicRankHistorical:i = 0
+  rewardMulHistorical:r = 0.1
+  country:t = "country_usa"
+  unitClass:t = "exp_tank"
+}
+
jsonc
// 对应的增量补丁:client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc
+// 只修改 us_m2a4 的历史模式收益倍率,不会影响其他模组对别的字段或载具的改动
+{
+  "ops": [
+    {
+      "op": "setParam",
+      "path": ["us_m2a4"],
+      "name": "rewardMulHistorical",
+      "value": { "type": "real", "value": 1.2 }
+    }
+  ]
+}
+
+

2. 支持叠加的 8 个客户端数据包

+

把文件按目标包路径放进 client/packs/<包路径>/ 下即可:

+
目标目录名常见内容备份方式
client/packs/char.vromfs.bin/config/shop.blk(科技树)、config/wpcost.blk(经济/权重/改装件)、config/unittags.blk、config/items.blk、config/modifications.blk常驻备份
client/packs/aces.vromfs.bin/gamedata/units/.../*.blk(载具模型/DM/炮塔)、gamedata/flightmodels/...(气动)、gamedata/weapons/...(武器/炮弹/导弹)、config/settings.blk常驻备份
client/packs/gui.vromfs.bin/新增独立 .nut 脚本、.tpl 模板、.css 样式(修改已有脚本/样式请看第 04 章 gui-patches)常驻备份
client/packs/lang.vromfs.bin/lang/units.csv、lang/menu.csv、lang/units_weaponry.csv 等本地化表按需自动备份,关闭还原
client/packs/mis.vromfs.bin/gamedata/missions/.../*.blk 联机/自定义任务按需自动备份,关闭还原
client/packs/game.vromfs.bin/danetlibs/...、game/... 脚本与配置按需自动备份,关闭还原
client/packs/ui/atlases.vromfs.bin/gameuiskin/<全小写载具id>_ico.svg(科技树与本地商城剪影图标)按需自动备份,关闭还原
client/packs/ui/images.vromfs.bin/units/<载具id>.ddsx 或 .png(资料卡/乘员栏载具图)按需自动备份,关闭还原
+

自动联动服务端:本地服务器在启动时直接读取叠加后的 .vromfs.bin。因此你通过补丁往 shop.blk / wpcost.blk 新增或修改载具后,服务端会自动识别新车价格、前置科技树、研发点、改装件、分房权重、AI 机器人池与礼包 GUID,无需手工同步两遍。

+
+

3. 包内文件的 3 种处理模式(按后缀自动识别)

+

构建器根据你在 client/packs/<包>/ 下放置的文件名自动决定处理方式:

+
  1. <原路径>.patch.jsonc → BLK 结构化增量补丁:解析目标 .blk 为保留完整类型的内存树,按 ops 逐条修改后重新编码为自包含二进制 BLK 写回;
  2. <原路径>.patch.csv → CSV 本地化增量合并:按第 1 列词条键合并进目标 .csv(已有键只更新你填写的语言列,新键追加到表尾);
  3. 其余文件(如 us_m2a4_mod_demo.blk、us_m2a4_mod_demo_ico.svg)→ 新增或替换文件: +
    • 如果路径以 .blk 结尾且你的源文件是可读文本 BLK(如从原版客户端解包修改得到的),构建器会自动将其编译为游戏引擎所需的二进制 BLK 写进包内;
    • 如果已经是二进制 BLK,或是 .svg / .ddsx / .nut / .tpl / .css,则原样写入包内。
+
+

4. BLK 增量补丁(*.blk.patch.jsonc)完整手册

+

4.1 基本格式与路径寻址

+
jsonc
{
+  "ops": [
+    // 按顺序执行的操作列表
+  ]
+}
+
  • path 是从 BLK 根节点出发的子块名数组,例如 ["country_usa", "army", "range[0]"];
  • 同名并列子块(如 shop.blk 里连续多个 range 块)可以用 名称[索引](0 起始)精确定位;不写索引默认命中第 0 个同名子块;
  • [] 表示当前文档根节点本身。
+

4.2 全部 7 种操作(op)

+
① setParam:设置参数(存在则覆盖并去重同名项,不存在则新增)
+

修改已有块上的单个字段时,永远优先用 setParam:

+
jsonc
{
+  "op": "setParam",
+  "path": ["us_m2a4"],
+  "name": "rewardMulHistorical",
+  "value": { "type": "real", "value": 1.2 },
+  "createBlocks": false // 可选,默认 false;设为 true 时自动补建缺失路径子块
+}
+
② addParam:追加同名参数(不删除已有同名项,适合 slaveUnit、folder、aircraftGift 等可重复键)
+
jsonc
{
+  "op": "addParam",
+  "path": ["country_usa", "army", "range[0]", "us_m2a4"],
+  "name": "slaveUnit",
+  "value": "my_extra_launcher"
+}
+
③ removeParam:删除参数(不填 value 删除全部同名参数;填 value 只删值匹配的项)
+
jsonc
{
+  "op": "removeParam",
+  "path": ["us_m2a4"],
+  "name": "showOnlyWhenBought"
+}
+
④ upsertBlock:确保路径子块存在,并向其追加 params 与 blocks
+
jsonc
{
+  "op": "upsertBlock",
+  "path": ["country_usa", "army", "range[0]", "my_custom_tank"],
+  "block": {
+    "params": [
+      { "name": "rank", "value": { "type": "int", "value": 8 } },
+      { "name": "reqAir", "value": "us_m1a2_sep2_abrams" }
     ]
   }
-}
-
-
- - -
-

- 6. 服务端 JS / TS 脚本 API - 6. Server JS / TS Scripting API -

-

- 运行于启动器内置 Node.js 24(原生开启 TypeScript 类型剥离),默认探测 server/index.ts → .mjs → .js。直接写 .ts 请遵循 erasableSyntaxOnly(避免 enum、namespace 和构造函数参数属性;如需第三方依赖可自行打包为单文件 .mjs)。 - Runs on bundled Node.js 24 with native TypeScript type stripping, auto-detecting server/index.ts → .mjs → .js. Follow erasableSyntaxOnly for raw .ts (no enum/namespace/parameter properties), or bundle to a single .mjs. -

-
-
- server/index.ts · Example - -
-
export default {
-  async setup(ctx) {
-    ctx.logger.info('mod ready');
-
-    // Filter candidate maps before matchmaking picks one
-    ctx.hooks.battle.onFilterMissions(({ missions }) => {
-      const picked = missions.filter((m) => /poland|berlin/i.test(m.level ?? m.name));
-      return picked.length > 0 ? picked : undefined;
-    });
-
-    // Register a custom matching RPC callable from Quirrel UI scripts
-    ctx.routes.matching.register('wto_mod.demo.ping', ({ userId, params }) => {
-      const store = ctx.storage.forPlayer(userId);
-      const count = (store.read<{ count: number }>()?.count ?? 0) + 1;
-      store.write({ count });
-      return { ok: true, count, echo: params };
-    });
+}
+

重要行为说明(避免重复键踩坑):如果目标路径的块原本不存在,upsertBlock 会自动创建它并写入 block.params 和 block.blocks;但如果目标块已经存在,upsertBlock 会把传入的 params(通过 appendParam)和 blocks 直接追加到块末尾,而不会覆盖已有同名参数!因此:新建子块或有意追加多值字段时可用 upsertBlock;若要覆盖已有块上的某个参数值,请务必使用 setParam。

+
⑤ addBlock:在父块下新增一个子块(支持 before / after 指定锚点位置)
+
jsonc
{
+  "op": "addBlock",
+  "path": ["country_usa", "army", "range[0]"],
+  "name": "my_custom_tank",
+  "after": "us_m3a1_stuart",
+  "block": {
+    "params": [
+      { "name": "rank", "value": { "type": "int", "value": 1 } },
+      { "name": "reqAir", "value": "us_m2a4" }
+    ]
+  }
+}
+
⑥ removeBlock:删除指定路径的子块
+
jsonc
{
+  "op": "removeBlock",
+  "path": ["country_usa", "army", "range[0]", "some_vehicle"]
+}
+
⑦ cloneBlock:深拷贝同文档里的已有块为新名称并嵌套 ops 微调(衍生新车神器!)
+

在 wpcost.blk 和 unittags.blk 里,一辆载具包含几十个维修/乘员/改装件/武器预设子块。用 cloneBlock 可以一键完整克隆原版原型车,再用嵌套 ops 只改差异字段:

+
jsonc
{
+  "op": "cloneBlock",
+  "from": ["us_m1a2_sep2_abrams"],
+  "toParent": [],
+  "newName": "us_m1a2_mod_example",
+  "replaceExisting": true,
+  "ops": [
+    { "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 10000 } },
+    { "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 50000 } },
+    { "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 34 } }
+  ]
+}
+

注意:cloneBlock 内部的嵌套 ops 是以刚克隆出来的新块为根节点运行的,所以修改新块自身顶层参数时 path 写 []。

+

4.3 全部 13 种 BLK 数据类型写法

+

直接写 JSON 原始值时,构建器会优先沿用目标块已有同名字段的 BLK 类型(若无同名字段:字符串 → string,布尔 → bool,整数 → int,含小数 → real)。为确保万无一失(尤其是把浮点字段设为 2.0 时 JSON 解析为整数 2),推荐显式写成 { "type": "<类型>", "value": <值> }:

+
typeBLK 文本后缀value 示例与说明
string:t"us_m2a4"
int:i120(32 位有符号整数)
real:r1.5(即使写 2,也会严格按 32 位浮点 :r 编码)
bool:btrue / false(对应文本 BLK 的 yes / no)
int64:i64"133700000000000000" 或整数(64 位整数)
point2:p2[1.0, 2.5](2 个浮点数)
point3:p3[0.0, 1.5, -2.0](3 个浮点数)
point4:p4[0.0, 1.0, 0.0, 1.0](4 个浮点数)
ipoint2:ip2[10, 20](2 个整数)
ipoint3:ip3[1, 2, 3](3 个整数)
ipoint4:ip4[0, 1, 2, 3](4 个整数)
color:c[255, 128, 0, 255]([r, g, b, a])或无符号打包整数 0xAARRGGBB
matrix:m12 个浮点数的数组(4 行 × 3 列变换矩阵)
+
+

5. 分房权重(BR)与内部 mrank(economicRank*)换算表

+

新手打开 wpcost.blk 最常困惑的一点是:为什么里面找不到 11.7 或 12.7 这样的分房权重数字?

+

在战雷内部,面板显示的 分房权重(Battle Rating, BR) 存储为从 0 开始的非负整数 mrank(字段名为 economicRank*),每 3 级整数对应 1.0 权重,小数位按 .0 → .3 → .7 循环:

+
  • 正向换算公式(mrank → 面板 BR):BR = 1.0 + Math.floor(mrank / 3) + [0, 0.3, 0.7][mrank % 3]
  • 反向换算口诀(面板 BR → mrank):(整数部分 - 1) × 3,再加小数档位(.0 加 0,.3 加 1,.7 加 2)。例如 11.7 → (11 - 1) × 3 + 2 = 32!
+

5.1 完整 mrank ↔ 面板 BR 速查表

+
mrank面板 BRmrank面板 BRmrank面板 BRmrank面板 BR
01.0104.3207.73011.0
11.3114.7218.03111.3
21.7125.0228.33211.7
32.0135.3238.73312.0
42.3145.7249.03412.3
52.7156.0259.33512.7
63.0166.3269.73613.0
73.3176.72710.03713.3
83.7187.02810.33813.7
94.0197.32910.73914.0
+

5.2 wpcost.blk 模式后缀与科技树等级 rank 的区别

+

战雷沿用了远古内测时期的模式英文名,千万不要把科技树大等级 rank 和分房权重 economicRank* 搞混:

+
字段名取值范围真实含义
rank1 .. 8科技树时代等级(Rank I – VIII):决定它在科技树第几大行、受哪一级的开线数量门槛限制,以及默认套用哪一档商店礼包价格
economicRankArcade0 .. 39+街机娱乐(AB, Arcade Battles) 的分房 mrank
economicRankHistorical0 .. 39+历史性能(RB, Realistic Battles) 的默认分房 mrank(战雷早期将历史模式称为 *Historical Battles*)
economicRankSimulation0 .. 39+全真模拟(SB, Simulator Battles) 的默认分房 mrank
economicRankTankHistorical0 .. 39+(可选)飞机/直升机进入陆战历史(Ground RB)时的独立对地分房权重;不填时沿用 economicRankHistorical
economicRankTankSimulation0 .. 39+(可选)飞机/直升机进入陆战全真(Ground SB)时的独立分房权重
+
+

6. shop.blk 科技树结构与 units.csv 四大词条后缀详解

+

6.1 config/shop.blk 的四层树状结构

+

打开 char.vromfs.bin 里的 config/shop.blk,所有国家的科技树都遵循统一的四层结构:

+
text
country_usa (或 country_germany / country_ussr / country_britain / country_japan / country_china / ...)
+ └─ army (陆军) | helicopters (直升机) | aviation (空军) | ships (远洋海军) | boats (近岸海军)
+     ├─ range { ... }       <-- range[0]:科技树第 1 纵列(如美系轻坦线)
+     ├─ range { ... }       <-- range[1]:科技树第 2 纵列(如美系中坦线,内部含折叠组 us_sherman_group)
+     ├─ range { ... }       <-- range[2]..range[4]:其余常规银狮研发纵列
+     └─ range { ... }       <-- range[5]..range[6]:右侧金币车 / 礼包车 / 活动车 / 联队车独立纵列
+

编写 shop.blk.patch.jsonc 时只需记住三条核心规则:

+
  1. 每个 range 就是科技树上的一条纵向列:因为它们都叫 range,在补丁 path 里用 "range[0]"、"range[1]"、"range[5]" 按从左到右(0 起始)定位;
  2. 折叠文件夹(*_group):当同一格折叠了多辆同系载具时,range 下会放一个以 _group 结尾的子块(例如 us_sherman_group),里面再嵌套各辆具体载具子块,折叠封面标题来自 units.csv 的 shop/group/<组名>;
  3. 为什么坦克和军舰的前置研发箭头也叫 reqAir? 因为《战争雷霆》最早立项时是纯空战游戏(*World of Planes*),所有载具在底层代码里都沿用了 air / aircraft 命名,因此无论是坦克、直升机还是战列舰,指定“上一辆前置研发载具”的字段一律叫 reqAir! +
    • 在 wpcost.blk 中设置 reqAir:t="us_m2a4":声明玩家必须先拥有 us_m2a4 才能研发本车;
    • 在 shop.blk 的同一 range 列中:连续排列且未写 reqAir 的两辆车默认自动画纵向实线箭头;写 reqAir:t="us_m2a4" 会显式从 us_m2a4 连出箭头;而写 reqAir:t=""(空字符串)则会显式断开与上方载具的箭头连接(科技树断线处以及右侧金币/礼包列里的车都用 reqAir:t="")。
+

6.2 lang/units.csv 的 4 个载具译名后缀与 CSV 增量合并

+

在 client/packs/lang.vromfs.bin/lang/units.csv.patch.csv 中为新载具添加译名时,每辆载具 <id> 共有 4 个标准词条键,分别对应不同界面与视距:

+
词条键格式游戏内显示位置示例(以 us_m2a4_mod_demo 为例)
<id>_shop科技树格子、底部乘员槽位、本地网页商店卡片上的简短名称"M2A4 (Mod Demo)" / "M2A4(教学改型)"
<id>_0资料卡顶部标题、研发完成弹窗、战后结算详单里的完整正式全称"Light Tank M2A4 (Mod Demo)" / "M2A4 轻型坦克(教学改型)"
<id>_1战斗中中距离 3D 视野目标标记上显示的中等长度名称"M2A4 Demo" / "M2A4 教学型"
<id>_2战斗中远距离目标标记 / 极简击杀播报显示的超短型号或车种名"M2A4" / "M2A4"
+

CSV 补丁文件写法示例(client/packs/lang.vromfs.bin/lang/units.csv.patch.csv):

+
csv
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
+"us_m2a4_mod_demo_shop";"M2A4 (Mod Demo)";"M2A4(教学改型)";"M2A4(教學改型)"
+"us_m2a4_mod_demo_0";"Light Tank M2A4 (Mod Demo)";"M2A4 轻型坦克(教学改型)";"M2A4 輕型坦克(教學改型)"
+"us_m2a4_mod_demo_1";"M2A4 Demo";"M2A4 教学型";"M2A4 教學型"
+"us_m2a4_mod_demo_2";"M2A4";"M2A4";"M2A4"
+
  • 必须以分号 ; 分隔并用双引号包裹每个字段,第 1 行写表头列名(只需列出你要填的语言列,未列出的语言列会自动保留原值或留空);
  • 如果第 1 列 ID 在原表已存在,只更新你提供的非空语言列;不存在则自动追加到表尾。
+
+

7. 修改游戏根目录 config.blk(client/config-blk.patch.jsonc)

+

如果模组需要调整游戏根目录的 config.blk(例如开启音效模组开关 sound{ enable_mod:b=yes } 或指定自定义机库 hangarBlk:t="..."),放一份标准 BLK 补丁到 client/config-blk.patch.jsonc 即可:

+
jsonc
{
+  "ops": [
+    {
+      "op": "setParam",
+      "path": ["sound"],
+      "name": "enable_mod",
+      "value": { "type": "bool", "value": true },
+      "createBlocks": true
+    }
+  ]
+}
+

启动器会在首次修改前自动将原版 config.blk 备份到 wtoffline/stock/config.blk,关闭相关模组后自动还原。

+
+

8. 端到端完整实战:5 分钟克隆一辆可试驾独立新坦克(us_m2a4_mod_demo)

+

下面我们把前面学到的知识串成一条完整闭环:复用原版美系初始轻坦 us_m2a4 的外观模型,衍生出一辆极速提升到 90 km/h、权重 1.3(mrank = 1)、挂在美系陆军 I 级科技树 M2A4 旁边的独立新载具 us_m2a4_mod_demo。由于每个存档天生拥有初始车 us_m2a4,你进游戏就能直接在美系陆军科技树看到它并点击「试驾」!

+

8.1 模组目录结构

+

在全局 mods/ 目录下新建 demo-standalone-m2a4/,结构如下:

+
text
mods/demo-standalone-m2a4/
+├─ mod.jsonc
+└─ client/
+   └─ packs/
+      ├─ aces.vromfs.bin/
+      │  └─ gamedata/units/tankmodels/
+      │     └─ us_m2a4_mod_demo.blk          # ① 载具物理/装甲/武器定义(基于原版 us_m2a4.blk 修改)
+      ├─ char.vromfs.bin/
+      │  └─ config/
+      │     ├─ wpcost.blk.patch.jsonc        # ② 克隆经济、分房权重、改装件与弹药架
+      │     ├─ shop.blk.patch.jsonc          # ③ 挂入美系陆军第 1 列 I 级科技树
+      │     └─ unittags.blk.patch.jsonc      # ④ 克隆载具分类标签与试车场配置
+      └─ lang.vromfs.bin/
+         └─ lang/
+            └─ units.csv.patch.csv           # ⑤ 注册 _shop / _0 / _1 / _2 中英文名称
+

8.2 各文件完整内容

+
清单 mod.jsonc
+
jsonc
{
+  "format": 1,
+  "id": "demo.standalone-m2a4",
+  "name": {
+    "zh-CN": "独立衍生载具示例:M2A4 教学改型",
+    "en": "Standalone Vehicle Demo: M2A4 Mod Demo"
   },
-};
+ "version": "0.1.0", + "author": "YourName", + "description": { + "zh-CN": "克隆原版 us_m2a4 新增一辆独立可研发、可试驾的 90km/h 高速轻坦。", + "en": "Clones stock us_m2a4 into a playable 90 km/h standalone tank in the US Rank I tree." + }, + "api_version": "0.1-experimental", + "game_versions": ["2.61.0.*"] +}
+
① 载具实体参数 client/packs/aces.vromfs.bin/gamedata/units/tankmodels/us_m2a4_mod_demo.blk
+

按第 01 章第 2 节任一方式取出原版 aces.vromfs.bin 中的 gamedata/units/tankmodels/us_m2a4.blk(文本或二进制均可),另存为 us_m2a4_mod_demo.blk。保持顶部的 model:t="m2a4" 不变(这样它会直接复用原版 M2A4 的 3D 模型和贴图),把里面的最大前进速度和加速改快即可(文本 .blk 在构建时会自动编译为二进制 .blk):

+
blk
model:t="m2a4"
+// ...(保留原版 us_m2a4.blk 其余内容不变,仅调高以下机动参数体验效果)...
+maxFwdSpeed:r=90.0
+maxRevSpeed:r=25.0
+maxAccel:r=12.0
+
② 经济与权重补丁 client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc
+

用 cloneBlock 一键复制 us_m2a4(自动继承全部武器、弹种、改装件与备用车配置),并把研发前提设为 us_m2a4、研发点设为 1000、银狮价格设为 500、三模式分房权重设为 1(即面板 1.3):

+
jsonc
{
+  "ops": [
+    {
+      "op": "cloneBlock",
+      "from": ["us_m2a4"],
+      "toParent": [],
+      "newName": "us_m2a4_mod_demo",
+      "replaceExisting": true,
+      "ops": [
+        { "op": "setParam", "path": [], "name": "reqAir", "value": "us_m2a4" },
+        { "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 1000 } },
+        { "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 500 } },
+        { "op": "setParam", "path": [], "name": "economicRank", "value": { "type": "int", "value": 1 } },
+        { "op": "setParam", "path": [], "name": "economicRankArcade", "value": { "type": "int", "value": 1 } },
+        { "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 1 } },
+        { "op": "setParam", "path": [], "name": "economicRankSimulation", "value": { "type": "int", "value": 1 } }
+      ]
+    }
+  ]
+}
+
③ 科技树位置补丁 client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc
+

在 country_usa -> army -> range[0] 的 I 级段末尾(us_m3a1_stuart 之后、us_m5a1_stuart 断线之前)插入新车块,并显式声明 reqAir: "us_m2a4",游戏就会在不打断原有斯图亚特研发线的前提下,从 M2A4 连出一条侧支研发箭头指向你的新车:

+
jsonc
{
+  "ops": [
+    {
+      "op": "addBlock",
+      "path": ["country_usa", "army", "range[0]"],
+      "name": "us_m2a4_mod_demo",
+      "after": "us_m3a1_stuart",
+      "block": {
+        "params": [
+          { "name": "rank", "value": { "type": "int", "value": 1 } },
+          { "name": "reqAir", "value": "us_m2a4" }
+        ]
+      }
+    }
+  ]
+}
+
④ 载具标签与试驾场补丁 client/packs/char.vromfs.bin/config/unittags.blk.patch.jsonc
+

同样用 cloneBlock 从 us_m2a4 克隆出 type:t="tank"、机库车位 hangar_place:t="tank"、陆战试车场 testFlight 与轻坦标签:

+
jsonc
{
+  "ops": [
+    {
+      "op": "cloneBlock",
+      "from": ["us_m2a4"],
+      "toParent": [],
+      "newName": "us_m2a4_mod_demo",
+      "replaceExisting": true
+    }
+  ]
+}
+
⑤ 多语言名称补丁 client/packs/lang.vromfs.bin/lang/units.csv.patch.csv
+

直接复用上面第 6.2 节的 4 行 CSV 内容即可。保存后在启动器勾选启用模组并启动游戏,切到美国陆军科技树 I 级,就能看到 M2A4(教学改型) 并立刻右键「试驾」体验 90 km/h 飙车!

- - +
+

02 · Client Packs & BLK Incremental Patching

+

Most War Thunder data mods—tweaking vehicle performance, shell penetration, missile maneuverability, tech-tree layouts, Silver Lion / Research Point prices, Battle Ratings, localized names, and vehicle icons—live inside .vromfs.bin data packs. This chapter explains how to modify those packs in a 100% stackable, conflict-free way, ending with a copy-pasteable walkthrough that clones a playable standalone tank into the US Rank I tech tree.

+
+

1. Plain-Language Intro: What Is BLK & Why Does It Differ from JSON?

+

War Thunder's Dagor Engine stores nearly all game configurations in BLK (DataBlock) files—compiled to compact binary inside .vromfs.bin packs, and readable as plain text .blk when unpacked. While text BLK looks superficially similar to JSON, it differs in three fundamental ways:

+
  1. Every parameter carries an explicit static type suffix: such as :i (32-bit integer), :r (32-bit float), :t (string), or :b (boolean yes/no). Writing :i where the engine expects :r causes the engine to ignore decimal values;
  2. Duplicate parameter names are allowed inside the same block: for instance, slaveUnit:t="launcher_a" followed immediately by slaveUnit:t="launcher_b" (converting naively to a plain JSON object would overwrite the first key!);
  3. Duplicate sibling block names are allowed under the same parent: most notably in shop.blk, where every army/aviation branch contains multiple sibling range { ... } blocks side by side.
+

Compare this 8-line stock text .blk excerpt (us_m2a4 in wpcost.blk) side by side with its .blk.patch.jsonc patch operation:

+
blk
// Stock readable text BLK (excerpt from char.vromfs.bin -> config/wpcost.blk)
+us_m2a4 {
+  value:i = 0
+  rank:i = 1
+  economicRankHistorical:i = 0
+  rewardMulHistorical:r = 0.1
+  country:t = "country_usa"
+  unitClass:t = "exp_tank"
+}
+
jsonc
// Matching incremental patch: client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc
+// Touches ONLY us_m2a4's Realistic reward multiplier without clobbering other fields or other mods!
+{
+  "ops": [
+    {
+      "op": "setParam",
+      "path": ["us_m2a4"],
+      "name": "rewardMulHistorical",
+      "value": { "type": "real", "value": 1.2 }
+    }
+  ]
+}
+
+

2. The 8 Overlayable Client Data Packs

+

Place your files under client/packs/<pack-path>/ matching the target archive's internal path:

+
Target DirectoryCommon ContentsBackup Strategy
client/packs/char.vromfs.bin/config/shop.blk (tech tree), config/wpcost.blk (economy/BR/modifications), config/unittags.blk, config/items.blk, config/modifications.blkAlways rebuilt from stock
client/packs/aces.vromfs.bin/gamedata/units/.../*.blk (vehicle models/DM/turrets), gamedata/flightmodels/... (FMs), gamedata/weapons/... (guns/shells/missiles), config/settings.blkAlways rebuilt from stock
client/packs/gui.vromfs.bin/New standalone .nut scripts, .tpl templates, .css stylesheets (to edit stock UI files, see Chapter 04 gui-patches)Always rebuilt from stock
client/packs/lang.vromfs.bin/lang/units.csv, lang/menu.csv, lang/units_weaponry.csv, and other localization CSVsBacked up on demand, restored on disable
client/packs/mis.vromfs.bin/gamedata/missions/.../*.blk multiplayer and custom missionsBacked up on demand, restored on disable
client/packs/game.vromfs.bin/danetlibs/..., game/... scripts and configsBacked up on demand, restored on disable
client/packs/ui/atlases.vromfs.bin/gameuiskin/<lowercase_unit_id>_ico.svg (tech-tree & local web store silhouette icons)Backed up on demand, restored on disable
client/packs/ui/images.vromfs.bin/units/<unit_id>.ddsx or .png (stat-card / crew-slot vehicle images)Backed up on demand, restored on disable
+

Automatic Server Sync: The local server reads static datasets directly from the overlaid .vromfs.bin packs on startup. Any vehicle added or tweaked in shop.blk / wpcost.blk is automatically picked up for prices, tech-tree prerequisites, Research Points, modifications, Battle Ratings, AI bot pools, and store pack GUIDs—no duplicate server registration needed.

+
+

3. Three File Handling Modes Inside Packs (Auto-Detected by Suffix)

+

The patcher determines how to process each file under client/packs/<pack>/ by its filename suffix:

+
  1. <target-path>.patch.jsonc → Structured Incremental BLK Patch: decodes the target .blk into a type-preserving tree, applies ops in order, and re-encodes a self-contained binary BLK;
  2. <target-path>.patch.csv → Incremental Localization CSV Merge: merges rows by column 0 (updating only the non-empty language columns you provide on existing keys, and appending new keys at the end);
  3. Any other file (e.g. us_m2a4_mod_demo.blk, us_m2a4_mod_demo_ico.svg) → Add or Replace File: +
    • If the path ends with .blk and your source file is plain text BLK (for example, extracted and edited from your stock client), the builder automatically compiles it into binary BLK for the engine;
    • Binary .blk files and other assets (.svg, .ddsx, .nut, .tpl, .css) are written into the archive as-is.
+
+

4. Complete BLK Incremental Patch (*.blk.patch.jsonc) Reference

+

4.1 Document Format & Path Addressing

+
jsonc
{
+  "ops": [
+    // Ordered list of patch operations
+  ]
+}
+ +

4.2 All 7 Patch Operations (op)

+
① setParam: Set a parameter (overwrites & deduplicates same-named params if present; appends if absent)
+

Always prefer setParam when updating a single parameter on an existing block:

+
jsonc
{
+  "op": "setParam",
+  "path": ["us_m2a4"],
+  "name": "rewardMulHistorical",
+  "value": { "type": "real", "value": 1.2 },
+  "createBlocks": false // Optional (default false); set true to auto-create missing blocks along path
+}
+
② addParam: Append a duplicate-named parameter (preserves existing entries; ideal for slaveUnit, folder, aircraftGift)
+
jsonc
{
+  "op": "addParam",
+  "path": ["country_usa", "army", "range[0]", "us_m2a4"],
+  "name": "slaveUnit",
+  "value": "my_extra_launcher"
+}
+
③ removeParam: Delete parameters (deletes all matching name when value is omitted, or only entries matching value)
+
jsonc
{
+  "op": "removeParam",
+  "path": ["us_m2a4"],
+  "name": "showOnlyWhenBought"
+}
+
④ upsertBlock: Find or create a child block and append params & blocks
+
jsonc
{
+  "op": "upsertBlock",
+  "path": ["country_usa", "army", "range[0]", "my_custom_tank"],
+  "block": {
+    "params": [
+      { "name": "rank", "value": { "type": "int", "value": 8 } },
+      { "name": "reqAir", "value": "us_m1a2_sep2_abrams" }
+    ]
+  }
+}
+

Important Behavior Note (Avoid Duplicate Keys): If the target block along path does not exist, upsertBlock creates it and populates block.params and block.blocks. However, if the target block already exists, upsertBlock appends every entry in block.params (via appendParam) and block.blocks to the end of the block without overwriting existing same-named parameters! Use upsertBlock to create new blocks or append multi-value params; to overwrite an existing parameter on an existing block, always use setParam.

+
⑤ addBlock: Insert a new child block under a parent (supports before / after sibling anchors)
+
jsonc
{
+  "op": "addBlock",
+  "path": ["country_usa", "army", "range[0]"],
+  "name": "my_custom_tank",
+  "after": "us_m3a1_stuart",
+  "block": {
+    "params": [
+      { "name": "rank", "value": { "type": "int", "value": 1 } },
+      { "name": "reqAir", "value": "us_m2a4" }
+    ]
+  }
+}
+
⑥ removeBlock: Delete a child block at path
+
jsonc
{
+  "op": "removeBlock",
+  "path": ["country_usa", "army", "range[0]", "some_vehicle"]
+}
+
⑦ cloneBlock: Deep-clone an existing block in the same file under newName with nested ops (essential for derived vehicles!)
+

In wpcost.blk and unittags.blk, each vehicle block contains dozens of repair, crew, modification, and weapon-preset sub-blocks. cloneBlock copies a stock donor vehicle completely in one step and lets you tweak only the differences via nested ops:

+
jsonc
{
+  "op": "cloneBlock",
+  "from": ["us_m1a2_sep2_abrams"],
+  "toParent": [],
+  "newName": "us_m1a2_mod_example",
+  "replaceExisting": true,
+  "ops": [
+    { "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 10000 } },
+    { "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 50000 } },
+    { "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 34 } }
+  ]
+}
+

Note: Nested ops inside cloneBlock run with the newly cloned block itself as the root, so use "path": [] when editing top-level fields on the cloned block.

+

4.3 All 13 BLK Data Types

+

When you write a plain JSON primitive, the patcher infers the BLK type from any existing parameter of the same name on that block (falling back to string, bool, int for integers, or real for non-integers). To guarantee exact binary types—especially when setting a float parameter to a whole number like 2.0, which JSON parses as integer 2—write { "type": "<type>", "value": <val> }:

+
typeText BLK Suffixvalue Example & Notes
string:t"us_m2a4"
int:i120 (signed 32-bit integer)
real:r1.5 (encoded strictly as 32-bit float :r even if written as 2)
bool:btrue / false (yes / no in text BLK)
int64:i64"133700000000000000" or integer (signed 64-bit integer)
point2:p2[1.0, 2.5] (2 floats)
point3:p3[0.0, 1.5, -2.0] (3 floats)
point4:p4[0.0, 1.0, 0.0, 1.0] (4 floats)
ipoint2:ip2[10, 20] (2 integers)
ipoint3:ip3[1, 2, 3] (3 integers)
ipoint4:ip4[0, 1, 2, 3] (4 integers)
color:c[255, 128, 0, 255] ([r, g, b, a]) or unsigned packed integer 0xAARRGGBB
matrix:mArray of 12 floats (4×3 transform matrix)
+
+

5. Battle Rating (BR) ↔ Internal mrank (economicRank*) Conversion & Lookup Table

+

A classic question when opening wpcost.blk for the first time is: why are there no 11.7 or 12.7 Battle Rating numbers anywhere in the file?

+

Internally, War Thunder stores displayed Battle Ratings (BR) as zero-based non-negative integers called mrank (stored in economicRank* fields), where every 3 integer steps equal 1.0 BR and fractional steps cycle .0 → .3 → .7:

+ +

5.1 Complete mrank ↔ Displayed BR Lookup Table

+
mrankDisplayed BRmrankDisplayed BRmrankDisplayed BRmrankDisplayed BR
01.0104.3207.73011.0
11.3114.7218.03111.3
21.7125.0228.33211.7
32.0135.3238.73312.0
42.3145.7249.03412.3
52.7156.0259.33512.7
63.0166.3269.73613.0
73.3176.72710.03713.3
83.7187.02810.33813.7
94.0197.32910.73914.0
+

5.2 Legacy Mode Suffixes in wpcost.blk vs Tech-Tree Tier rank

+

War Thunder retains internal field names from its alpha era—be careful not to confuse tech-tree tier rank with matchmaking BR economicRank*:

+
Field NameValue RangeMeaning
rank1 .. 8Tech-Tree Era Tier (Rank I – VIII): controls which horizontal tier row the vehicle occupies, tier unlock gates, and default store rank-tier pricing
economicRankArcade0 .. 39+Arcade Battles (AB) matchmaking mrank
economicRankHistorical0 .. 39+Realistic Battles (RB) default matchmaking mrank (RB was originally called *Historical Battles*)
economicRankSimulation0 .. 39+Simulator Battles (SB) default matchmaking mrank
economicRankTankHistorical0 .. 39+*(Optional)* Split Ground RB mrank for aircraft/helicopters with separate air vs ground BRs; falls back to economicRankHistorical when omitted
economicRankTankSimulation0 .. 39+*(Optional)* Split Ground SB mrank for aircraft/helicopters
+
+

6. shop.blk Anatomy & units.csv Localization Suffixes

+

6.1 The 4-Level Hierarchy of config/shop.blk

+

Inside char.vromfs.bin, config/shop.blk organizes every nation's research tree into a uniform 4-level hierarchy:

+
text
country_usa (or country_germany / country_ussr / country_britain / country_japan / country_china / ...)
+ └─ army | helicopters | aviation | ships | boats
+     ├─ range { ... }       <-- range[0]: 1st vertical column (e.g. US Light Tank line)
+     ├─ range { ... }       <-- range[1]: 2nd vertical column (e.g. US Medium Tank line, containing folder us_sherman_group)
+     ├─ range { ... }       <-- range[2]..range[4]: remaining regular Silver Lions research columns
+     └─ range { ... }       <-- range[5]..range[6]: right-hand Golden Eagle / Pack / Event / Squadron columns
+

Keep three rules in mind when writing shop.blk.patch.jsonc:

+
  1. Each sibling range block is one vertical column in the tech tree: since every column block is named range, address them left-to-right (zero-based) as "range[0]", "range[1]", "range[5]", etc.;
  2. Collapsible folder groups (*_group): when multiple variants share one tech-tree folder, range contains a child block ending in _group (e.g. us_sherman_group) whose children are the grouped vehicles; the folder's display label comes from shop/group/<group_name> in units.csv;
  3. Why is the prerequisite arrow field named reqAir even on tanks and ships? War Thunder began life as an aviation-only game (*World of Planes*), so air / aircraft remained the universal internal noun for any unit. Consequently, reqAir defines the research prerequisite vehicle across tanks, helicopters, aircraft, and ships alike! +
    • Setting reqAir:t="us_m2a4" in wpcost.blk requires owning us_m2a4 before researching the unit;
    • Inside a range column in shop.blk: consecutive vehicles with no reqAir property automatically connect with vertical arrows; reqAir:t="us_m2a4" draws an explicit arrow from us_m2a4; and reqAir:t="" (empty string) explicitly breaks the arrow from the vehicle above it (used at mid-column gaps and throughout the right-hand premium/pack columns).
+

6.2 All 4 lang/units.csv Keys & Incremental CSV Merging

+

When localizing a vehicle <id> in client/packs/lang.vromfs.bin/lang/units.csv.patch.csv, War Thunder uses 4 standard localization keys for different UI contexts and HUD distances:

+
Key PatternWhere It Appears in GameExample (for us_m2a4_mod_demo)
<id>_shopTech-tree card, crew slot bar, and local web store card short name"M2A4 (Mod Demo)" / "M2A4(教学改型)"
<id>_0Stat-card header, research completion modal, and battle debriefing full formal title"Light Tank M2A4 (Mod Demo)" / "M2A4 轻型坦克(教学改型)"
<id>_1In-battle medium-distance 3D HUD marker name"M2A4 Demo" / "M2A4 教学型"
<id>_2In-battle far-distance HUD marker / compact killfeed short name"M2A4" / "M2A4"
+

Example client/packs/lang.vromfs.bin/lang/units.csv.patch.csv:

+
csv
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
+"us_m2a4_mod_demo_shop";"M2A4 (Mod Demo)";"M2A4(教学改型)";"M2A4(教學改型)"
+"us_m2a4_mod_demo_0";"Light Tank M2A4 (Mod Demo)";"M2A4 轻型坦克(教学改型)";"M2A4 輕型坦克(教學改型)"
+"us_m2a4_mod_demo_1";"M2A4 Demo";"M2A4 教学型";"M2A4 教學型"
+"us_m2a4_mod_demo_2";"M2A4";"M2A4";"M2A4"
+ +
+

7. Patching Root config.blk (client/config-blk.patch.jsonc)

+

If your mod needs to adjust the client root config.blk (for example enabling sound mods via sound{ enable_mod:b=yes } or setting a custom hangar hangarBlk:t="..."), place a standard BLK patch at client/config-blk.patch.jsonc:

+
jsonc
{
+  "ops": [
+    {
+      "op": "setParam",
+      "path": ["sound"],
+      "name": "enable_mod",
+      "value": { "type": "bool", "value": true },
+      "createBlocks": true
+    }
+  ]
+}
+

The launcher backs up the stock config.blk to wtoffline/stock/config.blk before applying patches and restores it automatically when no enabled mod touches config.blk.

+
+

8. End-to-End Walkthrough: Clone a Playable Standalone Tank (us_m2a4_mod_demo) in 5 Minutes

+

Let's connect every piece from this chapter into a complete, copy-pasteable mod that derives a standalone us_m2a4_mod_demo light tank from stock us_m2a4—boosted to 90 km/h, rated at BR 1.3 (mrank = 1), and wired into US Ground Rank I with a research arrow from M2A4. Because every player profile owns the reserve us_m2a4 from the start, you can see the new tank in the US tree and Test Drive it immediately!

+

8.1 Mod Folder Tree

+

Create demo-standalone-m2a4/ inside your global mods/ directory:

+
text
mods/demo-standalone-m2a4/
+├─ mod.jsonc
+└─ client/
+   └─ packs/
+      ├─ aces.vromfs.bin/
+      │  └─ gamedata/units/tankmodels/
+      │     └─ us_m2a4_mod_demo.blk          # ① Tank physics/armor/weapons (copied from stock us_m2a4.blk)
+      ├─ char.vromfs.bin/
+      │  └─ config/
+      │     ├─ wpcost.blk.patch.jsonc        # ② Clone economy, BR, modifications & ammo racks
+      │     ├─ shop.blk.patch.jsonc          # ③ Insert into US Army column 0 (Rank I)
+      │     └─ unittags.blk.patch.jsonc      # ④ Clone unit class tags & test-drive mission
+      └─ lang.vromfs.bin/
+         └─ lang/
+            └─ units.csv.patch.csv           # ⑤ Localized _shop / _0 / _1 / _2 names
+

8.2 Complete File Contents

+
Manifest mod.jsonc
+
jsonc
{
+  "format": 1,
+  "id": "demo.standalone-m2a4",
+  "name": {
+    "zh-CN": "独立衍生载具示例:M2A4 教学改型",
+    "en": "Standalone Vehicle Demo: M2A4 Mod Demo"
+  },
+  "version": "0.1.0",
+  "author": "YourName",
+  "description": {
+    "zh-CN": "克隆原版 us_m2a4 新增一辆独立可研发、可试驾的 90km/h 高速轻坦。",
+    "en": "Clones stock us_m2a4 into a playable 90 km/h standalone tank in the US Rank I tree."
+  },
+  "api_version": "0.1-experimental",
+  "game_versions": ["2.61.0.*"]
+}
+
① Tank Model Definition client/packs/aces.vromfs.bin/gamedata/units/tankmodels/us_m2a4_mod_demo.blk
+

Extract stock gamedata/units/tankmodels/us_m2a4.blk from aces.vromfs.bin using any method from Chapter 01 Section 2, and save it as us_m2a4_mod_demo.blk. Keep model:t="m2a4" at the top (so the engine reuses the stock M2A4 3D mesh and textures) and raise its speed and acceleration (plain text .blk compiles to binary automatically on build):

+
blk
model:t="m2a4"
+// ... (keep the rest of stock us_m2a4.blk unchanged; tweak mobility below to feel the difference) ...
+maxFwdSpeed:r=90.0
+maxRevSpeed:r=25.0
+maxAccel:r=12.0
+
② Economy & BR Patch client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc
+

Use cloneBlock to copy us_m2a4 (inheriting all weapons, shells, modifications, and backup settings), and set reqAir to "us_m2a4", RP cost to 1000, SL price to 500, and all mode mrank values to 1 (displayed BR 1.3):

+
jsonc
{
+  "ops": [
+    {
+      "op": "cloneBlock",
+      "from": ["us_m2a4"],
+      "toParent": [],
+      "newName": "us_m2a4_mod_demo",
+      "replaceExisting": true,
+      "ops": [
+        { "op": "setParam", "path": [], "name": "reqAir", "value": "us_m2a4" },
+        { "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 1000 } },
+        { "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 500 } },
+        { "op": "setParam", "path": [], "name": "economicRank", "value": { "type": "int", "value": 1 } },
+        { "op": "setParam", "path": [], "name": "economicRankArcade", "value": { "type": "int", "value": 1 } },
+        { "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 1 } },
+        { "op": "setParam", "path": [], "name": "economicRankSimulation", "value": { "type": "int", "value": 1 } }
+      ]
+    }
+  ]
+}
+
③ Tech-Tree Slot Patch client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc
+

Insert us_m2a4_mod_demo into country_usa -> army -> range[0] right after us_m3a1_stuart (just before the us_m5a1_stuart Rank II break) with an explicit reqAir: "us_m2a4", creating a clean Rank I side-branch arrow from M2A4 without disturbing the stock Stuart chain:

+
jsonc
{
+  "ops": [
+    {
+      "op": "addBlock",
+      "path": ["country_usa", "army", "range[0]"],
+      "name": "us_m2a4_mod_demo",
+      "after": "us_m3a1_stuart",
+      "block": {
+        "params": [
+          { "name": "rank", "value": { "type": "int", "value": 1 } },
+          { "name": "reqAir", "value": "us_m2a4" }
+        ]
+      }
+    }
+  ]
+}
+
④ Unit Tags & Test-Drive Patch client/packs/char.vromfs.bin/config/unittags.blk.patch.jsonc
+

Clone us_m2a4 in unittags.blk so the new ID inherits type:t="tank", hangar_place:t="tank", the ground testFlight mission, and light-tank tags:

+
jsonc
{
+  "ops": [
+    {
+      "op": "cloneBlock",
+      "from": ["us_m2a4"],
+      "toParent": [],
+      "newName": "us_m2a4_mod_demo",
+      "replaceExisting": true
+    }
+  ]
+}
+
⑤ Localization Patch client/packs/lang.vromfs.bin/lang/units.csv.patch.csv
+

Copy the 4-row CSV snippet from Section 6.2 above. Enable the mod in the launcher, start the game, open the US Ground Rank I tree, and right-click M2A4 (Mod Demo) › Test Drive to take your 90 km/h light tank for a spin!

+
+
+ ← 上一章← Previous01 · 快速入门与清单规范01 · Quick Start & Manifest + +
+ - -
-

- 7. 内置官方模板、排错日志与 5 条黄金习惯 - 7. Bundled Templates, Logs & Best Practices -

-

- 启动器首次初始化模组目录时会自动分发 3 套官方模板(默认关闭,勾选即用),可直接对照学习: - Three official templates are seeded into a fresh mods folder on first launch (disabled by default) as runnable references: -

-
- - - - - - - - - - - - -
模板Template演示能力Demonstrates
example-vehicle-tweak零代码数据与本地化:battle.jsonc + wpcost.blk.patch.jsonc + units.csv.patch.csv。Code-free data & localization: battle.jsonc + wpcost.blk.patch.jsonc + units.csv.patch.csv.
example-server-script最小服务端脚本:onDatasetsLoaded、profile.onRefresh、独立存档与自定义 HTTP 路由。Minimal server script: onDatasetsLoaded, profile.onRefresh, isolated storage, and custom HTTP route.
official-map-selector完整全栈官方模组:UI 入口补丁 + 原生 DaGui 小地图网格弹窗 + 匹配 RPC + 独立存储 + battle.onFilterMissions 选图。Full-stack official mod: UI button patch + native DaGui map grid modal + matching RPC + storage + battle.onFilterMissions.
+
+
+

03 · 添加全新 3D 模型与贴图载具

+

本章专门讲解如何在 WTOffline 中制作带自定义 3D 模型(.grp)和贴图包(.dxp.bin)的全新载具模组,让多款不同作者的新车模组同时叠加共存、跨盘零拷贝秒挂、关闭即还原。

+
+

1. 核心术语通俗说明与跨盘零拷贝机制

+

在接触 3D 载具模组时,你会遇到以下 4 个高频底层名词——其实它们非常直观:

+
名词 / 后缀通俗解释
.grpDagor 引擎的 3D 模型与骨架归档文件(由官方 War Thunder CDK AssetViewer / 导出器编译生成),内含多级细节网格(LOD)、骨骼动画节点(animChar)、碰撞体与内构损伤模块(DM)几何体。
.dxp.binDagor 引擎的批量压缩贴图包,把一辆或多辆载具用到的多张漫反射、法线、金属度贴图打包在同一个文件里供 .grp 材质按名索引。
.ddsx单张 Dagor 压缩贴图文件(DDSx),常用于 UI 资料卡载具立绘(如 ui/images.vromfs.bin/units/<载具id>.ddsx)或涂装单贴图。
NTFS 目录联接点(Junction)可以理解成 Windows 文件系统底层的“零拷贝文件夹快捷方式”:游戏引擎访问 <游戏副本>/content/pkg_user/<模组ID> 时,操作系统直接把读写透明指向你放在任意盘符 mods/ 里的源文件夹——无需管理员权限、跨盘可用、占用 0 字节额外硬盘空间、挂载和拆除只需约 1 毫秒!
+

引擎是如何自动发现 client/addon/ 的?

+

经对 2.61.0.x 客户端 aces.exe 与 aces.vromfs.bin/config/settings.blk 核实:

+
  • 构建器会自动把所有已启用模组的挂载路径注册进 config/settings.blk 的 addons、addons_no_check 与 addonsWithBasePath 三个列表;
  • 凡是路径位于 /pkg_user/ 下的扩展目录(默认挂载到 <游戏副本>/content/pkg_user/<安全模组ID>),引擎会自动跳过 res/grp_hdr.vromfs.bin 包头强制校验,直接扫描 <目录>/res/ 下的全部 .grp 模型与 .dxp.bin 贴图包并注册进全局资源管理器;
  • 如果你的模组附带了正式 CDK 编译生成的 res/grp_hdr.vromfs.bin,构建器会自动改挂到 <游戏副本>/content/pkg_wto_<安全模组ID>,交给引擎原生的 grp_hdr 加载器处理;
  • 关闭模组时启动器只拆除该目录联接点本身,不会删改 mods/ 里的源文件。
+
+

2. 添加一辆全新 3D 模型载具的 6 步清单

+

假设你的模组 ID 是 demo.new-mbt,新车内部 ID 叫 us_mbt_demo:

+
text
mods/demo-new-mbt/
+├─ mod.jsonc
+└─ client/
+   ├─ addon/
+   │  └─ res/
+   │     ├─ us_mbt_demo.grp                # ① 3D 模型、骨架、碰撞体(CDK 导出)
+   │     └─ us_mbt_demo.dxp.bin            # ① 压缩贴图包(DDSx)
+   └─ packs/
+      ├─ aces.vromfs.bin/
+      │  └─ gamedata/units/tankmodels/
+      │     └─ us_mbt_demo.blk             # ② 载具物理、装甲、炮塔、武器配置(文本 BLK 自动编译)
+      ├─ char.vromfs.bin/
+      │  └─ config/
+      │     ├─ wpcost.blk.patch.jsonc      # ③ 价格、研发点、权重、改装件(用 cloneBlock 最快)
+      │     ├─ shop.blk.patch.jsonc        # ④ 挂进对应国家科技树纵列位置
+      │     └─ unittags.blk.patch.jsonc    # ④ 注册载具类型、机库车位、试车场与标签
+      ├─ lang.vromfs.bin/
+      │  └─ lang/
+      │     └─ units.csv.patch.csv         # ⑤ 中英文名称(_shop、_0、_1、_2)
+      ├─ ui/atlases.vromfs.bin/
+      │  └─ gameuiskin/
+      │     └─ us_mbt_demo_ico.svg         # ⑥ 科技树与本地商城剪影图标(文件名必须全小写)
+      └─ ui/images.vromfs.bin/
+         └─ units/
+            └─ us_mbt_demo.ddsx            # ⑥ 资料卡/乘员栏载具大图(可选,缺失时自动回退占位图)
+

关键核对要点

+
  1. 保持三处载具内部 ID 完全一致:tankmodels/us_mbt_demo.blk 文件名(或空军 flightmodels/us_jet_demo.blk)、wpcost.blk 块名、shop.blk 块名与 unittags.blk 块名必须一字不差。
  2. ui/atlases.vromfs.bin 图标路径必须全小写:原版图标包内部键名统一为全小写,请命名为 gameuiskin/<全小写载具id>_ico.svg(本地网页商店的商品卡片也会自动读取这张 SVG 图标!)。
  3. 验证 .blk 里的模型资产名与 .grp 一致:gamedata/units/tankmodels/us_mbt_demo.blk 顶部的 model:t="..." 名称必须与你在 CDK 中导出 .grp 时的资产名完全一致。
+
+

3. 银狮研发车 vs gift 商城礼包车(以及 AI 机器人池准入规则)

+

在 wpcost.blk.patch.jsonc 和 shop.blk.patch.jsonc 中,你可以自由决定这辆新车是走常规银狮研发线还是走本地网页商城礼包:

+

方式 A:常规银狮科技树研发车(推荐希望 AI 也能开这辆车出战时使用)

+
  • 在 wpcost.blk 中设置常规 value(银狮售价)与 reqExp(研发点),不要设置 gift、premPackAir、costGold、event 或 researchType(联队车标记),也不要在 shop.blk 设置 showOnlyWhenBought:b=yes;
  • 自动进入对局 AI 机器人池:本地服务器的分房机器人选择器(battle-ranks.ts)会自动把已挂入科技树(shop.blk)且不含 gift、premPackAir、event、researchType、showOnlyWhenBought 标记的常规银狮科技树载具纳入对应国家与分房权重的 AI 出战池!这意味着你在单机对局里也能遇到驾驶你自制新车的友军和敌军 AI。
+

方式 B:本地网页商城礼包车(gift:t="msi_notebook")

+

很多模组作者在翻看原版 wpcost.blk / shop.blk 时会好奇:为什么满地都是 gift:t="msi_notebook"?

+
  • 在原版战雷中,只要载具块带有任意非空的 gift:t="..." 字符串(官方历史遗留常填 "msi_notebook" 等推广代号),客户端就会把该车识别为“需通过商店礼包购买解锁的礼品车”,点击「购买」按钮时会拉起商店页面而非扣除银狮/金鹰;
  • WTOffline 自动生成本地商店商品:构建器扫描 wpcost.blk 时,会自动为每一辆带 gift 参数的载具注册确定性的本地商城商品 ID wto_pack_<载具ID>(例如 wto_pack_us_mbt_demo)与对应 GUID: +
    • 哪怕你一行服务端配置都不写,本地网页商店也会按该车的 rank 等级自动套用默认档位定价与金鹰/高账赠品,玩家点开游戏内置商店就能直接购买解锁!
    • 如果想给它单独定 GJN 售价和附赠金鹰/高账天数,只需在 server/tuning/store.jsonc 的 vehiclePacks.byVehicle 下加一行即可(详见第 05 章)。
  • 注意 AI 机器人池边界:带 gift、premPackAir、event、researchType 或 showOnlyWhenBought 标记的特殊载具不会自动混入常规 AI 机器人池,避免稀有礼包原型车在普通对局满街跑。
+
+

4. 配套涂装、瞄具、音效与原生目录的边界

+
  • 独立涂装 / 瞄具 / 单人任务:玩家照旧直接放进游戏目录原生的 UserSkins/、UserSights/、UserMissions/ 即可,启动器完全不会干预或清理这些原生文件夹,无需封装成模组;
  • 大型新车整合包顺带附赠的配套资源:如果你的新车模组配套做好了专属涂装、现代火控瞄具或专属火炮音效包,可以放进 client/files/ 随模组一起启停: +
    • client/files/UserSkins/mod_us_mbt_demo_camo/...(单模组独占子目录 → 自动走跨盘 NTFS Junction 零拷贝秒挂)
    • client/files/UserSights/us_mbt_demo/...(单模组独占子目录 → 自动走跨盘 NTFS Junction 零拷贝秒挂)
    • client/files/sound/mod/my_cannon.bank(多模组共享的平铺目录散文件 → 依次尝试文件符号链接 → 同盘硬链接 → 按大小与修改时间比对的增量缓存复制)
  • 玩家原生文件保护:如果 client/files/ 中的目标路径在游戏目录里已经作为玩家手动放置的原生文件/文件夹存在,启动器会自动跳过该项并在日志中输出冲突告警,不会覆盖或删除玩家的自有文件。
-

排错与 5 条黄金习惯Troubleshooting & 5 Golden Rules

-
    -
  • 查日志位置:启动器「设置 → 诊断 → 打开日志目录」查看 launcher.log(搜索 [build]、[mods]、[mod:<id>]),客户端界面/模型报错看 .game_logs/*.clog。Logs: Open the log folder in Launcher Settings → Diagnostics for launcher.log ([build], [mods], [mod:<id>]) and check .game_logs/*.clog for client UI/model issues.
  • -
  • 命名空间隔离:ID、载具名、涂装目录与自定义 RPC 一律带专属前缀;公共表永远用增量补丁,绝不整文件覆写。Namespace everything: Prefix IDs, units, asset folders, and custom RPCs; always patch shared tables incrementally.
  • -
  • 发布前完整回归:做一次「开启 → 游玩 → 关闭 → 重启」循环,确保卸载后客户端与主存档干干净净。Test the full toggle loop: Enable → play → disable → restart to verify clean restoration.
  • -
+
+

03 · Adding Custom 3D Vehicle Models & Textures

+

This chapter explains how to build brand-new 3D vehicle mods shipping custom geometry (.grp) and texture packs (.dxp.bin) in WTOffline so multiple vehicle packs from different authors stack cleanly, mount across drives with zero copying, and roll back cleanly when disabled.

+
+

1. Plain-Language Asset Glossary & Zero-Copy Mounting

+

When working with 3D vehicle mods, you will encounter four core asset and filesystem terms:

+
Term / ExtensionPlain-Language Meaning
.grpDagor Engine 3D geometry & skeleton archive (exported from the official War Thunder CDK AssetViewer / exporter), containing multi-LOD meshes, animation skeleton nodes (animChar), collision volumes, and internal damage-model (DM) parts.
.dxp.binDagor Engine compressed texture pack, bundling multiple diffuse, normal, and metallic/roughness DDSx textures referenced by name inside .grp materials.
.ddsxA single Dagor compressed texture file (DDSx), commonly used for UI stat-card vehicle portraits (ui/images.vromfs.bin/units/<unit_id>.ddsx) or standalone skin textures.
NTFS Directory JunctionThink of it as an OS-level zero-copy folder shortcut built into Windows NTFS: when the game engine opens <copy>/content/pkg_user/<modId>, Windows transparently serves the files straight from your mods/ folder on any drive—no administrator rights needed, works across drives, consumes 0 extra disk bytes, and mounts/unmounts in ~1 ms!
+

How the Engine Discovers client/addon/ Automatically

+

Verified directly against 2.61.0.x aces.exe (dlContent.cpp) and aces.vromfs.bin/config/settings.blk:

+
  • The patcher automatically registers every enabled mod's addon mount path into addons, addons_no_check, and addonsWithBasePath inside config/settings.blk;
  • Any addon path under /pkg_user/ (mounted by default at <copy>/content/pkg_user/<safeModId>) skips the mandatory res/grp_hdr.vromfs.bin header check and directly scans <addon>/res/ for all .grp model and .dxp.bin texture archives, registering them into the global asset manager;
  • If your mod ships an official CDK-compiled res/grp_hdr.vromfs.bin, the patcher mounts it at <copy>/content/pkg_wto_<safeModId> so the native grp_hdr loader handles it;
  • Disabling a mod removes only the directory junction itself and never deletes or modifies your source files inside mods/.
+
+

2. 6-Step Checklist for a Custom 3D Vehicle

+

Suppose your mod ID is demo.new-mbt and your new vehicle's internal ID is us_mbt_demo:

+
text
mods/demo-new-mbt/
+├─ mod.jsonc
+└─ client/
+   ├─ addon/
+   │  └─ res/
+   │     ├─ us_mbt_demo.grp                # ① 3D meshes, skeleton & collision (CDK export)
+   │     └─ us_mbt_demo.dxp.bin            # ① Compressed texture pack (DDSx)
+   └─ packs/
+      ├─ aces.vromfs.bin/
+      │  └─ gamedata/units/tankmodels/
+      │     └─ us_mbt_demo.blk             # ② Physics, armor, turret & weapons (text BLK compiles automatically)
+      ├─ char.vromfs.bin/
+      │  └─ config/
+      │     ├─ wpcost.blk.patch.jsonc      # ③ Price, RP, BR & modifications (fastest via cloneBlock)
+      │     ├─ shop.blk.patch.jsonc        # ④ Tech-tree column & position
+      │     └─ unittags.blk.patch.jsonc    # ④ Unit class, hangar slot, test-drive mission & tags
+      ├─ lang.vromfs.bin/
+      │  └─ lang/
+      │     └─ units.csv.patch.csv         # ⑤ Localized names (_shop, _0, _1, _2)
+      ├─ ui/atlases.vromfs.bin/
+      │  └─ gameuiskin/
+      │     └─ us_mbt_demo_ico.svg         # ⑥ Tech-tree & local web store silhouette icon (all lowercase!)
+      └─ ui/images.vromfs.bin/
+         └─ units/
+            └─ us_mbt_demo.ddsx            # ⑥ Stat-card / crew-slot portrait (optional; falls back to placeholder)
+

Key Verification Checks

+
  1. Keep the vehicle's internal ID identical everywhere: the tankmodels/us_mbt_demo.blk filename (or flightmodels/us_jet_demo.blk for aircraft) and the block names in wpcost.blk, shop.blk, and unittags.blk must match character for character.
  2. ui/atlases.vromfs.bin icon paths must be all lowercase: stock icon packs store paths in lowercase, so name your icon gameuiskin/<lowercase_unit_id>_ico.svg (the local web store also displays this exact SVG on pack cards!).
  3. Match .blk asset names to .grp exports: model:t="..." inside gamedata/units/tankmodels/us_mbt_demo.blk must match the exact asset name exported into your .grp archive from the CDK.
+
+

3. Regular Tech-Tree Vehicles vs gift Store Packs (& AI Bot Pool Rules)

+

In wpcost.blk.patch.jsonc and shop.blk.patch.jsonc, you can wire your custom vehicle either as a regular Silver Lions researchable vehicle or as a local web store pack vehicle:

+ +
  • Set normal value (Silver Lions price) and reqExp (Research Points) in wpcost.blk, and omit gift, premPackAir, costGold, event, and researchType (squadron tag), as well as showOnlyWhenBought:b=yes in shop.blk;
  • Automatically joins the AI bot pool: the local server's matchmaking bot selector (battle-ranks.ts) automatically includes tech-tree vehicles (inTechTree in shop.blk) that have none of gift, premPackAir, event, researchType, or showOnlyWhenBought! Both friendly and enemy AI bots at matching BRs and nations will spawn in your custom vehicle during offline battles.
+

Option B: Local Web Store Pack Vehicle (gift:t="msi_notebook")

+

Modders inspecting stock wpcost.blk / shop.blk often wonder: why do dozens of pack vehicles say gift:t="msi_notebook"?

+
  • In stock War Thunder, any non-empty gift:t="..." string (Gaijin historically reused promo strings like "msi_notebook" across countless store vehicles) marks the vehicle as an external store pack/gift unit whose Order button opens the web store instead of spending Silver Lions or Golden Eagles;
  • WTOffline auto-generates a local web store bundle: during copy building, WTOffline scans every vehicle carrying gift in wpcost.blk and automatically registers a deterministic local store product ID wto_pack_<unitId> (e.g. wto_pack_us_mbt_demo) and bundle GUID: +
    • Even with zero server config, the local web store automatically prices the pack using vehiclePacks.byRank for the vehicle's rank tier so players can buy and unlock it right away in the in-game store!
    • To customize its GJN price, Golden Eagles bonus, or Premium days, simply add an entry under vehiclePacks.byVehicle in server/tuning/store.jsonc (see Chapter 05).
  • AI Bot Pool Note: vehicles carrying gift, premPackAir, event, researchType, or showOnlyWhenBought are intentionally excluded from the automatic AI bot pool so rare pack prototypes do not flood standard bot lineups.
+
+

4. Companion Skins, Sights, Sounds & the Native Folder Boundary

+
  • Standalone skins, sights & single-player missions: players should continue placing standalone files directly into the game's native UserSkins/, UserSights/, and UserMissions/ folders—the launcher never touches or deletes player-managed native folders, and they do not need to be wrapped as mods;
  • Companion assets bundled inside a large vehicle overhaul mod: if your custom vehicle mod includes dedicated camouflages, custom FCS gun sights, or custom cannon sound banks, place them under client/files/ so they mount and unmount together with the mod: +
    • client/files/UserSkins/mod_us_mbt_demo_camo/... (mod-exclusive subfolder → mounts across drives via zero-copy NTFS Junction)
    • client/files/UserSights/us_mbt_demo/... (mod-exclusive subfolder → mounts across drives via zero-copy NTFS Junction)
    • client/files/sound/mod/my_cannon.bank (shared flat directory file → tries file symlink → same-drive hardlink → size/mtime incremental cached copy)
  • Native Player File Protection: if any target path under client/files/ already exists in the game folder as a player-created native file or folder, the launcher skips that item with a log warning and never overwrites or deletes player content.
+
+ +
+ +
+
+

04 · 客户端 GUI 补丁与声明式 EXE 补丁

+

实验期提示:界面脚本补丁(gui-patches)与声明式 exe 补丁(exe-patches)直接依赖目标游戏客户端的代码结构,游戏版本更新或离线核心补丁演进时可能需要同步维护。

+
+

1. 先懂概念:战雷原生 DaGui 界面三件套(.tpl + .css + .nut)

+

《战争雷霆》机库与大厅界面由 Dagor 自研的 DaGui 框架驱动(全部存放在 gui.vromfs.bin 包内)。一个完整的界面弹窗通常由三类文本文件配合完成:

+
文件后缀角色定位通俗解释
.tplHandyman 布局模板类似 HTML + Mustache 模板(如 gui/missions/wtomapselectormodal.tpl),声明窗口骨架、按钮节点、id 与数据占位符(如 <<wndTitle>>、{{#cards}}...{{/cards}})。
.cssDaGui 样式表定义节点宽高、边距、背景色、字体大小以及自定义状态属性选择器(如 [wtoSelected=yes])。
.nutQuirrel 界面逻辑脚本战雷使用的类 JS/Lua 强作用域脚本语言(Squirrel 衍生版),继承 BaseGuiHandlerWT 处理按钮点击、渲染 .tpl 并与本地服务器通信。
+

客户端界面扩展黄金准则:「大块逻辑独立新建 + 极简增量补丁挂入口」

+

像官方模板 templates/official-map-selector 一样,给游戏做新功能界面的最佳做法是:

+
  1. 把你自己的弹窗 .nut、.tpl、.css 作为新文件放进 client/packs/gui.vromfs.bin/:独立文件与其他模组零冲突、极易维护;
  2. 只用几行 client/gui-patches/ 增量补丁修改原版文件:挂一个入口按钮,并在全局样式表入口 gui/css.css 里注册你的新 .css!
+

必看高频踩坑:新增的独立 .css 不会被 DaGui 自动加载!
仅仅把 gui/missions/wtomapselector.css 放进 client/packs/gui.vromfs.bin/ 是不会生效的!DaGui 只从根入口 gui/css.css 加载样式表,因此你必须同时在 client/gui-patches/ 里给 gui/css.css 打一条补丁,追加一行 @import "missions\wtomapselector.css"(注意:DaGui 的 gui/css.css 路径相对于 gui/ 目录,使用反斜杠 \ 且行尾不写分号,详见下方 2.2 节真实示例)。

+
+

2. client/gui-patches/ 增量补丁格式与匹配规则

+

client/gui-patches/ 不仅能改 .nut 脚本,对 gui.vromfs.bin 里的 .nut、.tpl 和 .css 文本文件完全通用!每个补丁放在一个含 patch.jsonc 的子目录(支持多层子目录组织):

+
text
client/gui-patches/
+└─ mode-select-map-selector-button/
+   ├─ css/
+   │  ├─ patch.jsonc
+   │  ├─ find-css.css
+   │  └─ replace-css.css
+   ├─ tpl/
+   │  ├─ patch.jsonc
+   │  ├─ find-nav-right.tpl
+   │  └─ replace-nav-right.tpl
+   └─ script/
+      ├─ patch.jsonc
+      ├─ find-imports.nut
+      ├─ replace-imports.nut
+      ├─ find-buttons.nut
+      └─ replace-buttons.nut
+

2.1 .nut 脚本补丁示例

+
jsonc
// Adds a custom entry button to the mode selection panel.
+{
+  "id": "my-mod/add-button",
+  "title": "Add custom button to mode selector",
+  "features": [],
+  "variants": [
+    {
+      "written_for": "2.61.0.58",
+      "file": "scripts/gamemodes/gamemodeselect.nut",
+      "edits": [
+        {
+          "find": "find-imports.nut",
+          "replace": "replace-imports.nut"
+        },
+        {
+          "find": "find-buttons.nut",
+          "replace": "replace-buttons.nut"
+        }
+      ]
+    }
+  ]
+}
+

2.2 注册独立 .css 到 gui/css.css 的真实补丁示例

+
jsonc
// client/gui-patches/my-style/patch.jsonc
+{
+  "id": "my-mod/register-css",
+  "title": "Include custom stylesheet in gui/css.css",
+  "features": [],
+  "variants": [
+    {
+      "written_for": "2.61.0.58",
+      "file": "gui/css.css",
+      "edits": [
+        {
+          "find": "find-css.css",
+          "replace": "replace-css.css"
+        }
+      ]
+    }
+  ]
+}
+

find-css.css:

+
css
@import "missions\mapPreferences.css"
+

replace-css.css:

+
css
@import "missions\mapPreferences.css"
+@import "missions\wtomapselector.css"
+

2.3 匹配规则与大小写注意事项

+
  1. variant.file 必须全小写、精确区分大小写! 原版 gui.vromfs.bin 归档内的所有文件路径均为全小写(例如 scripts/gamemodes/gamemodeselect.nut、gui/gamemodeselect/gamemodeselect.tpl、gui/css.css)。虽然 Quirrel 代码里的 from "%scripts/gameModes/..." 导入语句不区分大小写,但 gui-patches 构建器在包内查找 variant.file 时做的是严格区分大小写的精确键匹配——如果写成驼峰 scripts/gameModes/gameModeSelect.nut,会直接报错 the data pack has no script ...!放进 client/packs/gui.vromfs.bin/ 的新增文件也请统一使用全小写路径。
  2. 每条 find 必须唯一命中 1 次: 每条 edit 的 find 原文片段在目标文件中需要恰好出现 1 次(自动兼容 \r\n 与 \n 换行差异);若出现 0 次或 ≥2 次,该补丁会整条跳过并记入 launcher.log,避免半应用写坏脚本。
  3. variants 与 written_for 的真实选择机制: written_for 只是便于阅读和报错排查的版本标注字符串,构建器不会按版本号盲选——它会对当前客户端文件逐一测试 variants 数组里的全部候选条目,且要求有且仅有 1 个 variant 能够完整命中(0 个命中 = 视为版本不匹配安全跳过;≥2 个同时命中 = 视为变体定义歧义直接拒绝)。
  4. 本地服务器地址占位符 {{LOCAL_ENDPOINT}}: 在任何 replace 文本中写入 {{LOCAL_ENDPOINT}},构建器都会自动将其替换为当前客户端绑定的本地服务器 127.0.0.1:<端口>(例如拼接内置浏览器 URL http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel)。离线版核心 GUI 补丁永远最先应用,各模组的 gui-patches 在其后按加载顺序依次叠加。
+
+

3. 必做检查:编译 sq.exe 并对完整 .nut 做字节码校验

+

战雷的 Quirrel 脚本在登录阶段预编译加载。如果 .nut 存在以下错误,游戏会在进入机库前一直卡死在「正在加载」界面:

+
  • 词法作用域重名冲突:局部变量名(let / local)与文件顶部 from "..." import * 导入的常量或原生函数重名;
  • 前向引用未声明函数或误用 Quirrel 保留字(如 base);
  • 误用反引号字符串 ` ... **:战雷内置 Quirrel VM 不支持 JS 风格反引号模板字符串,请统一使用 Quirrel 原生插值字符串 **$"hello {name}"`!
+

注意:sq.exe --syntax-check 只跑语法树解析,会漏掉作用域重名和未声明标识符错误;必须通过 compilestring(...) 触发完整字节码生成检查!

+

3.1 外部模组作者如何自行获取匹配的 sq.exe?

+

克隆 Gaijin 官方开源的 GaijinEntertainment/quirrel 仓库,检出与 2.61 客户端匹配的提交 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe,用 CMake + Visual Studio(C++17)即可在数秒内编译出 sq.exe:

+
powershell
git clone https://github.com/GaijinEntertainment/quirrel.git quirrel-src
+git -C quirrel-src checkout 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
+cmake -S quirrel-src -B quirrel-build
+cmake --build quirrel-build --config Release --target sq
+# 产物位于 quirrel-build\bin\Release\sq.exe
+

3.2 正确用法:必须对「完整 .nut 文件」执行 compilestring

+

切勿拿半截 replace.nut 片段直接喂给 compilestring!
replace.nut 只是补丁上下文中的几行代码片段,单独编译必然报语法或未定义变量错误。你必须针对完整的 .nut 文件(即你新建的独立 .nut 全文,或者将 find/replace 应用到原版 .nut 之后的完整结果文件)运行检查:

+
  • 如果克隆了 WTOffline 源码仓库:仓库内的 tools/src/wtotools/gui_check.py 已经封装好全自动导入符号解析与 compilestring 沙箱,可一键对解包的 gui.vromfs.bin 应用补丁并完成全量字节码校验;
  • 单文件快速自检示例(将文件内顶部 import 绑定名作为第 3 参数占位表传入 compilestring):
+
powershell
& "quirrel-build\bin\Release\sq.exe" -e "let io = require('io'); let f = io.file('your_complete_script.nut', 'rb'); let src = f.readblob(f.len()).as_string(); f.close(); compilestring(src, 'your_complete_script.nut'); print('OK\n')"
+
+

4. 声明式 exe 补丁(client/exe-patches/)

+

高级模组可以直接复用 WTOffline 本体的 @wto/exepatch 引擎对 win64/aces.exe 做特征码定位补丁。请使用声明式补丁文件,不要直接打包或分发修改后的 aces.exe 可执行文件。

+
text
client/exe-patches/
+└─ my-tweak/
+   └─ patch.jsonc
+

patch.jsonc 结构示例:

+
jsonc
// Brief description of what this binary patch changes.
+// Why the local server cannot do this alone.
+// What happens if this patch is skipped.
+{
+  "id": "my-tweak",
+  "title": "Example declarative exe patch",
+  "features": [],
+  "requires": [],
+  "variants": [
+    {
+      "written_for": "2.61.0.58",
+      "locate": {
+        "kind": "signature",
+        "pattern": "48 8B ?? ?? ?? ?? ?? 84 C0 74 ??",
+        "captures": []
+      },
+      "edit": {
+        "offset": 9,
+        "asm": "nop; nop",
+        "bytes": "90 90",
+        "expect_original": "74 ??",
+        "fixups": []
+      }
+    }
+  ]
+}
+

支持的 3 种定位器(locate.kind)

+
  • signature:字节特征码扫描(支持 ?? 通配字节与 captures 捕获相对偏移/跳转目标);
  • string_ref:按代码引用的固定 ASCII 字符串定位,可附加局部指令特征校验;
  • within:在依赖补丁或锚点所在的函数边界(基于 PE .pdata 异常表起止范围)内搜索局部特征。
+

核心隔离保护与冲突处理

+
  1. 核心离线与隔离补丁永远最先规划并锁定字节区间(涵盖断网隔离不连 Gaijin、不加载反作弊、存档目录与注册表隔离、禁止拉起官方启动器、本地 TLS/匹配公钥替换等);
  2. 任何模组 exe 补丁只要写入范围与核心补丁重叠 1 个字节,就会被构建器硬拒绝,并在日志中报错 overlaps protected core patch;
  3. 若两个不同模组的 exe 补丁写入同一段字节,后加载的补丁会被拒绝并明确报出冲突模组 ID;
  4. 若客户端更新后特征码未命中或 expect_original 不匹配,该模组补丁会安全跳过并记入 launcher.log,不会导致离线副本构建崩溃。
+
+
+

04 · Client GUI Patches & Declarative EXE Patches

+

Experimental Notice: GUI script patches (gui-patches) and declarative exe patches (exe-patches) depend directly on target client code layout and may require maintenance when the game or core offline patches update.

+
+

1. Plain-Language Intro: War Thunder's DaGui UI Triad (.tpl + .css + .nut)

+

War Thunder's hangar and lobby screens are powered by Dagor's native DaGui framework (packaged inside gui.vromfs.bin). Every screen or modal window combines three plain-text file types:

+
ExtensionRolePlain-Language Explanation
.tplHandyman Layout TemplateSimilar to HTML + Mustache (e.g. gui/missions/wtomapselectormodal.tpl); declares UI containers, buttons, element ids, and data-binding tags (<<wndTitle>>, {{#cards}}...{{/cards}}).
.cssDaGui StylesheetControls widths, heights, margins, colors, fonts, and custom attribute state selectors (such as [wtoSelected=yes]).
.nutQuirrel UI ScriptWar Thunder's statically-scoped scripting language (derived from Squirrel); subclasses BaseGuiHandlerWT to render .tpl views, handle button clicks, and call local server RPCs.
+

Best-Practice UI Pattern: "Standalone Files for Logic + Minimal Patch for Entry Hook"

+

Just like the bundled templates/official-map-selector mod, the cleanest way to add new UI is:

+
  1. Place your new standalone .nut, .tpl, and .css files under client/packs/gui.vromfs.bin/: standalone files have zero collision risk with other mods and survive game updates cleanly;
  2. Use minimal client/gui-patches/ edits on stock files: wire a button into an existing screen and register your stylesheet in gui/css.css!
+

Critical Rule: Standalone .css Files Are NOT Auto-Loaded by DaGui!
Dropping gui/missions/wtomapselector.css into client/packs/gui.vromfs.bin/ alone has no effect! DaGui loads stylesheets solely through the root manifest gui/css.css, so you must also patch gui/css.css via client/gui-patches/ to append @import "missions\wtomapselector.css" (note: paths inside gui/css.css are relative to gui/, use backslashes \, and have no trailing semicolon—see the real example in Section 2.2 below).

+
+

2. client/gui-patches/ Format & Matching Rules

+

client/gui-patches/ is not limited to .nut files—it works identically on .nut scripts, .tpl templates, and .css stylesheets inside gui.vromfs.bin! Each patch lives in a folder containing patch.jsonc (nested subdirectories are supported):

+
text
client/gui-patches/
+└─ mode-select-map-selector-button/
+   ├─ css/
+   │  ├─ patch.jsonc
+   │  ├─ find-css.css
+   │  └─ replace-css.css
+   ├─ tpl/
+   │  ├─ patch.jsonc
+   │  ├─ find-nav-right.tpl
+   │  └─ replace-nav-right.tpl
+   └─ script/
+      ├─ patch.jsonc
+      ├─ find-imports.nut
+      ├─ replace-imports.nut
+      ├─ find-buttons.nut
+      └─ replace-buttons.nut
+

2.1 .nut Script Patch Example

+
jsonc
// Adds a custom entry button to the mode selection panel.
+{
+  "id": "my-mod/add-button",
+  "title": "Add custom button to mode selector",
+  "features": [],
+  "variants": [
+    {
+      "written_for": "2.61.0.58",
+      "file": "scripts/gamemodes/gamemodeselect.nut",
+      "edits": [
+        {
+          "find": "find-imports.nut",
+          "replace": "replace-imports.nut"
+        },
+        {
+          "find": "find-buttons.nut",
+          "replace": "replace-buttons.nut"
+        }
+      ]
+    }
+  ]
+}
+

2.2 Real Example: Registering a Standalone .css in gui/css.css

+
jsonc
// client/gui-patches/my-style/patch.jsonc
+{
+  "id": "my-mod/register-css",
+  "title": "Include custom stylesheet in gui/css.css",
+  "features": [],
+  "variants": [
+    {
+      "written_for": "2.61.0.58",
+      "file": "gui/css.css",
+      "edits": [
+        {
+          "find": "find-css.css",
+          "replace": "replace-css.css"
+        }
+      ]
+    }
+  ]
+}
+

find-css.css:

+
css
@import "missions\mapPreferences.css"
+

replace-css.css:

+
css
@import "missions\mapPreferences.css"
+@import "missions\wtomapselector.css"
+

2.3 Four Critical Path & Variant Rules (Must-Read)

+
  1. variant.file Must Be All Lowercase & Exact Case-Sensitive! Every file path inside stock gui.vromfs.bin is all lowercase (e.g. scripts/gamemodes/gamemodeselect.nut, gui/gamemodeselect/gamemodeselect.tpl, gui/css.css). Even though Quirrel from "%scripts/gameModes/..." imports are case-insensitive at runtime, the gui-patches builder looks up variant.file in the archive map via exact case-sensitive string match—writing camelCase like scripts/gameModes/gameModeSelect.nut fails immediately with the data pack has no script ...! Keep added files under client/packs/gui.vromfs.bin/ all lowercase as well.
  2. Every find Snippet Must Match Exactly Once: Each edit's find text must occur uniquely once in the target file (\r\n vs \n line endings are normalized automatically). If it occurs 0 times or ≥2 times, the entire patch is skipped safely and logged to launcher.log without half-applying edits.
  3. How variants and written_for Actually Work: written_for is purely an informational version label for logs and diagnostics. At build time, the builder tests all entries in variants against the client archive and requires an exact single match (1 matching variant applies; 0 matches skips safely as a build mismatch; ≥2 simultaneous matches rejects the patch as an ambiguous variant definition).
  4. {{LOCAL_ENDPOINT}} Placeholder: Any occurrence of {{LOCAL_ENDPOINT}} in replace text is automatically expanded to the client's bound local server 127.0.0.1:<port> (for example http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel for embedded browser pages). Core offline GUI patches always run first; mod gui-patches run afterward in load order.
+
+

3. Mandatory Check: Building sq.exe & Full Quirrel Bytecode Verification

+

War Thunder pre-compiles Quirrel UI scripts during login. Any of the following mistakes in a .nut file will cause the client to hang indefinitely on the "Loading" screen:

+
  • Lexical scope name collisions: declaring a let / local variable that shadows a symbol imported via from "..." import * at the top of the file;
  • Forward references to undeclared functions or accidental use of Quirrel reserved words (such as base);
  • JS-style backtick strings (` ... )**: unsupported by War Thunder's Quirrel VM—always use Quirrel's native string interpolation **$"hello {name}"` instead!
+

Note: sq.exe --syntax-check runs AST parsing only and misses lexical collisions and undeclared identifiers—you must invoke compilestring(...) so the full bytecode generator runs!

+

3.1 How External Modders Build a Matching sq.exe

+

Clone Gaijin's open-source GaijinEntertainment/quirrel repository, check out commit 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe (matching 2.61 clients), and build sq with CMake + Visual Studio (C++17):

+
powershell
git clone https://github.com/GaijinEntertainment/quirrel.git quirrel-src
+git -C quirrel-src checkout 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
+cmake -S quirrel-src -B quirrel-build
+cmake --build quirrel-build --config Release --target sq
+# Output binary: quirrel-build\bin\Release\sq.exe
+

3.2 Run compilestring on a Complete .nut File (Not a Partial Snippet)

+

Note: Pass a complete .nut file to compilestring rather than an isolated replace.nut fragment.
replace.nut is only an in-place snippet and will fail out of context. Always run compilestring against a complete .nut file—either your standalone .nut script, or the full stock .nut file after applying your find/replace edits:

+
  • If you cloned the WTOffline repo: tools/src/wtotools/gui_check.py automatically resolves gui.vromfs.bin module exports, applies your gui-patches, and runs compilestring with stub bindings across every touched file;
  • Standalone full-file check example (pass a bindings table as the 3rd argument to compilestring if your file uses top-level from "..." import ... bindings):
+
powershell
& "quirrel-build\bin\Release\sq.exe" -e "let io = require('io'); let f = io.file('your_complete_script.nut', 'rb'); let src = f.readblob(f.len()).as_string(); f.close(); compilestring(src, 'your_complete_script.nut'); print('OK\n')"
+
+

4. Declarative EXE Patches (client/exe-patches/)

+

Advanced mods can reuse WTOffline's @wto/exepatch engine to apply signature-located binary patches to win64/aces.exe. Use declarative patch files instead of packaging or distributing modified aces.exe binaries.

+
text
client/exe-patches/
+└─ my-tweak/
+   └─ patch.jsonc
+

Example patch.jsonc:

+
jsonc
// Brief description of what this binary patch changes.
+// Why the local server cannot do this alone.
+// What happens if this patch is skipped.
+{
+  "id": "my-tweak",
+  "title": "Example declarative exe patch",
+  "features": [],
+  "requires": [],
+  "variants": [
+    {
+      "written_for": "2.61.0.58",
+      "locate": {
+        "kind": "signature",
+        "pattern": "48 8B ?? ?? ?? ?? ?? 84 C0 74 ??",
+        "captures": []
+      },
+      "edit": {
+        "offset": 9,
+        "asm": "nop; nop",
+        "bytes": "90 90",
+        "expect_original": "74 ??",
+        "fixups": []
+      }
+    }
+  ]
+}
+

Supported Locators (locate.kind)

+
  • signature: byte pattern scan supporting ?? wildcards and captures for displacements / relative branch targets;
  • string_ref: locates code referencing a fixed ASCII string literal, with optional local instruction verification;
  • within: searches inside the PE .pdata function boundaries of a required patch or anchor site.
+

Core Isolation Protection & Conflict Handling

+
  1. Core offline & isolation patches are always planned first and their byte ranges are locked (covering Gaijin network block, anti-cheat bypass in offline copy, save/registry isolation, launcher suppression, and local TLS/matching keys);
  2. Any mod exe patch overlapping even 1 byte of a core patch is hard-rejected with overlaps protected core patch in launcher.log;
  3. If two mods' exe patches write to overlapping byte ranges, the later mod's patch is rejected with the conflicting mod ID;
  4. If a signature or expect_original check fails on a newer game version, that mod patch is skipped cleanly and logged to launcher.log without breaking the offline copy build.
+
+ +
+ +
+
+

05 · 服务端零代码数值叠加(Tuning)

+

本地服务器把离线版自定的对局倍率、房间与 AI 数量、商城礼包、市场物价、战利品箱、兑换码、初始存档货币、联队等规则统一收纳在 12 份 .jsonc 配置文件中。模组作者一行代码都不用写,只需在 server/tuning/ 下放置同名 .jsonc 文件即可按字段精准叠加覆盖。

+

在线浏览全部 12 份内置默认配置文件全文与注释:
WT-Offline apps/server/tuning/ 源码目录

+
+

1. 多层合并优先级(注意启动器玩家覆盖!)

+

每次启动本地服务器时,同名的 tuning/<名称>.jsonc 按以下顺序从低到高逐层合并(后一层覆盖前一层):

+
text
1. 离线版内置默认配置(apps/server/tuning/<名称>.jsonc)
+2. 已启用模组 1 的 server/tuning/<名称>.jsonc
+3. 已启用模组 2 的 server/tuning/<名称>.jsonc
+   ...(按启动器「模组」页从上到下顺序依次叠加)
+N. 玩家在启动器「数值」页保存的个人覆盖(<客户端数据目录>/tuning/<名称>.jsonc,优先级最高)
+
  • 排查提示:由于玩家在启动器「数值(Tuning)」页手动改过的项优先级高于模组,如果测试模组时发现某个 battle.jsonc 或 new-profile.jsonc 字段修改没有生效,可以先检查该客户端的启动器「数值」页是否之前手动改过同一项(恢复默认或查看 <数据目录>/tuning/*.jsonc 即可)。
  • 所有合并后的最终结果在服务器启动时都会经过严格类型与数值范围校验;字段名写错或数值越界时会直接报出文件名、字段名与期望范围。
+
+

2. 全部 12 份可叠加配置文件一览

+
文件名管辖内容常用结构类型典型模组用途
battle.jsonc银狮/研发倍率、房间人数、AI 数量与重生次数、分房跨度 brSpreadMrank、子模式概率、攻击无人机出生分平面键值对象自定义收益倍率、调整 16v16 人数、放宽/收紧分房跨度、改 AI 重生次数
battle-economy.jsonc各类战斗行为基价与对局结算经济公式参数嵌套键值对象精细调整击杀、助攻、占点收益占比
store.jsonc金鹰包、银狮包、高账档位、以及 vehiclePacks(含 multiVehiclePacks 列表、byRank 列表、byVehicle 字典)列表($listOps)+ 字典合并为新增 gift 载具定礼包价、打包自定义多车组合包
marketplace.jsonc交易所载具券与涂装券参考价、稀有度与手续费嵌套对象 + 字典合并调整交易所物价、给新增市场载具券定价
trophies.jsonc经典战利品箱 supplyTrophies(银狮箱、老兵箱)与活动车金鹰直购价 directVehicles列表($listOps)+ 对象新增自定义银狮/金鹰抽卡箱、调整稀有车掉率权重
supply-chests.jsonc新版外部库存补给箱与奖池配置列表($listOps)+ 对象新增自制外部库存补给箱
recycling.jsonc道具回收与零件再合成配方嵌套键值对象修改道具回收比例与产出权重
redeem-codes.jsonc高账/GJN 前缀码规则与一次性固定兑换码 fixedCodes对象 + 字典合并为你的整合包添加专属福利兑换码
new-profile.jsonc新建存档初始银狮、金鹰与 GJN 余额平面键值对象制作高起点爽玩预设或硬核白手起家预设
research.jsonc自动挑选默认下一研发目标策略平面键值对象调整自动研发接续行为
clans.jsonc联队人数上限、活跃度与预置离线联队列表对象 + 列表($listOps)添加模组专属预置联队
limits.jsonc单次购买道具数量上限、战报/日志保留上限平面键值对象提高批量开箱/购买上限或历史战报条数
+
+

3. 对象字典合并 vs 列表增量语法($listOps)

+

理解合并器的两条规则,就能避免多模组互相覆盖:

+
  1. 普通对象 / 键值字典(如 vehiclePacks.byVehicle、redeem-codes.jsonc 的 fixedCodes)→ 自动按字段名递归合并: 你只需要写出新增或要改的那几个键(例如只写 "my_new_tank": { ... }),其他原有的几百个键会自动保留,不需要也不能套 $listOps!
  2. JSON 数组字段(如 vehiclePacks.multiVehiclePacks、goldenEaglePacks、supplyTrophies)→ 默认整数组替换,叠加请用 { "$listOps": [...] }: 如果你直接写 "multiVehiclePacks": [ ... ],它会把原版和前序模组的多车礼包清空替换掉!为了让多个模组安全共存,请把该数组属性写成仅包含唯一键 "$listOps" 的包装对象(注意:该对象内不能有除 "$listOps" 以外的任何其他平级字段,否则不会被识别为列表增量指令!):
+
jsonc
// 正确示例:server/tuning/store.jsonc
+// 注意:multiVehiclePacks、byRank、byVehicle 均嵌套在顶层 "vehiclePacks" 对象内部,且价格字段名为 "gjn"!
+{
+  "vehiclePacks": {
+    // ① multiVehiclePacks 是数组 → 用 { "$listOps": [...] } 无损追加/修改/删除
+    "multiVehiclePacks": {
+      "$listOps": [
+        {
+          "op": "append",
+          "items": [
+            {
+              "id": "mod_modern_duo_pack",
+              "title": { "en": "Modern Duo Pack", "zh": "现代双车组合包" },
+              "gjn": 49.99,
+              "goldenEagles": 2000,
+              "premiumDays": 15,
+              "vehicles": ["us_m1a2_sep2_abrams", "germ_leopard_2a7v"]
+            }
+          ]
+        },
+        {
+          "op": "upsertBy",
+          "key": "id",
+          "item": {
+            "id": "wto_pack_two_fronts",
+            "gjn": 19.99
+          }
+        },
+        {
+          "op": "removeBy",
+          "key": "id",
+          "value": "some_unwanted_pack_id"
+        }
+      ]
+    },
+
+    // ② byVehicle 是键值字典(非数组)→ 直接写载具 ID 即可递归合并,不要写 $listOps!
+    "byVehicle": {
+      "us_mbt_demo": {
+        "gjn": 59.99,
+        "goldenEagles": 2000,
+        "premiumDays": 15
+      }
+    }
+  }
+}
+

支持的全部 4 种 $listOps 操作

+
  • append:{ "op": "append", "items": [ ... ] } — 将 items 依次追加到当前数组末尾;
  • prepend:{ "op": "prepend", "items": [ ... ] } — 将 items 插入到当前数组开头;
  • upsertBy:{ "op": "upsertBy", "key": "<唯一键名>", "item": { ... } } — 在数组中查找 [key] === item[key] 的首项,找到则按对象递归合并局部字段,找不到则追加到末尾;
  • removeBy:{ "op": "removeBy", "key": "<键名>", "value": <匹配值> } — 删除数组中全部 [key] === value 的条目。
+
+

4. 高频配置文件真实字段速查与即用范例

+

以下字段名均已对照 apps/server/tuning/*.jsonc 与服务端校验器逐一核实,可直接复制进你的 server/tuning/:

+

4.1 battle.jsonc(对局收益、人数、分房跨度与 AI 重生)

+
jsonc
{
+  "rewardMultiplierSilverLions": 2.0,       // 银狮结算总倍率(默认 1.0)
+  "rewardMultiplierResearchPoints": 2.0,    // 研发点结算总倍率(默认 1.0)
+  "maxPlayers": 32,                         // 房间总席位(16v16 = 32:1 名本地玩家 + 最多 31 名 AI)
+  "maxBots": 31,                            // AI 机器人上限(默认 31)
+  "smallTeamsMaxPlayers": 16,               // 战术天空(small_teams_)小队空战总人数(默认 16 = 8v8)
+  "subModeChance": 0.5,                     // 同时勾选子模式与常规模式时抽中子模式的概率(0..1)
+  "brSpreadMrank": 3,                       // 分房权重浮动跨度(每 3 级 mrank = ±1.0 BR;设为 0 即严格同权重分房)
+  "botPoolLimitPerType": 80,                // 单兵种写入 customBots 的候选载具上限
+  "tankBotRespawns": 3,                     // 陆战多槽位对局每个 AI 的最大重生次数
+  "airBotRespawns": 2,                      // 空战多槽位对局每个 AI 的最大重生次数
+  "strikeUcavSpawnScore": 750,              // 陆战历史攻击无人机出生所需分数(默认 750)
+  "nuclearEscalationStrategicBombers": true // 空战核升级子模式是否启用战略核轰炸机(B-52H / Tu-95M)
+}
+

4.2 store.jsonc(本地网页商店与游戏内金鹰/银狮/礼包定价)

+
  • 顶层共 5 个字段:goldenEaglePacks(数组)、silverLionPacks(数组)、premiumForGoldenEagles(数组)、premiumForGjn(数组)、以及 vehiclePacks(对象);
  • vehiclePacks 下含 3 个子字段: +
    • multiVehiclePacks(数组,用 $listOps):每项必填 id、vehicles(非空不重复载具 ID 数组)、gjn(最低 0.01)、goldenEagles(整数 ≥0)、premiumDays(整数 ≥0),可选 silverLions(整数 ≥0),且命名方式必须三选一——自定义双语标题 "title": { "en": "...", "zh": "..." }、复用科技树折叠组名 "groupKey": "shop/group/..."、或国家新手包 "starter": true;
    • byRank(数组,按 upToRank 升序兜底单车礼包价):每项含 upToRank、gjn、goldenEagles、premiumDays(可选 silverLions);
    • byVehicle(键值字典):键为 wpcost.blk 中带 gift 的载具 ID,值为 { "gjn"?, "goldenEagles"?, "premiumDays"?, "silverLions"? }(未填字段自动回退该车 rank 对应的 byRank 档位)。
+

4.3 new-profile.jsonc(新建存档开局货币)

+
jsonc
{
+  "silverLions": 1000000, // 初始银狮(默认 150000)
+  "goldenEagles": 5000,   // 初始金鹰(默认 500)
+  "gjn": 50               // 初始 GJN 余额,支持最多两位小数(默认 0)
+}
+

4.4 redeem-codes.jsonc(添加模组专属一次性兑换码)

+

fixedCodes 是键值字典(每个存档每个兑换码限领一次,不区分大小写,未填奖励项默认为 0),直接按兑换码名合并即可:

+
jsonc
{
+  "fixedCodes": {
+    "MYMOD-GIFT-2026": {
+      "silverLions": 500000,
+      "goldenEagles": 1000,
+      "premiumDays": 7,
+      "gjn": 25
+    }
+  }
+}
+

4.5 trophies.jsonc(新增自定义银狮/金鹰战利品抽卡箱)

+

supplyTrophies 是数组,用 $listOps 追加新箱子,游戏客户端会自动按各奖品的 weight / weightTotal / weightEach 计算并展示公示掉率:

+
jsonc
{
+  "supplyTrophies": {
+    "$listOps": [
+      {
+        "op": "append",
+        "items": [
+          {
+            "id": "mod_lucky_trophy",
+            "iconStyle": "big_chest",
+            "silverLions": 100000,
+            "goldenEagles": 0,
+            "prizes": [
+              { "silverLions": 50000, "weight": 50 },
+              { "silverLions": 250000, "weight": 20 },
+              { "goldenEagles": 200, "weight": 10 },
+              { "item": "item_universal_spare", "count": 3, "weight": 15 },
+              { "eventVehicles": { "minRank": 3, "maxRank": 7, "pick": 6 }, "weightTotal": 5 }
+            ]
+          }
+        ]
+      }
+    ]
+  }
+}
+
+
+

05 · Server Code-Free Tuning Overlays

+

The local server consolidates all offline-defined battle multipliers, session/bot capacities, web store bundles, marketplace prices, trophy chests, redeem codes, starter balances, and clan rules into 12 .jsonc configuration files. Mod authors can overlay individual fields without writing a single line of code simply by placing matching .jsonc files inside server/tuning/.

+

Browse all 12 default tuning files with full comments online:
WT-Offline apps/server/tuning/ Source Directory

+
+

1. Multi-Layer Merge Precedence (Watch Out for Launcher Player Overrides!)

+

Whenever the local server starts, each tuning/<name>.jsonc file is merged from lowest to highest priority (later layers override earlier ones):

+
text
1. Shipped offline defaults (apps/server/tuning/<name>.jsonc)
+2. Enabled Mod 1's server/tuning/<name>.jsonc
+3. Enabled Mod 2's server/tuning/<name>.jsonc
+   ... (applied top-to-bottom in Launcher "Mods" load order)
+N. Player overrides saved in the Launcher "Tuning" tab (<dataFolder>/tuning/<name>.jsonc — HIGHEST PRIORITY!)
+
  • Crucial Debugging Tip: Because player overrides saved in the Launcher's "Tuning" tab take highest priority, if a field in your mod's battle.jsonc or new-profile.jsonc appears to be ignored during testing, check whether your test client has a manual override saved in the Launcher Tuning tab (<dataFolder>/tuning/*.jsonc) and reset that field to default!
  • Every merged configuration is validated strictly for types and numeric bounds at server startup; unknown keys or out-of-range numbers immediately report the exact file, key, and expected constraint.
+
+

2. All 12 Overlayable Tuning Files at a Glance

+
File NameGovernsMerge StructureTypical Mod Use Cases
battle.jsoncSL/RP multipliers, room size, AI bot count & respawns, brSpreadMrank, sub-mode chance, Strike UCAV spawn scoreFlat key-value objectCustom reward rates, 16v16 capacity tweaks, tighter/wider BR spread, bot respawn counts
battle-economy.jsoncBase action prices and battle settlement economy curvesNested key-value objectRebalance kills vs captures vs assists rewards
store.jsoncGE packs, SL packs, Premium tiers, and vehiclePacks (multiVehiclePacks list, byRank list, byVehicle map)Lists ($listOps) + map mergePrice custom gift vehicles, create custom multi-vehicle bundles
marketplace.jsoncMarketplace vehicle/skin coupon reference prices, rarity tiers & feesNested object + map mergeAdjust market economy or price custom market coupons
trophies.jsoncClassic supplyTrophies (SL chest, Veteran chest) & directVehicles GE buyout priceList ($listOps) + objectAdd custom gacha chests, tweak rare vehicle drop weights
supply-chests.jsoncExternal-inventory supply chests and drop poolsList ($listOps) + objectAdd custom external-inventory chests
recycling.jsoncItem recycling and crafting/re-roll recipesNested key-value objectCustomize item recycling ratios and output weights
redeem-codes.jsoncDynamic Premium/GJN code prefixes and one-time fixedCodesObject + map mergeAdd custom promo redeem codes for your modpack
new-profile.jsoncStarting Silver Lions, Golden Eagles, and GJN balances for new savesFlat key-value objectHigh-resource sandbox presets or zero-balance hardcore presets
research.jsoncAutomatic default next-research target selectionFlat key-value objectCustomize auto-selected research behavior
clans.jsoncSquadron member caps, activity rules, and preset offline squadronsObject + list ($listOps)Add custom preset squadrons
limits.jsoncMax items per purchase, battle report & log retention capsFlat key-value objectRaise bulk-purchase limits or retained battle log history
+
+

3. Recursive Key-Map Merge vs Additive List Operations ($listOps)

+

Understanding how the merger treats objects versus arrays prevents mods from clobbering one another:

+
  1. Plain Objects / Key-Value Maps (such as vehiclePacks.byVehicle and redeem-codes.jsonc fixedCodes) → Merge Recursively by Key Automatically: Just write the specific keys you want to add or override (e.g. "my_new_tank": { ... }). All other stock keys remain intact—do not wrap key-value maps in $listOps!
  2. JSON Array Properties (such as vehiclePacks.multiVehiclePacks, goldenEaglePacks, supplyTrophies) → Replace by Default; Use { "$listOps": [...] } to Stack: Writing a raw array "multiVehiclePacks": [ ... ] replaces the entire stock and earlier-mod list! To stack items cleanly across multiple mods, set that array property to an envelope object whose only key is "$listOps" (note: if the object has any sibling keys alongside "$listOps", it will NOT be recognized as a list-ops envelope!):
+
jsonc
// Correct Example: server/tuning/store.jsonc
+// Note: multiVehiclePacks, byRank, and byVehicle live INSIDE "vehiclePacks", and the GJN price key is "gjn"!
+{
+  "vehiclePacks": {
+    // ① multiVehiclePacks is an array -> wrap in { "$listOps": [...] } to stack safely
+    "multiVehiclePacks": {
+      "$listOps": [
+        {
+          "op": "append",
+          "items": [
+            {
+              "id": "mod_modern_duo_pack",
+              "title": { "en": "Modern Duo Pack", "zh": "现代双车组合包" },
+              "gjn": 49.99,
+              "goldenEagles": 2000,
+              "premiumDays": 15,
+              "vehicles": ["us_m1a2_sep2_abrams", "germ_leopard_2a7v"]
+            }
+          ]
+        },
+        {
+          "op": "upsertBy",
+          "key": "id",
+          "item": {
+            "id": "wto_pack_two_fronts",
+            "gjn": 19.99
+          }
+        },
+        {
+          "op": "removeBy",
+          "key": "id",
+          "value": "some_unwanted_pack_id"
+        }
+      ]
+    },
+
+    // ② byVehicle is a key-value map (NOT an array) -> write vehicle IDs directly without $listOps!
+    "byVehicle": {
+      "us_mbt_demo": {
+        "gjn": 59.99,
+        "goldenEagles": 2000,
+        "premiumDays": 15
+      }
+    }
+  }
+}
+

All 4 Supported $listOps Operations

+
  • append: { "op": "append", "items": [ ... ] } — appends items to the end of the array;
  • prepend: { "op": "prepend", "items": [ ... ] } — inserts items at the start of the array;
  • upsertBy: { "op": "upsertBy", "key": "<idField>", "item": { ... } } — finds the first element where entry[key] === item[key] and recursively merges item into it, or appends item if absent;
  • removeBy: { "op": "removeBy", "key": "<field>", "value": <matchValue> } — removes every element where entry[key] === value.
+
+

4. Practical Field Quick-Reference & Verified Snippets

+

Every key name below is verified directly against apps/server/tuning/*.jsonc and the server's strict tuning readers:

+

4.1 battle.jsonc (Multipliers, Session Size, BR Spread & Bot Respawns)

+
jsonc
{
+  "rewardMultiplierSilverLions": 2.0,       // Global Silver Lions reward multiplier (default 1.0)
+  "rewardMultiplierResearchPoints": 2.0,    // Global Research Points reward multiplier (default 1.0)
+  "maxPlayers": 32,                         // Total session slots (16v16 = 32: 1 local player + up to 31 bots)
+  "maxBots": 31,                            // Maximum AI bots (default 31)
+  "smallTeamsMaxPlayers": 16,               // Total slots when Tactical Skies (small_teams_) rolls (default 16 = 8v8)
+  "subModeChance": 0.5,                     // Probability (0..1) of rolling an enabled sub-mode alongside classic
+  "brSpreadMrank": 3,                       // Matchmaking mrank spread (3 steps = +/- 1.0 BR; 0 = exact-BR matches)
+  "botPoolLimitPerType": 80,                // Max vehicles per category emitted into customBots
+  "tankBotRespawns": 3,                     // Max respawns per AI bot in multi-slot Ground battles
+  "airBotRespawns": 2,                      // Max respawns per AI bot in multi-slot Air battles
+  "strikeUcavSpawnScore": 750,              // Spawn points required for Strike UCAV in Ground RB (default 750)
+  "nuclearEscalationStrategicBombers": true // Enable stage-3 strategic bombers (B-52H / Tu-95M) in Air RB Nuclear Escalation
+}
+

4.2 store.jsonc (Local Web Store & In-Game GE / SL / Vehicle Pack Pricing)

+
  • Top-level keys: goldenEaglePacks (array), silverLionPacks (array), premiumForGoldenEagles (array), premiumForGjn (array), and vehiclePacks (object);
  • Inside vehiclePacks: +
    • multiVehiclePacks (array; use $listOps): each entry requires id, vehicles (non-empty unique vehicle ID array), gjn (min 0.01), goldenEagles (int ≥0), premiumDays (int ≥0), optional silverLions (int ≥0), and exact one naming property—either custom bilingual "title": { "en": "...", "zh": "..." }, tech-tree folder "groupKey": "shop/group/...", or national starter pack "starter": true;
    • byRank (array; fallback single-vehicle pack tiers sorted by upToRank): each entry has upToRank, gjn, goldenEagles, premiumDays (optional silverLions);
    • byVehicle (key-value map): keyed by gift vehicle ID from wpcost.blk, with { "gjn"?, "goldenEagles"?, "premiumDays"?, "silverLions"? } (omitted fields fall back to the matching byRank tier).
+

4.3 new-profile.jsonc (Starting Balances for Brand-New Saves)

+
jsonc
{
+  "silverLions": 1000000, // Starting Silver Lions (default 150000)
+  "goldenEagles": 5000,   // Starting Golden Eagles (default 500)
+  "gjn": 50               // Starting GJN balance, up to 2 decimal places (default 0)
+}
+

4.4 redeem-codes.jsonc (Custom One-Time Promo Codes)

+

fixedCodes is a key-value map (redeemable once per save, case-insensitive; omitted currency fields default to 0)—merge new codes directly by key:

+
jsonc
{
+  "fixedCodes": {
+    "MYMOD-GIFT-2026": {
+      "silverLions": 500000,
+      "goldenEagles": 1000,
+      "premiumDays": 7,
+      "gjn": 25
+    }
+  }
+}
+

4.5 trophies.jsonc (Adding Custom Silver Lion / Golden Eagle Trophy Chests)

+

supplyTrophies is an array—use $listOps to append a custom chest, and the client will automatically compute and display drop probabilities from your weight / weightTotal / weightEach entries:

+
jsonc
{
+  "supplyTrophies": {
+    "$listOps": [
+      {
+        "op": "append",
+        "items": [
+          {
+            "id": "mod_lucky_trophy",
+            "iconStyle": "big_chest",
+            "silverLions": 100000,
+            "goldenEagles": 0,
+            "prizes": [
+              { "silverLions": 50000, "weight": 50 },
+              { "silverLions": 250000, "weight": 20 },
+              { "goldenEagles": 200, "weight": 10 },
+              { "item": "item_universal_spare", "count": 3, "weight": 15 },
+              { "eventVehicles": { "minRank": 3, "maxRank": 7, "pick": 6 }, "weightTotal": 5 }
+            ]
+          }
+        ]
+      }
+    ]
+  }
+}
+
+ +
+ +
+
+

06 · 服务端 JS/TS 脚本完整接口手册

+

实验期警告(API 0.1-experimental)
本章描述的所有服务端脚本接口与内部目录对象均处于极初期开发阶段,随时可能随本体迭代调整,现阶段不承诺向后兼容。

+
+

1. 运行环境、Node 24 可擦除 TS 语法与 VS Code 智能补全

+

本地服务器运行在启动器内置的 Electron 43 / Node.js 24 上,原生开启 TypeScript 类型剥离(Type Stripping)——玩家电脑上无需安装 Node.js 或 TypeScript 即可直接运行你的 .ts 源码!

+
  • 入口探测顺序:默认依次查找 server/index.ts → server/index.mjs → server/index.js(也可在 mod.jsonc 的 server.entry 中显式指定相对路径);
  • 若需引入第三方 npm 依赖或特殊语法:自行在发布前用 esbuild / tsc 打包为单文件 server/index.mjs 分发即可。
+

1.1 直接写 .ts 的语法限制(erasableSyntaxOnly 正误对照)

+

Node 24 原生类型剥离只会擦除纯类型标注,不会生成额外运行时 JS 代码。因此支持全部 interface、type、泛型与 as,但禁止使用 enum、namespace 或构造函数参数属性(constructor(private x: number)):

+
ts
// ❌ 错误写法:Node 24 原生 TS 剥离不支持 enum,启动会直接报语法错误!
+enum FilterMode { All = 'all', Include = 'include', Exclude = 'exclude' }
+
+// ✅ 正确写法:使用 as const 常量对象 + 联合类型(零运行时开销、100% 兼容!)
+const FILTER_MODE = { All: 'all', Include: 'include', Exclude: 'exclude' } as const;
+type FilterMode = (typeof FILTER_MODE)[keyof typeof FILTER_MODE];
+

1.2 外部模组作者如何获得完整的 VS Code 类型提示?

+

从 WTOffline 源码仓库下载 packages/mods/src/server-api.ts(及其引用的同级 types.ts)放到你的模组 server/ 目录下,然后用 import type 导入上下文类型:

+
ts
// ✅ 正确:import type 在运行时会被 Node 24 完全擦除,VS Code 拥有完整自动补全!
+import type { WtoServerModContext } from './server-api.ts';
+
+// ❌ 不要对 @wto/mods 做运行时值导入(外部独立模组目录没有 monorepo node_modules,运行时会找不到包)
+// import { something } from '@wto/mods';
+
+export default {
+  async setup(ctx: WtoServerModContext) {
+    ctx.logger.info('mod initialized');
+  },
+};
+

提示:除 export default { setup(ctx) { ... } } 外,运行时也兼容直接导出默认函数 export default function (ctx) { ... } 或具名导出 export function setup(ctx) { ... }。你也可以像 templates/official-map-selector/server/index.ts 一样直接在文件顶部声明自己用到的精简 interface,做到单文件零外部依赖。

+
+

2. WtoServerModContext 上下文对象全属性表

+
属性类型说明
ctx.apiVersionstring当前运行时的实验期 API 版本号("0.1-experimental")
ctx.manifestModManifest本模组解析后的 mod.jsonc 清单对象
ctx.modDirstring本模组根目录的绝对路径(可用 node:fs 读取模组附带的静态数据文件)
ctx.gameFolderstring当前运行的离线游戏副本根目录
ctx.dataFolderstring当前客户端的数据目录(含存档、缓存、日志)
ctx.portnumber本次启动的本地服务器监听端口
ctx.logger{ info, warn, error }自动带 [mod:<id>] 前缀的日志器,写入 launcher.log 与诊断包
ctx.storageModStorageApi按账号隔离或全局共享的独立原子 JSON 存档区(见第 3 节)
ctx.hooksServerModHooksApi生命周期、档案、匹配与对局结算钩子(见第 4 节)
ctx.routesServerModRoutesApimatching、http 与 char 三大协议路由扩展(见第 5 节)
+
+

3. 独立存档区(ctx.storage)

+

硬性最佳实践:请勿往玩家原版 profile.blk 塞入自定义非标字段(不仅可能干扰客户端反序列化,玩家关闭或卸载模组后还会在主存档残留脏数据)。所有模组自定进度、开关与统计请一律存入 ctx.storage:

+
ts
// ① 按本地玩家账号隔离:<dataFolder>/saves/<userId>/mods/<modId>.json
+const playerStore = ctx.storage.forPlayer(userId);
+const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 };
+playerStore.write({ wins: prev.wins + 1 }); // 临时文件原子替换写盘,防断电损坏
+// playerStore.remove();
+
+// ② 模组跨账号全局共享存储:<dataFolder>/mods-data/<modId>.json
+const sharedStore = ctx.storage.shared();
+
+

4. 全部生命周期、档案与对局钩子(ctx.hooks)

+

4.1 ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })

+

在本地服务器从叠加后的 .vromfs.bin 提取完静态数据集、尚未构建业务服务前触发。可读取或修改:

+
  • datasets.vehicles:载具目录数组(CatalogueVehicle[],含价格、研发点、权重、科技树信息)
  • datasets.battleEconomy:对局收益基数与单车系数表
  • datasets.battleSpawnRules:出生点、支援机与重生成本规则数据
  • datasets.multiplayerMissions:{ categories, missions } 联机任务元数据
  • datasets.uiLabels / datasets.unitNames:多语言界面标签与载具译名映射
  • datasets.get(datasetId) / datasets.set(datasetId, value):按数据集 ID 读取或替换任意底层数据集
+

4.2 ctx.hooks.onCataloguesReady(async (catalogues) => { ... })

+

在所有核心业务目录与服务初始化完毕、开始监听端口之前触发,可访问:

+
  • catalogues.tuning:合并完成后的全部只读 Tuning
  • catalogues.gameModes:GameModes 实例(提供 ids()、byId(id)、byName(name)、byEconomicName(name)、countries())
  • catalogues.profiles / accounts / research / equipment / repair
  • catalogues.store / inventory / trophies / items / crew / decor / unlocks / clans
  • catalogues.battleMatchmaker / battleEconomy / battleStreaks
  • catalogues.notifyInventoryChanged():通知在线客户端立刻刷新外部库存
  • catalogues.notifyUser(userId, eventName, payload):向指定在线玩家推送 mrpc.generic_notify 实时事件
+

4.3 ctx.hooks.onServerListening(({ port }) => { ... }) / onServerClosing(() => { ... })

+

分别在 HTTP/匹配端口监听就绪后、以及服务器关闭前(按模组逆序)触发,适合打印就绪地址或清理后台定时器。

+

4.4 档案钩子:ctx.hooks.profile.onRefresh((profile, userId) => { ... })

+

每次读取或更新玩家档案并跑完原生刷新管线后调用(profile 为 @wto/blk 的内存 BlkBlock)。建议只读取档案信息并把衍生数据存入 ctx.storage.forPlayer(userId)。

+

4.5 对局与匹配钩子(ctx.hooks.battle)

+
① ctx.hooks.battle.onBeforeMatchmake(({ userId, eventName, request }) => { ... })
+

玩家点击「加入战斗」发起 match.enqueue、尚未进入 BattleMatchmaker 之前触发,request 为客户端提交的原始入队参数对象。

+
② ctx.hooks.battle.onFilterMissions((ctx) => { ... })
+

BattleMatchmaker 已按当前模式与分房权重筛出双边候选任务池、尚未随机抽图时触发:

+
  • ctx:{ userId, modeId, modeName, economicName, minMrank, maxMrank, missions };
  • 每项 mission 结构为 { name, path, level?, type?, locName?, postfix? };
  • 返回值:返回过滤后的子集数组(返回 undefined 表示不干预)。若返回空数组 [],服务端会打印告警并自动回退到过滤前的候选池,确保玩家永远不会因筛选过严而卡死匹配。
+
ts
// 示例:只允许匹配关卡路径或名称包含 poland 或 berlin 的地图
+ctx.hooks.battle.onFilterMissions(({ missions }) => {
+  const picked = missions.filter((m) => /poland|berlin/i.test(m.level ?? m.name));
+  return picked.length > 0 ? picked : undefined;
+});
+
③ ctx.hooks.battle.onLiveFact(({ userId, roomId, fact }) => { ... })
+

对局进行中,每当客户端通过 wto_battle.fact 上报一条实时战斗事件时触发(roomId 为 16 位十六进制对局 sessionId)。fact 公共字段包含 { sessionId, localPlayerId, localTeam, kind },并按 fact.kind 携带以下精确字段:

+
fact.kind触发时机附加字段结构
"event"本地玩家产生得分/击杀/助攻/占点/伤害事件{ time, unit, code, expClass, victim, victimIsPlayer, friendly, modifier, damage }
"life"本地玩家单次出击生命段更新或阵亡结算{ unit, start, end, died }
"kill"战场右上角击杀播报栏产生任意击杀(含 AI 互杀){ time, killer, killerTeam, victim, victimTeam }(MPlayer ID,无玩家单位为 -1)
"strike"本地玩家投掷的核弹成功引爆{ time }
+
④ ctx.hooks.battle.onAfterSettle(({ userId, roomId, summary }) => { ... })
+

对局结束、服务端执行完原生 settleBattle 结算之后、档案正式写盘之前触发。summary 的真实结构为 { profile, report, session }:

+
  • summary.profile:已完成本局银狮/研发点结算的玩家档案 BlkBlock;
  • summary.report:客户端上报的本局完整事实 BattleReport(含 outcome: 'win' | 'lose' | 'running'、localTeam、teamAScore、teamBScore、sessionStart、sessionEnd、lives、events、feed、players 计分板、nuclearStrikes、spares);
  • summary.session:本局会话元数据 BattleSession(含 sessionId、roomId、modeId、modeName、economicName、difficulty、requiredClass、missionName、country 等)。
+

再次提醒:统计模组自定成就、连胜或战役进度时,请读写 ctx.storage.forPlayer(userId),切勿往 summary.profile 写入非原版自定义键!

+
+

5. 三大通信路由对比与 matchingApiFunc 正确签名(ctx.routes)

+

5.1 我该选哪种路由?(选型对照表)

+
路由接口适用场景协议格式客户端调用方式
ctx.routes.matching(最推荐)原生 DaGui .nut 界面弹窗与服务端读写 JSON 数据(如读取/保存选图规则、模组设置)纯 JSON 对象入参 + JSON 对象返回Quirrel 调用 matchingApiFunc("wto_mod.<方法名>", callback, params)
ctx.routes.http用 HTML/CSS/JS 做复杂可视化面板、外部浏览器管理页或 REST 接口(自动隔离在 /mods/<modId>/...)标准 HTTP 请求/响应系统浏览器或游戏内置浏览器打开 http://{{LOCAL_ENDPOINT}}/mods/<modId>/...
ctx.routes.char拦截包装原版 cln_* 档案动作,或注册底层二进制 BLK 动作二进制/文本请求体(Buffer)客户端底层 char 客户端动作请求
+

5.2 匹配服 JSON RPC(ctx.routes.matching)—— 注意客户端参数顺序!

+

服务端注册自定义匹配方法非常直观(req 含 { method, params, userId },同步返回任意 JSON 对象即可;也可用 wrap(method, (req, next) => ...) 包装原版匹配方法):

+
ts
ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({
+  ok: true,
+  userId,
+  echo: params,
+}));
+

P0 必看:Quirrel 端 matchingApiFunc 的第 2 个参数是 callback,第 3 个参数才是 params!
在原版 gui.vromfs.bin 的 %scripts/matching/api.nut 中,函数定义为 function matchingApiFunc(name, cb, params = null)。如果把 params 和 callback 写反,请求参数会变成空且回调永远不会触发!

+

客户端 .nut 正确调用写法:

+
squirrel
from "%scripts/matching/api.nut" import matchingApiFunc
+
+// ✅ 第 1 参数:方法名 | 第 2 参数:Callback 回调 | 第 3 参数:请求参数表 params
+matchingApiFunc("wto_mod.my_mod.ping",
+  Callback(@(resp) this.onPingResponse(resp), this),
+  {
+    hello = "world"
+  })
+

5.3 本地 HTTP 与内置浏览器网页路由(ctx.routes.http)

+

注册的子路径会自动挂载到 /mods/<你的modId>/... 命名空间下(支持精确路径与 /* 通配后缀):

+
ts
ctx.routes.http.register('/panel', () => ({
+  status: 200,
+  contentType: 'text/html; charset=utf-8',
+  body: '<!doctype html><meta charset="utf-8"><h1>My Mod Control Panel</h1>',
+}));
+
+ctx.routes.http.register('/api/*', (req) => ({
+  status: 200,
+  contentType: 'application/json; charset=utf-8',
+  body: JSON.stringify({ method: req.method, path: req.path, query: req.query }),
+}));
+

如果你想在游戏机库里点一个按钮直接用战雷内置浏览器打开这个网页,只需在 client/gui-patches/ 的替换脚本中引用 {{LOCAL_ENDPOINT}} 占位符即可:

+
squirrel
from "%scripts/onlineShop/url.nut" import openUrl
+
+openUrl("http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel", false, false)
+

5.4 Char 动作拦截与扩展(ctx.routes.char)

+
  • ctx.routes.char.register(action, handler):注册全新的自定义 cln_* 动作;
  • ctx.routes.char.wrap(action, async (req, next) => { ... }):按洋葱模型拦截现有 cln_* 动作(可在调用 await next(req) 前检查请求或在其后观测响应)。
+
+

6. 全栈模组实战拆解:官方选图器(official-map-selector)是如何串起来的?

+

打开 mods/official-map-selector/(仓库源码位于 mod-dev-docs/templates/official-map-selector/),它是学习「客户端原生 UI + 本地服务器 RPC + 独立存档 + 匹配钩子」完整闭环的最佳蓝本。整个模组仅由 5 个环节串联而成:

+
text
[1. 入口挂载补丁 client/gui-patches/]
+   ├─ gui/gamemodeselect/gamemodeselect.tpl  → 在模式选择底栏右侧插入「自定义地图池」按钮节点
+   ├─ scripts/gamemodes/gamemodeselect.nut   → 点击按钮调用 WtoMapSelectorModal.open({ gameMode })
+   └─ gui/css.css                            → 追加 @import "missions\wtomapselector.css"
+          │
+          ▼
+[2. 独立原生弹窗 client/packs/gui.vromfs.bin/ + lang.vromfs.bin/]
+   ├─ scripts/missions/wtomapselectormodal.nut  → 继承 BaseGuiHandlerWT,展示搜索框、黑白名单标签与战术小地图预览
+   ├─ gui/missions/wtomapselectormodal.tpl      → 弹窗骨架与卡片网格模板(wtomapselectorcards.tpl)
+   ├─ gui/missions/wtomapselector.css           → 卡片选中高亮样式
+   └─ lang/menu.csv.patch.csv                   → 注册 wto/mapSelector/* 中英文界面词条
+          │
+          ▼  matchingApiFunc("wto_mod.map_selector.get" / ".set", Callback(...), { modeName, ... })
+[3. 服务端匹配 RPC server/index.ts -> ctx.routes.matching.register]
+   ├─ onCataloguesReady 时扫描 catalogues.gameModes 建立各 PvP 模式可用双边地图池索引
+   ├─ wto_mod.map_selector.get → 返回该模式地图列表 + 当前玩家已保存的筛选规则
+   └─ wto_mod.map_selector.set → 校验参数并保存玩家的 all / include / exclude 选图列表
+          │
+          ▼
+[4. 玩家独立存档 ctx.storage.forPlayer(userId)]
+   └─ 原子写入 <dataFolder>/saves/<userId>/mods/official.map-selector.json(不改动 profile.blk)
+          │
+          ▼
+[5. 匹配选图拦截 ctx.hooks.battle.onFilterMissions]
+   └─ 玩家点「加入战斗」时按白名单/黑名单过滤候选 missions;若当前权重段过滤后为 0 张图则安全回退全池并记日志
+

建议把 templates/official-map-selector 从头到尾对照本图通读一遍——你需要的几乎所有全栈模组技巧都在里面有可直接复用的生产级示范代码!

+
+
+

06 · Server JS/TS Scripting API Reference

+

Experimental Warning (API 0.1-experimental)
All server scripting interfaces and internal catalogue objects documented here are in early active development and may change across WTOffline releases without backwards compatibility.

+
+

1. Runtime Environment, Node 24 Erasable TS Rules & VS Code Autocomplete

+

The local server runs inside the launcher's bundled Electron 43 / Node.js 24 runtime with native TypeScript type stripping enabled—players do not need Node.js or TypeScript installed on their PCs to run your .ts scripts directly!

+
  • Default entry lookup order: server/index.ts → server/index.mjs → server/index.js (or override via server.entry in mod.jsonc);
  • Third-party npm packages or non-erasable syntax: if needed, bundle your code ahead of time into a single-file server/index.mjs with esbuild or tsc.
+

1.1 Raw .ts Syntax Rule (erasableSyntaxOnly Do vs Don't)

+

Node 24's built-in TypeScript stripper erases type annotations without emitting extra runtime JS code. All interface, type, generic, and as constructs work natively, except enum, namespace, and constructor parameter properties (constructor(private x: number)):

+
ts
// ❌ DON'T: Node 24 native TS stripping rejects `enum` at startup!
+enum FilterMode { All = 'all', Include = 'include', Exclude = 'exclude' }
+
+// ✅ DO: Use an `as const` object + union type (zero runtime overhead, 100% compatible!)
+const FILTER_MODE = { All: 'all', Include: 'include', Exclude: 'exclude' } as const;
+type FilterMode = (typeof FILTER_MODE)[keyof typeof FILTER_MODE];
+

1.2 How External Modders Get Full VS Code Autocomplete

+

Download packages/mods/src/server-api.ts (along with its sibling types.ts) from the WTOffline repository into your mod's server/ folder and import types using import type:

+
ts
// ✅ DO: `import type` is completely erased by Node 24 at runtime while giving full VS Code IntelliSense!
+import type { WtoServerModContext } from './server-api.ts';
+
+// ❌ Avoid value-importing `@wto/mods` at runtime (external mod folders do not have monorepo node_modules)
+// import { something } from '@wto/mods';
+
+export default {
+  async setup(ctx: WtoServerModContext) {
+    ctx.logger.info('mod initialized');
+  },
+};
+

Tip: Alongside export default { setup(ctx) { ... } }, the runtime also accepts export default function (ctx) { ... } or a named export function setup(ctx) { ... }. You can also declare lightweight structural interface views directly at the top of server/index.ts (just like templates/official-map-selector/server/index.ts) for a zero-dependency single file.

+
+

2. WtoServerModContext Property Reference

+
PropertyTypeDescription
ctx.apiVersionstringActive experimental API tag ("0.1-experimental")
ctx.manifestModManifestParsed mod.jsonc manifest of this mod
ctx.modDirstringAbsolute path to this mod's root directory (read static mod files via node:fs)
ctx.gameFolderstringActive offline game copy root directory
ctx.dataFolderstringActive client data folder (saves, caches, logs)
ctx.portnumberBound local server port for the current session
ctx.logger{ info, warn, error }Logger prefixed with [mod:<id>], written to launcher.log and diagnostic exports
ctx.storageModStorageApiAtomic JSON storage scoped per player or shared across accounts (Section 3)
ctx.hooksServerModHooksApiLifecycle, profile, matchmaking, and battle settlement hooks (Section 4)
ctx.routesServerModRoutesApimatching, http, and char route extensions (Section 5)
+
+

3. Isolated Mod Storage (ctx.storage)

+

Recommended practice: Keep custom mod data out of the player's profile.blk (non-stock keys can interfere with client serialization and remain behind after a mod is removed). Store mod state, settings, and progression in ctx.storage:

+
ts
// ① Scoped per local player account: <dataFolder>/saves/<userId>/mods/<modId>.json
+const playerStore = ctx.storage.forPlayer(userId);
+const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 };
+playerStore.write({ wins: prev.wins + 1 }); // Atomic temp-file rename write
+// playerStore.remove();
+
+// ② Shared across all accounts for this mod: <dataFolder>/mods-data/<modId>.json
+const sharedStore = ctx.storage.shared();
+
+

4. Lifecycle, Profile & Battle Hooks (ctx.hooks)

+

4.1 ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })

+

Fires after static datasets are extracted from the overlaid .vromfs.bin packs and before domain catalogues are constructed. Inspect or mutate:

+
  • datasets.vehicles: vehicle array (CatalogueVehicle[] with prices, RP, BRs, tech-tree links)
  • datasets.battleEconomy: battle action reward rates and per-vehicle multipliers
  • datasets.battleSpawnRules: spawn costs, support planes, and spawn rules
  • datasets.multiplayerMissions: { categories, missions } mission metadata
  • datasets.uiLabels / datasets.unitNames: localized UI strings and vehicle names
  • datasets.get(datasetId) / datasets.set(datasetId, value): read or replace any raw dataset by ID
+

4.2 ctx.hooks.onCataloguesReady(async (catalogues) => { ... })

+

Fires after all domain catalogues and services are assembled, right before the server starts listening:

+
  • catalogues.tuning: merged read-only Tuning
  • catalogues.gameModes: GameModes instance (ids(), byId(id), byName(name), byEconomicName(name), countries())
  • catalogues.profiles / accounts / research / equipment / repair
  • catalogues.store / inventory / trophies / items / crew / decor / unlocks / clans
  • catalogues.battleMatchmaker / battleEconomy / battleStreaks
  • catalogues.notifyInventoryChanged(): push live external-inventory refresh to connected clients
  • catalogues.notifyUser(userId, eventName, payload): send a live mrpc.generic_notify event to a logged-in player
+

4.3 ctx.hooks.onServerListening(({ port }) => { ... }) / onServerClosing(() => { ... })

+

Fires once the HTTP/matching port is listening, and in reverse mod order right before shutdown (ideal for logging URLs or clearing timers).

+

4.4 Profile Hook: ctx.hooks.profile.onRefresh((profile, userId) => { ... })

+

Fires whenever a player profile is loaded or updated and finishes the native refresh pipeline (profile is an @wto/blk BlkBlock). Read profile facts here and persist derived mod state in ctx.storage.forPlayer(userId).

+

4.5 Matchmaking & Battle Hooks (ctx.hooks.battle)

+
① ctx.hooks.battle.onBeforeMatchmake(({ userId, eventName, request }) => { ... })
+

Fires when the player clicks To Battle! (match.enqueue) before BattleMatchmaker runs; request holds the raw client enqueue parameters.

+
② ctx.hooks.battle.onFilterMissions((ctx) => { ... })
+

Fires after BattleMatchmaker narrows candidate two-sided missions for the chosen mode and BR window, right before random map selection:

+
  • ctx: { userId, modeId, modeName, economicName, minMrank, maxMrank, missions };
  • Each mission has { name, path, level?, type?, locName?, postfix? };
  • Return value: return your filtered subset array (or undefined to leave unchanged). If an empty array [] is returned, the server logs a warning and safely falls back to the previous candidate pool so matchmaking never deadlocks.
+
ts
// Example: restrict matches to maps whose level path or name matches poland or berlin
+ctx.hooks.battle.onFilterMissions(({ missions }) => {
+  const picked = missions.filter((m) => /poland|berlin/i.test(m.level ?? m.name));
+  return picked.length > 0 ? picked : undefined;
+});
+
③ ctx.hooks.battle.onLiveFact(({ userId, roomId, fact }) => { ... })
+

Fires live during a running LocalMP battle whenever the client reports a wto_battle.fact event (roomId is the 16-character hex sessionId). fact always carries { sessionId, localPlayerId, localTeam, kind } plus fields determined by fact.kind:

+
fact.kindWhen It FiresAdditional fact Fields
"event"Local player scores a kill, assist, capture, hit, or award event{ time, unit, code, expClass, victim, victimIsPlayer, friendly, modifier, damage }
"life"Local player spawn life segment updates or ends in death{ unit, start, end, died }
"kill"Any kill appears in the HUD killfeed (including AI-vs-AI kills){ time, killer, killerTeam, victim, victimTeam } (MPlayer IDs, -1 if unit has no player)
"strike"Local player's nuclear bomb detonates{ time }
+
④ ctx.hooks.battle.onAfterSettle(({ userId, roomId, summary }) => { ... })
+

Fires at battle end right after native settleBattle applies SL/RP rewards and right before the updated profile is written to disk. summary has the exact shape { profile, report, session }:

+
  • summary.profile: the player's BlkBlock profile with post-battle rewards applied;
  • summary.report: parsed BattleReport (outcome: 'win' | 'lose' | 'running', localTeam, teamAScore, teamBScore, sessionStart, sessionEnd, lives, events, feed, players scoreboard rows, nuclearStrikes, spares);
  • summary.session: BattleSession metadata (sessionId, roomId, modeId, modeName, economicName, difficulty, requiredClass, missionName, country, etc.).
+

Reminder: Persist any custom mod achievements, streaks, or campaign progression in ctx.storage.forPlayer(userId) rather than mutating non-stock keys onto summary.profile!

+
+

5. Choosing Between the 3 Route Channels & Exact matchingApiFunc Signature (ctx.routes)

+

5.1 Which Route API Should I Use?

+
Route APIBest ForPayload FormatHow the Client Calls It
ctx.routes.matching *(Recommended)*Native DaGui .nut modals exchanging JSON data with your server script (settings, map rules, custom state)Plain JSON params in → JSON object outQuirrel matchingApiFunc("wto_mod.<method>", callback, params)
ctx.routes.httpRich HTML/CSS/JS web dashboards, external browser panels, or REST endpoints (auto-namespaced under /mods/<modId>/...)Standard HTTP request / responseSystem browser or War Thunder's embedded browser at http://{{LOCAL_ENDPOINT}}/mods/<modId>/...
ctx.routes.charWrapping stock cln_* profile actions or adding low-level binary BLK actionsRaw binary/text BufferLow-level client char action requests
+

5.2 Matching JSON RPC (ctx.routes.matching) — Mind the Client Argument Order!

+

Registering a custom matching RPC on the server takes just a few lines (req provides { method, params, userId } and returns any JSON object; wrap(method, (req, next) => ...) is also available):

+
ts
ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({
+  ok: true,
+  userId,
+  echo: params,
+}));
+

P0 Gotcha: In Quirrel's matchingApiFunc, callback Is the 2nd Argument and params Is the 3rd Argument!
In stock gui.vromfs.bin %scripts/matching/api.nut, the signature is function matchingApiFunc(name, cb, params = null). Passing (name, params, callback) in the wrong order sends empty params and skips your callback.

+

Correct Quirrel .nut call:

+
squirrel
from "%scripts/matching/api.nut" import matchingApiFunc
+
+// ✅ Arg 1: RPC method | Arg 2: Callback | Arg 3: Request params table
+matchingApiFunc("wto_mod.my_mod.ping",
+  Callback(@(resp) this.onPingResponse(resp), this),
+  {
+    hello = "world"
+  })
+

5.3 Local HTTP & Embedded Browser Routes (ctx.routes.http)

+

Routes are automatically namespaced under /mods/<yourModId>/... and support both exact paths and /* wildcards:

+
ts
ctx.routes.http.register('/panel', () => ({
+  status: 200,
+  contentType: 'text/html; charset=utf-8',
+  body: '<!doctype html><meta charset="utf-8"><h1>My Mod Control Panel</h1>',
+}));
+
+ctx.routes.http.register('/api/*', (req) => ({
+  status: 200,
+  contentType: 'application/json; charset=utf-8',
+  body: JSON.stringify({ method: req.method, path: req.path, query: req.query }),
+}));
+

To open that page inside War Thunder's native embedded browser from a hangar button, use the {{LOCAL_ENDPOINT}} placeholder inside a client/gui-patches/ replacement snippet:

+
squirrel
from "%scripts/onlineShop/url.nut" import openUrl
+
+openUrl("http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel", false, false)
+

5.4 Char Action Interception & Custom Actions (ctx.routes.char)

+
  • ctx.routes.char.register(action, handler): register a brand-new cln_* action;
  • ctx.routes.char.wrap(action, async (req, next) => { ... }): wrap an existing cln_* action around await next(req).
+
+

6. Full-Stack Case Study: How official-map-selector Connects End to End

+

Open mods/official-map-selector/ (source in mod-dev-docs/templates/official-map-selector/): it is a complete reference implementation connecting native client UI, matching RPCs, isolated player storage, and server matchmaking hooks across 5 clean layers:

+
text
[1. Minimal Entry Hooks: client/gui-patches/]
+   ├─ gui/gamemodeselect/gamemodeselect.tpl  → Inserts the "Custom Map Pool" button into the footer bar
+   ├─ scripts/gamemodes/gamemodeselect.nut   → Wires button click to WtoMapSelectorModal.open({ gameMode })
+   └─ gui/css.css                            → Appends @import "missions\wtomapselector.css"
+          │
+          ▼
+[2. Standalone Native Modal: client/packs/gui.vromfs.bin/ + lang.vromfs.bin/]
+   ├─ scripts/missions/wtomapselectormodal.nut  → Subclasses BaseGuiHandlerWT; renders search, filter tabs & tactical map preview
+   ├─ gui/missions/wtomapselectormodal.tpl      → Modal layout & card grid template (wtomapselectorcards.tpl)
+   ├─ gui/missions/wtomapselector.css           → Selected card badge & border styling
+   └─ lang/menu.csv.patch.csv                   → Localized wto/mapSelector/* UI strings (EN / ZH)
+          │
+          ▼  matchingApiFunc("wto_mod.map_selector.get" / ".set", Callback(...), { modeName, ... })
+[3. Server Matching RPCs: server/index.ts -> ctx.routes.matching.register]
+   ├─ Indexes playable two-sided map pools per PvP mode during onCataloguesReady(catalogues.gameModes)
+   ├─ wto_mod.map_selector.get → Returns the mode's map list + the player's saved filter rule
+   └─ wto_mod.map_selector.set → Validates & saves the player's all / include / exclude selection
+          │
+          ▼
+[4. Per-Account Isolated Storage: ctx.storage.forPlayer(userId)]
+   └─ Atomically writes <dataFolder>/saves/<userId>/mods/official.map-selector.json (never touches profile.blk)
+          │
+          ▼
+[5. Matchmaking Map Filter: ctx.hooks.battle.onFilterMissions]
+   └─ Filters candidate missions by whitelist/blacklist on "To Battle!", falling back to the full pool with a log warning if 0 maps match at that BR
+

Reading templates/official-map-selector alongside this diagram gives you a production-tested blueprint for virtually any full-stack WTOffline mod!

+
+ +
+ +
+
+

07 · 排错、日志、热重载与打包发布规范

+

1. 模组出错了去哪里看日志?

+

启动器的所有模组构建与运行日志都会汇入标准日志目录,可在 「设置 › 诊断 › 打开日志目录」 或 「关于 › 导出诊断日志」 直接打开:

+
  1. 启动器主日志(launcher.log): +
    • 搜索 [build]:查看本轮启用了哪些模组、各 .vromfs.bin 数据包叠加统计、以及哪条 gui-patches 或 exe-patches 被跳过与具体原因;
    • 搜索 [mods]:查看跨盘 Junction 挂载结果、被跳过的玩家原生文件重名告警、以及自动还原的按需备份数据包;
    • 搜索 [server] 或 [mod:<你的modId>]:查看服务端 tuning 校验错误、脚本加载报错堆栈、以及你在脚本里调用 ctx.logger.info/warn/error 打印的全部输出。
  2. 游戏客户端运行日志(<游戏副本目录>/.game_logs/*.clog): +
    • 若客户端 GUI 脚本运行报错或卡死在「正在加载」,查看最新的 .clog(并配合第 04 章的 sq.exe 完整字节码检查快速定位);
    • 若新增 3D 模型未渲染,搜索 .clog 中的 [PACK]、pkg_user 或模型资产名确认是否被引擎挂载。
+
+

2. 常见报错与疑难杂症速查表

+
现象 / 日志报错常见原因解决方法
启动器提示某模组目录读取失败mod.jsonc 存在 JSON 语法错误、拼错了未知字段名、id 含大写或非法字符、或声明的 server.entry 文件不存在对照第 01 章第 5 节字段表核对 mod.jsonc
点启动提示「存在阻塞性模组错误」启用的模组缺少 requires 前置、前置未勾选启用,或同时勾选了声明 conflicts 互斥的两个模组按「模组」页顶部的红色错误列表补齐前置或关闭其中一个互斥项
模组里的 server/tuning/*.jsonc 修改似乎没生效测试客户端曾在启动器「数值」页手动改过同一字段(<数据目录>/tuning/*.jsonc 优先级高于模组),或 store.jsonc 把 vehiclePacks 内部字段写到了根级在启动器「数值」页将该项重置为默认,并核对第 05 章的字段层级与 "gjn" 字段名
服务端加载 .ts 报语法错或找不到模块在 .ts 中写了 enum/namespace,或写了运行时值导入 import { ... } from '@wto/mods'改用 as const 对象 + 联合类型;类型提示一律写成 import type { ... } from './server-api.ts'
gui-patches 报错 the data pack has no script ...patch.jsonc 里的 variant.file 含有大写字母(如 scripts/gameModes/...)将 variant.file 改为全小写(如 scripts/gamemodes/gamemodeselect.nut)
新增的独立 .css 样式完全没生效只把 .css 放进了 client/packs/gui.vromfs.bin/,未在根样式表 gui/css.css 中注册在 client/gui-patches/ 给 gui/css.css 增加一条 @import "目录文件名.css" 补丁(见第 04 章 2.2 节)
客户端 matchingApiFunc 回调不触发或服务端收到空 params把 matchingApiFunc 的第 2、第 3 个参数顺序写反了记住签名是 matchingApiFunc(methodName, callback, params)——callback 在第 2 位,params 在第 3 位!
进机库一直卡在「正在加载」新增或修补后的完整 .nut 存在词法作用域重名、未声明标识符、保留字 base 误用或反引号字符串 ` ... | 用 sq.exe 对**完整 .nut 文件**跑 compilestring 字节码校验,插值字符串统一用 $"..."`
日志提示 overlaps protected core patch模组的 client/exe-patches/ 试图修改离线版核心隔离补丁锁定的字节区间核心隔离区段受保护不可覆盖,请改用非重叠地址或服务端方案
日志提示 target already exists as a native/player fileclient/files/ 中的某文件与玩家自己在 UserSkins/ 或 UserSights/ 手动放的文件重名给模组附带的配套子目录加上专属前缀(如 mod_<你的id>_...)避免撞名
+
+

3. 开发调试热重载循环(改完文件怎么最快看到效果?)

+

在本地编写与调试模组时,了解客户端与服务端各自的加载时机能省下大量时间:

+
  1. 修改客户端内容(client/packs/、client/gui-patches/、client/exe-patches/、client/addon/、client/files/、config-blk.patch.jsonc): +
    • 先正常退出游戏客户端;
    • 保存你修改的模组源文件后,直接在启动器点击 「启动游戏」:启动器会自动比对所有启用模组源文件的大小与修改时间指纹(Fingerprint),一旦发现任一补丁或包内文件有改动,就会自动从 wtoffline/stock/ 重新叠加生成最新数据包并启动游戏!
    • 提示:如果只是微调已通过 NTFS Junction 挂载的 client/addon/res/ 或 client/files/UserSkins/<子目录>/ 内部贴图,文件本身已经是零拷贝直连的,重启游戏(或游戏内点刷新涂装)即可直接读取最新文件。
  2. 修改服务端内容(server/index.ts 与 server/tuning/*.jsonc): +
    • 每次退出游戏并在启动器重新点击 「启动游戏」拉起新一轮本地服务器会话时,服务器都会重新合并全部 server/tuning/*.jsonc,并通过带时间戳的 ESM 动态导入(?wto_mod=<timestamp>)全新加载 server/index.ts,无需重启启动器本身。
+
+

4. 模组打包与发布分享规范(.zip 结构)

+

当你完成测试准备把模组分享给其他玩家时,请遵循统一的压缩包目录约定,让玩家解压即用、不踩套娃目录坑:

+
  1. 压缩包内保留且仅保留一层顶层模组文件夹: 假设你的模组目录叫 my-awesome-mod,打包后的 my-awesome-mod.zip 内部结构应当是:
+
text
my-awesome-mod.zip
+└─ my-awesome-mod/          <-- 唯一顶层文件夹(玩家直接解压到 mods/ 即可得到 mods/my-awesome-mod/mod.jsonc)
+   ├─ mod.jsonc
+   ├─ client/
+   └─ server/
+
  • 不要把 mod.jsonc 裸放在 .zip 根目录(玩家直接“解压到当前文件夹”会把散文件撒满 mods/ 根目录导致无法识别);
  • 也不要套两层文件夹(如 my-awesome-mod/my-awesome-mod/mod.jsonc),启动器只扫描 mods/ 下的一级子目录!
+
  1. 打包前清理无关开发垃圾文件: 请剔除 .git/、node_modules/(若用第三方库请预打包进单文件 server/index.mjs)、.DS_Store、Thumbs.db、编辑器备份文件(*.bak、*.swp)以及临时解包参考用的原版大文件。
+
+

5. 跨盘与非 NTFS 磁盘行为说明

+
  • NTFS 硬盘(绝大多数 Windows 电脑):client/addon/(3D 模型与贴图)和单模组独占子目录(如 UserSkins/<子目录>)全部通过 NTFS Directory Junction 挂载——跨盘可用、免管理员权限、0 额外空间、约 1 毫秒完成;
  • 平铺共享目录散文件(如 sound/mod/*.bank):依次尝试文件符号链接(开启 Windows 开发者模式时跨盘零拷贝)→ 同盘硬链接 → 按文件大小与修改时间比对的增量缓存复制(未改动文件下次启动自动跳过);
  • exFAT 移动硬盘:因文件系统不支持 Junction 和硬链接,自动退化为按大小与修改时间比对的增量缓存复制,功能照常可用。
+
+

6. 开发与发布建议

+
  1. 命名空间隔离:模组 ID 用 <作者>.<模组名>;新增载具 ID、武器、涂装子目录、自定义匹配 RPC(wto_mod.<模组名>.*)、自定义 Char 动作均加上专属前缀,避免与其他模组撞名;
  2. 公共表优先使用增量补丁而非整文件覆盖:修改 shop.blk、wpcost.blk、unittags.blk、units.csv、menu.csv 时使用 .patch.jsonc / .patch.csv,多车礼包与抽卡箱数组使用 $listOps;
  3. 只读原版,不污染玩家主存档:模组自定数据一律写进 ctx.storage.forPlayer(userId),卸载模组后玩家主存档干干净净;
  4. 界面大逻辑拆独立文件:新弹窗放 client/packs/gui.vromfs.bin/,client/gui-patches/ 里只留几行挂入口按钮与 @import 样式的最小补丁,游戏大版本更新时几乎不用重写;
  5. 发布前做一次完整的「启用 → 进游验证 → 关闭 → 再进游还原」测试循环:确认启用时功能正常、关闭后彻底无痕还原,且能与其他常用模组同时勾选共存。
+
+
+

07 · Troubleshooting, Logs, Reload Loop & Packaging

+

1. Where to Check Logs When Something Goes Wrong

+

All mod build and runtime logs flow into the launcher's standard log directory—open Settings › Diagnostics › Open logs folder or About › Export diagnostics:

+
  1. Launcher Main Log (launcher.log): +
    • Filter [build]: see which mods ran in the current build, .vromfs.bin overlay counts, and exact reasons why any gui-patches or exe-patches item was skipped;
    • Filter [mods]: see cross-drive Junction mounts, skipped native player-file collision warnings, and restored on-demand stock packs;
    • Filter [server] or [mod:<yourModId>]: see server tuning validation errors, script load stack traces, and everything printed via ctx.logger.info/warn/error.
  2. Game Client Runtime Logs (<copyFolder>/.game_logs/*.clog): +
    • If a client UI script throws at runtime or hangs on "Loading", check the newest .clog (and run sq.exe full bytecode verification from Chapter 04);
    • If a custom 3D model fails to appear, search .clog for [PACK], pkg_user, or your asset name to confirm engine mounting.
+
+

2. Common Issues & Solutions Lookup Table

+
Symptom / Log MessageCommon CauseSolution
Discovery error on Launcher Mods pagemod.jsonc syntax error, unknown field name, uppercase/invalid id, or missing server.entry fileValidate mod.jsonc against the schema table in Chapter 01 Section 5
"Blocking mod errors" when clicking LaunchMissing or disabled requires dependency, or two enabled mods declaring conflictsEnable the missing dependency or disable one of the conflicting mods highlighted in red
server/tuning/*.jsonc changes appear ignoredTest client has a manual override saved in the Launcher Tuning tab (<dataFolder>/tuning/*.jsonc has highest priority), or store.jsonc placed vehiclePacks subkeys at rootReset overridden fields in the Launcher Tuning tab and check vehiclePacks nesting + "gjn" key names in Chapter 05
Server .ts fails with syntax or module-not-found errorRaw .ts used enum/namespace, or value-imported import { ... } from '@wto/mods'Replace enum with as const + union type; use import type { ... } from './server-api.ts' for types
gui-patches fails with the data pack has no script ...variant.file in patch.jsonc used camelCase / uppercase letters (e.g. scripts/gameModes/...)Change variant.file to all lowercase (e.g. scripts/gamemodes/gamemodeselect.nut)
Standalone .css stylesheet has no effectAdded .css to client/packs/gui.vromfs.bin/ without registering it in gui/css.cssAdd a client/gui-patches/ patch on gui/css.css appending @import "folderstyle.css" (Chapter 04 Section 2.2)
Client matchingApiFunc callback does not fire or params arrive emptySwapped the 2nd and 3rd arguments of matchingApiFuncUse matchingApiFunc(methodName, callback, params) (callback is 2nd, params is 3rd)
Game hangs indefinitely on "Loading" before hangarResulting complete .nut file has a lexical scope collision, undeclared identifier, base keyword misuse, or backtick string ` ... | Run sq.exe compilestring on the **complete .nut file** and use $"..."` for string interpolation
Log reports overlaps protected core patchMod client/exe-patches/ overlaps locked core offline/isolation patch bytesCore isolation bytes are protected; pick a non-overlapping site or use a server-side hook
Log reports target already exists as a native/player fileA path under client/files/ collides with a player-owned file in UserSkins/ or UserSights/Prefix bundled companion subfolders with your mod namespace (e.g. mod_<yourId>_...)
+
+

3. Development Reload Loop (Fastest Edit-Test Cycle)

+

Knowing when client builds versus server scripts reload keeps iteration fast while developing:

+
  1. Client-side edits (client/packs/, client/gui-patches/, client/exe-patches/, client/addon/, client/files/, config-blk.patch.jsonc): +
    • Close the running game client first;
    • Save your edited mod files and click Launch in the launcher: the launcher hashes source file sizes and mtime timestamps into a deterministic build fingerprint, automatically rebuilding any affected .vromfs.bin packs from wtoffline/stock/ before starting the game!
    • Tip: textures inside already-mounted NTFS Junction directories (client/addon/res/ or client/files/UserSkins/<subfolder>/) point directly to your mods/ folder with zero copying, so restarting the client (or refreshing skins in-game) reads updated assets immediately.
  2. Server-side edits (server/index.ts & server/tuning/*.jsonc): +
    • Every time you exit the game and click Launch to start a new session, the local server restarts cleanly, re-merges all server/tuning/*.jsonc overlays, and reloads server/index.ts with a cache-busting ESM query (?wto_mod=<timestamp>)—no need to restart the launcher itself.
+
+

4. Packaging & Sharing Your Mod (.zip Layout Rules)

+

When packaging your mod for players to download, follow a consistent archive structure so unzipping into mods/ works every time:

+
  1. Wrap your mod in a single top-level <mod-folder>/ directory inside the .zip: For a mod folder named my-awesome-mod, structure my-awesome-mod.zip as:
+
text
my-awesome-mod.zip
+└─ my-awesome-mod/          <-- Single top-level folder (extracting straight into mods/ yields mods/my-awesome-mod/mod.jsonc)
+   ├─ mod.jsonc
+   ├─ client/
+   └─ server/
+
  • Do NOT place mod.jsonc loose at the root of the .zip (extracting into mods/ scatters loose files across mods/ where discovery ignores them);
  • Do NOT double-nest folders (my-awesome-mod/my-awesome-mod/mod.jsonc), as the launcher scans direct child directories of mods/ only!
+
  1. Exclude development & temporary clutter: Omit .git/, node_modules/ (bundle third-party JS dependencies into a single server/index.mjs if needed), .DS_Store, Thumbs.db, editor backup files (*.bak, *.swp), and any unpacked stock game reference files.
+
+

5. Cross-Drive & Non-NTFS Disk Behavior

+
  • NTFS Volumes (standard on Windows): client/addon/ (3D models & textures) and mod-exclusive subfolders (e.g. UserSkins/<subfolder>) mount via NTFS Directory Junctions—works across drives, requires no admin rights, uses 0 extra disk space, and completes in ~1 ms;
  • Shared Flat-Folder Files (e.g. sound/mod/*.bank): tries file symlink (zero-copy across drives when Windows Developer Mode is on) → same-drive NTFS hardlink → incremental size/mtime cached copy (unchanged files are skipped on subsequent launches);
  • exFAT External Drives: since exFAT does not support Junctions or hardlinks, the deployer automatically falls back to incremental size/mtime cached copies with full functional parity.
+
+

6. Practical Recommendations for Mod Authors

+
  1. Namespace Everything: format your mod ID as <author>.<mod-name> and prefix custom vehicle IDs, weapons, skin subfolders, custom matching RPCs (wto_mod.<mod_name>.*), and custom Char actions to avoid collisions between mods;
  2. Prefer Incremental Patches Over Replacing Shared Tables: use .patch.jsonc / .patch.csv for shop.blk, wpcost.blk, unittags.blk, units.csv, and menu.csv, and use $listOps on shared tuning arrays like multiVehiclePacks and supplyTrophies;
  3. Read Stock Profiles, Persist in Isolated Storage: write all custom mod state to ctx.storage.forPlayer(userId) so player saves remain 100% clean if your mod is disabled or uninstalled;
  4. Keep UI Logic in Standalone Files: put custom modals under client/packs/gui.vromfs.bin/ and keep client/gui-patches/ down to a few lines wiring the entry button and gui/css.css @import so game updates rarely break your mod;
  5. Run One Full "Enable → Play → Disable → Relaunch" Cycle Before Release: verify your mod works when enabled, restores stock behavior cleanly when disabled, and coexists peacefully alongside other enabled mods.
+
+
-
- +
+ ← 上一章← Previous06 · 服务端 JS/TS 脚本 API06 · Server Scripting API + +
+
diff --git a/site/home.css b/site/home.css index d09b21e..95f193f 100644 --- a/site/home.css +++ b/site/home.css @@ -55,6 +55,16 @@ code { opacity: 0.24; } +body[data-page='dev-docs'] .bg-stage, +body[data-page='mod-docs'] .bg-stage { + opacity: 0.26; +} + +:root[data-mode='light'] body[data-page='dev-docs'] .bg-stage, +:root[data-mode='light'] body[data-page='mod-docs'] .bg-stage { + opacity: 0.14; +} + .bg-slide { position: absolute; inset: -3%; @@ -1041,30 +1051,156 @@ p.lede { /* ---------------- Documentation Subpages (/dev-docs, /mod-docs) ---------------- */ .wrap-doc { - max-width: 1140px; + max-width: 1180px; } .doc-layout { display: grid; - grid-template-columns: 230px minmax(0, 1fr); - gap: clamp(24px, 4vw, 44px); + grid-template-columns: 276px minmax(0, 1fr); + gap: clamp(24px, 3.8vw, 42px); align-items: start; padding: 10px 0 clamp(36px, 6vh, 64px); } .doc-toc { position: sticky; - top: 76px; - padding: 16px; + top: 74px; + max-height: calc(100vh - 92px); + overflow-y: auto; + padding: 15px; border-radius: var(--r-md); border: 1px solid var(--border); + background: var(--doc-card); + -webkit-backdrop-filter: blur(14px); + backdrop-filter: blur(14px); + display: flex; + flex-direction: column; + gap: 12px; +} + +.doc-tools { + display: flex; + flex-direction: column; + gap: 8px; +} + +.doc-search { + position: relative; +} + +.doc-search-input { + width: 100%; + height: 34px; + padding: 0 11px; + border-radius: var(--r-sm); + border: 1px solid var(--border-2); + background: var(--glass-2); + color: var(--text); + font-family: var(--font-ui); + font-size: 13px; + outline: none; + transition: border-color 0.2s var(--ease), background 0.2s var(--ease); +} + +.doc-search-input::placeholder { + color: var(--text-faint); +} + +.doc-search-input:focus { + border-color: var(--accent); background: var(--surface); - -webkit-backdrop-filter: blur(12px); - backdrop-filter: blur(12px); +} + +.doc-search-results { + display: none; + flex-direction: column; + gap: 4px; + margin-top: 6px; + max-height: 280px; + overflow-y: auto; + padding: 6px; + border-radius: var(--r-sm); + border: 1px solid var(--border-2); + background: var(--elev); + box-shadow: var(--shadow-md); +} + +.doc-search-results.open { + display: flex; +} + +.doc-search-item { + display: flex; + flex-direction: column; + gap: 2px; + padding: 7px 9px; + border-radius: var(--r-xs); + text-decoration: none; + color: var(--text); + border: 1px solid transparent; + transition: background 0.16s var(--ease), border-color 0.16s var(--ease); +} + +.doc-search-item:hover { + background: var(--accent-soft); + border-color: rgba(229, 57, 53, 0.35); +} + +.doc-search-item-head { + font-size: 12.5px; + font-weight: 600; + color: var(--text); +} + +.doc-search-item-chap { + font-family: var(--font-mono); + font-size: 11px; + color: var(--accent); +} + +.doc-search-item-snip { + font-size: 12px; + color: var(--text-faint); + line-height: 1.45; +} + +.doc-search-empty { + padding: 8px 10px; + font-size: 12.5px; + color: var(--text-faint); +} + +.doc-expand-btn { + width: 100%; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + padding: 6px 10px; + border-radius: var(--r-sm); + border: 1px solid var(--border); + background: var(--glass-2); + color: var(--text-dim); + font-family: var(--font-ui); + font-size: 12.5px; + font-weight: 500; + cursor: pointer; + transition: color 0.2s var(--ease), border-color 0.2s var(--ease), background 0.2s var(--ease); +} + +.doc-expand-btn:hover { + color: var(--text); + border-color: var(--border-2); +} + +.doc-expand-btn.active { + color: #ffffff; + background: var(--accent); + border-color: var(--accent); } .doc-toc-title { - margin: 0 0 10px; + margin: 0 0 6px; font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.14em; @@ -1078,7 +1214,7 @@ p.lede { gap: 2px; } -.doc-toc a { +.doc-toc nav > a { padding: 6px 10px; border-radius: var(--r-xs); border-left: 2px solid transparent; @@ -1089,17 +1225,68 @@ p.lede { transition: color 0.2s var(--ease), background 0.2s var(--ease), border-color 0.2s var(--ease); } -.doc-toc a:hover { +.doc-toc nav > a:hover { color: var(--text); background: var(--glass-2); } -.doc-toc a.active { +.doc-toc nav > a.active { color: var(--accent); + font-weight: 600; border-left-color: var(--accent); background: var(--accent-soft); } +.doc-subtoc { + display: flex; + flex-direction: column; + gap: 1px; + margin: 2px 0 6px 10px; + padding-left: 8px; + border-left: 1px solid var(--border); +} + +.doc-subtoc:empty { + display: none; +} + +.doc-subtoc a { + padding: 4px 8px; + border-radius: var(--r-xs); + color: var(--text-faint); + text-decoration: none; + font-size: 12px; + line-height: 1.4; + transition: color 0.18s var(--ease), background 0.18s var(--ease); +} + +.doc-subtoc a:hover { + color: var(--text); + background: var(--glass-2); +} + +.doc-toc-card { + padding-top: 10px; + border-top: 1px solid var(--border); + font-size: 12px; + color: var(--text-faint); + line-height: 1.55; +} + +.doc-toc-card a { + display: inline-flex; + align-items: center; + gap: 4px; + margin-top: 6px; + color: var(--accent); + font-weight: 600; + text-decoration: none; +} + +.doc-toc-card a:hover { + text-decoration: underline; +} + .doc-body { display: flex; flex-direction: column; @@ -1109,35 +1296,62 @@ p.lede { .doc-section { scroll-margin-top: 80px; - padding: clamp(20px, 3vw, 30px); + padding: clamp(22px, 3.2vw, 34px); border-radius: var(--r-lg); border: 1px solid var(--border); - background: var(--card); - -webkit-backdrop-filter: blur(14px); - backdrop-filter: blur(14px); + background: var(--doc-card); + -webkit-backdrop-filter: blur(16px); + backdrop-filter: blur(16px); + box-shadow: var(--shadow-sm); } .doc-section h2 { - margin: 0 0 12px; + margin: 0 0 16px; + padding-bottom: 12px; + border-bottom: 1px solid var(--border); font-family: var(--font-display); - font-size: clamp(20px, 2.4vw, 25px); + font-size: clamp(22px, 2.6vw, 28px); font-weight: 700; letter-spacing: -0.01em; line-height: 1.25; -} - -.doc-section h3 { - margin: 22px 0 8px; - font-size: 15.5px; - font-weight: 660; color: var(--text); } +.doc-section h3 { + scroll-margin-top: 84px; + margin: 30px 0 12px; + padding-left: 11px; + border-left: 3px solid var(--accent); + font-size: 18px; + font-weight: 700; + line-height: 1.35; + color: var(--text); +} + +.doc-section h4 { + scroll-margin-top: 84px; + margin: 22px 0 8px; + font-size: 15.5px; + font-weight: 660; + line-height: 1.4; + color: var(--text); +} + +.doc-section h5 { + scroll-margin-top: 84px; + margin: 18px 0 6px; + font-family: var(--font-mono); + font-size: 13.8px; + font-weight: 660; + line-height: 1.45; + color: var(--accent); +} + .doc-section p { - margin: 0 0 12px; + margin: 0 0 13px; color: var(--text-dim); font-size: 14.5px; - line-height: 1.75; + line-height: 1.78; } .doc-section p:last-child { @@ -1146,52 +1360,158 @@ p.lede { .doc-section ul, .doc-section ol { - margin: 0 0 14px; - padding-left: 1.35em; + margin: 0 0 15px; + padding-left: 1.45em; color: var(--text-dim); - font-size: 14px; + font-size: 14.3px; +} + +.doc-section ul ul, +.doc-section ol ul, +.doc-section ul ol, +.doc-section ol ol { + margin: 6px 0 8px; + padding-left: 1.35em; } .doc-section li { - margin-bottom: 6px; - line-height: 1.68; + margin-bottom: 7px; + line-height: 1.72; +} + +.doc-section li > .doc-pre, +.doc-section li > blockquote { + margin-top: 10px; + margin-bottom: 12px; } .doc-section li strong { color: var(--text); } -.doc-section a { +.doc-section a:not(.btn) { color: var(--accent); text-decoration: none; } -.doc-section a:hover { +.doc-section a:not(.btn):hover { text-decoration: underline; } +.doc-chapter { + display: none; +} + +.doc-chapter.active, +body.doc-expand-all .doc-chapter { + display: block; + animation: tabSwitch 0.32s var(--ease) both; +} + +body.doc-expand-all .doc-pager { + display: none; +} + +.doc-pager { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 12px; + margin-top: 28px; + padding-top: 20px; + border-top: 1px solid var(--border); +} + +.doc-pager-btn { + display: inline-flex; + flex-direction: column; + align-items: flex-start; + gap: 2px; + padding: 10px 16px; + border-radius: var(--r-sm); + border: 1px solid var(--border); + background: var(--surface); + color: var(--text); + text-decoration: none; + cursor: pointer; + min-width: 180px; + transition: border-color 0.2s var(--ease), transform 0.2s var(--ease); +} + +.doc-pager-btn.next { + margin-left: auto; + align-items: flex-end; + text-align: right; +} + +.doc-pager-btn:hover { + border-color: var(--accent); + transform: translateY(-2px); +} + +.doc-pager-label { + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-faint); + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.doc-pager-title { + font-size: 13.5px; + font-weight: 600; + color: var(--text); +} + +.doc-section blockquote { + margin: 15px 0; + padding: 13px 16px; + border-radius: var(--r-sm); + border: 1px solid color-mix(in srgb, var(--accent-2) 32%, transparent); + border-left: 3px solid var(--accent-2); + background: color-mix(in srgb, var(--accent-2) 8%, transparent); + color: var(--text); + font-size: 13.8px; + line-height: 1.72; +} + +.doc-section blockquote p { + color: var(--text); + margin: 0 0 6px; +} + +.doc-section blockquote p:last-child { + margin-bottom: 0; +} + +.doc-section hr { + border: none; + border-top: 1px solid var(--border); + margin: 26px 0; +} + .doc-callout { - margin: 14px 0; + margin: 15px 0; padding: 13px 16px; border-radius: var(--r-sm); border: 1px solid rgba(229, 57, 53, 0.34); border-left: 3px solid var(--accent); background: var(--accent-soft); - font-size: 13.5px; + font-size: 13.8px; color: var(--text); - line-height: 1.68; + line-height: 1.7; } .doc-callout.info { - border-color: rgba(49, 227, 238, 0.30); + border-color: color-mix(in srgb, var(--accent-2) 32%, transparent); border-left-color: var(--accent-2); - background: rgba(49, 227, 238, 0.08); + background: color-mix(in srgb, var(--accent-2) 8%, transparent); } .doc-table-wrap { width: 100%; overflow-x: auto; - margin: 14px 0; + margin: 15px 0; border-radius: var(--r-sm); border: 1px solid var(--border); } @@ -1200,7 +1520,7 @@ p.lede { width: 100%; border-collapse: collapse; font-size: 13.5px; - line-height: 1.6; + line-height: 1.64; } .doc-table th, @@ -1257,15 +1577,15 @@ p.lede { .doc-pre { position: relative; - margin: 14px 0; + margin: 15px 0; border-radius: var(--r-sm); border: 1px solid var(--border); - background: rgba(7, 10, 12, 0.72); + background: rgba(7, 10, 12, 0.82); overflow: hidden; } :root[data-mode='light'] .doc-pre { - background: #f5f7f9; + background: #f4f6f9; } .doc-pre-head { @@ -1286,7 +1606,7 @@ p.lede { overflow-x: auto; font-family: var(--font-mono); font-size: 12.5px; - line-height: 1.62; + line-height: 1.64; color: var(--text); } @@ -1301,29 +1621,33 @@ p.lede { display: flex; flex-wrap: wrap; gap: 10px; - margin-top: 16px; + margin-top: 18px; } -@media (max-width: 860px) { +@media (max-width: 900px) { .doc-layout { grid-template-columns: 1fr; } .doc-toc { position: static; + max-height: none; } .doc-toc nav { flex-direction: row; flex-wrap: wrap; gap: 6px; } - .doc-toc a { + .doc-toc nav > a { border-left: none; border: 1px solid var(--border); padding: 5px 10px; } - .doc-toc a.active { + .doc-toc nav > a.active { border-color: var(--accent); } + .doc-subtoc { + display: none; + } } /* ---------------- Community CTA & Scope Banner ---------------- */ diff --git a/site/home.js b/site/home.js index eef6926..70f8ab5 100644 --- a/site/home.js +++ b/site/home.js @@ -1,22 +1,66 @@ /* ============================================================ - * WTOffline Project Homepage & All-Releases Script - * Classic non-module script so opening HTML files directly via - * file:// works without a local server. - * Handles: language toggle, color theme toggle, opening shutter, - * scroll reveal, pointer spotlight, sticky header, internal page - * transition, and live release catalog rendering. + * WTOffline Website & Documentation Reader Script + * Zero-dependency classic script supporting: + * - Bilingual toggle (zh-CN / EN) and dark/light theme toggle + * - Rotating public-domain daylight military backdrop + * - Smooth internal navigation (with automatic file:// fallback + * so local preview clicks on /dev-docs, /mod-docs, /releases work) + * - Multi-chapter documentation reader with pushState history, + * sub-heading deep links, active chapter sub-TOC, live full-book + * search, expand-all mode (for native Ctrl+F), and clipboard fallback + * - Dynamic release catalog rendering (R2 primary -> GitHub fallback) * ============================================================ */ (function () { 'use strict'; - // Primary release feed is served via edge object storage to keep origin server load low; - // falls back to GitHub Releases API when unavailable. var PRIMARY_FEED = 'https://dl.wto-project.net/releases'; var FALLBACK_FEED = 'https://api.github.com/repos/N0VAN0M4LY/WT-Offline/releases?per_page=30'; var GH_RELEASES = 'https://github.com/N0VAN0M4LY/WT-Offline/releases'; + var SUN_SVG = + '' + + '' + + '' + + ''; + var MOON_SVG = + '' + + '' + + ''; + var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; var pageKind = document.body.getAttribute('data-page') || 'home'; + var docRefreshHook = null; + + // ---- Copy text helper with non-HTTPS / file:// fallback ---- + function copyText(text) { + if (navigator.clipboard && navigator.clipboard.writeText) { + return navigator.clipboard.writeText(text).catch(function () { + return legacyCopy(text); + }); + } + return legacyCopy(text); + } + + function legacyCopy(text) { + return new Promise(function (resolve, reject) { + try { + var ta = document.createElement('textarea'); + ta.value = text; + ta.setAttribute('readonly', ''); + ta.style.position = 'fixed'; + ta.style.opacity = '0'; + ta.style.left = '-9999px'; + document.body.appendChild(ta); + ta.select(); + var ok = document.execCommand('copy'); + document.body.removeChild(ta); + if (ok) resolve(); + else reject(new Error('copy failed')); + } catch (err) { + reject(err); + } + }); + } // ---- Language (zh / en) ---- var currentLang = 'zh'; @@ -37,6 +81,7 @@ currentLang = currentLang === 'zh' ? 'en' : 'zh'; applyLang(currentLang); try { localStorage.setItem('wto.site.lang', currentLang); } catch (err) { /* noop */ } + if (docRefreshHook) docRefreshHook(); }); })(); @@ -60,6 +105,10 @@ ? 'WTOffline · 战争雷霆本地单机离线项目' : 'WTOffline · Local Single-Player Offline Project for War Thunder'; } + var searchInput = document.querySelector('[data-doc-search]'); + if (searchInput) { + searchInput.placeholder = lang === 'zh' ? '搜索全书关键词…' : 'Search all chapters…'; + } } // ---- Color mode (dark default / light optional) ---- @@ -68,13 +117,20 @@ var saved = null; try { saved = localStorage.getItem('wto.site.mode'); } catch (e) { /* noop */ } var mode = saved === 'light' || saved === 'dark' ? saved : 'dark'; - root.setAttribute('data-mode', mode); + setMode(mode); + + function setMode(m) { + root.setAttribute('data-mode', m); + document.querySelectorAll('[data-mode-toggle]').forEach(function (btn) { + btn.innerHTML = m === 'dark' ? SUN_SVG : MOON_SVG; + }); + } document.addEventListener('click', function (e) { var btn = e.target.closest('[data-mode-toggle]'); if (!btn) return; var next = root.getAttribute('data-mode') === 'dark' ? 'light' : 'dark'; - root.setAttribute('data-mode', next); + setMode(next); try { localStorage.setItem('wto.site.mode', next); } catch (err) { /* noop */ } }); })(); @@ -128,7 +184,6 @@ img.src = slides[index]; } - // Activate initial slide on next frame so Ken Burns scale eases in requestAnimationFrame(function () { nodes[0].classList.add('active'); }); @@ -189,53 +244,260 @@ window.addEventListener('scroll', update, { passive: true }); })(); + // ---- Resolve extensionless routes cleanly when previewed via file:// ---- + function resolveInternalHref(href) { + if (location.protocol !== 'file:') return href; + var m = /^\/(|releases|dev-docs|mod-docs)(#.*)?$/.exec(href); + if (!m) return href; + var page = m[1] ? m[1] + '.html' : 'index.html'; + return page + (m[2] || ''); + } + // ---- Smooth internal page navigation ---- (function initLeaveTransition() { - if (reduce) return; - if (document.startViewTransition) return; document.addEventListener('click', function (e) { var a = e.target.closest('a'); - if (!a) return; + if (!a || a.hasAttribute('data-chapter') || a.hasAttribute('data-doc-jump')) return; var href = a.getAttribute('href') || ''; if (a.target === '_blank' || a.hasAttribute('download')) return; if (!href || href.charAt(0) === '#' || /^(https?:)?\/\//.test(href)) return; if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; + + var resolved = resolveInternalHref(href); + if (reduce || (document.startViewTransition && location.protocol !== 'file:')) { + if (resolved !== href) { + e.preventDefault(); + location.href = resolved; + } + return; + } e.preventDefault(); document.body.classList.add('leaving'); - setTimeout(function () { location.href = href; }, 260); + setTimeout(function () { location.href = resolved; }, 240); }); })(); - // ---- Documentation TOC active section highlight & code copy ---- - (function initDocHelpers() { - var tocLinks = document.querySelectorAll('.doc-toc a[href^="#"]'); - if (tocLinks.length && 'IntersectionObserver' in window) { - var sections = []; - tocLinks.forEach(function (link) { - var target = document.querySelector(link.getAttribute('href')); - if (target) sections.push({ el: target, link: link }); + // ---- Multi-chapter documentation reader, sub-TOC, search & expand-all ---- + (function initDocReader() { + var chapters = Array.prototype.slice.call(document.querySelectorAll('.doc-chapter')); + var chapterLinks = Array.prototype.slice.call(document.querySelectorAll('.doc-toc a[data-chapter]')); + + if (chapters.length && chapterLinks.length) { + var activeChapterId = chapters[0].id; + var subTocEl = document.createElement('div'); + subTocEl.className = 'doc-subtoc'; + + function rebuildSubToc() { + if (subTocEl.parentNode) subTocEl.parentNode.removeChild(subTocEl); + subTocEl.innerHTML = ''; + if (document.body.classList.contains('doc-expand-all')) return; + + var activeChap = document.getElementById(activeChapterId); + var activeLink = chapterLinks.filter(function (a) { + return a.getAttribute('data-chapter') === activeChapterId; + })[0]; + if (!activeChap || !activeLink) return; + + var lang = document.body.getAttribute('data-lang') || 'zh'; + var scope = activeChap.querySelector('.lang-' + lang) || activeChap; + var headings = scope.querySelectorAll('h3[id]'); + if (!headings.length) return; + + headings.forEach(function (h) { + var sub = document.createElement('a'); + sub.href = '#' + h.id; + sub.setAttribute('data-doc-jump', h.id); + sub.textContent = h.textContent || ''; + subTocEl.appendChild(sub); + }); + activeLink.insertAdjacentElement('afterend', subTocEl); + } + + function findChapterContaining(targetId) { + if (!targetId) return null; + var direct = chapters.filter(function (c) { return c.id === targetId; })[0]; + if (direct) return { chapter: direct, anchor: null }; + var el = document.getElementById(targetId); + if (!el) return null; + var parentChap = el.closest('.doc-chapter'); + return parentChap ? { chapter: parentChap, anchor: el } : null; + } + + function activateTarget(rawId, scrollBehavior, historyMode) { + var resolved = findChapterContaining(rawId) || { chapter: chapters[0], anchor: null }; + activeChapterId = resolved.chapter.id; + + chapters.forEach(function (c) { + c.classList.toggle('active', c.id === activeChapterId); + }); + chapterLinks.forEach(function (a) { + var on = a.getAttribute('data-chapter') === activeChapterId; + a.classList.toggle('active', on); + a.setAttribute('aria-current', on ? 'page' : 'false'); + }); + + rebuildSubToc(); + + var hashVal = resolved.anchor ? '#' + resolved.anchor.id : '#' + activeChapterId; + if (historyMode === 'push' && history.pushState && location.hash !== hashVal) { + history.pushState(null, '', hashVal); + } else if (historyMode === 'replace' && history.replaceState) { + history.replaceState(null, '', hashVal); + } + + if (scrollBehavior) { + requestAnimationFrame(function () { + if (resolved.anchor) { + resolved.anchor.scrollIntoView({ behavior: reduce ? 'auto' : 'smooth', block: 'start' }); + } else { + var layout = document.querySelector('.doc-layout'); + if (layout) { + var top = layout.getBoundingClientRect().top + window.scrollY - 76; + window.scrollTo({ top: Math.max(0, top), behavior: reduce ? 'auto' : 'smooth' }); + } + } + }); + } + } + + var initialHash = decodeURIComponent((location.hash || '').replace(/^#/, '')); + activateTarget(initialHash || chapters[0].id, Boolean(initialHash && initialHash !== chapters[0].id), 'none'); + + document.addEventListener('click', function (e) { + var chapBtn = e.target.closest('[data-chapter]'); + if (chapBtn) { + e.preventDefault(); + var cid = chapBtn.getAttribute('data-chapter'); + if (cid) activateTarget(cid, true, 'push'); + return; + } + + var jumpBtn = e.target.closest('[data-doc-jump]'); + if (jumpBtn) { + e.preventDefault(); + var jid = jumpBtn.getAttribute('data-doc-jump'); + var resultsBox = document.querySelector('.doc-search-results'); + if (resultsBox) resultsBox.classList.remove('open'); + if (jid) activateTarget(jid, true, 'push'); + return; + } + + // Intercept internal #anchor links inside doc body + var inDocLink = e.target.closest('.doc-body a[href^="#"]'); + if (inDocLink) { + var hid = decodeURIComponent((inDocLink.getAttribute('href') || '').slice(1)); + if (hid && findChapterContaining(hid)) { + e.preventDefault(); + activateTarget(hid, true, 'push'); + } + return; + } + + var expandBtn = e.target.closest('[data-expand-all]'); + if (expandBtn) { + var expanded = document.body.classList.toggle('doc-expand-all'); + expandBtn.classList.toggle('active', expanded); + expandBtn.setAttribute('aria-pressed', expanded ? 'true' : 'false'); + rebuildSubToc(); + } }); - if (sections.length) { - sections[0].link.classList.add('active'); - var io = new IntersectionObserver(function (entries) { - entries.forEach(function (entry) { - if (!entry.isIntersecting) return; - sections.forEach(function (s) { - s.link.classList.toggle('active', s.el === entry.target); + + window.addEventListener('popstate', function () { + var h = decodeURIComponent((location.hash || '').replace(/^#/, '')); + activateTarget(h || chapters[0].id, true, 'none'); + }); + + // Full-book instant search + var searchInput = document.querySelector('[data-doc-search]'); + var resultsBox = document.querySelector('.doc-search-results'); + + function runSearch() { + if (!searchInput || !resultsBox) return; + var q = (searchInput.value || '').trim().toLowerCase(); + if (!q) { + resultsBox.classList.remove('open'); + resultsBox.innerHTML = ''; + return; + } + var lang = document.body.getAttribute('data-lang') || 'zh'; + var hits = []; + + chapters.forEach(function (chap) { + var linkEl = chapterLinks.filter(function (a) { return a.getAttribute('data-chapter') === chap.id; })[0]; + var chapTitle = linkEl ? (linkEl.querySelector('.lang-' + lang) || linkEl).textContent : chap.id; + var scope = chap.querySelector('.lang-' + lang) || chap; + var blocks = scope.querySelectorAll('h2, h3, h4, h5, p, li, td, pre'); + var lastHeadingId = chap.id; + var lastHeadingTitle = chapTitle; + + blocks.forEach(function (node) { + if (/^H[2-5]$/.test(node.tagName)) { + if (node.id) lastHeadingId = node.id; + lastHeadingTitle = node.textContent || chapTitle; + } + if (hits.length >= 12) return; + var txt = (node.textContent || '').replace(/\s+/g, ' ').trim(); + var pos = txt.toLowerCase().indexOf(q); + if (pos === -1) return; + // Deduplicate consecutive hits pointing to the same target anchor + if (hits.length && hits[hits.length - 1].targetId === lastHeadingId) return; + var start = Math.max(0, pos - 24); + var snip = (start > 0 ? '…' : '') + txt.slice(start, pos + q.length + 46) + (pos + q.length + 46 < txt.length ? '…' : ''); + hits.push({ + targetId: lastHeadingId, + chapTitle: chapTitle, + secTitle: lastHeadingTitle, + snippet: snip }); }); - }, { rootMargin: '-18% 0px -68% 0px' }); - sections.forEach(function (s) { io.observe(s.el); }); + }); + + if (!hits.length) { + resultsBox.innerHTML = '
' + + (lang === 'zh' ? '未找到匹配内容' : 'No matching sections found') + + '
'; + } else { + resultsBox.innerHTML = hits.map(function (h) { + return '' + + '' + esc(h.chapTitle) + '' + + '' + esc(h.secTitle) + '' + + '' + esc(h.snippet) + '' + + ''; + }).join(''); + } + resultsBox.classList.add('open'); } + + if (searchInput && resultsBox) { + searchInput.addEventListener('input', runSearch); + searchInput.addEventListener('focus', function () { + if ((searchInput.value || '').trim()) runSearch(); + }); + document.addEventListener('click', function (e) { + if (!e.target.closest('.doc-search')) { + resultsBox.classList.remove('open'); + } + }); + } + + docRefreshHook = function () { + applyLang(currentLang); + rebuildSubToc(); + if (searchInput && (searchInput.value || '').trim()) runSearch(); + }; } + // Code block copy button document.addEventListener('click', function (e) { var btn = e.target.closest('[data-copy-code]'); - if (!btn || !navigator.clipboard) return; + if (!btn) return; var box = btn.closest('.doc-pre'); var codeEl = box && box.querySelector('pre code'); if (!codeEl) return; - navigator.clipboard.writeText(codeEl.textContent || '').then(function () { + var lang = document.body.getAttribute('data-lang') || 'zh'; + var scoped = codeEl.querySelector('.lang-' + lang); + var text = (scoped || codeEl).textContent || ''; + copyText(text).then(function () { btn.innerHTML = '已复制Copied'; setTimeout(function () { btn.innerHTML = '复制Copy'; @@ -606,9 +868,9 @@ } var copyBtn = e.target.closest('[data-copy]'); - if (copyBtn && navigator.clipboard) { + if (copyBtn) { var val = copyBtn.getAttribute('data-copy') || ''; - navigator.clipboard.writeText(val).then(function () { + copyText(val).then(function () { copyBtn.innerHTML = '已复制Copied'; setTimeout(function () { copyBtn.innerHTML = '复制Copy'; diff --git a/site/tokens.css b/site/tokens.css index 1d4bae5..0558f61 100644 --- a/site/tokens.css +++ b/site/tokens.css @@ -1,5 +1,5 @@ /* ============================================================ - * WTOffline Homepage Design Tokens + * WTOffline Homepage & Documentation Design Tokens * Aligned with the launcher ordnance palette: dark slate base, * signal crimson primary actions, subtle tactical cyan glow. * Supports dark (default) and light modes via [data-mode]. @@ -25,24 +25,25 @@ /* Corner radii */ --r-xs: 4px; --r-sm: 6px; - --r-md: 10px; --r-lg: 14px; + --r-md: 10px; /* Dark ordnance palette (default) */ --page: #0b0f11; --canvas: radial-gradient(circle at 18% 0%, #172026 0%, #0b0f11 58%); - --surface: rgba(20, 27, 31, 0.72); - --card: rgba(22, 29, 34, 0.84); - --elev: rgba(18, 24, 28, 0.90); - --glass-2: rgba(255, 255, 255, 0.035); + --surface: rgba(20, 27, 31, 0.78); + --card: rgba(22, 29, 34, 0.86); + --doc-card: rgba(16, 22, 26, 0.94); + --elev: rgba(18, 24, 28, 0.92); + --glass-2: rgba(255, 255, 255, 0.045); - --border: rgba(255, 255, 255, 0.09); - --border-2: rgba(255, 255, 255, 0.20); + --border: rgba(255, 255, 255, 0.10); + --border-2: rgba(255, 255, 255, 0.22); --grid-line: rgba(207, 216, 220, 0.09); - --text: #e8eef1; - --text-dim: rgba(207, 216, 220, 0.72); - --text-faint: rgba(207, 216, 220, 0.46); + --text: #edf2f5; + --text-dim: rgba(224, 232, 236, 0.84); + --text-faint: rgba(207, 216, 220, 0.66); --accent: #e53935; --accent-hover: #f04a46; @@ -60,23 +61,24 @@ --page: #eef2f5; --canvas: radial-gradient(circle at 18% 0%, #ffffff 0%, #e7edf2 62%); - --surface: rgba(255, 255, 255, 0.76); - --card: rgba(255, 255, 255, 0.88); - --elev: rgba(255, 255, 255, 0.94); - --glass-2: rgba(19, 25, 27, 0.035); + --surface: rgba(255, 255, 255, 0.82); + --card: rgba(255, 255, 255, 0.90); + --doc-card: rgba(255, 255, 255, 0.96); + --elev: rgba(255, 255, 255, 0.95); + --glass-2: rgba(19, 25, 27, 0.045); - --border: rgba(19, 25, 27, 0.10); - --border-2: rgba(19, 25, 27, 0.22); + --border: rgba(19, 25, 27, 0.11); + --border-2: rgba(19, 25, 27, 0.24); --grid-line: rgba(19, 25, 27, 0.08); - --text: #161d21; - --text-dim: rgba(22, 29, 33, 0.70); - --text-faint: rgba(22, 29, 33, 0.48); + --text: #141b1f; + --text-dim: rgba(20, 27, 31, 0.80); + --text-faint: rgba(20, 27, 31, 0.62); --accent: #d32f2f; --accent-hover: #b71c1c; --accent-soft: rgba(211, 47, 47, 0.12); - --accent-2: #0097a7; + --accent-2: #00838f; --ok: #2e7d32; --shadow-sm: 0 6px 20px rgba(19, 25, 27, 0.07);