diff --git a/mod-dev-docs/README.md b/mod-dev-docs/README.md index 832f49b..4f5d1cb 100644 --- a/mod-dev-docs/README.md +++ b/mod-dev-docs/README.md @@ -11,23 +11,23 @@ | 章节 | 内容概览 | | --- | --- | -| [01 · 快速入门与清单规范](zh-CN/01-quick-start.md) | 5 分钟做出第一个模组、目录结构、`mod.jsonc` 全字段表、依赖/互斥/排序、风险徽标与启动器调试 | -| [02 · 客户端数据包与 BLK 增量补丁](zh-CN/02-client-packs-and-blk.md) | 8 个可叠加 `.vromfs.bin` 包、BLK 补丁全部 7 种操作(含 `cloneBlock`)、13 种 BLK 类型写法、文本 `.blk` 自动编译、CSV 词条合并、`config.blk` 补丁 | -| [03 · 添加全新 3D 模型与贴图载具](zh-CN/03-custom-3d-vehicles.md) | `client/addon/res/`(`.grp` + `.dxp.bin`)跨盘 NTFS Junction 零拷贝挂载、挂进科技树/经济/图标/译名、原生涂装瞄具边界说明 | -| [04 · 客户端 GUI 补丁与声明式 EXE 补丁](zh-CN/04-client-gui-and-exe.md) | 增量 GUI 脚本补丁、新增原生 DaGui 弹窗、`sq.exe` Quirrel 完整字节码检查、声明式 `exe` 补丁与核心隔离保护红线 | -| [05 · 服务端零代码数值叠加(Tuning)](zh-CN/05-server-tuning.md) | 12 份 `server/tuning/*.jsonc` 说明、多层合并顺序、`$listOps` 列表增量操作(`append` / `prepend` / `upsertBy` / `removeBy`) | -| [06 · 服务端 JS/TS 脚本完整接口手册](zh-CN/06-server-scripting-api.md) | Node 24 原生 TS 语法要求、`WtoServerModContext`、独立存档区 `storage`、全部生命周期与对局钩子(含 `onFilterMissions`)、`char` / `matching` / `http` 路由与完整范例 | -| [07 · 排错、日志与最佳实践](zh-CN/07-troubleshooting-and-faq.md) | 定位 `launcher.log` 与本地服务器日志、冲突分析、防止损坏玩家存档、跨盘与非 NTFS 磁盘行为说明 | +| [01 · 快速入门与清单规范](zh-CN/01-quick-start.md) | 叠加架构、原版数据解包与查阅指南、5 分钟做出第一个模组、标准目录结构、`mod.jsonc` 全字段表、叠加能力徽标与依赖排序 | +| [02 · 客户端数据包与 BLK 增量补丁](zh-CN/02-client-packs-and-blk.md) | BLK 与 JSON 差异对照、8 个可叠加数据包、全部 7 种 BLK 补丁操作与 13 种类型、分房权重(BR ↔ `mrank`)速查表、`shop.blk` 与 `units.csv` 详解、从零克隆独立新坦克完整实战 | +| [03 · 添加全新 3D 模型与贴图载具](zh-CN/03-custom-3d-vehicles.md) | `.grp`/`.dxp.bin`/`.ddsx` 与跨盘 NTFS Junction 通俗说明、新车 6 步接入清单、`gift` 礼包机制与 AI 机器人池准入规则、配套外置资源边界 | +| [04 · 客户端 GUI 补丁与声明式 EXE 补丁](zh-CN/04-client-gui-and-exe.md) | DaGui 三件套(`.tpl`/`.css`/`.nut`)与 `gui/css.css` 注册规则、全小写精确路径与 `variants` 唯一命中机制、`sq.exe` 编译与完整字节码校验、声明式 `exe` 补丁与核心隔离锁 | +| [05 · 服务端零代码数值叠加(Tuning)](zh-CN/05-server-tuning.md) | 多层合并优先级(含启动器玩家覆盖说明)、12 份 `server/tuning/*.jsonc` 一览、`store.jsonc` 等核心字段速查与 `$listOps` 增量语法 | +| [06 · 服务端 JS/TS 脚本完整接口手册](zh-CN/06-server-scripting-api.md) | Node 24 可擦除 TS 语法对照与 VS Code 类型补全、`WtoServerModContext`、独立存档区、生命周期与对局钩子精确结构、`matchingApiFunc` 签名与三大路由对比、`official-map-selector` 全栈拆解 | +| [07 · 排错、日志与最佳实践](zh-CN/07-troubleshooting-and-faq.md) | 日志定位、常见报错速查表、开发调试热重载循环、`.zip` 打包发布规范、跨盘与非 NTFS 磁盘行为、开发与发布建议 | ### 自带官方模组模板(`templates/`) -以下 3 个模组会随 WTOffline 启动器自动分发到玩家首次初始化的全局 `mods/` 目录(默认关闭,勾选即用),可直接对照源码学习或复制改造: +以下 3 个模组会随 WTOffline 启动器自动分发到玩家首次初始化的全局 `mods/` 目录(默认关闭,勾选即用),可直接打开阅读源码或复制改造: | 模板目录 | 定位 | 演示的核心能力 | | --- | --- | --- | | `templates/example-vehicle-tweak/` | 零代码数据与本地化示例 | `server/tuning/battle.jsonc` + `wpcost.blk.patch.jsonc` + `lang/units.csv.patch.csv` | | `templates/example-server-script/` | 服务端脚本最小示例 | `server/index.ts`、`onDatasetsLoaded`、`profile.onRefresh`、独立存档区、自定义 `/mods//status` 路由 | -| `templates/official-map-selector/` | 实用全栈官方模组 | 模式选择 UI 按钮补丁 + 原生 DaGui 小地图网格弹窗 + 多语言词条 + 自定义匹配 RPC + 独立存档 + `battle.onFilterMissions` 白/黑名单选图 | +| `templates/official-map-selector/` | 实用全栈官方模组 | 模式选择 UI 按钮补丁 + `gui/css.css` 样式注册 + 原生 DaGui 小地图网格弹窗 + 多语言词条 + 自定义匹配 RPC + 独立存档 + `battle.onFilterMissions` 白/黑名单选图 | --- @@ -40,10 +40,20 @@ | Chapter | Topics | | --- | --- | -| [01 · Quick Start & Manifest](en/01-quick-start.md) | Build your first mod in 5 minutes, folder layout, full `mod.jsonc` schema, dependencies/conflicts/ordering, risk badges | -| [02 · Client Packs & BLK Patching](en/02-client-packs-and-blk.md) | 8 overlayable `.vromfs.bin` packs, all 7 BLK patch ops (including `cloneBlock`), all 13 BLK types, auto text-BLK compilation, CSV merging, `config.blk` patches | -| [03 · Custom 3D Vehicle Models](en/03-custom-3d-vehicles.md) | `client/addon/res/` (`.grp` + `.dxp.bin`) cross-drive zero-copy NTFS Junction mounting, tech tree/economy/icons/localization wiring, native skins/sights boundary | -| [04 · Client GUI & Declarative EXE Patches](en/04-client-gui-and-exe.md) | Incremental GUI script patches, adding standalone native DaGui modals, full Quirrel bytecode checks (`sq.exe`), declarative `exe` patches & core isolation lock | -| [05 · Server Code-Free Tuning Overlays](en/05-server-tuning.md) | All 12 `server/tuning/*.jsonc` files, multi-layer precedence, `$listOps` (`append`, `prepend`, `upsertBy`, `removeBy`) | -| [06 · Server JS/TS Scripting API Reference](en/06-server-scripting-api.md) | Node 24 erasable TypeScript rules, `WtoServerModContext`, isolated `storage`, all lifecycle & battle hooks (including `onFilterMissions`), `char` / `matching` / `http` routes | -| [07 · Troubleshooting & FAQ](en/07-troubleshooting-and-faq.md) | Reading logs, diagnosing conflicts, keeping player saves clean, cross-drive and exFAT fallback behavior | +| [01 · Quick Start & Manifest](en/01-quick-start.md) | Additive architecture, how to unpack & inspect stock game files, build your first mod in 5 minutes, folder layout, full `mod.jsonc` schema, additive capability badges & load-order rules | +| [02 · Client Packs & BLK Patching](en/02-client-packs-and-blk.md) | BLK vs JSON side-by-side intro, 8 overlayable `.vromfs.bin` packs, all 7 BLK patch ops & 13 BLK types, BR ↔ `mrank` conversion table, `shop.blk` & `units.csv` anatomy, end-to-end standalone tank clone walkthrough | +| [03 · Custom 3D Vehicle Models](en/03-custom-3d-vehicles.md) | Plain-language `.grp`/`.dxp.bin`/`.ddsx` & cross-drive NTFS Junction guide, 6-step custom 3D vehicle checklist, `gift` store packs & AI bot pool rules, companion files boundary | +| [04 · Client GUI & Declarative EXE Patches](en/04-client-gui-and-exe.md) | DaGui triad (`.tpl`/`.css`/`.nut`) & `gui/css.css` `@import` rule, lowercase case-sensitive paths & single-match `variants`, building & running `sq.exe` bytecode checks, declarative `exe` patches & core isolation lock | +| [05 · Server Code-Free Tuning Overlays](en/05-server-tuning.md) | Multi-layer precedence (including Launcher Tuning tab overrides), all 12 `server/tuning/*.jsonc` files, verified field quick-reference (`store.jsonc`, `battle.jsonc`, etc.), and `$listOps` rules | +| [06 · Server JS/TS Scripting API Reference](en/06-server-scripting-api.md) | Node 24 erasable TS Do/Don't & VS Code autocomplete setup, `WtoServerModContext`, isolated `storage`, exact battle hook payloads, `matchingApiFunc` signature & route comparison, `official-map-selector` full-stack case study | +| [07 · Troubleshooting & FAQ](en/07-troubleshooting-and-faq.md) | Reading logs, troubleshooting lookup table, development reload loop, `.zip` packaging & distribution rules, cross-drive/exFAT fallback behavior, and practical recommendations | + +### Official Bundled Mod Templates (`templates/`) + +The launcher automatically seeds these 3 ready-to-read official templates into the global `mods/` folder on first initialization (disabled by default—enable to try, or copy to start your own mod): + +| Template Folder | Scope | Demonstrated Capabilities | +| --- | --- | --- | +| `templates/example-vehicle-tweak/` | Code-free data & localization | `server/tuning/battle.jsonc` + `wpcost.blk.patch.jsonc` + `lang/units.csv.patch.csv` | +| `templates/example-server-script/` | Minimal server TypeScript mod | `server/index.ts`, `onDatasetsLoaded`, `profile.onRefresh`, isolated per-player storage, custom `/mods//status` HTTP route | +| `templates/official-map-selector/` | Full-stack official mod | Mode-select UI button patch + `gui/css.css` stylesheet registration + standalone native DaGui map-grid modal + localized labels + custom matching RPC + isolated storage + `battle.onFilterMissions` whitelist/blacklist filtering | diff --git a/mod-dev-docs/en/01-quick-start.md b/mod-dev-docs/en/01-quick-start.md index 4081822..60d59ea 100644 --- a/mod-dev-docs/en/01-quick-start.md +++ b/mod-dev-docs/en/01-quick-start.md @@ -1,40 +1,87 @@ # 01 · Quick Start & Manifest Reference -> **Target Spec**: `format: 1` · `api_version: "0.1-experimental"` (experimental; subject to breaking changes) +> **Target Spec**: `format: 1` · `api_version: "0.1-experimental"` (experimental API; subject to breaking changes as core development progresses) -## 1. Additive Mod Architecture +## 1. Core Concept: Additive Overlay Architecture -WTOffline uses a **stackable, additive** mod architecture. Mods supply incremental patches and added files rather than replacing full `.vromfs.bin` archives: +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 (`wtoffline/stock/`), applies core offline patches first, then layers every enabled mod's client patches and added files in the order shown on the **Mods** page; -2. Large 3D model and texture addons mount across drives with zero copying via **Windows NTFS Directory Junctions**; -3. The local server extracts static data from the overlaid packs, layers `server/tuning/*.jsonc` in the same order, and loads `server/index.ts` scripts; -4. Disabling a mod or switching presets cleanly unmounts junctions and restores stock packs. +1. Before launching the game, the launcher starts from clean stock backups (`/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. -- **Global repository**: defaults to `%APPDATA%\WTOffline Launcher\mods` (configurable to any drive under **Mods › Presets & repository**). -- **Per-client configuration**: toggles, load order, and presets live in each client's `/mods-config.json`. +- **Global mod repository**: defaults to `%APPDATA%\WTOffline Launcher\mods` (configurable to any drive under **Mods › Presets & repository**). +- **3 official templates seeded on first launch**: the first time the launcher initializes the global `mods/` folder, it automatically seeds **`example-vehicle-tweak`** (code-free vehicle & localization tweak), **`example-server-script`** (minimal server TypeScript mod), and **`official-map-selector`** (full-stack native DaGui modal + server map filter), all disabled by default. Click **Mods › Open mods folder** right away to inspect their code or duplicate one as a starting point! +- **Per-client configuration**: mod toggles, load order, and named presets are saved independently per client in `/mods-config.json`. --- -## 2. Build Your First Mod in 5 Minutes +## 2. Prerequisite: How to Unpack & Inspect Stock Game Files -1. Open **Mods › Open mods folder** in the launcher. -2. Create a folder `my-first-mod` containing `mod.jsonc`: +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.bin` | Tech-tree layout (`config/shop.blk`), vehicle prices/RP/BR/modifications (`config/wpcost.blk`), unit classification tags (`config/unittags.blk`), items, and unlocks | +| `aces.vromfs.bin` | Tank models & armor (`gamedata/units/tankmodels/*.blk`), aircraft flight models (`gamedata/flightmodels/*.blk`), ships, shells, and missiles (`gamedata/weapons/...`) | +| `gui.vromfs.bin` | All client UI Quirrel scripts (`scripts/**/*.nut`), Handyman templates (`gui/**/*.tpl`), and DaGui stylesheets (`gui/**/*.css`) | +| `lang.vromfs.bin` | Localization tables (`lang/units.csv` vehicle names, `lang/menu.csv` UI strings, `lang/units_weaponry.csv` weapons & ammo names) | +| `ui/atlases.vromfs.bin` | Tech-tree and local web store vehicle silhouette icons (`gameuiskin/_ico.svg`) | +| `ui/images.vromfs.bin` | Stat-card and crew-slot vehicle portraits (`units/.ddsx`) | + +> **Note on the backup folder**: Treat `/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//`. + +### 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": { "en": "My First Mod", "zh-CN": "我的第一个模组" }, + "name": { + "zh-CN": "我的第一个模组", + "en": "My First Mod" + }, "version": "0.1.0", "author": "YourName", - "description": "Doubles Silver Lions and Research Points battle rewards.", + "description": { + "zh-CN": "把对局银狮和研发点倍率调整为 2 倍。", + "en": "Doubles Silver Lions and Research Points battle rewards." + }, "api_version": "0.1-experimental", "game_versions": ["2.61.0.*"] } ``` -3. Create `my-first-mod/server/tuning/battle.jsonc`: +4. Create `my-first-mod/server/tuning/battle.jsonc`: ```jsonc { @@ -43,22 +90,22 @@ WTOffline uses a **stackable, additive** mod architecture. Mods supply increment } ``` -4. Return to the launcher (the Mods page refreshes automatically on focus), enable your mod, and click **Launch**. +5. Switch back to the launcher window (the Mods page refreshes automatically on focus, or click **Refresh**), enable your mod, and click **Launch**. --- -## 3. Standard Folder Layout +## 4. Complete Standard Folder Layout -Create only the folders your mod actually needs: +Create only the subdirectories your mod actually uses—unused folders can be omitted completely: ```text / -├─ mod.jsonc # Required: manifest -├─ server/ # Optional: server extensions -│ ├─ tuning/ # *.jsonc tuning overlays -│ └─ index.ts (or index.mjs / .js) # server script entry -└─ client/ # Optional: client extensions - ├─ packs/ # .vromfs.bin additive overlays +├─ 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/ @@ -67,39 +114,52 @@ Create only the folders your mod actually needs: │ ├─ game.vromfs.bin/ │ ├─ ui/atlases.vromfs.bin/ │ └─ ui/images.vromfs.bin/ - ├─ addon/ # 3D model & texture pack (res/*.grp, res/*.dxp.bin) - ├─ gui-patches/ # declarative GUI script patches - ├─ exe-patches/ # declarative exe patches + ├─ 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 patch + └─ config-blk.patch.jsonc # optional root config.blk incremental patch ``` --- -## 4. `mod.jsonc` Schema Reference +## 5. Full `mod.jsonc` Schema Reference -Unknown fields are rejected by strict validation. +Manifest parsing enforces **strict whitelist validation**: typos or unknown keys are rejected immediately with a detailed error message on the Launcher Mods page. | Field | Required | Type | Description | | --- | --- | --- | --- | -| `format` | Yes | `1` | Manifest format version (currently `1`) | -| `id` | Yes | `string` | Globally unique ID matching `/^[a-z0-9][a-z0-9._-]{0,63}$/` | -| `name` | Yes | `string \| { [lang]: string }` | Display name (plain string or locale map) | -| `version` | Yes | `string` | Mod version (SemVer recommended) | +| `format` | Yes | `1` | Manifest schema version, currently fixed to integer `1` | +| `id` | Yes | `string` | Globally unique mod ID matching `/^[a-z0-9][a-z0-9._-]{0,63}$/` (lowercase letters, digits, `.`, `_`, `-`; must start with letter/digit; max 64 chars; `.` recommended) | +| `name` | Yes | `string \| { [lang]: string }` | Display name as a plain string or locale map (e.g. `zh-CN`, `en`) | +| `version` | Yes | `string` | Mod version string (SemVer such as `0.1.0` recommended) | | `author` | Yes | `string` | Author or team name | -| `description` | No | `string \| { [lang]: string }` | Short description | -| `api_version` | Yes | `string` | Target API tag, currently `"0.1-experimental"` | -| `game_versions` | No | `string[]` | Game version wildcards (e.g. `["2.61.0.*"]`); mismatch warns only | -| `requires` | No | `string[]` | Required dependency mod IDs (blocking error if missing/disabled) | -| `conflicts` | No | `string[]` | Incompatible mod IDs (blocking error if both enabled) | -| `load_after` | No | `string[]` | Recommended load-order predecessors (used by Auto-sort) | -| `load_before` | No | `string[]` | Recommended load-order successors | -| `server` | No | `{ entry?: string, tuning?: string }` | Custom relative paths for server script entry and tuning folder | +| `description` | No | `string \| { [lang]: string }` | Short summary as a plain string or locale map | +| `api_version` | Yes | `string` | Target API version tag, currently fixed to `"0.1-experimental"` | +| `game_versions` | No | `string[]` | Supported game build wildcards (e.g. `["2.61.0.*"]`); mismatches emit a warning without blocking launch | +| `requires` | No | `string[]` | 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**) | +| `conflicts` | No | `string[]` | Mutually incompatible mod IDs; enabling both raises a **blocking error** | +| `load_after` | No | `string[]` | 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_before` | No | `string[]` | Optional mods this mod should load before; also participates in order hints & **Auto-Sort** | +| `server` | No | `{ entry?: string, tuning?: string }` | Explicit relative paths (no `..`) overriding default auto-detection of `server/index.{ts,mjs,js}` and `server/tuning` | --- -## 5. Load Order, Risk Badges & Conflict Detection +## 6. Automatically Computed Capability & Risk Badges (Additive Multi-Badge) -- **Priority**: items lower in the list load later and take higher priority. -- **Risk badges**: automatically inferred as `data`, `gui`, `script`, and `exe`. -- **Conflict checks**: missing/disabled dependencies and declared conflicts block launching; whole-file overrides warn; shared BLK/CSV/tuning overlays report informational merge notices. +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`: + +- **Data / Assets (`data`)**: contains `server/tuning/`, `client/packs/`, `client/addon/`, `client/files/`, or `client/config-blk.patch.jsonc` (a manifest-only mod with none of `gui`/`script`/`exe` also defaults to `data`); +- **UI Patches (`gui`)**: contains `client/gui-patches/`; +- **Server Script (`script`)**: contains an executable server JS/TS entry script; +- **Binary Patches (`exe`)**: contains `client/exe-patches/` (high-risk; guarded by the core offline isolation patch lock). + +--- + +## 7. Load Order Rules & Conflict Detection + +- **Load order & priority**: mods load **top-to-bottom; items lower in the list (larger index) load later and take higher priority**; +- **One-click Auto-Sort**: the launcher's **Auto-sort by dependencies** button topologically sorts mods using `requires`, `load_after`, and `load_before` together; +- **Additive merge** (`info`): when multiple mods patch the same BLK, CSV, or `tuning` file, their edits stack cleanly in load order; +- **Order & override warnings** (`warning`): emitted when a mod sits above a `requires` / `load_after` target, mismatches `game_versions`, or replaces an entire pack/companion file already modified by an earlier mod; +- **Blocking errors** (`error`): missing `requires` dependencies, disabled dependencies, or simultaneously enabled `conflicts` prevent launch and highlight the exact items to fix. diff --git a/mod-dev-docs/en/02-client-packs-and-blk.md b/mod-dev-docs/en/02-client-packs-and-blk.md index 3faa4bc..9cc6382 100644 --- a/mod-dev-docs/en/02-client-packs-and-blk.md +++ b/mod-dev-docs/en/02-client-packs-and-blk.md @@ -1,53 +1,458 @@ # 02 · Client Packs & BLK Incremental Patching -## 1. Supported `.vromfs.bin` Packs - -Place overlays under `client/packs//`: -- **Always rebuilt from stock**: `char.vromfs.bin`, `aces.vromfs.bin`, `gui.vromfs.bin` -- **On-demand backup & restore**: `lang.vromfs.bin`, `mis.vromfs.bin`, `game.vromfs.bin`, `ui/atlases.vromfs.bin`, `ui/images.vromfs.bin` - -Because the local server extracts static datasets directly from the overlaid packs on startup, vehicles added or edited in `shop.blk` and `wpcost.blk` automatically flow into research trees, prices, modifications, AI pools, and offline store bundle GUIDs. +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. --- -## 2. File Handling Rules +## 1. Plain-Language Intro: What Is BLK & Why Does It Differ from JSON? -1. **`.patch.jsonc`** — Type-preserving structured BLK patch applied to `` inside the pack. -2. **`.patch.csv`** — Semicolon-separated localization CSV merger keyed by column 0. -3. **Any other file** — Added or replaced directly. Plain text `.blk` files are compiled to binary BLK automatically before packing. +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 } + } + ] +} +``` --- -## 3. BLK Patch Operations (`*.blk.patch.jsonc`) +## 2. The 8 Overlayable Client Data Packs -Every patch file has `{ "ops": [...] }`. Path segments support indexed sibling selectors such as `"range[2]"` (zero-based). +Place your files under `client/packs//` matching the target archive's internal path: -- **`setParam`**: `{ "op": "setParam", "path": [...], "name": "...", "value": ..., "createBlocks": false }` -- **`addParam`**: appends a repeated parameter without removing existing entries (ideal for `slaveUnit`, `folder`, `aircraftGift`). -- **`removeParam`**: removes all matching params by `name` (or only those matching optional `value`). -- **`upsertBlock`**: finds or creates a block along `path` and merges `block.params` and `block.blocks`. -- **`addBlock`**: inserts a new child block (`before` / `after` sibling anchor optional). -- **`removeBlock`**: deletes the block at `path`. -- **`cloneBlock`**: deep-clones an existing block (`from`) into `toParent` under `newName`, optionally applying nested `ops` rooted at the cloned block (fastest way to derive a modded vehicle in `wpcost.blk`). +| Target Directory | Common Contents | Backup 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.blk` | Always 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.blk` | Always 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 CSVs | Backed up on demand, restored on disable | +| `client/packs/mis.vromfs.bin/` | `gamedata/missions/.../*.blk` multiplayer and custom missions | Backed up on demand, restored on disable | +| `client/packs/game.vromfs.bin/` | `danetlibs/...`, `game/...` scripts and configs | Backed up on demand, restored on disable | +| `client/packs/ui/atlases.vromfs.bin/` | `gameuiskin/_ico.svg` (tech-tree & local web store silhouette icons) | Backed up on demand, restored on disable | +| `client/packs/ui/images.vromfs.bin/` | `units/.ddsx` or `.png` (stat-card / crew-slot vehicle images) | Backed up on demand, restored on disable | -### Explicit BLK Types - -Use `{ "type": "", "value": }` whenever an exact Dagor BLK type is needed: -`string`, `int`, `real`, `bool`, `int64`, `point2`, `point3`, `point4`, `ipoint2`, `ipoint3`, `ipoint4`, `color` (`[r,g,b,a]` or packed `0xAARRGGBB`), `matrix` (12 reals). +> **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. --- -## 4. Localization CSV Patches (`*.csv.patch.csv`) +## 3. Three File Handling Modes Inside Packs (Auto-Detected by Suffix) + +The patcher determines how to process each file under `client/packs//` by its filename suffix: + +1. **`.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. **`.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 + ] +} +``` + +- `path` is an array of child block names starting from the BLK root, e.g. `["country_usa", "army", "range[0]"]`; +- Duplicate sibling blocks (such as consecutive `range` blocks in `shop.blk`) can be addressed precisely with **`name[index]`** (zero-based); omitting `[index]` selects occurrence `0`; +- `[]` refers to the root block of the current document. + +### 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": "", "value": }`: + +| `type` | Text BLK Suffix | `value` Example & Notes | +| --- | --- | --- | +| `string` | `:t` | `"us_m2a4"` | +| `int` | `:i` | `120` (signed 32-bit integer) | +| `real` | `:r` | `1.5` (encoded strictly as 32-bit float `:r` even if written as `2`) | +| `bool` | `:b` | `true` / `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` | `:m` | Array 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`: + +- **Forward formula (`mrank` → displayed BR)**: `BR = 1.0 + Math.floor(mrank / 3) + [0, 0.3, 0.7][mrank % 3]` +- **Reverse formula (displayed BR → `mrank`)**: `(wholePart - 1) × 3` plus the decimal step (`+0` for `.0`, `+1` for `.3`, `+2` for `.7`). For example, `11.7` → `(11 - 1) × 3 + 2 = 32`! + +### 5.1 Complete `mrank` ↔ Displayed BR Lookup Table + +| `mrank` | Displayed BR | `mrank` | Displayed BR | `mrank` | Displayed BR | `mrank` | Displayed BR | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `0` | **1.0** | `10` | **4.3** | `20` | **7.7** | `30` | **11.0** | +| `1` | **1.3** | `11` | **4.7** | `21` | **8.0** | `31` | **11.3** | +| `2` | **1.7** | `12` | **5.0** | `22` | **8.3** | `32` | **11.7** | +| `3` | **2.0** | `13` | **5.3** | `23` | **8.7** | `33` | **12.0** | +| `4` | **2.3** | `14` | **5.7** | `24` | **9.0** | `34` | **12.3** | +| `5` | **2.7** | `15` | **6.0** | `25` | **9.3** | `35` | **12.7** | +| `6` | **3.0** | `16` | **6.3** | `26` | **9.7** | `36` | **13.0** | +| `7` | **3.3** | `17` | **6.7** | `27` | **10.0** | `37` | **13.3** | +| `8` | **3.7** | `18` | **7.0** | `28` | **10.3** | `38` | **13.7** | +| `9` | **4.0** | `19` | **7.3** | `29` | **10.7** | `39` | **14.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 Name | Value Range | Meaning | +| --- | --- | --- | +| `rank` | `1` .. `8` | **Tech-Tree Era Tier (Rank I – VIII)**: controls which horizontal tier row the vehicle occupies, tier unlock gates, and default store rank-tier pricing | +| `economicRankArcade` | `0` .. `39+` | **Arcade Battles (AB)** matchmaking `mrank` | +| `economicRankHistorical` | `0` .. `39+` | **Realistic Battles (RB)** default matchmaking `mrank` (RB was originally called *Historical Battles*) | +| `economicRankSimulation` | `0` .. `39+` | **Simulator Battles (SB)** default matchmaking `mrank` | +| `economicRankTankHistorical` | `0` .. `39+` | *(Optional)* Split **Ground RB** `mrank` for aircraft/helicopters with separate air vs ground BRs; falls back to `economicRankHistorical` when omitted | +| `economicRankTankSimulation` | `0` .. `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/` 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 `` 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 Pattern | Where It Appears in Game | Example (for `us_m2a4_mod_demo`) | +| --- | --- | --- | +| `_shop` | **Tech-tree card, crew slot bar, and local web store card** short name | `"M2A4 (Mod Demo)"` / `"M2A4(教学改型)"` | +| `_0` | **Stat-card header, research completion modal, and battle debriefing** full formal title | `"Light Tank M2A4 (Mod Demo)"` / `"M2A4 轻型坦克(教学改型)"` | +| `_1` | In-battle **medium-distance 3D HUD marker** name | `"M2A4 Demo"` / `"M2A4 教学型"` | +| `_2` | In-battle **far-distance HUD marker / compact killfeed** short name | `"M2A4"` / `"M2A4"` | + +Example `client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`: ```csv "";"";"";"" -"my_custom_tank_shop";"M1A2 Mod";"M1A2 魔改型";"M1A2 魔改型" +"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" ``` -Existing keys update only the supplied non-empty language columns; new keys are appended cleanly. +- Fields must be separated by semicolons `;` and wrapped in double quotes, with column headers on line 1 (list only the language columns you want to populate; omitted columns keep their stock values or default to empty); +- Existing row keys update only your non-empty columns in place; new keys are appended to the end of the file. --- -## 5. Root `config.blk` Patches (`client/config-blk.patch.jsonc`) +## 7. Patching Root `config.blk` (`client/config-blk.patch.jsonc`) -Uses the exact same BLK patch format against `/config.blk`. The launcher backs up the stock `config.blk` automatically and restores it when no enabled mod patches it. +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! diff --git a/mod-dev-docs/en/03-custom-3d-vehicles.md b/mod-dev-docs/en/03-custom-3d-vehicles.md index 6461d81..814718d 100644 --- a/mod-dev-docs/en/03-custom-3d-vehicles.md +++ b/mod-dev-docs/en/03-custom-3d-vehicles.md @@ -1,33 +1,97 @@ # 03 · Adding Custom 3D Vehicle Models & Textures -## 1. How 3D Asset Mounting Works +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. -Verified directly against 2.61.0.x `aces.exe` (`dlContent.cpp`) and `config/settings.blk`: -- Any addon path under `/pkg_user/` skips the `res/grp_hdr.vromfs.bin` check and directly scans `/res/` for all `.grp` (3D geometry/skeleton/collision) and `.dxp.bin` (DDSx texture) archives; -- If a mod ships a compiled CDK `res/grp_hdr.vromfs.bin`, the patcher mounts it under `content/pkg_wto_` so the native `grp_hdr` loader handles it; -- The patcher automatically registers all enabled mod addon folders in `aces.vromfs.bin` `config/settings.blk` (`addons`, `addons_no_check`, `addonsWithBasePath`). +--- -### Cross-Drive Zero-Copy Mounting +## 1. Plain-Language Asset Glossary & Zero-Copy Mounting -Each mod's `client/addon/` is mounted into `/content/pkg_user/` via a **Windows NTFS Directory Junction**: -- Works across drives (e.g. `mods/` on C: or D:, client on J:); -- Requires no administrator privileges; -- Uses 0 extra bytes and mounts/unmounts in ~1 ms without touching source files in `mods/`. +When working with 3D vehicle mods, you will encounter four core asset and filesystem terms: + +| Term / Extension | Plain-Language Meaning | +| --- | --- | +| **`.grp`** | Dagor 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.bin`** | Dagor Engine **compressed texture pack**, bundling multiple diffuse, normal, and metallic/roughness DDSx textures referenced by name inside `.grp` materials. | +| **`.ddsx`** | A **single** Dagor compressed texture file (DDSx), commonly used for UI stat-card vehicle portraits (`ui/images.vromfs.bin/units/.ddsx`) or standalone skin textures. | +| **NTFS Directory Junction** | Think of it as an **OS-level zero-copy folder shortcut** built into Windows NTFS: when the game engine opens `/content/pkg_user/`, 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 `/content/pkg_user/`) **skips the mandatory `res/grp_hdr.vromfs.bin` header check and directly scans `/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 `/content/pkg_wto_` 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 -1. **`client/addon/res/.grp` + `.dxp.bin`**: 3D model and textures exported via War Thunder CDK; -2. **`client/packs/aces.vromfs.bin/gamedata/units/.../.blk`**: vehicle FM/DM/weapons (plain text BLK compiles automatically); -3. **`client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc`**: economy, BR, modifications (use `cloneBlock` from a similar stock vehicle); -4. **`client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc`** & **`unittags.blk.patch.jsonc`**: tech tree slot and unit tags; -5. **`client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`**: localized names (`_shop`, `_0`, `_1`, `_2`); -6. **`client/packs/ui/atlases.vromfs.bin/gameuiskin/_ico.svg`** & optional **`ui/images.vromfs.bin/units/.ddsx`**: silhouette icon (used in tech tree and local web store) and statcard image. +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/_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. Native Skins, Sights & Companion Files Boundary +## 3. Regular Tech-Tree Vehicles vs `gift` Store Packs (& AI Bot Pool Rules) -- Standalone user skins (`UserSkins/`), sights (`UserSights/`), and missions (`UserMissions/`) continue to use the game's native folders and are never managed or deleted by the launcher. -- Large overhaul/vehicle mods may optionally bundle companion skins, sights, or sound banks under `client/files/`. Exclusive subdirectories under `UserSkins/`, `UserSights/`, and `UserMissions/` mount via cross-drive Junctions; any target colliding with a player-owned native file is skipped with a warning and never overwritten. +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**: + +### Option A: Regular Silver Lions Tech-Tree Vehicle (Recommended If You Want AI Bots to Drive It) + +- 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_`** (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**. diff --git a/mod-dev-docs/en/04-client-gui-and-exe.md b/mod-dev-docs/en/04-client-gui-and-exe.md index ec34528..d150d32 100644 --- a/mod-dev-docs/en/04-client-gui-and-exe.md +++ b/mod-dev-docs/en/04-client-gui-and-exe.md @@ -1,33 +1,216 @@ # 04 · Client GUI Patches & Declarative EXE Patches -> **Experimental Notice**: GUI script patches and declarative `exe` patches depend on target client builds and may need updates after game or core 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. Extending Client UI (Recommended Pattern) +## 1. Plain-Language Intro: War Thunder's DaGui UI Triad (`.tpl` + `.css` + `.nut`) -1. Place new standalone `.nut`, `.tpl`, and `.css` files under `client/packs/gui.vromfs.bin/` (keep paths lowercase to match stock archive conventions); -2. Place minimal entry-point edits under `client/gui-patches//` using `patch.jsonc` + `find.nut` / `replace.nut` fragments. +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: -Core offline GUI patches always run first; mod GUI patches apply afterward in load order. Every `find` snippet must match uniquely once or the patch is skipped safely. `{{LOCAL_ENDPOINT}}` in replacement text expands to `127.0.0.1:`. +| Extension | Role | Plain-Language Explanation | +| --- | --- | --- | +| **`.tpl`** | **Handyman Layout Template** | Similar to HTML + Mustache (e.g. `gui/missions/wtomapselectormodal.tpl`); declares UI containers, buttons, element `id`s, and data-binding tags (`<>`, `{{#cards}}...{{/cards}}`). | +| **`.css`** | **DaGui Stylesheet** | Controls widths, heights, margins, colors, fonts, and custom attribute state selectors (such as `[wtoSelected=yes]`). | +| **`.nut`** | **Quirrel UI Script** | War Thunder's statically-scoped scripting language (derived from Squirrel); subclasses `BaseGuiHandlerWT` to render `.tpl` views, handle button clicks, and call local server RPCs. | -### Mandatory Quirrel Bytecode Check +### Best-Practice UI Pattern: "Standalone Files for Logic + Minimal Patch for Entry Hook" -Before shipping any new or patched `.nut` script, compile the complete resulting script with `compilestring` via `sq.exe` to catch lexical scope conflicts, reserved keywords (such as `base`), and forward references that would otherwise hang login at "Loading": +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:` (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](https://github.com/GaijinEntertainment/quirrel)** repository, check out commit `19f17df9b6ee43c91ef5c635fd45970ec76c5dbe` (matching 2.61 clients), and build `sq` with CMake + Visual Studio (C++17): ```powershell -& "build\quirrel-cli\bin\Release\sq.exe" -e "local f = compilestring(readfile('your_script.nut'), 'your_script.nut'); println('OK')" +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')" ``` --- -## 2. Declarative EXE Patches (`client/exe-patches/`) +## 4. Declarative EXE Patches (`client/exe-patches/`) -Mods reuse WTOffline's `@wto/exepatch` format (`patch.jsonc` with `id`, `title`, `features`, `requires`, and `variants` using `signature`, `string_ref`, or `within` locators). **Never distribute modified `aces.exe` binaries.** +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. -### Core Isolation Lock (Hard Security Boundary) +```text +client/exe-patches/ +└─ my-tweak/ + └─ patch.jsonc +``` -1. Core offline and isolation patches are planned first and their byte ranges are locked; -2. Any mod `exe` patch whose write range overlaps a protected core patch is **rejected** (`overlaps protected core patch`); -3. Overlapping patches between two mods reject the later patch with the conflicting mod ID; -4. Unmatched patterns on another game build are skipped cleanly and logged without breaking the core build. +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. diff --git a/mod-dev-docs/en/05-server-tuning.md b/mod-dev-docs/en/05-server-tuning.md index ed53f89..804fc52 100644 --- a/mod-dev-docs/en/05-server-tuning.md +++ b/mod-dev-docs/en/05-server-tuning.md @@ -1,31 +1,200 @@ # 05 · Server Code-Free Tuning Overlays -The local server stores all offline-defined economy, battle, store, marketplace, chest, redeem-code, clan, and limit values in **12 `.jsonc` tuning files**. Mods can overlay any of them under `server/tuning/.jsonc` without writing code. +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/`. -## 1. Merge Precedence +> Browse all 12 default tuning files with full comments online: +> **[WT-Offline `apps/server/tuning/` Source Directory](https://git.wto-project.net/Sh3ll_in_Sh3ll/WT-Offline/src/branch/main/apps/server/tuning)** -1. Shipped defaults (`apps/server/tuning/.jsonc`) -2. Enabled mods' `server/tuning/.jsonc` in load order -3. Player overrides (`/tuning/.jsonc`, highest priority) +--- -## 2. All 12 Tuning Files +## 1. Multi-Layer Merge Precedence (Watch Out for Launcher Player Overrides!) -`battle.jsonc`, `battle-economy.jsonc`, `store.jsonc`, `marketplace.jsonc`, `trophies.jsonc`, `supply-chests.jsonc`, `recycling.jsonc`, `redeem-codes.jsonc`, `new-profile.jsonc`, `research.jsonc`, `clans.jsonc`, `limits.jsonc`. +Whenever the local server starts, each `tuning/.jsonc` file is merged from lowest to highest priority (later layers override earlier ones): -## 3. Additive List Operations (`$listOps`) +```text +1. Shipped offline defaults (apps/server/tuning/.jsonc) +2. Enabled Mod 1's server/tuning/.jsonc +3. Enabled Mod 2's server/tuning/.jsonc + ... (applied top-to-bottom in Launcher "Mods" load order) +N. Player overrides saved in the Launcher "Tuning" tab (/tuning/.jsonc — HIGHEST PRIORITY!) +``` -Objects merge recursively by key; plain arrays replace the previous array. To stack items across multiple mods without clobbering, wrap list edits in `{ "$listOps": [...] }`: +- **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 (`/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 Name | Governs | Merge Structure | Typical Mod Use Cases | +| --- | --- | --- | --- | +| `battle.jsonc` | SL/RP multipliers, room size, AI bot count & respawns, `brSpreadMrank`, sub-mode chance, Strike UCAV spawn score | Flat key-value object | Custom reward rates, 16v16 capacity tweaks, tighter/wider BR spread, bot respawn counts | +| `battle-economy.jsonc` | Base action prices and battle settlement economy curves | Nested key-value object | Rebalance kills vs captures vs assists rewards | +| `store.jsonc` | GE packs, SL packs, Premium tiers, and `vehiclePacks` (`multiVehiclePacks` list, `byRank` list, `byVehicle` map) | Lists (`$listOps`) + map merge | Price custom `gift` vehicles, create custom multi-vehicle bundles | +| `marketplace.jsonc` | Marketplace vehicle/skin coupon reference prices, rarity tiers & fees | Nested object + map merge | Adjust market economy or price custom market coupons | +| `trophies.jsonc` | Classic `supplyTrophies` (SL chest, Veteran chest) & `directVehicles` GE buyout price | List (`$listOps`) + object | Add custom gacha chests, tweak rare vehicle drop weights | +| `supply-chests.jsonc` | External-inventory supply chests and drop pools | List (`$listOps`) + object | Add custom external-inventory chests | +| `recycling.jsonc` | Item recycling and crafting/re-roll recipes | Nested key-value object | Customize item recycling ratios and output weights | +| `redeem-codes.jsonc` | Dynamic Premium/GJN code prefixes and one-time `fixedCodes` | Object + map merge | Add custom promo redeem codes for your modpack | +| `new-profile.jsonc` | Starting Silver Lions, Golden Eagles, and GJN balances for new saves | Flat key-value object | High-resource sandbox presets or zero-balance hardcore presets | +| `research.jsonc` | Automatic default next-research target selection | Flat key-value object | Customize auto-selected research behavior | +| `clans.jsonc` | Squadron member caps, activity rules, and preset offline squadrons | Object + list (`$listOps`) | Add custom preset squadrons | +| `limits.jsonc` | Max items per purchase, battle report & log retention caps | Flat key-value object | Raise 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"! { - "multiVehiclePacks": { - "$listOps": [ - { "op": "append", "items": [{ "id": "mod_duo_pack", "priceGjn": 49.99, "vehicles": ["us_m2a4"] }] }, - { "op": "upsertBy", "key": "id", "item": { "id": "wto_pack_two_fronts", "priceGjn": 19.99 } }, - { "op": "removeBy", "key": "id", "value": "some_pack_id" } - ] + "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 + } + } } } ``` -Supported ops: `append`, `prepend`, `upsertBy`, `removeBy`. +### 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": "", "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": "", "value": }` — 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 } + ] + } + ] + } + ] + } +} +``` diff --git a/mod-dev-docs/en/06-server-scripting-api.md b/mod-dev-docs/en/06-server-scripting-api.md index 1cf12df..2de31dd 100644 --- a/mod-dev-docs/en/06-server-scripting-api.md +++ b/mod-dev-docs/en/06-server-scripting-api.md @@ -1,40 +1,265 @@ # 06 · Server JS/TS Scripting API Reference -> **Experimental Warning (API `0.1-experimental`)**: All server script contracts, internal catalogue classes, and hook shapes are unstable and may change across releases without backwards compatibility. +> **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 & TypeScript Rules +--- -Server scripts run inside Electron 43's bundled **Node.js 24** with built-in TypeScript type stripping (`erasableSyntaxOnly` syntax: no `enum`, `namespace`, or parameter properties). Pre-bundled `.mjs` / `.js` files are also supported. +## 1. Runtime Environment, Node 24 Erasable TS Rules & VS Code Autocomplete -Default entry lookup order: `server/index.ts` → `server/index.mjs` → `server/index.js` (or explicit `server.entry` in `mod.jsonc`). +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) { + async setup(ctx: WtoServerModContext) { ctx.logger.info('mod initialized'); }, }; ``` -Full TypeScript definitions live in `packages/mods/src/server-api.ts`. +> 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` +--- -- `apiVersion`, `manifest`, `modDir`, `gameFolder`, `dataFolder`, `port` -- `logger`: `{ info(msg), warn(msg), error(msg) }` (prefixed with `[mod:]`) -- `storage`: - - `storage.forPlayer(userId)` → atomic JSON file under `/saves//mods/.json` (never mutate stock `profile.blk` with custom keys) - - `storage.shared()` → `/mods-data/.json` -- `hooks`: - - `onDatasetsLoaded(datasets)` — inspect/mutate `vehicles`, `battleEconomy`, `battleSpawnRules`, `multiplayerMissions`, `uiLabels`, `unitNames`, or `get(id)` / `set(id, value)` - - `onCataloguesReady(catalogues)` — access `tuning`, `gameModes`, `profiles`, `accounts`, `research`, `equipment`, `repair`, `store`, `inventory`, `trophies`, `items`, `crew`, `decor`, `unlocks`, `clans`, `battleMatchmaker`, `battleEconomy`, `battleStreaks`, `notifyInventoryChanged()`, `notifyUser(userId, eventName, payload)` - - `onServerListening({ port })` / `onServerClosing()` - - `profile.onRefresh(profile, userId)` - - `battle.onBeforeMatchmake({ userId, eventName, request })` - - `battle.onFilterMissions({ userId, modeId, modeName, economicName, minMrank, maxMrank, missions })` — return a filtered/reordered subset of candidate missions (empty results safely fall back to the prior pool) - - `battle.onLiveFact({ userId, roomId, fact })` - - `battle.onAfterSettle({ userId, roomId, summary })` -- `routes`: - - `routes.char.register(action, handler)` / `routes.char.wrap(action, wrapper)` - - `routes.matching.register(method, handler)` / `routes.matching.wrap(method, wrapper)` (callable from client Quirrel via `matchingApiFunc`) - - `routes.http.register(subPath, handler)` — automatically namespaced under `/mods//...` (supports exact paths and `/*` wildcards) +## 2. `WtoServerModContext` Property Reference + +| Property | Type | Description | +| --- | --- | --- | +| `ctx.apiVersion` | `string` | Active experimental API tag (`"0.1-experimental"`) | +| `ctx.manifest` | `ModManifest` | Parsed `mod.jsonc` manifest of this mod | +| `ctx.modDir` | `string` | Absolute path to this mod's root directory (read static mod files via `node:fs`) | +| `ctx.gameFolder` | `string` | Active offline game copy root directory | +| `ctx.dataFolder` | `string` | Active client data folder (saves, caches, logs) | +| `ctx.port` | `number` | Bound local server port for the current session | +| `ctx.logger` | `{ info, warn, error }` | Logger prefixed with `[mod:]`, written to `launcher.log` and diagnostic exports | +| `ctx.storage` | `ModStorageApi` | Atomic JSON storage scoped per player or shared across accounts (Section 3) | +| `ctx.hooks` | `ServerModHooksApi` | Lifecycle, profile, matchmaking, and battle settlement hooks (Section 4) | +| `ctx.routes` | `ServerModRoutesApi` | `matching`, `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: /saves//mods/.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: /mods-data/.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.kind` | When It Fires | Additional `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 API | Best For | Payload Format | How 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 out | Quirrel `matchingApiFunc("wto_mod.", callback, params)` | +| **`ctx.routes.http`** | Rich HTML/CSS/JS web dashboards, external browser panels, or REST endpoints (auto-namespaced under `/mods//...`) | Standard HTTP request / response | System browser or War Thunder's embedded browser at `http://{{LOCAL_ENDPOINT}}/mods//...` | +| **`ctx.routes.char`** | Wrapping stock `cln_*` profile actions or adding low-level binary BLK actions | Raw binary/text `Buffer` | Low-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//...`** and support both exact paths and `/*` wildcards: + +```ts +ctx.routes.http.register('/panel', () => ({ + status: 200, + contentType: 'text/html; charset=utf-8', + body: '

My Mod Control Panel

', +})); + +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 /saves//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! diff --git a/mod-dev-docs/en/07-troubleshooting-and-faq.md b/mod-dev-docs/en/07-troubleshooting-and-faq.md index 4faa480..4fc506e 100644 --- a/mod-dev-docs/en/07-troubleshooting-and-faq.md +++ b/mod-dev-docs/en/07-troubleshooting-and-faq.md @@ -1,21 +1,83 @@ -# 07 · Troubleshooting & Best Practices +# 07 · Troubleshooting, Logs, Reload Loop & Packaging -## 1. Where to Check Logs +## 1. Where to Check Logs When Something Goes Wrong -Open **Settings › Diagnostics › Open logs folder** or **About › Export diagnostics**: -- **`launcher.log`**: filter `[build]` for pack/GUI/exe patch reports, `[mods]` for Junction mount and native-file conflict warnings, and `[mod:]` for server script logs and stack traces. -- **`/.game_logs/*.clog`**: client Quirrel runtime errors and `[PACK]` / `pkg_user` asset loading logs. +All mod build and runtime logs flow into the launcher's standard log directory—open **Settings › Diagnostics › Open logs folder** or **About › Export diagnostics**: -## 2. Common Issues +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:]`: see server `tuning` validation errors, script load stack traces, and everything printed via `ctx.logger.info/warn/error`. +2. **Game Client Runtime Logs (`/.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. -- **Discovery error in Mods page**: check `mod.jsonc` JSON syntax, unknown keys, `id` format, and `server.entry` path. -- **Blocking errors on Launch**: enable missing `requires` dependencies or disable one of two mutually conflicting mods. -- **Node TS syntax error**: avoid `enum`/`namespace`/parameter properties in raw `.ts`, or bundle to `.mjs`. -- **`overlaps protected core patch`**: mod `exe` patch collided with a locked core isolation patch; choose a non-overlapping site. -- **Client hangs at "Loading"**: run full `sq.exe` `compilestring` bytecode checks on all modified/added `.nut` files. +--- -## 3. Cross-Drive & Non-NTFS Behavior +## 2. Common Issues & Solutions Lookup Table -- NTFS drives mount `client/addon/` and exclusive `UserSkins/`/`UserSights/`/`UserMissions/` folders via cross-drive **NTFS Directory Junctions** (no admin required, 0 extra space). -- Flat shared files (`sound/mod/*.bank`) try file symlink → same-drive hardlink → size/mtime cached copy. -- exFAT drives automatically fall back to incremental cached copies. +| Symptom / Log Message | Common Cause | Solution | +| --- | --- | --- | +| Discovery error on Launcher Mods page | `mod.jsonc` syntax error, unknown field name, uppercase/invalid `id`, or missing `server.entry` file | Validate `mod.jsonc` against the schema table in Chapter 01 Section 5 | +| "Blocking mod errors" when clicking Launch | Missing or disabled `requires` dependency, or two enabled mods declaring `conflicts` | Enable the missing dependency or disable one of the conflicting mods highlighted in red | +| `server/tuning/*.jsonc` changes appear ignored | Test client has a manual override saved in the Launcher **Tuning** tab (`/tuning/*.jsonc` has highest priority), or `store.jsonc` placed `vehiclePacks` subkeys at root | Reset 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 error | Raw `.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 effect | Added `.css` to `client/packs/gui.vromfs.bin/` without registering it in `gui/css.css` | Add a `client/gui-patches/` patch on `gui/css.css` appending `@import "folder\style.css"` (Chapter 04 Section 2.2) | +| Client `matchingApiFunc` callback does not fire or `params` arrive empty | Swapped the 2nd and 3rd arguments of `matchingApiFunc` | Use `matchingApiFunc(methodName, callback, params)` (`callback` is 2nd, `params` is 3rd) | +| Game hangs indefinitely on "Loading" before hangar | Resulting 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 patch` | Mod `client/exe-patches/` overlaps locked core offline/isolation patch bytes | Core isolation bytes are protected; pick a non-overlapping site or use a server-side hook | +| Log reports `target already exists as a native/player file` | A 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__...`) | + +--- + +## 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//`) 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=`)—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 `/` 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! +2. **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/`) 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 `.` and prefix custom vehicle IDs, weapons, skin subfolders, custom matching RPCs (`wto_mod..*`), 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. diff --git a/mod-dev-docs/zh-CN/01-quick-start.md b/mod-dev-docs/zh-CN/01-quick-start.md index 3ec228a..5039896 100644 --- a/mod-dev-docs/zh-CN/01-quick-start.md +++ b/mod-dev-docs/zh-CN/01-quick-start.md @@ -4,21 +4,61 @@ ## 1. 核心思路:添加式叠加架构 -WTOffline 采用**添加式、按加载顺序逐层叠加**的模组架构,模组通过增量补丁与新增文件作用于客户端与服务端,不支持直接整包替换原版 `.vromfs.bin` 归档文件: +WTOffline 采用**添加式、按加载顺序逐层叠加**的模组架构。模组通过增量补丁与新增文件作用于客户端与服务端,**不支持直接整包替换原版 `.vromfs.bin` 归档文件**: -1. 启动游戏前,启动器从纯净原版备份(`wtoffline/stock/`)出发,先应用离线版核心补丁,再按玩家在「模组」页排好的顺序,依次叠加所有启用模组的客户端补丁与新增文件; +1. 启动游戏前,启动器从纯净原版备份(`<游戏副本>/wtoffline/stock/`)出发,先应用离线版核心补丁,再按玩家在「模组」页排好的顺序,依次叠加所有已启用模组的客户端补丁与新增文件; 2. 大体积 3D 模型和贴图包通过 **Windows NTFS 目录联接点(Junction)** 跨盘零拷贝挂载; -3. 本地服务器启动时自动读取叠加后的客户端数据包,再按同一顺序合并各模组的 `server/tuning/*.jsonc` 与加载 `server/index.ts` 脚本; -4. 关掉模组或切换预设,启动器自动拆除联接点并还原原版文件,不破坏客户端本体。 +3. 本地服务器启动时自动读取叠加后的客户端数据包,再按同一顺序合并各模组的 `server/tuning/*.jsonc` 并加载 `server/index.ts` 脚本; +4. 关掉模组或切换预设时,启动器自动拆除联接点并从 `wtoffline/stock/` 还原原版文件,不破坏客户端本体。 - **全局模组仓库**:默认位于 `%APPDATA%\WTOffline Launcher\mods`(可在启动器「模组 › 预设与仓库」修改到任意硬盘)。 -- **每客户端独立配置**:开关、加载顺序和命名预设分别保存在各自客户端的数据目录 `mods-config.json` 里。 +- **首次启动自带 3 个官方模板**:启动器首次初始化全局 `mods/` 目录时,会自动放入 **`example-vehicle-tweak`**(零代码改车与译名)、**`example-server-script`**(服务端 TS 脚本最小示例)和 **`official-map-selector`**(原生 DaGui 弹窗 + 服务端选图全栈模组)三个现成模组(默认未勾选)。点击「模组 › 打开模组目录」即可直接阅读源码或复制改造! +- **每客户端独立配置**:模组开关、加载顺序和命名预设分别保存在各自客户端的数据目录 `<数据目录>/mods-config.json` 中。 --- -## 2. 5 分钟做出你的第一个模组 +## 2. 前置准备:如何解包与查阅原版游戏数据 -1. 在启动器里打开 **「模组 › 打开模组目录」**; +在动手改载具属性、挂科技树或写界面补丁之前,你需要先知道原版游戏里的内部载具 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`: @@ -50,13 +90,13 @@ WTOffline 采用**添加式、按加载顺序逐层叠加**的模组架构,模 } ``` -5. 切回启动器窗口(页面会自动刷新,或点击「刷新」),勾选启用并启动游戏即可生效。 +5. 切回启动器窗口(页面获得焦点时会自动刷新,也可点击「刷新」),勾选启用你的模组并点击「启动游戏」即可生效。 --- -## 3. 完整标准目录结构 +## 4. 完整标准目录结构 -只创建你用到的目录,未用到的部分完全不必建立: +按需创建你实际用到的子目录,未用到的部分完全不必建立: ```text / @@ -75,7 +115,7 @@ WTOffline 采用**添加式、按加载顺序逐层叠加**的模组架构,模 │ ├─ ui/atlases.vromfs.bin/ │ └─ ui/images.vromfs.bin/ ├─ addon/ # 3D 模型与贴图扩展包(res/*.grp, res/*.dxp.bin) - ├─ gui-patches/ # GUI 脚本增量补丁(与本体 patches/gui 同格式) + ├─ gui-patches/ # GUI 脚本/模板/样式增量补丁(与本体 patches/gui 同格式) ├─ exe-patches/ # 声明式 exe 补丁(与本体 patches/exe 同格式) ├─ files/ # 可选:大型整合包附带的配套涂装/瞄具/音效/任务 └─ config-blk.patch.jsonc # 可选:游戏根目录 config.blk 的增量补丁 @@ -83,42 +123,43 @@ WTOffline 采用**添加式、按加载顺序逐层叠加**的模组架构,模 --- -## 4. `mod.jsonc` 全字段参考 +## 5. `mod.jsonc` 全字段参考 -清单元数据解析采用**严格白名单校验**,写错字段名或出现未定义字段会被拒绝并在启动器报错区显示具体原因。 +清单元数据解析采用**严格白名单校验**,写错字段名或出现未定义字段会被直接拒绝,并在启动器报错区显示具体原因。 | 字段 | 必填 | 类型 | 说明 | | --- | --- | --- | --- | | `format` | 是 | `1` | 清单格式版本号,目前固定为整数 `1` | -| `id` | 是 | `string` | 全局唯一模组 ID,仅允许小写字母、数字、`.`、`_`、`-`,首字符须为字母或数字,最长 64 位(推荐 `<作者>.<模组名>`) | -| `name` | 是 | `string \| { [lang]: string }` | 展示名称,支持字符串或按语言代码映射(如 `zh-CN`、`en`) | +| `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 }` | 模组简介,支持多语言对象 | +| `description` | 否 | `string \| { [lang]: string }` | 模组简介,支持单字符串或多语言对象 | | `api_version` | 是 | `string` | 目标接口标识,当前固定填 `"0.1-experimental"` | -| `game_versions` | 否 | `string[]` | 声明适配的游戏版本通配符列表(如 `["2.61.0.*"]`);与客户端版本不符时仅警告,不强行阻断 | -| `requires` | 否 | `string[]` | 前置依赖模组 ID 列表;缺失或未启用时作为**阻塞错误**阻止启动 | +| `game_versions` | 否 | `string[]` | 声明适配的游戏版本通配符列表(如 `["2.61.0.*"]`);与客户端版本不符时仅发出警告,不强行阻断启动 | +| `requires` | 否 | `string[]` | 前置依赖模组 ID 列表:缺失或未启用时作为**阻塞错误**阻止启动;同时约束加载顺序(若排在前置模组上方会触发 `dependency-order` 顺序警告,并参与启动器「按依赖自动排序」) | | `conflicts` | 否 | `string[]` | 已知互斥模组 ID 列表;同时启用时作为**阻塞错误**阻止启动 | -| `load_after` | 否 | `string[]` | 建议排在这些模组 ID 之后(越靠后优先级越高);供启动器「按依赖自动排序」使用 | -| `load_before` | 否 | `string[]` | 建议排在这些模组 ID 之前 | +| `load_after` | 否 | `string[]` | 建议排在这些可选模组 ID 之后(越靠下越晚加载、优先级越高);不强制要求对方启用,若同时启用则参与顺序提示与「按依赖自动排序」 | +| `load_before` | 否 | `string[]` | 建议排在这些可选模组 ID 之前;同样参与顺序提示与「按依赖自动排序」 | | `server` | 否 | `{ entry?: string, tuning?: string }` | 显式覆盖服务端入口文件(相对路径,不得含 `..`)和 `tuning` 目录路径(默认自动探测 `server/index.{ts,mjs,js}` 与 `server/tuning`) | --- -## 5. 启动器自动计算的能力与风险徽标 +## 6. 启动器自动计算的能力与风险徽标(多徽标叠加) -启动器扫描模组目录后会自动标注以下徽标,帮助玩家判断安全性: +启动器扫描模组目录后会自动计算并展示能力徽标。**徽标是多选累加(非互斥)的**——例如同时包含数据包修改与服务端脚本的模组会同时显示 `data` 和 `script` 两个徽标,而 `official-map-selector` 会同时显示 `data`、`gui`、`script` 三个徽标: -- **数据/资源(`data`)**:仅包含 `server/tuning`、`client/packs`、`client/addon`、`client/files`、`config-blk.patch.jsonc`; +- **数据/资源(`data`)**:包含 `server/tuning/`、`client/packs/`、`client/addon/`、`client/files/` 或 `client/config-blk.patch.jsonc`(若模组仅含清单且无 `gui`/`script`/`exe`,也默认归类显示 `data`); - **界面补丁(`gui`)**:包含 `client/gui-patches/`; -- **服务端脚本(`script`)**:包含可执行服务端 JS/TS 脚本; -- **二进制补丁(`exe`)**:包含 `client/exe-patches/`(高风险,且受核心隔离补丁锁保护)。 +- **服务端脚本(`script`)**:包含可执行服务端 JS/TS 入口脚本; +- **二进制补丁(`exe`)**:包含 `client/exe-patches/`(高风险,且受离线核心隔离补丁锁保护)。 --- -## 6. 排序规则与冲突检测 +## 7. 排序规则与冲突检测 -- **优先级**:列表中**越靠下(序号越大)越晚加载、优先级越高**; -- **叠加合并**(提示 `info`):两个模组对同一个 BLK / CSV / `tuning` 文件做增量补丁时,按顺序先后叠加; -- **文件覆写**(警告 `warning`):后序模组用整文件替换了前序模组改过的数据包文件或外置文件; -- **阻塞错误**(错误 `error`):缺少 `requires` 前置、前置未启用、或触发 `conflicts` 互斥时,启动器禁止启动并高亮提示处理。 +- **加载顺序与优先级**:列表中**从上到下依次加载;越靠下(序号越大)越晚加载、覆盖优先级越高**; +- **一键自动排序**:启动器的「按依赖自动排序」会综合全部模组的 `requires`、`load_after` 与 `load_before` 进行拓扑排序; +- **叠加合并**(提示 `info`):两个模组对同一个 BLK / CSV / `tuning` 文件做增量补丁时,按顺序先后安全叠加; +- **顺序与覆写警告**(警告 `warning`):模组排在了 `requires` / `load_after` 目标之前、目标游戏版本不匹配、或后序模组用整文件替换了前序模组修改过的数据包文件/外置配套文件; +- **阻塞错误**(错误 `error`):缺少 `requires` 前置模组、前置模组未启用、或同时启用了声明 `conflicts` 互斥的模组时,启动器禁止启动并高亮提示处理。 diff --git a/mod-dev-docs/zh-CN/02-client-packs-and-blk.md b/mod-dev-docs/zh-CN/02-client-packs-and-blk.md index 3d748b3..c97bee0 100644 --- a/mod-dev-docs/zh-CN/02-client-packs-and-blk.md +++ b/mod-dev-docs/zh-CN/02-client-packs-and-blk.md @@ -1,43 +1,82 @@ # 02 · 客户端数据包与 BLK 增量补丁 -大多数战雷模组(魔改载具性能、炮弹穿深、导弹机动、科技树排布、价格权重、新任务、新译名、载具图标)都落在游戏的数据包(`.vromfs.bin`)里。本章介绍如何以**完全可叠加、互不顶掉**的方式修改这些数据包。 +绝大多数《战争雷霆》数据模组(调整载具性能、炮弹穿深、导弹机动、科技树排布、银狮/研发点价格、分房权重、本地化译名、载具图标)都落在游戏的 `.vromfs.bin` 数据包中。本章讲解如何以**完全可叠加、多模组互不顶掉**的方式修改这些数据包,并在章末带你从零克隆出一辆能在美系科技树看到并直接试驾的独立新坦克。 --- -## 1. 支持叠加的 8 个客户端数据包 +## 1. 先懂概念:什么是 BLK?它为什么和 JSON 不一样? -把文件按目标包名放进 `client/packs/<包路径>/` 下即可: +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/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/<载具名>_ico.svg`(科技树与本地商城剪影图标) | 按需自动备份,关闭还原 | -| `client/packs/ui/images.vromfs.bin/` | `units/<载具名>.ddsx` 或 `.png`(资料卡/乘员栏载具图) | 按需自动备份,关闭还原 | +| `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,无需手工同步两遍。 +> **自动联动服务端**:本地服务器在启动时直接读取叠加后的 `.vromfs.bin`。因此你通过补丁往 `shop.blk` / `wpcost.blk` 新增或修改载具后,服务端会自动识别新车价格、前置科技树、研发点、改装件、分房权重、AI 机器人池与礼包 GUID,无需手工同步两遍。 --- -## 2. 包内文件的 3 种处理模式(按后缀自动识别) +## 3. 包内文件的 3 种处理模式(按后缀自动识别) 构建器根据你在 `client/packs/<包>/` 下放置的文件名自动决定处理方式: -1. **`<原路径>.patch.jsonc` → BLK 结构化增量补丁**:解析目标 `.blk` 为保留类型的内存树,按 `ops` 逐条修改后重新编码为自包容二进制 BLK 写回; -2. **`<原路径>.patch.csv` → CSV 本地化增量合并**:按第 1 列词条键合并进目标 `.csv`(已有键更新对应语言列,新键追加到表尾); -3. **其余文件(如 `my_tank.blk`、`my_tank_ico.svg`)→ 新增或替换文件**: - - 如果路径以 `.blk` 结尾且你的源文件是**可读文本 BLK**(如从 CDK/解包工具改出来的),构建器会自动将其编译为游戏引擎所需的**二进制 BLK** 写进包内; - - 如果已经是二进制 BLK 或 `.svg` / `.ddsx` / `.nut` / `.tpl`,则原样写入包内。 +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`,则原样写入包内。 --- -## 3. BLK 增量补丁(`*.blk.patch.jsonc`)完整手册 +## 4. BLK 增量补丁(`*.blk.patch.jsonc`)完整手册 -### 3.1 基本格式与路径寻址 +### 4.1 基本格式与路径寻址 ```jsonc { @@ -48,12 +87,15 @@ ``` - `path` 是从 BLK 根节点出发的子块名数组,例如 `["country_usa", "army", "range[0]"]`; -- 同名子块(如 `shop.blk` 里连续多个 `range` 块)可以用 **`名称[索引]`**(0 起始)精确定位,不写索引默认命中第 0 个; -- `[]` 表示根节点本身。 +- 同名并列子块(如 `shop.blk` 里连续多个 `range` 块)可以用 **`名称[索引]`**(0 起始)精确定位;不写索引默认命中第 0 个同名子块; +- `[]` 表示当前文档根节点本身。 -### 3.2 全部 7 种操作(`op`) +### 4.2 全部 7 种操作(`op`) + +#### ① `setParam`:设置参数(存在则覆盖并去重同名项,不存在则新增) + +修改已有块上的单个字段时,**永远优先用 `setParam`**: -#### ① `setParam`:设置参数(存在则覆盖并去重,不存在则新增) ```jsonc { "op": "setParam", @@ -64,7 +106,8 @@ } ``` -#### ② `addParam`:追加同名参数(不删除已有同名项,适合 `slaveUnit`、`folder`、`aircraftGift` 等重复键) +#### ② `addParam`:追加同名参数(不删除已有同名项,适合 `slaveUnit`、`folder`、`aircraftGift` 等可重复键) + ```jsonc { "op": "addParam", @@ -74,7 +117,8 @@ } ``` -#### ③ `removeParam`:删除参数(不填 `value` 删除全部同名参数;填 `value` 只删匹配值) +#### ③ `removeParam`:删除参数(不填 `value` 删除全部同名参数;填 `value` 只删值匹配的项) + ```jsonc { "op": "removeParam", @@ -83,7 +127,8 @@ } ``` -#### ④ `upsertBlock`:查找或创建子块,并合并传入的 `params` 与 `blocks` +#### ④ `upsertBlock`:确保路径子块存在,并向其追加 `params` 与 `blocks` + ```jsonc { "op": "upsertBlock", @@ -97,22 +142,27 @@ } ``` -#### ⑤ `addBlock`:在父块下新增一个子块(支持 `before` / `after` 指定插入位置) +> **重要行为说明(避免重复键踩坑)**:如果目标路径的块**原本不存在**,`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_m1a2_sep2_abrams", + "after": "us_m3a1_stuart", "block": { "params": [ - { "name": "rank", "value": { "type": "int", "value": 8 } } + { "name": "rank", "value": { "type": "int", "value": 1 } }, + { "name": "reqAir", "value": "us_m2a4" } ] } } ``` #### ⑥ `removeBlock`:删除指定路径的子块 + ```jsonc { "op": "removeBlock", @@ -120,7 +170,10 @@ } ``` -#### ⑦ `cloneBlock`:复制同文档里的已有块为新名称并嵌套 `ops` 微调(魔改/衍生新车利器!) +#### ⑦ `cloneBlock`:深拷贝同文档里的已有块为新名称并嵌套 `ops` 微调(衍生新车神器!) + +在 `wpcost.blk` 和 `unittags.blk` 里,一辆载具包含几十个维修/乘员/改装件/武器预设子块。用 `cloneBlock` 可以一键完整克隆原版原型车,再用嵌套 `ops` 只改差异字段: + ```jsonc { "op": "cloneBlock", @@ -135,48 +188,123 @@ ] } ``` -> 注意:`cloneBlock` 内部的嵌套 `ops` 是以**克隆出来的新块为根节点**(所以改它自身字段时 `path` 写 `[]`)。 -### 3.3 全部 13 种 BLK 数据类型写法 +> 注意:`cloneBlock` 内部的嵌套 `ops` 是以**刚克隆出来的新块为根节点**运行的,所以修改新块自身顶层参数时 `path` 写 `[]`。 -直接写 JS 原始值时,构建器会优先沿用原字段的 BLK 类型(找不到原字段时:字符串→`string`,布尔→`bool`,整数→`int`,小数→`real`)。需要强制指定类型时,写 `{ "type": "<类型>", "value": <值> }`: +### 4.3 全部 13 种 BLK 数据类型写法 -| `type` | BLK 文本后缀 | `value` 示例 | +直接写 JSON 原始值时,构建器会优先沿用目标块已有同名字段的 BLK 类型(若无同名字段:字符串 → `string`,布尔 → `bool`,整数 → `int`,含小数 → `real`)。为确保万无一失(尤其是把浮点字段设为 `2.0` 时 JSON 解析为整数 `2`),推荐显式写成 `{ "type": "<类型>", "value": <值> }`: + +| `type` | BLK 文本后缀 | `value` 示例与说明 | | --- | --- | --- | | `string` | `:t` | `"us_m2a4"` | -| `int` | `:i` | `120` | -| `real` | `:r` | `1.5`(即使数值为 `2`,也会严格按浮点写入) | -| `bool` | `:b` | `true` / `false` | -| `int64` | `:i64` | `"133700000000000000"` 或整数 | -| `point2` | `:p2` | `[1.0, 2.5]` | -| `point3` | `:p3` | `[0.0, 1.5, -2.0]` | -| `point4` | `:p4` | `[0.0, 1.0, 0.0, 1.0]` | -| `ipoint2` | `:ip2` | `[10, 20]` | -| `ipoint3` | `:ip3` | `[1, 2, 3]` | -| `ipoint4` | `:ip4` | `[0, 1, 2, 3]` | -| `color` | `:c` | `[255, 128, 0, 255]`(`[r, g, b, a]`)或打包整数 `0xAARRGGBB` | -| `matrix` | `:m` | 12 个浮点数的数组(4 行 × 3 列) | +| `int` | `:i` | `120`(32 位有符号整数) | +| `real` | `:r` | `1.5`(即使写 `2`,也会严格按 32 位浮点 `:r` 编码) | +| `bool` | `:b` | `true` / `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` | `:m` | 12 个浮点数的数组(4 行 × 3 列变换矩阵) | --- -## 4. CSV 本地化增量合并(`*.csv.patch.csv`) +## 5. 分房权重(BR)与内部 `mrank`(`economicRank*`)换算表 -在 `client/packs/lang.vromfs.bin/lang/` 下放置与原文件同名加 `.patch.csv` 的文件(如 `units.csv.patch.csv`、`menu.csv.patch.csv`): +新手打开 `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` | 面板 BR | `mrank` | 面板 BR | `mrank` | 面板 BR | `mrank` | 面板 BR | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `0` | **1.0** | `10` | **4.3** | `20` | **7.7** | `30` | **11.0** | +| `1` | **1.3** | `11` | **4.7** | `21` | **8.0** | `31` | **11.3** | +| `2` | **1.7** | `12` | **5.0** | `22` | **8.3** | `32` | **11.7** | +| `3` | **2.0** | `13` | **5.3** | `23` | **8.7** | `33` | **12.0** | +| `4` | **2.3** | `14` | **5.7** | `24` | **9.0** | `34` | **12.3** | +| `5` | **2.7** | `15` | **6.0** | `25` | **9.3** | `35` | **12.7** | +| `6` | **3.0** | `16` | **6.3** | `26` | **9.7** | `36` | **13.0** | +| `7` | **3.3** | `17` | **6.7** | `27` | **10.0** | `37` | **13.3** | +| `8` | **3.7** | `18` | **7.0** | `28` | **10.3** | `38` | **13.7** | +| `9` | **4.0** | `19` | **7.3** | `29` | **10.7** | `39` | **14.0** | + +### 5.2 `wpcost.blk` 模式后缀与科技树等级 `rank` 的区别 + +战雷沿用了远古内测时期的模式英文名,千万不要把**科技树大等级 `rank`** 和**分房权重 `economicRank*`** 搞混: + +| 字段名 | 取值范围 | 真实含义 | +| --- | --- | --- | +| `rank` | `1` .. `8` | **科技树时代等级(Rank I – VIII)**:决定它在科技树第几大行、受哪一级的开线数量门槛限制,以及默认套用哪一档商店礼包价格 | +| `economicRankArcade` | `0` .. `39+` | **街机娱乐(AB, Arcade Battles)** 的分房 `mrank` | +| `economicRankHistorical` | `0` .. `39+` | **历史性能(RB, Realistic Battles)** 的默认分房 `mrank`(战雷早期将历史模式称为 *Historical Battles*) | +| `economicRankSimulation` | `0` .. `39+` | **全真模拟(SB, Simulator Battles)** 的默认分房 `mrank` | +| `economicRankTankHistorical` | `0` .. `39+` | (可选)飞机/直升机进入**陆战历史(Ground RB)**时的独立对地分房权重;不填时沿用 `economicRankHistorical` | +| `economicRankTankSimulation` | `0` .. `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` 中为新载具添加译名时,每辆载具 `` 共有 **4 个标准词条键**,分别对应不同界面与视距: + +| 词条键格式 | 游戏内显示位置 | 示例(以 `us_m2a4_mod_demo` 为例) | +| --- | --- | --- | +| `_shop` | **科技树格子、底部乘员槽位、本地网页商店卡片**上的简短名称 | `"M2A4 (Mod Demo)"` / `"M2A4(教学改型)"` | +| `_0` | **资料卡顶部标题、研发完成弹窗、战后结算详单**里的完整正式全称 | `"Light Tank M2A4 (Mod Demo)"` / `"M2A4 轻型坦克(教学改型)"` | +| `_1` | 战斗中**中距离 3D 视野目标标记**上显示的中等长度名称 | `"M2A4 Demo"` / `"M2A4 教学型"` | +| `_2` | 战斗中**远距离目标标记 / 极简击杀播报**显示的超短型号或车种名 | `"M2A4"` / `"M2A4"` | + +CSV 补丁文件写法示例(`client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`): ```csv "";"";"";"" -"my_custom_tank_shop";"M1A2 Mod";"M1A2 魔改型";"M1A2 魔改型" -"my_custom_tank_0";"M1A2 Mod Experimental";"M1A2 实验魔改型";"M1A2 實驗魔改型" +"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 列 ID 在原表已存在,只更新你提供的非空语言列;不存在则追加到表尾。 +- 必须以分号 `;` 分隔并用双引号包裹每个字段,第 1 行写表头列名(只需列出你要填的语言列,未列出的语言列会自动保留原值或留空); +- 如果第 1 列 ID 在原表已存在,只更新你提供的非空语言列;不存在则自动追加到表尾。 --- -## 5. 修改游戏根目录 `config.blk`(`client/config-blk.patch.jsonc`) +## 7. 修改游戏根目录 `config.blk`(`client/config-blk.patch.jsonc`) -如果模组需要调整游戏根目录的 `config.blk`(例如开启音效包 `sound{ enable_mod:b=yes }` 或指定自定义机库 `hangarBlk:t="..."`),放一份标准 BLK 补丁到 `client/config-blk.patch.jsonc` 即可: +如果模组需要调整游戏根目录的 `config.blk`(例如开启音效模组开关 `sound{ enable_mod:b=yes }` 或指定自定义机库 `hangarBlk:t="..."`),放一份标准 BLK 补丁到 `client/config-blk.patch.jsonc` 即可: ```jsonc { @@ -192,4 +320,139 @@ } ``` -启动器会自动先备份原版 `config.blk` 到 `wtoffline/stock/config.blk`,关掉模组后自动还原。 +启动器会在首次修改前自动将原版 `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 飙车! diff --git a/mod-dev-docs/zh-CN/03-custom-3d-vehicles.md b/mod-dev-docs/zh-CN/03-custom-3d-vehicles.md index 9bec5b2..7df17fd 100644 --- a/mod-dev-docs/zh-CN/03-custom-3d-vehicles.md +++ b/mod-dev-docs/zh-CN/03-custom-3d-vehicles.md @@ -1,23 +1,28 @@ # 03 · 添加全新 3D 模型与贴图载具 -本章专门讲解如何在 WTOffline 中制作**带自定义 3D 模型(`.grp`)和贴图(`.dxp.bin`)的全新载具模组**,并让多款不同作者的新车模组同时叠加共存、跨盘零拷贝秒挂、关闭即还原。 +本章专门讲解如何在 WTOffline 中制作**带自定义 3D 模型(`.grp`)和贴图包(`.dxp.bin`)的全新载具模组**,让多款不同作者的新车模组同时叠加共存、跨盘零拷贝秒挂、关闭即还原。 --- -## 1. 引擎加载机制(为什么放 `client/addon/` 就够了) +## 1. 核心术语通俗说明与跨盘零拷贝机制 -经对 2.61.0.x 客户端 `aces.exe` 与 `config/settings.blk` 核对: -- 引擎启动时会读取 `aces.vromfs.bin` `config/settings.blk` 中的 `addons`、`addons_no_check` 与 `addonsWithBasePath` 三个列表; -- 凡是路径包含 `/pkg_user/` 的扩展目录,引擎会**跳过 `res/grp_hdr.vromfs.bin` 强制校验,直接扫描 `<目录>/res/` 下的全部 `.grp` 模型与 `.dxp.bin` 贴图包并注册进全局资源管理器**,同时读取里面的 `gamedata/units/unitsList.blk`; -- 如果模组自带正式 War Thunder CDK 编译的 `res/grp_hdr.vromfs.bin`,启动器会自动改挂到 `content/pkg_wto_` 走原生 `grp_hdr` 路径。 +在接触 3D 载具模组时,你会遇到以下 4 个高频底层名词——其实它们非常直观: -### 跨盘零拷贝挂载(不复制几个 GB 的模型!) +| 名词 / 后缀 | 通俗解释 | +| --- | --- | +| **`.grp`** | Dagor 引擎的 **3D 模型与骨架归档文件**(由官方 War Thunder CDK `AssetViewer` / 导出器编译生成),内含多级细节网格(LOD)、骨骼动画节点(`animChar`)、碰撞体与内构损伤模块(DM)几何体。 | +| **`.dxp.bin`** | Dagor 引擎的**批量压缩贴图包**,把一辆或多辆载具用到的多张漫反射、法线、金属度贴图打包在同一个文件里供 `.grp` 材质按名索引。 | +| **`.ddsx`** | **单张** Dagor 压缩贴图文件(DDSx),常用于 UI 资料卡载具立绘(如 `ui/images.vromfs.bin/units/<载具id>.ddsx`)或涂装单贴图。 | +| **NTFS 目录联接点(Junction)** | 可以理解成 **Windows 文件系统底层的“零拷贝文件夹快捷方式”**:游戏引擎访问 `<游戏副本>/content/pkg_user/<模组ID>` 时,操作系统直接把读写透明指向你放在任意盘符 `mods/` 里的源文件夹——**无需管理员权限、跨盘可用、占用 0 字节额外硬盘空间、挂载和拆除只需约 1 毫秒**! | -无论全局 `mods/` 目录在 C 盘还是 D 盘、游戏副本在 J 盘,启动器都会用 **Windows NTFS 目录联接点(Junction)** 把你的 `client/addon/` 直接挂载到 `<游戏副本>/content/pkg_user/<安全模组ID>`: -- **不需要管理员权限**; -- **支持跨盘符**; -- **0 字节额外空间、约 1 毫秒完成**; -- 关闭模组时只拆除联接点本身,绝不删改 `mods/` 里的源文件。 +### 引擎是如何自动发现 `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/` 里的源文件。 --- @@ -40,36 +45,53 @@ mods/demo-new-mbt/ ├─ char.vromfs.bin/ │ └─ config/ │ ├─ wpcost.blk.patch.jsonc # ③ 价格、研发点、权重、改装件(用 cloneBlock 最快) - │ ├─ shop.blk.patch.jsonc # ④ 挂进对应国家科技树位置 - │ └─ unittags.blk.patch.jsonc # ④ 注册载具类型/年代/标签 + │ ├─ 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 # ⑥ 科技树与本地商城剪影图标(文件名全小写) + │ └─ us_mbt_demo_ico.svg # ⑥ 科技树与本地商城剪影图标(文件名必须全小写) └─ ui/images.vromfs.bin/ └─ units/ - └─ us_mbt_demo.ddsx # ⑥ 载具资料卡/乘员栏卡片图(可选,无图时游戏回退占位) + └─ us_mbt_demo.ddsx # ⑥ 资料卡/乘员栏载具大图(可选,缺失时自动回退占位图) ``` -### 关键细节提醒 +### 关键核对要点 -1. **确保 `wpcost.blk` 与 `shop.blk` 的载具块名完全一致**: - - 本地服务器会从叠加后的 `char.vromfs.bin` 自动提取这辆车的研发链、银狮/金鹰/礼包价格、分房权重、改装件与挂载预设; - - 如果在 `wpcost.blk` 里设置了 `gift:t="msi_notebook"`,构建器会自动给这辆新车分配确定性的本地商城 GUID,玩家可以立刻在本地网页商店看到并购买它(还可以在 `server/tuning/store.jsonc` 里给它定自定义 GJN 价格和附赠内容!)。 -2. **`ui/atlases.vromfs.bin` 路径大小写**: - - 原版图标包内部路径统一为**全小写**,请把图标命名为 `gameuiskin/<全小写载具id>_ico.svg`。 -3. **验证 3D 模型资源名匹配**: - - `gamedata/units/tankmodels/us_mbt_demo.blk` 里的 `model:t="..."` 与 `animChar` 名称必须与 `.grp` 内部导出的资产名一致。 +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. 配套涂装、瞄具、音效与原生目录的边界 +## 3. 银狮研发车 vs `gift` 商城礼包车(以及 AI 机器人池准入规则) -- **独立涂装 / 瞄具 / 单人任务**:玩家照旧直接放进游戏目录的 `UserSkins/`、`UserSights/`、`UserMissions/` 即可,**不需要**封装成模组; -- **大型新车整合包附带配套资源**:如果你的新车模组顺手附带了专属涂装、火控瞄具或音效包,可以放进 `client/files/`: - - `client/files/UserSkins/us_mbt_demo_camo/...`(独占子目录 → 跨盘 Junction 零拷贝) - - `client/files/UserSights/us_mbt_demo/...`(独占子目录 → 跨盘 Junction 零拷贝) - - `client/files/sound/mod/my_cannon.bank`(平铺散文件 → 优先符号链接/同盘硬链接,跨盘退化增量缓存) -- **原生文件保护红线**:如果 `client/files/` 中的某路径与玩家自己手动放进 `UserSkins/` / `UserSights/` 的文件重名,启动器会跳过并在日志中提示冲突,**绝不覆盖玩家原生文件**。 +在 `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/` 中的目标路径在游戏目录里已经作为玩家手动放置的原生文件/文件夹存在,启动器会自动跳过该项并在日志中输出冲突告警,不会覆盖或删除玩家的自有文件。 diff --git a/mod-dev-docs/zh-CN/04-client-gui-and-exe.md b/mod-dev-docs/zh-CN/04-client-gui-and-exe.md index ba61ed4..427ac95 100644 --- a/mod-dev-docs/zh-CN/04-client-gui-and-exe.md +++ b/mod-dev-docs/zh-CN/04-client-gui-and-exe.md @@ -1,38 +1,58 @@ # 04 · 客户端 GUI 补丁与声明式 EXE 补丁 -> **实验期提示**:界面脚本补丁(`gui-patches`)与声明式 `exe` 补丁(`exe-patches`)依赖目标游戏客户端的代码结构,游戏更新或本体补丁演进时可能需要同步维护。 +> **实验期提示**:界面脚本补丁(`gui-patches`)与声明式 `exe` 补丁(`exe-patches`)直接依赖目标游戏客户端的代码结构,游戏版本更新或离线核心补丁演进时可能需要同步维护。 --- -## 1. 客户端界面扩展的两种组合做法(推荐最佳实践) +## 1. 先懂概念:战雷原生 DaGui 界面三件套(`.tpl` + `.css` + `.nut`) -如果你要给游戏加一个新界面(例如自带的 `official-map-selector` 地图池弹窗),最佳实践是**“大块逻辑独立新建 + 极简增量补丁挂入口”**: +《战争雷霆》机库与大厅界面由 Dagor 自研的 **DaGui** 框架驱动(全部存放在 `gui.vromfs.bin` 包内)。一个完整的界面弹窗通常由三类文本文件配合完成: -1. **新增独立的 `.nut` / `.tpl` / `.css` 文件**:直接放进 `client/packs/gui.vromfs.bin/` 下(例如 `scripts/missions/wtoMapSelectorModal.nut`、`gui/missions/wtoMapSelectorModal.tpl`、`gui/missions/wtoMapSelector.css`)。独立文件零冲突、极易维护; -2. **用最小 GUI 增量补丁挂载入口按钮**:把修改原版脚本的几行放进 `client/gui-patches/<补丁名>/`。 +| 文件后缀 | 角色定位 | 通俗解释 | +| --- | --- | --- | +| **`.tpl`** | **Handyman 布局模板** | 类似 HTML + Mustache 模板(如 `gui/missions/wtomapselectormodal.tpl`),声明窗口骨架、按钮节点、`id` 与数据占位符(如 `<>`、`{{#cards}}...{{/cards}}`)。 | +| **`.css`** | **DaGui 样式表** | 定义节点宽高、边距、背景色、字体大小以及自定义状态属性选择器(如 `[wtoSelected=yes]`)。 | +| **`.nut`** | **Quirrel 界面逻辑脚本** | 战雷使用的类 JS/Lua 强作用域脚本语言(Squirrel 衍生版),继承 `BaseGuiHandlerWT` 处理按钮点击、渲染 `.tpl` 并与本地服务器通信。 | -> 注意:`gui.vromfs.bin` 内部路径为**全小写**。虽然 Quirrel 的 `import` 路径大小写不敏感,但放进 `client/packs/gui.vromfs.bin/` 的文件名建议保持小写或与原版一致。 +### 客户端界面扩展黄金准则:「大块逻辑独立新建 + 极简增量补丁挂入口」 + +像官方模板 `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/` 补丁格式 +## 2. `client/gui-patches/` 增量补丁格式与匹配规则 -每个补丁一个子目录,内含 `patch.jsonc` 和引用的原文/替换片段文件: +`client/gui-patches/` 不仅能改 `.nut` 脚本,**对 `gui.vromfs.bin` 里的 `.nut`、`.tpl` 和 `.css` 文本文件完全通用**!每个补丁放在一个含 `patch.jsonc` 的子目录(支持多层子目录组织): ```text client/gui-patches/ -└─ my-button-patch/ - ├─ patch.jsonc - ├─ find.nut - └─ replace.nut +└─ 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 ``` -`patch.jsonc` 示例: +### 2.1 `.nut` 脚本补丁示例 ```jsonc // Adds a custom entry button to the mode selection panel. -// Needed because the stock UI has no hook for custom modal windows. -// Without this patch, the custom map selector button is not shown. { "id": "my-mod/add-button", "title": "Add custom button to mode selector", @@ -43,8 +63,12 @@ client/gui-patches/ "file": "scripts/gamemodes/gamemodeselect.nut", "edits": [ { - "find": "find.nut", - "replace": "replace.nut" + "find": "find-imports.nut", + "replace": "replace-imports.nut" + }, + { + "find": "find-buttons.nut", + "replace": "replace-buttons.nut" } ] } @@ -52,28 +76,94 @@ client/gui-patches/ } ``` -### 规则与注意事项 -- **执行顺序**:离线版核心 GUI 补丁永远先应用,各模组的 `gui-patches` 在其后按启动器排序依次应用; -- **唯一命中保护**:每条 `edit` 的 `find` 文本必须在目标脚本中**恰好出现 1 次**,否则该补丁整条跳过并写入日志,绝不半应用写坏脚本; -- 替换文本里可以使用占位符 `{{LOCAL_ENDPOINT}}`,构建器会自动替换为当前本地服务器地址(`127.0.0.1:<端口>`); -- **多版本适配**:当游戏版本更新导致原文变化时,只需在 `variants` 数组里追加一个新的写法条目,构建器会自动选取恰好命中的那一条。 +### 2.2 注册独立 `.css` 到 `gui/css.css` 的真实补丁示例 -### 必做检查:用 Quirrel `compilestring` 做完整字节码检查 +```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" + } + ] + } + ] +} +``` -战雷使用的 Quirrel 脚本在登录阶段预加载。如果 `.nut` 存在**词法作用域冲突**(例如局部变量和顶部 `from ... import *` 常量重名)、**前向引用未声明函数**、或误用 **Quirrel 保留字(如 `base`)**,会导致登录一直卡在「正在加载」。 +`find-css.css`: -只做 AST 语法检查会漏掉这些错误,**必须**用项目匹配的 Quirrel 编译器(`sq.exe`)通过 `compilestring` 跑完整字节码编译: +```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](https://github.com/GaijinEntertainment/quirrel)** 仓库,检出与 2.61 客户端匹配的提交 `19f17df9b6ee43c91ef5c635fd45970ec76c5dbe`,用 CMake + Visual Studio(C++17)即可在数秒内编译出 `sq.exe`: ```powershell -# 示例:用 sq.exe 验证单个 .nut 文件能否通过完整字节码编译 -& "build\quirrel-cli\bin\Release\sq.exe" -e "local f = compilestring(readfile('your_script.nut'), 'your_script.nut'); println('OK')" +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')" ``` --- -## 3. 声明式 `exe` 补丁(`client/exe-patches/`) +## 4. 声明式 `exe` 补丁(`client/exe-patches/`) -模组可以直接复用 WTOffline 本体的 `@wto/exepatch` 引擎对 `win64/aces.exe` 做特征码定位补丁,**严禁直接分发修改后的 `aces.exe`**。 +高级模组可以直接复用 WTOffline 本体的 `@wto/exepatch` 引擎对 `win64/aces.exe` 做特征码定位补丁。请使用声明式补丁文件,不要直接打包或分发修改后的 `aces.exe` 可执行文件。 ```text client/exe-patches/ @@ -81,7 +171,7 @@ client/exe-patches/ └─ patch.jsonc ``` -`patch.jsonc` 结构: +`patch.jsonc` 结构示例: ```jsonc // Brief description of what this binary patch changes. @@ -112,14 +202,15 @@ client/exe-patches/ } ``` -### 定位方式(`locate.kind`) -- `signature`:字节特征码扫描(支持 `??` 通配与 `captures` 捕获偏移/相对跳转目标); +### 支持的 3 种定位器(`locate.kind`) + +- `signature`:字节特征码扫描(支持 `??` 通配字节与 `captures` 捕获相对偏移/跳转目标); - `string_ref`:按代码引用的固定 ASCII 字符串定位,可附加局部指令特征校验; -- `within`:在依赖补丁或锚点所在的函数范围(按 PE 异常表边界)内搜索局部特征。 +- `within`:在依赖补丁或锚点所在的函数边界(基于 PE `.pdata` 异常表起止范围)内搜索局部特征。 -### 安全红线与核心补丁锁(不可绕过) +### 核心隔离保护与冲突处理 -1. **核心离线与隔离补丁永远最先规划并锁定字节区间**(包括不连 Gaijin、不加载反作弊、目录与注册表隔离、禁止拉起官方启动器、本地 TLS/匹配公钥等); -2. **任何模组 `exe` 补丁如果与核心补丁字节重叠,会被构建器硬拒绝**并在日志中报错 `overlaps protected core patch`; -3. 如果两个模组的 `exe` 补丁写入同一段字节,后序补丁会被拒绝并标注冲突模组 ID; -4. 如果当前游戏版本找不到特征码或原字节不匹配,该补丁会被跳过并写入日志,不会导致核心构建崩溃。 +1. **核心离线与隔离补丁永远最先规划并锁定字节区间**(涵盖断网隔离不连 Gaijin、不加载反作弊、存档目录与注册表隔离、禁止拉起官方启动器、本地 TLS/匹配公钥替换等); +2. **任何模组 `exe` 补丁只要写入范围与核心补丁重叠 1 个字节,就会被构建器硬拒绝**,并在日志中报错 `overlaps protected core patch`; +3. 若两个不同模组的 `exe` 补丁写入同一段字节,后加载的补丁会被拒绝并明确报出冲突模组 ID; +4. 若客户端更新后特征码未命中或 `expect_original` 不匹配,该模组补丁会安全跳过并记入 `launcher.log`,不会导致离线副本构建崩溃。 diff --git a/mod-dev-docs/zh-CN/05-server-tuning.md b/mod-dev-docs/zh-CN/05-server-tuning.md index 2ed3167..b191e9e 100644 --- a/mod-dev-docs/zh-CN/05-server-tuning.md +++ b/mod-dev-docs/zh-CN/05-server-tuning.md @@ -1,90 +1,200 @@ # 05 · 服务端零代码数值叠加(Tuning) -本地服务器把离线版自定的经济、对局、商城、补给箱、兑换码、联队、研发策略等数值统一放进了 **12 份 `.jsonc` 配置文件**。模组作者一行代码都不用写,只需在 `server/tuning/` 下放同名 `.jsonc` 文件即可按字段叠加修改。 +本地服务器把离线版自定的对局倍率、房间与 AI 数量、商城礼包、市场物价、战利品箱、兑换码、初始存档货币、联队等规则统一收纳在 **12 份 `.jsonc` 配置文件**中。模组作者一行代码都不用写,只需在 `server/tuning/` 下放置同名 `.jsonc` 文件即可按字段精准叠加覆盖。 + +> 在线浏览全部 12 份内置默认配置文件全文与注释: +> **[WT-Offline `apps/server/tuning/` 源码目录](https://git.wto-project.net/Sh3ll_in_Sh3ll/WT-Offline/src/branch/main/apps/server/tuning)** --- -## 1. 多层合并优先级 +## 1. 多层合并优先级(注意启动器玩家覆盖!) -从低到高依次合并(后者覆盖前者): +每次启动本地服务器时,同名的 `tuning/<名称>.jsonc` 按以下顺序从低到高逐层合并(后一层覆盖前一层): ```text 1. 离线版内置默认配置(apps/server/tuning/<名称>.jsonc) 2. 已启用模组 1 的 server/tuning/<名称>.jsonc 3. 已启用模组 2 的 server/tuning/<名称>.jsonc - ...(按启动器「模组」页从上到下顺序) -N. 玩家在启动器「数值」页的手动设置(<客户端数据目录>/tuning/<名称>.jsonc,最高优先级) + ...(按启动器「模组」页从上到下顺序依次叠加) +N. 玩家在启动器「数值」页保存的个人覆盖(<客户端数据目录>/tuning/<名称>.jsonc,优先级最高) ``` -> 所有合并结果在服务器启动时都会经过严格类型和范围校验;字段类型或范围不合法时会直接报出模组 ID、文件名与期望值。 +- **排查提示**:由于**玩家在启动器「数值(Tuning)」页手动改过的项优先级高于模组**,如果测试模组时发现某个 `battle.jsonc` 或 `new-profile.jsonc` 字段修改没有生效,可以先检查该客户端的启动器「数值」页是否之前手动改过同一项(恢复默认或查看 `<数据目录>/tuning/*.jsonc` 即可)。 +- 所有合并后的最终结果在服务器启动时都会经过严格类型与数值范围校验;字段名写错或数值越界时会直接报出文件名、字段名与期望范围。 --- ## 2. 全部 12 份可叠加配置文件一览 -| 文件名 | 管辖内容 | 典型模组用途 | -| --- | --- | --- | -| `battle.jsonc` | 银狮/研发倍率、房间人数、AI 数量与重生次数、分房权重跨度(`brSpreadMrank`)、子模式概率、攻击无人机出生分 | 自定义收益倍率、调整对局人数、放宽分房跨度、调整 AI 重生次数 | -| `battle-economy.jsonc` | 各类战斗行为基价与对局结算经济参数 | 精细调整击杀/占点/助攻收益占比 | -| `store.jsonc` | 金鹰包、银狮包、高账价格、单车礼包价(`byVehicle`/`byRank`)、多车礼包(`multiVehiclePacks`) | 为新增载具定礼包价、打包自定义多车特惠礼包 | -| `marketplace.jsonc` | 交易所载具券与外观券参考价、品质与手续费 | 调整市场物价、给新增市场车定价 | -| `trophies.jsonc` | 经典战利品箱(银狮箱、老兵箱、奖池直购价)与权重规则 | 新增自定义抽卡箱、调整稀有载具掉率 | -| `supply-chests.jsonc` | 新版外部库存补给箱与掉落池 | 新增自制外部库存箱子 | -| `recycling.jsonc` | 道具回收与零件再合成配方 | 修改合成消耗或产出权重 | -| `redeem-codes.jsonc` | 离线兑换码与作弊码规则 | 添加专属模组礼包兑换码 | -| `new-profile.jsonc` | 新建存档初始银狮、金鹰与 GJN 余额 | 自定义初始货币与开局资源 | -| `research.jsonc` | 自动挑选默认研发目标策略 | 修改研发体验 | -| `clans.jsonc` | 联队活跃度、人数上限、预置联队 | 新增自定义预置联队 | -| `limits.jsonc` | 单次购买道具上限、战报/日志保留条数 | 提高单次购买上限或日志保留量 | +| 文件名 | 管辖内容 | 常用结构类型 | 典型模组用途 | +| --- | --- | --- | --- | +| `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. 列表增量合并语法(`$listOps`) +## 3. 对象字典合并 vs 列表增量语法(`$listOps`) -默认情况下,JSON 对象按字段递归合并,普通数组会**整体替换**上一层的数组。 -为了避免两个模组同时往多车礼包、兑换码、补给箱列表里加内容时互相顶掉,任何数组字段都支持用 **`{ "$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 +// 正确示例:server/tuning/store.jsonc +// 注意:multiVehiclePacks、byRank、byVehicle 均嵌套在顶层 "vehiclePacks" 对象内部,且价格字段名为 "gjn"! { - "multiVehiclePacks": { + "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_modern_duo_pack", - "title": { "en": "Modern Duo Pack", "zh": "现代双车组合包" }, - "priceGjn": 49.99, - "goldenEagles": 2000, - "premiumDays": 15, - "vehicles": ["us_m1a2_sep2_abrams", "germ_leopard_2a7v"] + "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 } + ] } ] - }, - // ② 按指定键(如 id)查找:存在则按对象递归合并修改,不存在则追加 - { - "op": "upsertBy", - "key": "id", - "item": { - "id": "wto_pack_two_fronts", - "priceGjn": 19.99 - } - }, - // ③ 按指定键与值删除某一项 - { - "op": "removeBy", - "key": "id", - "value": "some_unwanted_pack_id" } ] } } ``` - -支持的 4 种 `$listOps` 操作: -- `append`:`{ "op": "append", "items": [...] }` — 追加到末尾; -- `prepend`:`{ "op": "prepend", "items": [...] }` — 插入到开头; -- `upsertBy`:`{ "op": "upsertBy", "key": "<字段名>", "item": { ... } }` — 按字段匹配合并,找不到就追加; -- `removeBy`:`{ "op": "removeBy", "key": "<字段名>", "value": <匹配值> }` — 删除全部匹配条目。 diff --git a/mod-dev-docs/zh-CN/06-server-scripting-api.md b/mod-dev-docs/zh-CN/06-server-scripting-api.md index ea5c143..61f3ba9 100644 --- a/mod-dev-docs/zh-CN/06-server-scripting-api.md +++ b/mod-dev-docs/zh-CN/06-server-scripting-api.md @@ -1,135 +1,177 @@ # 06 · 服务端 JS/TS 脚本完整接口手册 > **实验期警告(API `0.1-experimental`)** -> 本章描述的所有服务端脚本接口与内部对象均处于极初期开发阶段,随时可能随本体开发变动,不保证向后兼容。 +> 本章描述的所有服务端脚本接口与内部目录对象均处于极初期开发阶段,随时可能随本体迭代调整,现阶段不承诺向后兼容。 --- -## 1. 运行环境与语法规则 +## 1. 运行环境、Node 24 可擦除 TS 语法与 VS Code 智能补全 -本地服务器运行在启动器内置的 **Electron 43 / Node.js 24** 上,**原生开启 TypeScript 类型剥离(`strip`)**,玩家电脑无需安装 Node 或 TypeScript。 +本地服务器运行在启动器内置的 **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` 中自定义相对路径); -- **直接写 `.ts` 的语法约定**:遵循 TypeScript 的 `erasableSyntaxOnly` 规则——支持全部类型注解、`interface`、`type`、泛型与 `as`,但**不要使用**需要代码生成的 `enum`、`namespace` 或构造函数参数属性(改用 `as const` 对象与联合类型即可); -- 如果你的项目想使用任意 TS 语法或第三方 npm 包,自行用 esbuild / tsc 打包成单文件 `.mjs` 分发即可。 +- **入口探测顺序**:默认依次查找 `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) { + async setup(ctx: WtoServerModContext) { ctx.logger.info('mod initialized'); - // 在此注册钩子、路由与初始化逻辑 }, }; ``` -(也支持直接导出默认函数 `export default function (ctx) { ... }` 或具名导出 `export function setup(ctx) { ... }`。) + +> 提示:除 `export default { setup(ctx) { ... } }` 外,运行时也兼容直接导出默认函数 `export default function (ctx) { ... }` 或具名导出 `export function setup(ctx) { ... }`。你也可以像 `templates/official-map-selector/server/index.ts` 一样直接在文件顶部声明自己用到的精简 `interface`,做到单文件零外部依赖。 --- -## 2. `WtoServerModContext`(注入给 `setup(ctx)` 的上下文对象) +## 2. `WtoServerModContext` 上下文对象全属性表 | 属性 | 类型 | 说明 | | --- | --- | --- | | `ctx.apiVersion` | `string` | 当前运行时的实验期 API 版本号(`"0.1-experimental"`) | | `ctx.manifest` | `ModManifest` | 本模组解析后的 `mod.jsonc` 清单对象 | -| `ctx.modDir` | `string` | 本模组根目录的绝对路径(可用 `node:fs` 读取模组自带的配置文件) | +| `ctx.modDir` | `string` | 本模组根目录的绝对路径(可用 `node:fs` 读取模组附带的静态数据文件) | | `ctx.gameFolder` | `string` | 当前运行的离线游戏副本根目录 | | `ctx.dataFolder` | `string` | 当前客户端的数据目录(含存档、缓存、日志) | | `ctx.port` | `number` | 本次启动的本地服务器监听端口 | -| `ctx.logger` | `{ info, warn, error }` | 带 `[mod:]` 前缀的日志输出器,自动进入启动器日志与诊断导出 | -| `ctx.storage` | `ModStorageApi` | 按账号隔离或全局共享的独立 JSON 存档区(见第 3 节) | -| `ctx.hooks` | `ServerModHooksApi` | 生命周期、档案、匹配与对局钩子(见第 4 节) | -| `ctx.routes` | `ServerModRoutesApi` | `char`、`matching` 与本地 HTTP 路由扩展(见第 5 节) | - -完整 TypeScript 定义源码见仓库 `packages/mods/src/server-api.ts`。 +| `ctx.logger` | `{ info, warn, error }` | 自动带 `[mod:]` 前缀的日志器,写入 `launcher.log` 与诊断包 | +| `ctx.storage` | `ModStorageApi` | 按账号隔离或全局共享的独立原子 JSON 存档区(见第 3 节) | +| `ctx.hooks` | `ServerModHooksApi` | 生命周期、档案、匹配与对局结算钩子(见第 4 节) | +| `ctx.routes` | `ServerModRoutesApi` | `matching`、`http` 与 `char` 三大协议路由扩展(见第 5 节) | --- ## 3. 独立存档区(`ctx.storage`) -**硬性最佳实践**:请勿往原版 `profile.blk` 写入非标准字段(容易影响客户端序列化或卸载模组后污染存档)。统一使用 `ctx.storage`: +**硬性最佳实践**:请勿往玩家原版 `profile.blk` 塞入自定义非标字段(不仅可能干扰客户端反序列化,玩家关闭或卸载模组后还会在主存档残留脏数据)。所有模组自定进度、开关与统计请一律存入 `ctx.storage`: ```ts // ① 按本地玩家账号隔离:/saves//mods/.json const playerStore = ctx.storage.forPlayer(userId); const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 }; -playerStore.write({ wins: prev.wins + 1 }); // 原子写盘 +playerStore.write({ wins: prev.wins + 1 }); // 临时文件原子替换写盘,防断电损坏 // playerStore.remove(); -// ② 模组全局共享存储:/mods-data/.json +// ② 模组跨账号全局共享存储:/mods-data/.json const sharedStore = ctx.storage.shared(); ``` --- -## 4. 全部生命周期与业务钩子(`ctx.hooks`) +## 4. 全部生命周期、档案与对局钩子(`ctx.hooks`) ### 4.1 `ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })` -在本地服务器从叠加后的 `.vromfs.bin` 提取完静态数据集、尚未组装业务目录前触发。可读取或原地修改: -- `datasets.vehicles`:载具目录数组(含价格、研发点、权重、科技树信息) -- `datasets.battleEconomy`:对局收益基数与每车系数表 -- `datasets.battleSpawnRules`:出生点、支援机与规则数据 -- `datasets.multiplayerMissions`:`{ categories, missions }` 联机任务数据 -- `datasets.uiLabels` / `datasets.unitNames`:多语言标签与载具名映射 -- `datasets.get(datasetId)` / `datasets.set(datasetId, value)`:按 ID 读取或替换任意数据集 + +在本地服务器从叠加后的 `.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` 实时推送 +- `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`)。 + +每次读取或更新玩家档案并跑完原生刷新管线后调用(`profile` 为 `@wto/blk` 的内存 `BlkBlock`)。建议只读取档案信息并把衍生数据存入 `ctx.storage.forPlayer(userId)`。 ### 4.5 对局与匹配钩子(`ctx.hooks.battle`) -#### ① `ctx.hooks.battle.onBeforeMatchmake((ctx) => { ... })` -玩家点击「加入战斗」进入匹配队列、尚未调用 `BattleMatchmaker` 之前触发: -- `ctx`:`{ userId, eventName, request }`(`request` 为客户端发来的原始 `match.enqueue` 参数对象)。 +#### ① `ctx.hooks.battle.onBeforeMatchmake(({ userId, eventName, request }) => { ... })` + +玩家点击「加入战斗」发起 `match.enqueue`、尚未进入 `BattleMatchmaker` 之前触发,`request` 为客户端提交的原始入队参数对象。 #### ② `ctx.hooks.battle.onFilterMissions((ctx) => { ... })` -`BattleMatchmaker` 已按模式与分房权重筛选出两队候选任务池、尚未随机抽图时触发。 + +`BattleMatchmaker` 已按当前模式与分房权重筛出双边候选任务池、尚未随机抽图时触发: + - `ctx`:`{ userId, modeId, modeName, economicName, minMrank, maxMrank, missions }`; -- 每条 `mission` 包含 `{ name, path, level, type, locName, postfix }`; -- **返回值**:返回过滤/重排后的子集数组(返回 `undefined` 表示不干预)。若返回空数组,服务端会记录告警并自动回退到上一层候选池,避免卡死匹配。 +- 每项 `mission` 结构为 `{ name, path, level?, type?, locName?, postfix? }`; +- **返回值**:返回过滤后的子集数组(返回 `undefined` 表示不干预)。若返回空数组 `[]`,服务端会打印告警并自动回退到过滤前的候选池,确保玩家永远不会因筛选过严而卡死匹配。 ```ts -// 示例:只允许匹配名称包含 poland 或 berlin 的地图 +// 示例:只允许匹配关卡路径或名称包含 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((ctx) => { ... })` -对局进行中收到客户端上报的实时战斗事实(击杀、占点、生命段、核弹爆炸)时触发: -- `ctx`:`{ userId, roomId, fact }`。 +#### ③ `ctx.hooks.battle.onLiveFact(({ userId, roomId, fact }) => { ... })` -#### ④ `ctx.hooks.battle.onAfterSettle((ctx) => { ... })` -对局结束并写入原生结算后、档案落盘前触发: -- `ctx`:`{ userId, roomId, summary }`(`summary` 含 `{ profile, report, session }`),可在此发放额外自定义奖励或累计模组统计。 +对局进行中,每当客户端通过 `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. 协议路由与本地网页扩展(`ctx.routes`) +## 5. 三大通信路由对比与 `matchingApiFunc` 正确签名(`ctx.routes`) -### 5.1 Char 动作扩展(`ctx.routes.char`) -- `ctx.routes.char.register(action, handler)`:注册全新的自定义 `cln_*` 动作(如配合客户端 GUI 补丁发来的请求); -- `ctx.routes.char.wrap(action, async (req, next) => { ... })`:拦截并包装现有 `cln_*` 动作(可在调用 `await next(req)` 前后改请求或改响应)。 +### 5.1 我该选哪种路由?(选型对照表) -### 5.2 匹配服 RPC 扩展(`ctx.routes.matching`) -客户端 Quirrel 脚本可以直接用 `matchingApiFunc("wto_mod.<你的方法>", params, callback)` 调用本地服务器匹配接口! -- `ctx.routes.matching.register(method, (req) => ({ ... }))`:注册自定义 RPC(`req` 含 `{ method, params, userId }`,直接返回 JSON 对象); -- `ctx.routes.matching.wrap(method, (req, next) => { ... })`:包装现有匹配服 RPC。 +| 路由接口 | 适用场景 | 协议格式 | 客户端调用方式 | +| --- | --- | --- | --- | +| **`ctx.routes.matching`**(最推荐) | 原生 DaGui `.nut` 界面弹窗与服务端读写 JSON 数据(如读取/保存选图规则、模组设置) | 纯 JSON 对象入参 + JSON 对象返回 | Quirrel 调用 `matchingApiFunc("wto_mod.<方法名>", callback, params)` | +| **`ctx.routes.http`** | 用 HTML/CSS/JS 做复杂可视化面板、外部浏览器管理页或 REST 接口(自动隔离在 `/mods//...`) | 标准 HTTP 请求/响应 | 系统浏览器或游戏内置浏览器打开 `http://{{LOCAL_ENDPOINT}}/mods//...` | +| **`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 }) => ({ @@ -139,19 +181,85 @@ ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({ })); ``` -### 5.3 本地 HTTP / 内置浏览器网页路由(`ctx.routes.http`) -自动挂载在 **`/mods/<你的modId>/...`** 命名空间下,支持精确路径和 `/*` 通配后缀,既可用系统浏览器访问,也可以通过游戏内置浏览器直接打开: +> **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: '

My Mod Panel

', + body: '

My Mod Control Panel

', })); ctx.routes.http.register('/api/*', (req) => ({ status: 200, contentType: 'application/json; charset=utf-8', - body: JSON.stringify({ path: req.path, query: req.query }), + 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)] + └─ 原子写入 /saves//mods/official.map-selector.json(不改动 profile.blk) + │ + ▼ +[5. 匹配选图拦截 ctx.hooks.battle.onFilterMissions] + └─ 玩家点「加入战斗」时按白名单/黑名单过滤候选 missions;若当前权重段过滤后为 0 张图则安全回退全池并记日志 +``` + +建议把 `templates/official-map-selector` 从头到尾对照本图通读一遍——你需要的几乎所有全栈模组技巧都在里面有可直接复用的生产级示范代码! diff --git a/mod-dev-docs/zh-CN/07-troubleshooting-and-faq.md b/mod-dev-docs/zh-CN/07-troubleshooting-and-faq.md index 0e96306..fac4b9e 100644 --- a/mod-dev-docs/zh-CN/07-troubleshooting-and-faq.md +++ b/mod-dev-docs/zh-CN/07-troubleshooting-and-faq.md @@ -1,44 +1,83 @@ -# 07 · 排错、日志与最佳实践 +# 07 · 排错、日志、热重载与打包发布规范 ## 1. 模组出错了去哪里看日志? -启动器所有模组构建与运行日志都会汇入标准日志目录,可在 **「设置 › 诊断 › 打开日志目录」** 或 **「关于 › 导出诊断日志」** 直接查看: +启动器的所有模组构建与运行日志都会汇入标准日志目录,可在 **「设置 › 诊断 › 打开日志目录」** 或 **「关于 › 导出诊断日志」** 直接打开: 1. **启动器主日志(`launcher.log`)**: - - 搜索 `[build]`:查看本轮启用了哪些模组、各数据包叠加统计、以及哪条 GUI 补丁或 `exe` 补丁被跳过及精确原因; - - 搜索 `[mods]`:查看跨盘 Junction 挂载结果、被跳过的原生文件冲突告警、以及还原的可选数据包; - - 搜索 `[server]` 或 `[mod:<你的modId>]`:查看服务端脚本加载报错、堆栈、以及你在脚本里调用 `ctx.logger.info/warn/error` 打印的全部输出。 -2. **游戏客户端日志(`<客户端目录>/.game_logs/*.clog`)**: - - 若客户端 GUI 脚本报错或卡在「正在加载」,查看最新的 `.clog`(或先用 `sq.exe` 做完整字节码检查定位); - - 若新增 3D 模型未渲染,搜索 `.clog` 中的 `[PACK]`、`pkg_user` 或模型资源名确认是否被引擎加载。 + - 搜索 `[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. 常见报错速查 +## 2. 常见报错与疑难杂症速查表 -| 现象 / 报错 | 原因 | 解决方法 | +| 现象 / 日志报错 | 常见原因 | 解决方法 | | --- | --- | --- | -| 启动器提示某模组目录读取失败 | `mod.jsonc` JSON 语法错误、含未知字段、`id` 不合规范或 `server.entry` 路径不存在 | 对照第 01 章字段表核对 `mod.jsonc` | -| 点启动提示「存在阻塞性模组错误」 | 启用的模组缺少 `requires` 前置、前置未勾选,或同时启用了声明 `conflicts` 互斥的模组 | 按「模组」页顶部的红色错误列表补齐前置或关闭互斥项 | -| 服务端加载 `.ts` 报语法错(如 `enum` 不支持) | Node 24 原生 TS 剥离不支持需要额外代码生成的 TypeScript 语法 | 改用 `as const` 对象 + 联合类型,或自行编译为 `.mjs` | -| 日志提示 `overlaps protected core patch` | 模组的 `client/exe-patches/` 试图修改离线版核心隔离补丁锁定的字节 | 不可覆盖核心隔离区段,请改用其他钩点或服务端方案 | -| 日志提示 `target already exists as a native/player file` | `client/files/` 中的某文件与玩家自己在 `UserSkins/` 或 `UserSights/` 手动放的文件重名 | 给模组自带的配套子目录加上专属前缀(如 `mod_<你的id>_...`)避免撞名 | -| 进机库一直卡在「正在加载」 | 新增或修补的 `.nut` 脚本存在 Quirrel 词法作用域冲突、保留字误用或前向引用 | 用 `sq.exe` 对最终 `.nut` 跑完整 `compilestring` 字节码检查 | +| 启动器提示某模组目录读取失败 | `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 file` | `client/files/` 中的某文件与玩家自己在 `UserSkins/` 或 `UserSights/` 手动放的文件重名 | 给模组附带的配套子目录加上专属前缀(如 `mod_<你的id>_...`)避免撞名 | --- -## 3. 跨盘与非 NTFS 磁盘说明 +## 3. 开发调试热重载循环(改完文件怎么最快看到效果?) -- **NTFS 硬盘(绝大多数 Windows 电脑)**:`client/addon/`(3D 模型与贴图)和独占子目录(如 `UserSkins/<子目录>`)全部通过 **NTFS Directory Junction** 挂载——**跨盘可用、免管理员、0 额外空间、1 毫秒完成**; -- **平铺散文件(如 `sound/mod/*.bank`)**:依次尝试文件符号链接(开 Windows 开发者模式时跨盘零拷贝)→ 同盘硬链接 → 增量缓存复制(未修改文件下次启动自动跳过); +在本地编写与调试模组时,了解客户端与服务端各自的加载时机能省下大量时间: + +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=`)全新加载 `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/` 下的一级子目录! +2. **打包前清理无关开发垃圾文件**: + 请剔除 `.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 和硬链接,自动退化为按大小与修改时间比对的增量缓存复制,功能照常可用。 --- -## 4. 给模组制作组的 5 条黄金习惯 +## 6. 开发与发布建议 -1. **命名空间隔离一切**:模组 ID 用 `<作者>.<模组名>`;新增载具、武器、涂装子目录、自定义匹配 RPC、自定义 Char 动作全部带自己前缀(如 `wto_mod.<名称>`),避免和其他模组撞车; -2. **公共表一律用补丁,绝不整文件覆盖**:修改 `shop.blk`、`wpcost.blk`、`unittags.blk`、`units.csv` 时永远用 `.patch.jsonc` / `.patch.csv`; -3. **只读原版,不污染主存档**:模组持久化数据全部写进 `ctx.storage.forPlayer(userId)`,卸载模组后玩家主存档干干净净; -4. **界面大逻辑拆独立文件**:新弹窗放 `client/packs/gui.vromfs.bin/`,`gui-patches/` 里只留几行挂入口按钮的代码,换版本几乎不用重写; -5. **发布前做一次“开 → 玩 → 关 → 重启”循环**:确认启用时生效、关掉后彻底还原,且与其他模组一起开不冲突。 +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. **发布前做一次完整的「启用 → 进游验证 → 关闭 → 再进游还原」测试循环**:确认启用时功能正常、关闭后彻底无痕还原,且能与其他常用模组同时勾选共存。