面向模组创作者的完整在线手册:从解包查看原版文件、5 分钟入门、BLK/CSV 增量补丁、自定义 3D 载具、GUI/EXE 补丁到服务端零代码调参与全栈脚本案例,中英双语零删减呈现。The complete unabridged 7-chapter handbook for mod authors—from inspecting stock archives and 5-minute quick start to BLK/CSV patches, custom 3D vehicles, GUI/EXE hooks, tuning overlays, and full-stack server scripts.
Target Spec: format: 1 · api_version: "0.1-experimental" (experimental API; subject to breaking changes as core development progresses)
1. Core Concept: Additive Overlay Architecture
WTOffline uses a stackable, load-order additive mod architecture. Mods supply incremental patches and added files to the client and server, and do not replace whole stock .vromfs.bin archives:
Before launching the game, the launcher starts from clean stock backups (<copy>/wtoffline/stock/), applies core offline patches first, and then layers every enabled mod's client patches and added files in the exact order shown on the Mods page;
Large 3D model and texture addons mount across drives with zero file copying via Windows NTFS Directory Junctions;
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;
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 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 <dataFolder>/mods-config.json.
2. Prerequisite: How to Unpack & Inspect Stock Game Files
Before tweaking vehicle stats, wiring tech-tree entries, or patching UI scripts, you need to look up stock internal vehicle IDs (for example, the US reserve light tank M2A4 is us_m2a4, and the M1A2 SEP V2 is us_m1a2_sep2_abrams) and stock file paths.
2.1 Where Stock Archives Live in the Game Client
Inside your War Thunder client folder (and offline copy folder), stock game data lives inside .vromfs.bin virtual filesystem archives:
Stock Archive Path (relative to client root)
Key Contents Inside
char.vromfs.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)
Tech-tree and local web store vehicle silhouette icons (gameuiskin/<unit_id>_ico.svg)
ui/images.vromfs.bin
Stat-card and crew-slot vehicle portraits (units/<unit_id>.ddsx)
Note on the backup folder: Treat <copy>/wtoffline/stock/ as read-only. The launcher relies on wtoffline/stock/ to rebuild overlays and restore clean files when mods are disabled; modifying files inside stock/ can prevent automatic restoration. Place all mod changes under mods/<your-mod>/.
2.2 Practical Ways to Inspect Stock Files
You can inspect stock .blk, .csv, and .nut files directly from your own local game installation:
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.
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:
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 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; <author>.<mod-name> 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 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
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.blk (or .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.
直接复用上面第 6.2 节的 4 行 CSV 内容即可。保存后在启动器勾选启用模组并启动游戏,切到美国陆军科技树 I 级,就能看到 M2A4(教学改型) 并立刻右键「试驾」体验 90 km/h 飙车!
02 · Client Packs & BLK Incremental Patching
Most War Thunder data mods—tweaking vehicle performance, shell penetration, missile maneuverability, tech-tree layouts, Silver Lion / Research Point prices, Battle Ratings, localized names, and vehicle icons—live inside .vromfs.bin data packs. This chapter explains how to modify those packs in a 100% stackable, conflict-free way, ending with a copy-pasteable walkthrough that clones a playable standalone tank into the US Rank I tech tree.
1. Plain-Language Intro: What Is BLK & Why Does It Differ from JSON?
War Thunder's Dagor Engine stores nearly all game configurations in BLK (DataBlock) files—compiled to compact binary inside .vromfs.bin packs, and readable as plain text .blk when unpacked. While text BLK looks superficially similar to JSON, it differs in three fundamental ways:
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;
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!);
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.blk incremental patch:
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/<lowercase_unit_id>_ico.svg (tech-tree & local web store silhouette icons), units/<lowercase_unit_id>.ddsx (default DXT5 crew-slot portrait)
Backed up on demand, restored on disable
client/packs/ui/images.vromfs.bin/
images/*.png / .avif / .ddsx (custom UI images, or vehicle portraits via wpcost.blkcustomImage:t="!ui/images/..." / customTooltipImage:t="!ui/images/..."; note: plain .dds is not supported by UI PictureManager)
Backed up on demand, restored on disable
Automatic Server Sync: The local server reads static datasets directly from the overlaid .vromfs.bin packs on startup. Any vehicle added or tweaked in shop.blk / wpcost.blk is automatically picked up for prices, tech-tree prerequisites, Research Points, modifications, Battle Ratings, AI bot pools, and store pack GUIDs—no duplicate server registration needed.
3. Three File Handling Modes Inside Packs (Auto-Detected by Suffix)
The patcher determines how to process each file under client/packs/<pack>/ by its filename suffix:
<target-path>.patch.blk (Recommended) or <target-path>.patch.jsonc → Incremental BLK Patch: decodes the target .blk into a type-preserving tree, applies the patch in order, and re-encodes a self-contained binary BLK. Different mods may mix .patch.blk and .patch.jsonc on the same target and stack cleanly; within a single mod, pick one format per target file;
<target-path>.patch.csv → Incremental Localization CSV Merge: merges rows by column 0 (updating only the non-empty language columns you provide on existing keys, and appending new keys at the end);
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, the builder automatically expands include / includeOnce and Dagor @override: / @delete: directives and 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 Reference
Two incremental BLK patch formats are supported:
*.blk.patch.blk (Recommended): native Dagor BLK syntax with include, @override:, @delete:, and @clone:—compact and lets you paste stock BLK blocks directly;
*.blk.patch.jsonc (Compatible / Programmatic): structured JSONC op list, kept for backwards compatibility and automated generators.
4.1 Dagor-Style BLK Patches (*.blk.patch.blk) & include Compilation
Statements execute strictly top-to-bottom in source order, with identical rules in both *.blk.patch.blk and standalone text .blk files (unprefixed items always append/add; modifying existing items explicitly uses @ directives).
① File Inheritance (include / includeOnce)
Syntax
Behavior
include "germ_pzkpfw_maus.blk"
Loads and expands the target .blk into the current block (resolved relative to the current pack directory; supports ../, /gamedata/..., #/gamedata/..., and War Thunder CDK #/develop/gameBase/...).
includeOnce "../common/smoke.blk"
Same as include, but expands a given normalized path at most once per compilation.
include resolves against the live in-memory pack archive (stock files + earlier mods) as well as sibling .blk files in the same mod, with automatic circular-include detection;
All @ directives accept both quoted ("@override:model":t = "...") and unquoted (@override:model:t = "...", @override:ikPilot { ... }) Dagor syntax;
Ideal for derived vehicles without copying thousands of stock lines:
blk
// client/packs/aces.vromfs.bin/gamedata/units/tankmodels/germ_pzkpfw_walross.blk
include "germ_pzkpfw_maus.blk"
"@override:model":t = "pzkpfw_VIII_walross"
"@delete:commonWeapons" {}
commonWeapons {
// Paste new weapon blocks directly here
}
Inserts right after/before a sibling anchor (supports anchor[index] and @clone:src->dst as target)
Typo Guard & Escaping: Any unknown "@xxx:..." prefix fails immediately with a line number so misspelled directives are never silently baked into binary BLKs. Use @@ to escape a literal leading @.
{
"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.
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)
Important Behavior Note (Avoid Duplicate Keys): If the target block along pathdoes not exist, upsertBlock creates it and populates block.params and block.blocks. However, if the target block already exists, upsertBlockappends 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)
⑦ 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:
Note: Nested ops inside cloneBlock run with the newly cloned block itself as the root, so use "path": [] when editing top-level fields on the cloned block.
4.3 All 13 BLK Data Types
When you write a plain JSON primitive, the patcher infers the BLK type from any existing parameter of the same name on that block (falling back to string, bool, int for integers, or real for non-integers). To guarantee exact binary types—especially when setting a float parameter to a whole number like 2.0, which JSON parses as integer 2—write { "type": "<type>", "value": <val> }:
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)
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:
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 RBmrank for aircraft/helicopters with separate air vs ground BRs; falls back to economicRankHistorical when omitted
economicRankTankSimulation
0 .. 39+
(Optional) Split Ground SBmrank for aircraft/helicopters
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.blk (or .patch.jsonc):
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.;
Collapsible folder groups (*_group): when multiple variants share one tech-tree folder, range contains a child block ending in _group (e.g. us_sherman_group) whose children are the grouped vehicles; the folder's display label comes from shop/group/<group_name> in units.csv;
Why is the prerequisite arrow field named reqAir even on tanks and ships?
War Thunder began life as an aviation-only game (World of Planes), so air / aircraft remained the universal internal noun for any unit. Consequently, reqAir defines the research prerequisite vehicle across tanks, helicopters, aircraft, and ships alike!
Setting reqAir:t="us_m2a4" in wpcost.blk requires owning us_m2a4 before researching the unit;
Inside a range column in shop.blk: consecutive vehicles with no reqAir property automatically connect with vertical arrows; reqAir:t="us_m2a4" draws an explicit arrow from us_m2a4; and reqAir:t="" (empty string) explicitly breaks the arrow from the vehicle above it (used at mid-column gaps and throughout the right-hand premium/pack columns).
6.2 All 4 lang/units.csv Keys & Incremental CSV Merging
When localizing a vehicle <id> in client/packs/lang.vromfs.bin/lang/units.csv.patch.csv, War Thunder uses 4 standard localization keys for different UI contexts and HUD distances:
Key Pattern
Where It Appears in Game
Example (for us_m2a4_mod_demo)
<id>_shop
Tech-tree card, crew slot bar, and local web store card short name
"M2A4 (Mod Demo)" / "M2A4(教学改型)"
<id>_0
Stat-card header, research completion modal, and battle debriefing full formal title
"Light Tank M2A4 (Mod Demo)" / "M2A4 轻型坦克(教学改型)"
<id>_1
In-battle medium-distance 3D HUD marker name
"M2A4 Demo" / "M2A4 教学型"
<id>_2
In-battle far-distance HUD marker / compact killfeed short name
"M2A4" / "M2A4"
Example client/packs/lang.vromfs.bin/lang/units.csv.patch.csv:
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.
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 BLK patch at client/config-blk.patch.blk (recommended; client/config-blk.patch.jsonc is also supported):
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 # ① Inherits stock us_m2a4.blk via include & boosts speed
├─ char.vromfs.bin/
│ └─ config/
│ ├─ wpcost.blk.patch.blk # ② Clone economy, BR, modifications & ammo racks
│ ├─ shop.blk.patch.blk # ③ Insert into US Army column 0 (Rank I)
│ └─ unittags.blk.patch.blk # ④ 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
Inherit stock us_m2a4.blk directly via include (no need to unpack or copy thousands of stock lines) and override just its speed and acceleration (compiled to binary automatically on build):
② Economy & BR Patch client/packs/char.vromfs.bin/config/wpcost.blk.patch.blk
Use @clone: 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):
③ Tech-Tree Slot Patch client/packs/char.vromfs.bin/config/shop.blk.patch.blk
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:t = "us_m2a4", creating a clean Rank I side-branch arrow from M2A4 without disturbing the stock Stuart chain:
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!
自动进入对局 AI 机器人池:本地服务器的分房机器人选择器(battle-ranks.ts)会自动把已挂入科技树(shop.blk)且不含gift、premPackAir、event、researchType、showOnlyWhenBought 标记的常规银狮科技树载具纳入对应国家与分房权重的 AI 出战池!这意味着你在单机对局里也能遇到驾驶你自制新车的友军和敌军 AI。
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.
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/<unit_id>.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 <copy>/content/pkg_user/<modId>, Windows transparently serves the files straight from your mods/ folder on any drive—no administrator rights needed, works across drives, consumes 0 extra disk bytes, and mounts/unmounts in ~1 ms!
How the Engine Discovers client/addon/ Automatically
Verified directly against 2.61.0.x aces.exe (dlContent.cpp) and aces.vromfs.bin/config/settings.blk:
The patcher automatically registers every enabled mod's addon mount path into addons, addons_no_check, and addonsWithBasePath inside config/settings.blk;
Any addon path under /pkg_user/ (mounted by default at <copy>/content/pkg_user/<safeModId>) skips the mandatory res/grp_hdr.vromfs.bin header check and directly scans <addon>/res/ for all .grp model and .dxp.bin texture archives, registering them into the global asset manager;
If your mod ships an official CDK-compiled res/grp_hdr.vromfs.bin, the patcher mounts it at <copy>/content/pkg_wto_<safeModId> so the native grp_hdr loader handles it;
Disabling a mod removes only the directory junction itself and never deletes or modifies your source files inside mods/.
2. 6-Step Checklist for a Custom 3D Vehicle
Suppose your mod ID is demo.new-mbt and your new vehicle's internal ID is us_mbt_demo:
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.
ui/atlases.vromfs.bin icon paths must be all lowercase: stock icon packs store paths in lowercase, so name your icon gameuiskin/<lowercase_unit_id>_ico.svg (the local web store also displays this exact SVG on pack cards!).
Match .blk asset names to .grp exports: model:t="..." inside gamedata/units/tankmodels/us_mbt_demo.blk must match the exact asset name exported into your .grp archive from the CDK.
3. Regular Tech-Tree Vehicles vs gift Store Packs (& AI Bot Pool Rules)
In wpcost.blk.patch.blk and shop.blk.patch.blk (or .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 omitgift, premPackAir, costGold, event, and researchType (squadron tag), as well as showOnlyWhenBought:b=yes in shop.blk;
Automatically joins the AI bot pool: the local server's matchmaking bot selector (battle-ranks.ts) automatically includes tech-tree vehicles (inTechTree in shop.blk) that have none of gift, premPackAir, event, researchType, or showOnlyWhenBought! Both friendly and enemy AI bots at matching BRs and nations will spawn in your custom vehicle during offline battles.
Option B: Local Web Store Pack Vehicle (gift:t="msi_notebook")
Modders inspecting stock wpcost.blk / shop.blk often wonder: why do dozens of pack vehicles say gift:t="msi_notebook"?
In stock War Thunder, any non-empty gift:t="..." string (Gaijin historically reused promo strings like "msi_notebook" across countless store vehicles) marks the vehicle as an external store pack/gift unit whose Order button opens the web store instead of spending Silver Lions or Golden Eagles;
WTOffline auto-generates a local web store bundle: during copy building, WTOffline scans every vehicle carrying gift in wpcost.blk and automatically registers a deterministic local store product ID wto_pack_<unitId> (e.g. wto_pack_us_mbt_demo) and bundle GUID:
Even with zero server config, the local web store automatically prices the pack using vehiclePacks.byRank for the vehicle's rank tier so players can buy and unlock it right away in the in-game store!
To customize its GJN price, Golden Eagles bonus, or Premium days, simply add an entry under vehiclePacks.byVehicle in server/tuning/store.jsonc (see Chapter 05).
AI Bot Pool Note: vehicles carrying gift, premPackAir, event, researchType, or showOnlyWhenBought are intentionally excluded from the automatic AI bot pool so rare pack prototypes do not flood standard bot lineups.
4. Companion Skins, Sights, Sounds & the Native Folder Boundary
Standalone skins, sights & single-player missions: players should continue placing standalone files directly into the game's native UserSkins/, UserSights/, and UserMissions/ folders—the launcher never touches or deletes player-managed native folders, and they do not need to be wrapped as mods;
Companion assets bundled inside a large vehicle overhaul mod: if your custom vehicle mod includes dedicated camouflages, custom FCS gun sights, or custom cannon sound banks, place them under client/files/ so they mount and unmount together with the mod:
client/files/UserSkins/mod_us_mbt_demo_camo/... (mod-exclusive subfolder → mounts across drives via zero-copy NTFS Junction)
client/files/UserSights/us_mbt_demo/... (mod-exclusive subfolder → mounts across drives via zero-copy NTFS Junction)
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.
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/ 的新增文件也请统一使用全小写路径。
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.
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:
Extension
Role
Plain-Language Explanation
.tpl
Handyman Layout Template
Similar to HTML + Mustache (e.g. gui/missions/wtomapselectormodal.tpl); declares UI containers, buttons, element ids, and data-binding tags (<<wndTitle>>, {{#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.
Best-Practice UI Pattern: "Standalone Files for Logic + Minimal Patch for Entry Hook"
Just like the bundled templates/official-map-selector mod, the cleanest way to add new UI is:
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;
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):
2.3 Four Critical Path & Variant Rules (Must-Read)
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.
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.
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).
{{LOCAL_ENDPOINT}} Placeholder: Any occurrence of {{LOCAL_ENDPOINT}} in replace text is automatically expanded to the client's bound local server 127.0.0.1:<port> (for example http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel for embedded browser pages). Core offline GUI patches always run first; mod gui-patches run afterward in load order.
3. Mandatory Check: Building sq.exe & Full Quirrel Bytecode Verification
War Thunder pre-compiles Quirrel UI scripts during login. Any of the following mistakes in a .nut file will cause the client to hang indefinitely on the "Loading" screen:
Lexical scope name collisions: declaring a let / local variable that shadows a symbol imported via from "..." import * at the top of the file;
Forward references to undeclared functions or accidental use of Quirrel reserved words (such as base);
JS-style backtick strings (`...)**: unsupported by War Thunder's Quirrel VM—always use Quirrel's native string interpolation **$"hello {name}"` instead!
Note: sq.exe --syntax-check runs AST parsing only and misses lexical collisions and undeclared identifiers—you must invoke compilestring(...) so the full bytecode generator runs!
3.1 How External Modders Build a Matching sq.exe
Clone Gaijin's open-source GaijinEntertainment/quirrel repository, check out commit 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe (matching 2.61 clients), and build sq with CMake + Visual Studio (C++17):
3.2 Run compilestring on a Complete .nut File (Not a Partial Snippet)
Note: Pass a complete .nut file to compilestring rather than an isolated replace.nut fragment. replace.nut is only an in-place snippet and will fail out of context. Always run compilestring against a complete .nut file—either your standalone .nut script, or the full stock .nut file after applying your find/replace edits:
If you cloned the WTOffline repo: tools/src/wtotools/gui_check.py automatically resolves gui.vromfs.bin module exports, applies your gui-patches, and runs compilestring with stub bindings across every touched file;
Standalone full-file check example (pass a bindings table as the 3rd argument to compilestring if your file uses top-level from "..." import ... bindings):
powershell
& "quirrel-build\bin\Release\sq.exe" -e "let io = require('io'); let f = io.file('your_complete_script.nut', 'rb'); let src = f.readblob(f.len()).as_string(); f.close(); compilestring(src, 'your_complete_script.nut'); print('OK\n')"
4. Declarative EXE Patches (client/exe-patches/)
Advanced mods can reuse WTOffline's @wto/exepatch engine to apply signature-located binary patches to win64/aces.exe. Use declarative patch files instead of packaging or distributing modified aces.exe binaries.
text
client/exe-patches/
└─ my-tweak/
└─ patch.jsonc
Example patch.jsonc:
jsonc
// Brief description of what this binary patch changes.
// Why the local server cannot do this alone.
// What happens if this patch is skipped.
{
"id": "my-tweak",
"title": "Example declarative exe patch",
"features": [],
"requires": [],
"variants": [
{
"written_for": "2.61.0.58",
"locate": {
"kind": "signature",
"pattern": "48 8B ?? ?? ?? ?? ?? 84 C0 74 ??",
"captures": []
},
"edit": {
"offset": 9,
"asm": "nop; nop",
"bytes": "90 90",
"expect_original": "74 ??",
"fixups": []
}
}
]
}
Supported Locators (locate.kind)
signature: byte pattern scan supporting ?? wildcards and captures for displacements / relative branch targets;
string_ref: locates code referencing a fixed ASCII string literal, with optional local instruction verification;
within: searches inside the PE .pdata function boundaries of a required patch or anchor site.
Core Isolation Protection & Conflict Handling
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);
Any mod exe patch overlapping even 1 byte of a core patch is hard-rejected with overlaps protected core patch in launcher.log;
If two mods' exe patches write to overlapping byte ranges, the later mod's patch is rejected with the conflicting mod ID;
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.
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. Multi-Layer Merge Precedence (Watch Out for Launcher Player Overrides!)
Whenever the local server starts, each tuning/<name>.jsonc file is merged from lowest to highest priority (later layers override earlier ones):
text
1. Shipped offline defaults (apps/server/tuning/<name>.jsonc)
2. Enabled Mod 1's server/tuning/<name>.jsonc
3. Enabled Mod 2's server/tuning/<name>.jsonc
... (applied top-to-bottom in Launcher "Mods" load order)
N. Player overrides saved in the Launcher "Tuning" tab (<dataFolder>/tuning/<name>.jsonc — HIGHEST PRIORITY!)
Crucial Debugging Tip: Because player overrides saved in the Launcher's "Tuning" tab take highest priority, if a field in your mod's battle.jsonc or new-profile.jsonc appears to be ignored during testing, check whether your test client has a manual override saved in the Launcher Tuning tab (<dataFolder>/tuning/*.jsonc) and reset that field to default!
Every merged configuration is validated strictly for types and numeric bounds at server startup; unknown keys or out-of-range numbers immediately report the exact file, key, and expected constraint.
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:
Plain Objects / Key-Value Maps (such as vehiclePacks.byVehicle and redeem-codes.jsoncfixedCodes) → 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!
JSON Array Properties (such as vehiclePacks.multiVehiclePacks, goldenEaglePacks, supplyTrophies) → Replace by Default; Use { "$listOps": [...] } to Stack: Writing a raw array "multiVehiclePacks": [ ... ] replaces the entire stock and earlier-mod list! To stack items cleanly across multiple mods, set that array property to an envelope object whose only key is "$listOps" (note: if the object has any sibling keys alongside "$listOps", it will NOT be recognized as a list-ops envelope!):
jsonc
// Correct Example: server/tuning/store.jsonc
// Note: multiVehiclePacks, byRank, and byVehicle live INSIDE "vehiclePacks", and the GJN price key is "gjn"!
{
"vehiclePacks": {
// ① multiVehiclePacks is an array -> wrap in { "$listOps": [...] } to stack safely
"multiVehiclePacks": {
"$listOps": [
{
"op": "append",
"items": [
{
"id": "mod_modern_duo_pack",
"title": { "en": "Modern Duo Pack", "zh": "现代双车组合包" },
"gjn": 49.99,
"goldenEagles": 2000,
"premiumDays": 15,
"vehicles": ["us_m1a2_sep2_abrams", "germ_leopard_2a7v"]
}
]
},
{
"op": "upsertBy",
"key": "id",
"item": {
"id": "wto_pack_two_fronts",
"gjn": 19.99
}
},
{
"op": "removeBy",
"key": "id",
"value": "some_unwanted_pack_id"
}
]
},
// ② byVehicle is a key-value map (NOT an array) -> write vehicle IDs directly without $listOps!
"byVehicle": {
"us_mbt_demo": {
"gjn": 59.99,
"goldenEagles": 2000,
"premiumDays": 15
}
}
}
}
All 4 Supported $listOps Operations
append: { "op": "append", "items": [ ... ] } — appends items to the end of the array;
prepend: { "op": "prepend", "items": [ ... ] } — inserts items at the start of the array;
upsertBy: { "op": "upsertBy", "key": "<idField>", "item": { ... } } — finds the first element where entry[key] === item[key] and recursively merges item into it, or appends item if absent;
removeBy: { "op": "removeBy", "key": "<field>", "value": <matchValue> } — removes every element where entry[key] === value.
4. Practical Field Quick-Reference & Verified Snippets
Every key name below is verified directly against apps/server/tuning/*.jsonc and the server's strict tuning readers:
{
"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)
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)
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:
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.
The local server runs inside the launcher's bundled Electron 43 / Node.js 24 runtime with native TypeScript type stripping enabled—players do not need Node.js or TypeScript installed on their PCs to run your .ts scripts directly!
Default entry lookup order: server/index.ts → server/index.mjs → server/index.js (or override via server.entry in mod.jsonc);
Third-party npm packages or non-erasable syntax: if needed, bundle your code ahead of time into a single-file server/index.mjs with esbuild or tsc.
1.1 Raw .ts Syntax Rule (erasableSyntaxOnly Do vs Don't)
Node 24's built-in TypeScript stripper erases type annotations without emitting extra runtime JS code. All interface, type, generic, and as constructs work natively, except enum, namespace, and constructor parameter properties (constructor(private x: number)):
ts
// ❌ DON'T: Node 24 native TS stripping rejects `enum` at startup!
enum FilterMode { All = 'all', Include = 'include', Exclude = 'exclude' }
// ✅ DO: Use an `as const` object + union type (zero runtime overhead, 100% compatible!)
const FILTER_MODE = { All: 'all', Include: 'include', Exclude: 'exclude' } as const;
type FilterMode = (typeof FILTER_MODE)[keyof typeof FILTER_MODE];
1.2 How External Modders Get Full VS Code Autocomplete
Download packages/mods/src/server-api.ts (along with its sibling types.ts) from the WTOffline repository into your mod's server/ folder and import types using import type:
ts
// ✅ DO: `import type` is completely erased by Node 24 at runtime while giving full VS Code IntelliSense!
import type { WtoServerModContext } from './server-api.ts';
// ❌ Avoid value-importing `@wto/mods` at runtime (external mod folders do not have monorepo node_modules)
// import { something } from '@wto/mods';
export default {
async setup(ctx: WtoServerModContext) {
ctx.logger.info('mod initialized');
},
};
Tip: Alongside export default { setup(ctx) { ... } }, the runtime also accepts export default function (ctx) { ... } or a named export function setup(ctx) { ... }. You can also declare lightweight structural interface views directly at the top of server/index.ts (just like templates/official-map-selector/server/index.ts) for a zero-dependency single file.
2. WtoServerModContext Property Reference
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:<id>], 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: <dataFolder>/saves/<userId>/mods/<modId>.json
const playerStore = ctx.storage.forPlayer(userId);
const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 };
playerStore.write({ wins: prev.wins + 1 }); // Atomic temp-file rename write
// playerStore.remove();
// ② Shared across all accounts for this mod: <dataFolder>/mods-data/<modId>.json
const sharedStore = ctx.storage.shared();
Fires whenever a player profile is loaded or updated and finishes the native refresh pipeline (profile is an @wto/blkBlkBlock). 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:
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)
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;
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)
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):
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.
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)
ctx.routes.char.register(action, handler): register a brand-new cln_* action;
ctx.routes.char.wrap(action, async (req, next) => { ... }): wrap an existing cln_* action around await next(req).
6. Full-Stack Case Study: How official-map-selector Connects End to End
Open mods/official-map-selector/ (source in mod-dev-docs/templates/official-map-selector/): it is a complete reference implementation connecting native client UI, matching RPCs, isolated player storage, and server matchmaking hooks across 5 clean layers:
text
[1. Minimal Entry Hooks: client/gui-patches/]
├─ gui/gamemodeselect/gamemodeselect.tpl → Inserts the "Custom Map Pool" button into the footer bar
├─ scripts/gamemodes/gamemodeselect.nut → Wires button click to WtoMapSelectorModal.open({ gameMode })
└─ gui/css.css → Appends @import "missions\wtomapselector.css"
│
▼
[2. Standalone Native Modal: client/packs/gui.vromfs.bin/ + lang.vromfs.bin/]
├─ scripts/missions/wtomapselectormodal.nut → Subclasses BaseGuiHandlerWT; renders search, filter tabs & tactical map preview
├─ gui/missions/wtomapselectormodal.tpl → Modal layout & card grid template (wtomapselectorcards.tpl)
├─ gui/missions/wtomapselector.css → Selected card badge & border styling
└─ lang/menu.csv.patch.csv → Localized wto/mapSelector/* UI strings (EN / ZH)
│
▼ matchingApiFunc("wto_mod.map_selector.get" / ".set", Callback(...), { modeName, ... })
[3. Server Matching RPCs: server/index.ts -> ctx.routes.matching.register]
├─ Indexes playable two-sided map pools per PvP mode during onCataloguesReady(catalogues.gameModes)
├─ wto_mod.map_selector.get → Returns the mode's map list + the player's saved filter rule
└─ wto_mod.map_selector.set → Validates & saves the player's all / include / exclude selection
│
▼
[4. Per-Account Isolated Storage: ctx.storage.forPlayer(userId)]
└─ Atomically writes <dataFolder>/saves/<userId>/mods/official.map-selector.json (never touches profile.blk)
│
▼
[5. Matchmaking Map Filter: ctx.hooks.battle.onFilterMissions]
└─ Filters candidate missions by whitelist/blacklist on "To Battle!", falling back to the full pool with a log warning if 0 maps match at that BR
Reading templates/official-map-selector alongside this diagram gives you a production-tested blueprint for virtually any full-stack WTOffline mod!
All mod build and runtime logs flow into the launcher's standard log directory—open Settings › Diagnostics › Open logs folder or About › Export diagnostics:
Launcher Main Log (launcher.log):
Filter [build]: see which mods ran in the current build, .vromfs.bin overlay counts, and exact reasons why any gui-patches or exe-patches item was skipped;
Filter [mods]: see cross-drive Junction mounts, skipped native player-file collision warnings, and restored on-demand stock packs;
Filter [server] or [mod:<yourModId>]: see server tuning validation errors, script load stack traces, and everything printed via ctx.logger.info/warn/error.
Game Client Runtime Logs (<copyFolder>/.game_logs/*.clog):
If a client UI script throws at runtime or hangs on "Loading", check the newest .clog (and run sq.exe full bytecode verification from Chapter 04);
If a custom 3D model fails to appear, search .clog for [PACK], pkg_user, or your asset name to confirm engine mounting.
2. Common Issues & Solutions Lookup Table
Symptom / Log 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 (<dataFolder>/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.execompilestring 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_<yourId>_...)
3. Development Reload Loop (Fastest Edit-Test Cycle)
Knowing when client builds versus server scripts reload keeps iteration fast while developing:
Save your edited mod files and click Launch in the launcher: the launcher hashes source file sizes and mtime timestamps into a deterministic build fingerprint, automatically rebuilding any affected .vromfs.bin packs from wtoffline/stock/ before starting the game!
Tip: textures inside already-mounted NTFS Junction directories (client/addon/res/ or client/files/UserSkins/<subfolder>/) point directly to your mods/ folder with zero copying, so restarting the client (or refreshing skins in-game) reads updated assets immediately.
Every time you exit the game and click Launch to start a new session, the local server restarts cleanly, re-merges all server/tuning/*.jsonc overlays, and reloads server/index.ts with a cache-busting ESM query (?wto_mod=<timestamp>)—no need to restart the launcher itself.
4. Packaging & Sharing Your Mod (.zip Layout Rules)
When packaging your mod for players to download, follow a consistent archive structure so unzipping into mods/ works every time:
Wrap your mod in a single top-level <mod-folder>/ directory inside the .zip:
For a mod folder named my-awesome-mod, structure my-awesome-mod.zip as:
text
my-awesome-mod.zip
└─ my-awesome-mod/ <-- Single top-level folder (extracting straight into mods/ yields mods/my-awesome-mod/mod.jsonc)
├─ mod.jsonc
├─ client/
└─ server/
Do NOT place mod.jsonc loose at the root of the .zip (extracting into mods/ scatters loose files across mods/ where discovery ignores them);
Do NOT double-nest folders (my-awesome-mod/my-awesome-mod/mod.jsonc), as the launcher scans direct child directories of mods/ only!
Exclude development & temporary clutter:
Omit .git/, node_modules/ (bundle third-party JS dependencies into a single server/index.mjs if needed), .DS_Store, Thumbs.db, editor backup files (*.bak, *.swp), and any unpacked stock game reference files.
5. Cross-Drive & Non-NTFS Disk Behavior
NTFS Volumes (standard on Windows): client/addon/ (3D models & textures) and mod-exclusive subfolders (e.g. UserSkins/<subfolder>) mount via NTFS Directory Junctions—works across drives, requires no admin rights, uses 0 extra disk space, and completes in ~1 ms;
Shared Flat-Folder Files (e.g. sound/mod/*.bank): tries file symlink (zero-copy across drives when Windows Developer Mode is on) → same-drive NTFS hardlink → incremental size/mtime cached copy (unchanged files are skipped on subsequent launches);
exFAT External Drives: since exFAT does not support Junctions or hardlinks, the deployer automatically falls back to incremental size/mtime cached copies with full functional parity.
6. Practical Recommendations for Mod Authors
Namespace Everything: format your mod ID as <author>.<mod-name> and prefix custom vehicle IDs, weapons, skin subfolders, custom matching RPCs (wto_mod.<mod_name>.*), and custom Char actions to avoid collisions between mods;
Prefer Incremental Patches Over Replacing Shared Tables: use .patch.blk (or .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;
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;
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;
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.