refactor(repo)!: move apps, shared packages, and patch definitions

Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.

BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 03:20:54 +08:00
1 parent 9c813ccf7d
commit 930ea07630
476 files changed
+275 -251

No files matched your search

@@ -0,0 +1,138 @@
/**
* Dataset: the battle reward factors the game files carry (implementation notes "3d").
*
* char.vromfs.bin config/wpcost.blk, per vehicle:
* unitClass, expMul, rewardMul<Arcade|Historical|Simulation>, battleTimeAward<...>, timedAward<...>
* char.vromfs.bin config/warpoints.blk:
* aKill (Silver Lions of a reference kill), aiKillK, winK, defeatK, wpMultiplier (premium account),
* units{} (Silver Lions factor by the destroyed unit's expClass)
* char.vromfs.bin config/rank.blk:
* xpMultiplier (premium account), goldPlaneExpMul (premium vehicle / talisman),
* expForVictoryVersusPerSec, expForPlayingVersusPerSec, crew_exp_mul_<difficulty>, denominateFreeExp,
* units{} (Research Points factor by the destroyed unit's expClass),
* ExpSkillBonus{<economic name>{BonusLevel<N>{bonusPercent, kills|damage}}}
*
* The stock client shows the same factors on the vehicle card (gui.vromfs.bin scripts/airinfo.nut,
* reward formula: expMul x (1 + premium + talisman), rewardMul x (1 + premium)).
*/
import type { BlkBlock } from '@wto/blk';
import { blockAt, numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export type EconomyDifficulty = 'arcade' | 'historical' | 'simulation';
const DIFFICULTY_SUFFIX: Readonly<Record<EconomyDifficulty, string>> = {
arcade: 'Arcade',
historical: 'Historical',
simulation: 'Simulation',
};
export interface VehicleEconomy {
readonly unitClass: string;
readonly expMul: number;
readonly rewardMul: Readonly<Record<EconomyDifficulty, number>>;
readonly battleTimeAward: Readonly<Record<EconomyDifficulty, number>>;
readonly timedAward: Readonly<Record<EconomyDifficulty, number>>;
}
export interface SkillBonusLevel {
readonly level: number;
readonly bonusPercent: number;
/** Kills needed, or naval damage needed when `metric` is "damage". */
readonly threshold: number;
readonly metric: 'kills' | 'damage';
}
export interface BattleEconomyData {
readonly vehicles: Readonly<Record<string, VehicleEconomy>>;
readonly killSilverLions: number;
readonly aiKillK: number;
readonly winK: number;
readonly defeatK: number;
readonly premiumSilverLionsMul: number;
readonly premiumResearchMul: number;
readonly talismanResearchMul: number;
readonly silverLionsClassFactors: Readonly<Record<string, number>>;
readonly researchClassFactors: Readonly<Record<string, number>>;
readonly researchPerSecondWin: number;
readonly researchPerSecondPlaying: number;
readonly crewExpMul: Readonly<Record<EconomyDifficulty, number>>;
readonly freeResearchDivisor: number;
readonly skillBonus: Readonly<Record<string, readonly SkillBonusLevel[]>>;
}
export const battleEconomy: Dataset<BattleEconomyData> = {
id: 'battle-economy',
version: 1,
extract: (source) => {
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
const rank = source.readBlk('char.vromfs.bin', 'config/rank.blk');
const required = (block: BlkBlock, file: string, name: string): number => {
const value = numberField(block, name);
if (value === undefined) throw new Error(`${file}: ${name} is missing`);
return value;
};
return {
vehicles: Object.fromEntries(wpcost.blocks.map((vehicle) => [vehicle.name, vehicleEconomy(vehicle)])),
killSilverLions: required(warpoints, 'warpoints.blk', 'aKill'),
aiKillK: required(warpoints, 'warpoints.blk', 'aiKillK'),
winK: required(warpoints, 'warpoints.blk', 'winK'),
defeatK: required(warpoints, 'warpoints.blk', 'defeatK'),
premiumSilverLionsMul: required(warpoints, 'warpoints.blk', 'wpMultiplier'),
premiumResearchMul: required(rank, 'rank.blk', 'xpMultiplier'),
talismanResearchMul: required(rank, 'rank.blk', 'goldPlaneExpMul'),
silverLionsClassFactors: numberMap(blockAt(warpoints, 'units')),
researchClassFactors: numberMap(blockAt(rank, 'units')),
researchPerSecondWin: required(rank, 'rank.blk', 'expForVictoryVersusPerSec'),
researchPerSecondPlaying: required(rank, 'rank.blk', 'expForPlayingVersusPerSec'),
crewExpMul: {
arcade: required(rank, 'rank.blk', 'crew_exp_mul_arcade'),
historical: required(rank, 'rank.blk', 'crew_exp_mul_historical'),
simulation: required(rank, 'rank.blk', 'crew_exp_mul_simulation'),
},
freeResearchDivisor: required(rank, 'rank.blk', 'denominateFreeExp'),
skillBonus: skillBonusTable(blockAt(rank, 'ExpSkillBonus')),
};
},
};
function vehicleEconomy(vehicle: BlkBlock): VehicleEconomy {
const perDifficulty = (prefix: string, fallback: number): Record<EconomyDifficulty, number> => ({
arcade: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.arcade}`) ?? fallback,
historical: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.historical}`) ?? fallback,
simulation: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.simulation}`) ?? fallback,
});
return {
unitClass: stringField(vehicle, 'unitClass') ?? '',
expMul: numberField(vehicle, 'expMul') ?? 1,
// The client reads a missing rewardMul as 1.0 (scripts/unit/unit.nut getWpRewardMulList).
rewardMul: perDifficulty('rewardMul', 1),
battleTimeAward: perDifficulty('battleTimeAward', 0),
timedAward: perDifficulty('timedAward', 0),
};
}
function numberMap(block: BlkBlock | undefined): Record<string, number> {
return Object.fromEntries((block?.params ?? []).flatMap((param) =>
param.value.type === 'real' || param.value.type === 'int' ? [[param.name, param.value.value]] : []));
}
function skillBonusTable(block: BlkBlock | undefined): Record<string, SkillBonusLevel[]> {
return Object.fromEntries((block?.blocks ?? []).map((event) => [
event.name,
event.blocks.flatMap((level): SkillBonusLevel[] => {
const index = /^BonusLevel(\d+)$/.exec(level.name)?.[1];
const bonusPercent = numberField(level, 'bonusPercent');
const kills = numberField(level, 'kills');
const damage = numberField(level, 'damage');
if (index === undefined || bonusPercent === undefined || (kills === undefined && damage === undefined)) return [];
return [{
level: Number(index),
bonusPercent,
threshold: kills ?? damage ?? 0,
metric: kills !== undefined ? 'kills' : 'damage',
}];
}).sort((a, b) => a.level - b.level),
]));
}
@@ -0,0 +1,195 @@
/**
* Dataset: the extra vehicles a battle adds to a player's lineup, as the game files list them.
*
* aces.vromfs.bin config/gameplay.blk
* missionSupportPlane{ <event name>{ UnitPreset{ killStreakTagName:t rankRange:ip2 spawnScoreToShow:i
* spawnScoreToUse:i <country>{ unitName:t weapon:t } } } }
* Killstreak aircraft (the nuclear carrier) per session rank bracket, one per country.
* RandomSpawnUnits{ <event economic name>{ <country>{ <group>{ minPlayerMRank:i
* maxDiffBetweenTopUnitAndSessionRank:i mRanksCount:i <unit>{ addModification:t addWeapon:t
* forceWeapon:t } } } } }
* The random vehicle groups (dice slots: random tank and SPAA in ground battles, random fighter
* and bomber in naval battles). The stock client reads the same block for forced weapons
* (scripts/unit/randomunitsforceweapon.nut).
* char.vromfs.bin config/wpcost.blk
* ucav_*_killstreak{ country:t ... }
* The strike UCAVs, one per country.
* char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical
* Starting points and unit cost parameters for Ground Realistic Battles.
*/
import type { BlkBlock } from '@wto/blk';
import { findParam } from '@wto/blk';
import { blockAt, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export interface SupportPlaneUnit {
readonly unitName: string;
readonly weapon: string;
}
export interface SupportPlanePreset {
readonly killStreakTag: string;
/** Session rank bracket (`rankRange`, inclusive). */
readonly minMrank: number;
readonly maxMrank: number;
readonly spawnScoreToShow: number;
readonly spawnScoreToUse: number;
/** By country. */
readonly units: Readonly<Record<string, SupportPlaneUnit>>;
}
export interface StrikeUcav {
readonly country: string;
readonly unitName: string;
}
export interface RandomSpawnUnit {
readonly unitName: string;
readonly addModifications: readonly string[];
readonly forceWeapon?: string;
}
export interface RandomSpawnGroup {
/** `tank`, `spaa`, `fighter`, `bomber`: the key of `random_units` and of gui.blk `randomSpawnUnitPresets`. */
readonly name: string;
readonly minPlayerMrank: number;
readonly maxDiffBetweenTopUnitAndSessionRank: number;
readonly mranksCount: number;
readonly units: readonly RandomSpawnUnit[];
}
interface SpawnScoreParameterSet {
readonly parameters: Readonly<Record<string, number>>;
readonly classCosts: Readonly<Record<string, number>>;
}
export interface SpawnScoreRules {
readonly common: Readonly<Record<string, number>>;
readonly tankHistorical: SpawnScoreParameterSet;
readonly overrides: ReadonlyArray<SpawnScoreParameterSet & {
readonly minMrank: number;
readonly maxMrank: number;
}>;
}
export interface BattleSpawnRulesData {
/** By event name (`missionSupportPlane` keys are game mode names). */
readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>;
readonly strikeUcavs: readonly StrikeUcav[];
readonly spawnScore: SpawnScoreRules;
/** By event economic name, then country. */
readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>;
}
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
id: 'battle-spawn-rules',
version: 3,
extract: (source) => {
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
return {
supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')),
strikeUcavs: extractStrikeUcavs(wpcost.blocks),
spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')),
randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')),
};
},
};
function extractSpawnScore(root: BlkBlock | undefined): SpawnScoreRules {
const tankHistorical = blockAt(root, 'TankHistorical');
return {
common: numericParams(root),
tankHistorical: spawnScoreParams(tankHistorical),
overrides: (blockAt(tankHistorical, 'override_params_by_session_rank')?.blocks ?? []).map((block) => ({
...spawnScoreParams(block),
minMrank: numberField(block, 'minMRank') ?? -1,
maxMrank: numberField(block, 'maxMRank') ?? -1,
})),
};
}
function spawnScoreParams(block: BlkBlock | undefined): SpawnScoreParameterSet {
return {
parameters: numericParams(block),
classCosts: numericParams(blockAt(block, 'respawn_cost_mul_by_exp_class')),
};
}
function numericParams(block: BlkBlock | undefined): Record<string, number> {
const params = block?.params ?? [];
return Object.fromEntries(params.flatMap(({ name, value }) =>
value.type === 'int' || value.type === 'real' ? [[name, value.value]] : []));
}
function extractSupportPlanes(root: BlkBlock | undefined): Record<string, SupportPlanePreset[]> {
const byEvent: Record<string, SupportPlanePreset[]> = {};
for (const eventBlk of root?.blocks ?? []) {
const presets: SupportPlanePreset[] = [];
for (const preset of eventBlk.blocks) {
if (preset.name !== 'UnitPreset') continue;
const range = findParam(preset, 'rankRange')?.value;
const spawnScoreToUse = numberField(preset, 'spawnScoreToUse');
if (range?.type !== 'ipoint2' || spawnScoreToUse === undefined) continue;
const units: Record<string, SupportPlaneUnit> = {};
for (const countryBlk of preset.blocks) {
const unitName = stringField(countryBlk, 'unitName');
const weapon = stringField(countryBlk, 'weapon');
if (countryBlk.name.startsWith('country_') && unitName && weapon) units[countryBlk.name] = { unitName, weapon };
}
presets.push({
killStreakTag: stringField(preset, 'killStreakTagName') ?? '',
minMrank: range.value[0],
maxMrank: range.value[1],
spawnScoreToShow: numberField(preset, 'spawnScoreToShow') ?? spawnScoreToUse,
spawnScoreToUse,
units,
});
}
if (presets.length > 0) byEvent[eventBlk.name] = presets;
}
return byEvent;
}
function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcav[] {
return wpcostBlocks.flatMap((unitBlk) => {
const country = stringField(unitBlk, 'country') ?? '';
return STRIKE_UCAV_PATTERN.test(unitBlk.name) && country.startsWith('country_')
? [{ country, unitName: unitBlk.name }]
: [];
});
}
function extractRandomSpawnUnits(
root: BlkBlock | undefined,
): Record<string, Record<string, RandomSpawnGroup[]>> {
const byEvent: Record<string, Record<string, RandomSpawnGroup[]>> = {};
for (const eventBlk of root?.blocks ?? []) {
const byCountry: Record<string, RandomSpawnGroup[]> = {};
for (const countryBlk of eventBlk.blocks) {
if (!countryBlk.name.startsWith('country_')) continue;
const groups = countryBlk.blocks.flatMap((groupBlk): RandomSpawnGroup[] => {
const units = groupBlk.blocks.map((unitBlk): RandomSpawnUnit => {
const forceWeapon = stringField(unitBlk, 'forceWeapon');
return {
unitName: unitBlk.name,
addModifications: stringList(unitBlk, 'addModification'),
...(forceWeapon ? { forceWeapon } : {}),
};
});
return units.length === 0 ? [] : [{
name: groupBlk.name,
minPlayerMrank: numberField(groupBlk, 'minPlayerMRank') ?? 0,
maxDiffBetweenTopUnitAndSessionRank: numberField(groupBlk, 'maxDiffBetweenTopUnitAndSessionRank') ?? 0,
mranksCount: numberField(groupBlk, 'mRanksCount') ?? 0,
units,
}];
});
if (groups.length > 0) byCountry[countryBlk.name] = groups;
}
byEvent[eventBlk.name] = byCountry;
}
return byEvent;
}
@@ -0,0 +1,124 @@
/**
* Dataset: the battle awards ("streaks") of char.vromfs.bin config/unlocks.blk (implementation notes "3e").
*
* unlockable{ id:t type:t="streak" hidden:b isAfterFlight:b isMultiStage:b
* amount_warpoints:i|ip3 amount_exp:i|ip3 reward of a single-stage award
* wpA:p3 wpB:p3 expA:p3 expB:p3 reward terms of a multi-stage award
* stage{ param:i amount_warpoints amount_exp } first stage of a multi-stage award
* mode{ type:t <mode parameters> condition{ type:t <condition parameters> } ... }
* }
*
* Three-value parameters (p3 / ip3) are per difficulty: arcade, realistic, simulator. Hidden
* awards are kept and flagged: the stock client does not show them (scripts/unlocks
* isUnlockVisible), but wagers name some of them as win conditions (hidden_win_streak ...).
* Online the battle server evaluates these definitions; battle/battle-streaks.ts does it offline.
*/
import type { BlkBlock, BlkValue } from '@wto/blk';
import type { Dataset } from './dataset.ts';
export type StreakValue = string | number | boolean;
/** Every parameter of a block by name, repeated names in order; three-value parameters spread. */
export type StreakParams = Readonly<Record<string, readonly StreakValue[]>>;
export interface StreakCondition {
readonly type: string;
readonly params: StreakParams;
}
export interface StreakMode {
readonly type: string;
readonly params: StreakParams;
readonly conditions: readonly StreakCondition[];
}
export type PerDifficulty = readonly [number, number, number];
export interface StreakDefinition {
readonly id: string;
readonly hidden: boolean;
readonly afterFlight: boolean;
readonly multiStage: boolean;
readonly wp: PerDifficulty;
readonly exp: PerDifficulty;
readonly stage?: { readonly param: number; readonly wp: PerDifficulty; readonly exp: PerDifficulty };
readonly wpA: PerDifficulty;
readonly wpB: PerDifficulty;
readonly expA: PerDifficulty;
readonly expB: PerDifficulty;
readonly mode?: StreakMode;
}
export const battleStreaks: Dataset<readonly StreakDefinition[]> = {
id: 'battle-streaks',
version: 2,
extract: (source) => source.readBlk('char.vromfs.bin', 'config/unlocks.blk').blocks
.filter((block) => block.name === 'unlockable')
.flatMap((block): StreakDefinition[] => {
const params = paramsOf(block);
const id = params.id?.[0];
if (params.type?.[0] !== 'streak' || typeof id !== 'string') return [];
const stage = block.blocks.find((child) => child.name === 'stage');
const stageParams = stage && paramsOf(stage);
const stageParam = stageParams?.param?.[0];
const mode = block.blocks.find((child) => child.name === 'mode');
return [{
id,
hidden: params.hidden?.[0] === true,
afterFlight: params.isAfterFlight?.[0] === true,
multiStage: params.isMultiStage?.[0] === true,
wp: perDifficulty(params.amount_warpoints),
exp: perDifficulty(params.amount_exp),
...(stageParams && typeof stageParam === 'number'
? { stage: { param: stageParam, wp: perDifficulty(stageParams.amount_warpoints), exp: perDifficulty(stageParams.amount_exp) } }
: {}),
wpA: perDifficulty(params.wpA),
wpB: perDifficulty(params.wpB),
expA: perDifficulty(params.expA),
expB: perDifficulty(params.expB),
...(mode ? { mode: unlockModeOf(mode) } : {}),
}];
}),
};
/** An unlock mode block: its type, parameters and condition{} children (also used by wagers). */
export function unlockModeOf(block: BlkBlock): StreakMode {
const params = paramsOf(block);
return {
type: String(params.type?.[0] ?? ''),
params,
conditions: block.blocks.filter((child) => child.name === 'condition').map((condition) => {
const conditionParams = paramsOf(condition);
return { type: String(conditionParams.type?.[0] ?? ''), params: conditionParams };
}),
};
}
function paramsOf(block: BlkBlock): Record<string, StreakValue[]> {
const out: Record<string, StreakValue[]> = {};
for (const param of block.params) (out[param.name] ??= []).push(...valuesOf(param.value));
return out;
}
function valuesOf(value: BlkValue): StreakValue[] {
switch (value.type) {
case 'string':
case 'int':
case 'real':
case 'bool':
return [value.value];
case 'point3':
case 'ipoint3':
return [...value.value];
default:
return [];
}
}
/** An int applies to every difficulty; a three-value parameter is per difficulty; missing is 0. */
function perDifficulty(values: readonly StreakValue[] | undefined): PerDifficulty {
const numbers = (values ?? []).filter((value): value is number => typeof value === 'number');
if (numbers.length >= 3) return [numbers[0]!, numbers[1]!, numbers[2]!];
const single = numbers[0] ?? 0;
return [single, single, single];
}
@@ -0,0 +1,36 @@
/** Typed reads of BLK parameters for dataset extraction; a missing or differently typed parameter reads as undefined. */
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
export function stringField(block: BlkBlock | undefined, name: string): string | undefined {
const value = block && findParam(block, name)?.value;
return value?.type === 'string' ? value.value : undefined;
}
export function numberField(block: BlkBlock | undefined, name: string): number | undefined {
const value = block && findParam(block, name)?.value;
return value?.type === 'int' || value?.type === 'real' ? value.value : undefined;
}
export function boolField(block: BlkBlock | undefined, name: string): boolean | undefined {
const value = block && findParam(block, name)?.value;
return value?.type === 'bool' ? value.value : undefined;
}
/** Every string value of a repeated parameter, in order. */
export function stringList(block: BlkBlock | undefined, name: string): string[] {
if (!block) return [];
return block.params.flatMap((param) => param.name === name && param.value.type === 'string' ? [param.value.value] : []);
}
/** Every bool parameter of a block, by name. */
export function boolFields(block: BlkBlock | undefined): Record<string, boolean> {
if (!block) return {};
return Object.fromEntries(block.params.flatMap((param) => param.value.type === 'bool' ? [[param.name, param.value.value]] : []));
}
/** Follow a path of first-found sub-blocks. */
export function blockAt(block: BlkBlock | undefined, ...names: string[]): BlkBlock | undefined {
let current = block;
for (const name of names) current = current && findBlock(current, name);
return current;
}
@@ -0,0 +1,75 @@
/**
* Dataset: squadron creation, edit, member-limit upgrade, battalion-to-normal upgrade prices,
* and free tag decorators from char.vromfs.bin config/warpoints.blk (implementation notes;
* aces.exe 0x906fe0..0x907070; scripts/clans/clanType.nut).
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const WARPOINTS = 'config/warpoints.blk';
export interface ClanEconomy {
readonly normalCreateGold: number;
readonly normalCreateSilver: number;
readonly normalPrimaryEditGold: number;
readonly normalPrimaryEditSilver: number;
readonly normalSecondaryEditGold: number;
readonly normalSecondaryEditSilver: number;
readonly battalionCreateGold: number;
readonly battalionCreateSilver: number;
readonly battalionPrimaryEditGold: number;
readonly battalionPrimaryEditSilver: number;
readonly battalionSecondaryEditGold: number;
readonly battalionSecondaryEditSilver: number;
readonly battalionMembersUpgradeGold: number;
readonly battalionMembersUpgradeStep: number;
readonly battalionMembersUpgradeLimit: number;
readonly upgradeBattalionToNormalGold: number;
readonly upgradeBattalionToNormalSilver: number;
readonly normalFreeDecorators: readonly string[];
readonly battalionFreeDecorators: readonly string[];
}
export const clanEconomy: Dataset<ClanEconomy> = {
id: 'clan-economy',
version: 3,
extract: (source) => {
const wp = source.readBlk('char.vromfs.bin', WARPOINTS);
const required = (key: string): number => {
const value = numberField(wp, key);
if (value === undefined) throw new Error(`${WARPOINTS} has no ${key}; this game build differs from the verified ones`);
return value;
};
// scripts/clans/clanType.nut reads these costs as `blk?[name] ?? 0`; 2.61.0.37 has no
// clanCreateWPCost, costWPPrimaryInfo or costWPSecondaryInfo, so they are 0 there too.
const clientDefaultZero = (key: string): number => numberField(wp, key) ?? 0;
return {
normalCreateGold: required('clanCreateGoldCost'),
normalCreateSilver: clientDefaultZero('clanCreateWPCost'),
normalPrimaryEditGold: clientDefaultZero('costGoldPrimaryInfo'),
normalPrimaryEditSilver: clientDefaultZero('costWPPrimaryInfo'),
normalSecondaryEditGold: required('costGoldSecondaryInfo'),
normalSecondaryEditSilver: clientDefaultZero('costWPSecondaryInfo'),
battalionCreateGold: required('battalionCreateGoldCost'),
battalionCreateSilver: clientDefaultZero('battalionCreateWPCost'),
battalionPrimaryEditGold: clientDefaultZero('battalionCostGoldPrimaryInfo'),
battalionPrimaryEditSilver: required('battalionCostWPPrimaryInfo'),
battalionSecondaryEditGold: required('battalionCostGoldSecondaryInfo'),
battalionSecondaryEditSilver: required('battalionCostWPSecondaryInfo'),
battalionMembersUpgradeGold: required('battalionMembersUpgradeCost'),
battalionMembersUpgradeStep: required('battalionMembersUpgradeStep'),
battalionMembersUpgradeLimit: required('battalionMembersUpgradeLimit'),
upgradeBattalionToNormalGold: required('clanUpgradeCostGoldBattalionToNormal'),
upgradeBattalionToNormalSilver: clientDefaultZero('clanUpgradeCostWPBattalionToNormal'),
normalFreeDecorators: readDecorList(wp, 'clanTagDecorators'),
battalionFreeDecorators: readDecorList(wp, 'battalionTagDecorators'),
};
},
};
function readDecorList(wp: BlkBlock, blockName: string): readonly string[] {
const block = findBlock(wp, blockName);
if (!block) throw new Error(`${WARPOINTS} has no ${blockName}; this game build differs from the verified ones`);
return block.params.flatMap((p) => (p.name === 'decor' && p.value.type === 'string' ? [p.value.value] : []));
}
@@ -0,0 +1,96 @@
/**
* Dataset: crew skills, skill point packs, per-vehicle crew training prices, and
* Expert-to-Ace Golden Eagles discount stages.
*
* char.vromfs.bin config/crew_skills.blk
* crew_skills{ <page>{ type:t <skill>{ skill_level_exp{ level1:i ... levelN:i } } } }
* levelN is the skill point cost of level N (the scripts add them up into costTbl).
* char.vromfs.bin config/warpoints.blk
* crewSkillPointsCost{ <pack>{ costGold:i crewExp:i } }
* expert_to_ace_cost_reduce{ stage{ percent:i discount:i } }
* char.vromfs.bin config/wpcost.blk, per vehicle
* trainCost:i (training a crew, silver lions), train2Cost:i (expert, silver lions),
* train3Cost_gold:i (ace, golden eagles), train3Cost_exp:i (free ace RP threshold)
*/
import type { BlkBlock } from '@wto/blk';
import { findBlock } from '@wto/blk';
import { numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export interface SkillFacts {
readonly name: string;
/** Cost of each level, index 0 = level 1; the length is the maximum level. */
readonly levelCosts: readonly number[];
}
export interface SkillPage {
readonly name: string;
readonly type: string;
readonly skills: readonly SkillFacts[];
}
export interface SkillPointPack {
readonly name: string;
readonly goldenEagles: number;
readonly points: number;
}
export interface AceDiscountStage {
readonly percent: number;
readonly discount: number;
}
export interface CrewTrainingPrices {
readonly vehicle: string;
readonly training: number;
readonly expert: number;
readonly aceGoldenEagles: number;
readonly aceResearchPoints: number;
}
export interface CrewSkillData {
readonly pages: readonly SkillPage[];
readonly packs: readonly SkillPointPack[];
readonly aceDiscountStages: readonly AceDiscountStage[];
readonly training: readonly CrewTrainingPrices[];
}
export const crewSkillData: Dataset<CrewSkillData> = {
id: 'crew-skills',
version: 2,
extract: (source) => {
const skills = findBlock(source.readBlk('char.vromfs.bin', 'config/crew_skills.blk'), 'crew_skills');
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
const packs = findBlock(warpoints, 'crewSkillPointsCost');
const aceReduce = findBlock(warpoints, 'expert_to_ace_cost_reduce');
return {
pages: (skills?.blocks ?? []).map(pageOf),
packs: (packs?.blocks ?? []).map((pack) => ({ name: pack.name, goldenEagles: numberField(pack, 'costGold') ?? 0, points: numberField(pack, 'crewExp') ?? 0 })),
aceDiscountStages: (aceReduce?.blocks ?? [])
.filter((stage) => stage.name === 'stage')
.map((stage) => ({ percent: numberField(stage, 'percent') ?? 0, discount: numberField(stage, 'discount') ?? 0 }))
.filter((stage) => stage.percent > 0 && stage.discount > 0)
.sort((a, b) => a.percent - b.percent),
training: source.readBlk('char.vromfs.bin', 'config/wpcost.blk').blocks.map((vehicle) => ({
vehicle: vehicle.name,
training: numberField(vehicle, 'trainCost') ?? 0,
expert: numberField(vehicle, 'train2Cost') ?? 0,
aceGoldenEagles: numberField(vehicle, 'train3Cost_gold') ?? 0,
aceResearchPoints: numberField(vehicle, 'train3Cost_exp') ?? 0,
})),
};
},
};
function pageOf(page: BlkBlock): SkillPage {
return {
name: page.name,
type: stringField(page, 'type') ?? '',
skills: page.blocks.map((skill) => {
const levels = findBlock(skill, 'skill_level_exp');
const levelCosts: number[] = [];
for (let level = 1; levels && numberField(levels, `level${level}`) !== undefined; level++) levelCosts.push(numberField(levels, `level${level}`)!);
return { name: skill.name, levelCosts };
}),
};
}
@@ -0,0 +1,163 @@
/**
* Extract datasets once and reuse the result while the game files stay the same
*:
*
* 1. every pack the dataset read has the same size and modification time as when it was
* extracted: use the cached result;
* 2. otherwise compare the SHA-1 of the files the dataset actually read (and of the file
* listings it used): all equal, the result still holds, so only the pack stamps are
* updated (the build rewrites char.vromfs.bin on every launch without touching what
* the datasets read);
* 3. otherwise extract again.
*
* Cache entries live in <data folder>/cache/datasets/<dataset id>.json.
*/
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../../storage/atomic-file.ts';
import type { GameFiles, GamePackName, PackStamp } from '../game-files.ts';
import type { Dataset, DatasetSource } from './dataset.ts';
interface FileInput {
readonly pack: GamePackName;
readonly path: string;
readonly sha1: string;
}
interface ListingInput {
readonly pack: GamePackName;
readonly sha1: string;
}
interface CacheEntry {
readonly id: string;
readonly version: number;
readonly packs: Partial<Record<GamePackName, PackStamp>>;
readonly files: readonly FileInput[];
readonly listings: readonly ListingInput[];
readonly data: unknown;
}
export type DatasetOrigin = 'cache' | 'cache, verified by content' | 'extracted';
export class DatasetCache {
readonly #folder: string;
readonly #gameFiles: GameFiles;
readonly #report: (line: string) => void;
constructor(dataFolder: string, gameFiles: GameFiles, report: (line: string) => void) {
this.#folder = join(dataFolder, 'cache', 'datasets');
this.#gameFiles = gameFiles;
this.#report = report;
}
load<T>(dataset: Dataset<T>): T {
const entryPath = join(this.#folder, `${dataset.id}.json`);
const cached = readEntry(entryPath);
if (cached && cached.id === dataset.id && cached.version === dataset.version) {
if (this.#stampsMatch(cached)) return this.#use(dataset, cached, 'cache');
if (this.#contentMatches(cached)) {
writeEntry(entryPath, { ...cached, packs: this.#stamps(Object.keys(cached.packs) as GamePackName[]) });
return this.#use(dataset, cached, 'cache, verified by content');
}
}
const started = Date.now();
const tracked = new TrackedSource(this.#gameFiles);
const data = dataset.extract(tracked);
const entry: CacheEntry = {
id: dataset.id,
version: dataset.version,
packs: this.#stamps(tracked.packs()),
files: tracked.files(),
listings: tracked.listings(),
data,
};
writeEntry(entryPath, entry);
this.#report(`dataset ${dataset.id}: extracted in ${Date.now() - started} ms (${entry.files.length} files)`);
return data;
}
#use<T>(dataset: Dataset<T>, entry: CacheEntry, origin: DatasetOrigin): T {
this.#report(`dataset ${dataset.id}: ${origin}`);
return entry.data as T;
}
#stamps(packs: readonly GamePackName[]): Partial<Record<GamePackName, PackStamp>> {
return Object.fromEntries(packs.map((pack) => [pack, this.#gameFiles.packStamp(pack)]));
}
#stampsMatch(entry: CacheEntry): boolean {
return Object.entries(entry.packs).every(([pack, stamp]) => {
const current = this.#gameFiles.packStamp(pack as GamePackName);
return stamp !== undefined && current.size === stamp.size && current.mtimeMs === stamp.mtimeMs;
});
}
#contentMatches(entry: CacheEntry): boolean {
return entry.files.every(({ pack, path, sha1 }) => this.#gameFiles.pack(pack).fileDigest(path) === sha1)
&& entry.listings.every(({ pack, sha1 }) => listingDigest(this.#gameFiles.pack(pack).paths()) === sha1);
}
}
/** Reads through to the game files and remembers every input. */
class TrackedSource implements DatasetSource {
readonly #gameFiles: GameFiles;
readonly #files = new Map<string, FileInput>();
readonly #listings = new Map<GamePackName, ListingInput>();
constructor(gameFiles: GameFiles) {
this.#gameFiles = gameFiles;
}
readBlk(pack: GamePackName, path: string): BlkBlock {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readBlk(path);
}
readText(pack: GamePackName, path: string): string {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readText(path);
}
listFiles(pack: GamePackName): readonly string[] {
const paths = this.#gameFiles.pack(pack).paths();
this.#listings.set(pack, { pack, sha1: listingDigest(paths) });
return paths;
}
packs(): GamePackName[] {
return [...new Set([...this.#files.values(), ...this.#listings.values()].map((input) => input.pack))];
}
files(): FileInput[] {
return [...this.#files.values()];
}
listings(): ListingInput[] {
return [...this.#listings.values()];
}
}
function listingDigest(paths: readonly string[]): string {
return createHash('sha1').update(paths.join('\n')).digest('hex');
}
function readEntry(path: string): CacheEntry | undefined {
try {
return JSON.parse(readFileSync(path, 'utf8')) as CacheEntry;
} catch {
return undefined;
}
}
function writeEntry(path: string, entry: CacheEntry): void {
writeFileAtomic(path, JSON.stringify(entry));
}
@@ -0,0 +1,26 @@
/**
* A dataset: a set of static facts extracted from the player's game files (implementation notes
* 3.4). Each dataset declares what it produces and reads its inputs only through the source
* it is given, so the cache knows exactly which files the result depends on.
*
* A dataset only records what the game files say; deciding what the facts mean for a game
* rule belongs to the rules layer.
*/
import type { BlkBlock } from '@wto/blk';
import type { GamePackName } from '../game-files.ts';
export interface DatasetSource {
readBlk(pack: GamePackName, path: string): BlkBlock;
readText(pack: GamePackName, path: string): string;
/** Every file path in a pack, sorted. */
listFiles(pack: GamePackName): readonly string[];
}
export interface Dataset<T> {
/** File name of the cache entry; unique among datasets. */
readonly id: string;
/** Raise when the extraction code or the shape of the result changes: old cache entries are then ignored. */
readonly version: number;
/** The result must survive JSON.stringify / JSON.parse unchanged. */
extract(source: DatasetSource): T;
}
@@ -0,0 +1,44 @@
/**
* Dataset: the decorations that can be bought.
*
* char.vromfs.bin config/skins.blk, config/decals.blk, config/attachable.blk: one block per
* decoration, named like the client keys it (skins "<vehicle>/<skin>", decals and attachables by
* name), with
* cost:i silver lions (missing = -1)
* costGold:i golden eagles (missing = -1; -1 means not for sale)
* unlock:t an unlock that also gives it
* Only decorations with a positive price are recorded: the others are either free (the client
* counts them as owned, aces.exe 0x95e1c5) or not for sale.
*/
import type { BlkBlock } from '@wto/blk';
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export type DecorKind = 'skin' | 'decal' | 'attachable';
export interface DecorPrice {
readonly kind: DecorKind;
/** The client's key: "<vehicle>/<skin>" for skins, the name otherwise. */
readonly key: string;
readonly silverLions: number;
readonly goldenEagles: number;
}
const SOURCES: readonly { kind: DecorKind; path: string }[] = [
{ kind: 'skin', path: 'config/skins.blk' },
{ kind: 'decal', path: 'config/decals.blk' },
{ kind: 'attachable', path: 'config/attachable.blk' },
];
export const decorCatalogue: Dataset<readonly DecorPrice[]> = {
id: 'decor-catalogue',
version: 1,
extract: (source) => SOURCES.flatMap(({ kind, path }) =>
source.readBlk('char.vromfs.bin', path).blocks.flatMap((entry) => priceOf(kind, entry))),
};
function priceOf(kind: DecorKind, entry: BlkBlock): DecorPrice[] {
const silverLions = Math.max(0, numberField(entry, 'cost') ?? 0);
const goldenEagles = Math.max(0, numberField(entry, 'costGold') ?? 0);
return silverLions > 0 || goldenEagles > 0 ? [{ kind, key: entry.name, silverLions, goldenEagles }] : [];
}
@@ -0,0 +1,108 @@
/**
* Dataset: stock game references to external inventory itemdef IDs outside shop.blk vehicles
*:
* - Decorator marketplace coupons in char.vromfs.bin config/{skins,decals,attachable}.blk;
* - Unlock/pilot-icon marketplace coupons in char.vromfs.bin config/unlocks.blk;
* - Workshop referenced itemdef IDs in aces.vromfs.bin config/workshop.blk.
*/
import type { BlkBlock } from '@wto/blk';
import { numberField, stringField } from './blk-fields.ts';
import type { Dataset, DatasetSource } from './dataset.ts';
import type { DecorKind } from './decor-catalogue.ts';
import { parseLocalizedCsvMap } from './lang-csv.ts';
import type { LocalizedText } from './unit-names.ts';
export interface MarketplaceDecorCoupon {
readonly itemdefId: number;
readonly kind: DecorKind;
readonly resourceKey: string;
readonly rarityColor?: string;
readonly name: LocalizedText;
}
export interface MarketplaceUnlockCoupon {
readonly itemdefId: number;
readonly unlockId: string;
readonly unlockType: string;
readonly name: LocalizedText;
}
export interface ExternalItemSources {
readonly decorCoupons: readonly MarketplaceDecorCoupon[];
readonly unlockCoupons: readonly MarketplaceUnlockCoupon[];
readonly workshopItemdefIds: readonly number[];
}
const DECOR_FILES: readonly { kind: DecorKind; blkPath: string; csvPath: string }[] = [
{ kind: 'skin', blkPath: 'config/skins.blk', csvPath: 'lang/unlocks_skins.csv' },
{ kind: 'decal', blkPath: 'config/decals.blk', csvPath: 'lang/unlocks_decals.csv' },
{ kind: 'attachable', blkPath: 'config/attachable.blk', csvPath: 'lang/unlocks_attachables.csv' },
];
export const externalItemSources: Dataset<ExternalItemSources> = {
id: 'external-item-sources',
version: 1,
extract: (source) => ({
decorCoupons: DECOR_FILES.flatMap(({ kind, blkPath, csvPath }) => extractDecorCoupons(source, kind, blkPath, csvPath)),
unlockCoupons: extractUnlockCoupons(source),
workshopItemdefIds: [...collectWorkshopIds(source.readBlk('aces.vromfs.bin', 'config/workshop.blk'))].sort((a, b) => a - b),
}),
};
function extractDecorCoupons(
source: DatasetSource,
kind: DecorKind,
blkPath: string,
csvPath: string,
): MarketplaceDecorCoupon[] {
const locMap = parseLocalizedCsvMap(source.readText('lang.vromfs.bin', csvPath));
const root = source.readBlk('char.vromfs.bin', blkPath);
const out: MarketplaceDecorCoupon[] = [];
for (const entry of root.blocks) {
const itemdefId = numberField(entry, 'marketplaceItemdefId');
if (!itemdefId || itemdefId <= 0) continue;
const key = entry.name;
const localized = locMap.get(key)
?? locMap.get(`decals/${key}`)
?? locMap.get(`attachables/${key}`)
?? { en: humanizeKey(key), zh: humanizeKey(key) };
const rarityColor = stringField(entry, 'userlogColoredText') ?? undefined;
out.push({ itemdefId, kind, resourceKey: key, ...(rarityColor ? { rarityColor } : {}), name: localized });
}
return out;
}
function extractUnlockCoupons(source: DatasetSource): MarketplaceUnlockCoupon[] {
const menuLoc = parseLocalizedCsvMap(source.readText('lang.vromfs.bin', 'lang/menu.csv'));
const achieveLoc = parseLocalizedCsvMap(source.readText('lang.vromfs.bin', 'lang/unlocks_achievements.csv'));
const root = source.readBlk('char.vromfs.bin', 'config/unlocks.blk');
const out: MarketplaceUnlockCoupon[] = [];
for (const entry of root.blocks) {
const itemdefId = numberField(entry, 'marketplaceItemdefId');
const unlockId = stringField(entry, 'id');
if (!itemdefId || itemdefId <= 0 || !unlockId) continue;
const unlockType = stringField(entry, 'type') ?? 'unlock';
const localized = achieveLoc.get(`${unlockId}/name`)
?? menuLoc.get(`${unlockId}/name`)
?? achieveLoc.get(unlockId)
?? menuLoc.get(unlockId)
?? { en: humanizeKey(unlockId), zh: humanizeKey(unlockId) };
out.push({ itemdefId, unlockId, unlockType, name: localized });
}
return out;
}
function collectWorkshopIds(block: BlkBlock, out = new Set<number>()): Set<number> {
for (const param of block.params) {
if (param.value.type === 'int' && param.value.value >= 1000) out.add(param.value.value);
else if (param.value.type === 'string' && /^\d{4,}$/.test(param.value.value)) out.add(Number(param.value.value));
}
if (/^\d{4,}$/.test(block.name)) out.add(Number(block.name));
for (const child of block.blocks) collectWorkshopIds(child, out);
return out;
}
function humanizeKey(key: string): string {
const leaf = key.includes('/') ? key.slice(key.indexOf('/') + 1) : key;
return leaf.replace(/[_-]+/g, ' ').replace(/\b[a-z]/g, (ch) => ch.toUpperCase());
}
@@ -0,0 +1,235 @@
/**
* Dataset: the classic items, char.vromfs.bin config/items.blk.
* One block per item, named after the item:
*
* <item>{
* type:t rateBooster, personalDiscounts, wager, missionOrder, universalSpare
* cost:i costGold:i price of one piece; most items have none (prizes only)
* sell_count_step:i pieces per purchase
* purchase_feature:t sold only to players with that feature ("devItemShop")
* expiredTimeH:r lifetime in hours from when the player gets it
* expiredTimeHAfterActivation:r lifetime in hours from activation
* expiredAt:t absolute end, "YYYY-MM-DD hh:mm:ss" UTC
* canPacked:b the pieces stack under one uid
* universalSpareParams{ numSpares:i country:t... unitType:t... minRank:i maxRank:i }
* rateBoosterParams{ wpRate:i xpRate:i percent added to the battle's Silver Lions / Research Points
* personal:b no: "(all allies)" booster; missing = personal
* spentInSessionTimeMin:i each such span of one battle counts as one more battle
* event{ type:t condition{...} } only rewards of this event (kill, kill_ground, assist)
* stop{ type:t num:i } ends after num sessionsStarted / killedPlayers / killedGround
* }
* wagerParams{ minWager:i maxWager:i wagerStep:i goldWager:b maxWins:i maxFails:i
* win{ <unlock mode> } what one battle must achieve to complete a stage
* active{ <unlock mode> condition{...} } which battles count at all
* winParams{ reward{ param:i <type>RewardParams:p3 } ... } wpRewardParams, goldRewardParams,
* rpRewardParams, freeRpRewardParams: (a, b, c)
* }
* personalDiscountsParams{ purchasesMaxCount:i discountsDesc{ <category>{ <key>:i aircrafts{ <vehicle>:i } } } }
* }
*/
import { findParam, type BlkBlock } from '@wto/blk';
import { unlockModeOf, type StreakMode } from './battle-streaks.ts';
import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const ITEMS = 'config/items.blk';
export interface SpareConditions {
readonly spares: number;
/** Empty: any country. */
readonly countries: readonly string[];
/** The client's lower-case unit type names (aircraft, tank, ship, helicopter, boat); empty: any. */
readonly unitTypes: readonly string[];
readonly minRank?: number;
readonly maxRank?: number;
}
export interface BoosterDefinition {
readonly wpPercent: number;
readonly rpPercent: number;
/** False for the "(all allies)" boosters. */
readonly personal: boolean;
/** spentInSessionTimeMin; 0 when a battle counts once however long it lasts. */
readonly minutesPerBattle: number;
/** rateBoosterParams/event: the booster only adds to the rewards of this event. */
readonly event?: StreakMode;
readonly stop: { readonly type: string; readonly count: number };
}
export type WagerRewardKind = 'rp' | 'freeRp' | 'wp' | 'gold';
export type WagerRewardTerms = readonly [a: number, b: number, c: number];
export interface WagerReward {
/** The stage (number of won battles) from which this reward applies. */
readonly stage: number;
readonly terms: Readonly<Partial<Record<WagerRewardKind, WagerRewardTerms>>>;
}
export interface WagerDefinition {
readonly minStake: number;
readonly maxStake: number;
readonly stakeStep: number;
readonly goldenEagles: boolean;
readonly maxWins: number;
readonly maxFails: number;
readonly win?: StreakMode;
readonly active?: StreakMode;
/** Sorted by stage. */
readonly rewards: readonly WagerReward[];
}
/** One category of a discount description: percentages by key, and by vehicle under "aircrafts". */
export interface DiscountCategory {
readonly name: string;
readonly keys: Readonly<Record<string, number>>;
readonly vehicles: Readonly<Record<string, number>>;
}
export interface DiscountDefinition {
readonly maxPurchases: number;
readonly categories: readonly DiscountCategory[];
}
export interface ItemDefinition {
readonly name: string;
readonly type: string;
readonly silverLions: number;
readonly goldenEagles: number;
readonly piecesPerPurchase: number;
readonly purchaseFeature?: string;
readonly lifetimeHours?: number;
readonly lifetimeHoursAfterActivation?: number;
/** Unix milliseconds. */
readonly expiresAt?: number;
readonly stacks: boolean;
readonly spare?: SpareConditions;
readonly booster?: BoosterDefinition;
readonly wager?: WagerDefinition;
readonly discount?: DiscountDefinition;
/** External inventory craft-part itemdef id granted on recycling (299000..299004; implementation notes). */
readonly recycleItemResult?: number;
}
export const itemCatalogue: Dataset<readonly ItemDefinition[]> = {
id: 'item-catalogue',
version: 3,
extract: (source) => source.readBlk('char.vromfs.bin', ITEMS).blocks.flatMap(itemOf),
};
function itemOf(entry: BlkBlock): ItemDefinition[] {
const type = stringField(entry, 'type');
if (type === undefined) return [];
const lifetimeHours = positive(numberField(entry, 'expiredTimeH'));
const lifetimeHoursAfterActivation = positive(numberField(entry, 'expiredTimeHAfterActivation'));
const expiresAt = utcTime(stringField(entry, 'expiredAt'));
const purchaseFeature = stringField(entry, 'purchase_feature');
const recycleItemResult = positive(numberField(entry, 'recycleItemResult'));
const spare = spareOf(blockAt(entry, 'universalSpareParams'));
const booster = boosterOf(blockAt(entry, 'rateBoosterParams'));
const wager = wagerOf(blockAt(entry, 'wagerParams'));
const discount = discountOf(blockAt(entry, 'personalDiscountsParams'));
return [{
name: entry.name,
type,
silverLions: Math.max(0, numberField(entry, 'cost') ?? 0),
goldenEagles: Math.max(0, numberField(entry, 'costGold') ?? 0),
piecesPerPurchase: Math.max(1, numberField(entry, 'sell_count_step') ?? 1),
stacks: boolField(entry, 'canPacked') ?? false,
...(purchaseFeature ? { purchaseFeature } : {}),
...(lifetimeHours !== undefined ? { lifetimeHours } : {}),
...(lifetimeHoursAfterActivation !== undefined ? { lifetimeHoursAfterActivation } : {}),
...(expiresAt !== undefined ? { expiresAt } : {}),
...(recycleItemResult !== undefined ? { recycleItemResult } : {}),
...(spare ? { spare } : {}),
...(booster ? { booster } : {}),
...(wager ? { wager } : {}),
...(discount ? { discount } : {}),
}];
}
function spareOf(params: BlkBlock | undefined): SpareConditions | undefined {
if (!params) return undefined;
const minRank = numberField(params, 'minRank');
const maxRank = numberField(params, 'maxRank');
return {
spares: Math.max(1, numberField(params, 'numSpares') ?? 1),
countries: stringList(params, 'country'),
unitTypes: stringList(params, 'unitType'),
...(minRank !== undefined ? { minRank } : {}),
...(maxRank !== undefined ? { maxRank } : {}),
};
}
function boosterOf(params: BlkBlock | undefined): BoosterDefinition | undefined {
if (!params) return undefined;
const event = blockAt(params, 'event');
const stop = blockAt(params, 'stop');
return {
wpPercent: Math.max(0, numberField(params, 'wpRate') ?? 0),
rpPercent: Math.max(0, numberField(params, 'xpRate') ?? 0),
personal: boolField(params, 'personal') ?? true,
minutesPerBattle: Math.max(0, numberField(params, 'spentInSessionTimeMin') ?? 0),
...(event ? { event: unlockModeOf(event) } : {}),
stop: { type: stringField(stop, 'type') ?? 'sessionsStarted', count: Math.max(1, numberField(stop, 'num') ?? 1) },
};
}
const REWARD_KINDS: Readonly<Record<string, WagerRewardKind>> = {
rpRewardParams: 'rp', freeRpRewardParams: 'freeRp', wpRewardParams: 'wp', goldRewardParams: 'gold',
};
function wagerOf(params: BlkBlock | undefined): WagerDefinition | undefined {
if (!params) return undefined;
const win = blockAt(params, 'win');
const active = blockAt(params, 'active');
const rewards = (blockAt(params, 'winParams')?.blocks ?? []).filter((block) => block.name === 'reward').flatMap((reward): WagerReward[] => {
const stage = numberField(reward, 'param') ?? 0;
const terms: Partial<Record<WagerRewardKind, WagerRewardTerms>> = {};
for (const [name, kind] of Object.entries(REWARD_KINDS)) {
const value = findParam(reward, name)?.value;
if (value?.type === 'point3' && value.value.some((part) => part !== 0)) terms[kind] = [value.value[0], value.value[1], value.value[2]];
}
return stage > 0 && Object.keys(terms).length > 0 ? [{ stage, terms }] : [];
}).sort((a, b) => a.stage - b.stage);
return {
minStake: Math.max(0, numberField(params, 'minWager') ?? 0),
maxStake: Math.max(0, numberField(params, 'maxWager') ?? 0),
stakeStep: Math.max(1, numberField(params, 'wagerStep') ?? 1),
goldenEagles: boolField(params, 'goldWager') ?? false,
maxWins: Math.max(0, numberField(params, 'maxWins') ?? 0),
maxFails: Math.max(0, numberField(params, 'maxFails') ?? 0),
...(win ? { win: unlockModeOf(win) } : {}),
...(active ? { active: unlockModeOf(active) } : {}),
rewards,
};
}
function discountOf(params: BlkBlock | undefined): DiscountDefinition | undefined {
if (!params) return undefined;
const description = blockAt(params, 'discountsDesc');
return {
maxPurchases: numberField(params, 'purchasesMaxCount') ?? 0,
categories: (description?.blocks ?? []).map((category) => ({
name: category.name,
keys: intsOf(category),
vehicles: intsOf(blockAt(category, 'aircrafts')),
})),
};
}
function intsOf(block: BlkBlock | undefined): Record<string, number> {
if (!block) return {};
return Object.fromEntries(block.params.flatMap((param) => param.value.type === 'int' ? [[param.name, param.value.value]] : []));
}
function positive(value: number | undefined): number | undefined {
return value !== undefined && value > 0 ? value : undefined;
}
/** "YYYY-MM-DD hh:mm:ss" in UTC, as the scripts read it (getTimestampFromStringUtc). */
function utcTime(text: string | undefined): number | undefined {
const match = text && /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/.exec(text.trim());
if (!match) return undefined;
const [, year, month, day, hour, minute, second] = match.map(Number) as [number, number, number, number, number, number, number];
return Date.UTC(year, month - 1, day, hour, minute, second);
}
@@ -0,0 +1,57 @@
/**
* Shared semicolon-separated localization CSV parser for files in `lang.vromfs.bin`.
*/
export interface LocalizedCsvText {
readonly en: string;
readonly zh: string;
}
export function parseSemicolonCsvRow(line: string): string[] {
const fields: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i]!;
if (ch === '"') {
if (inQuotes && line[i + 1] === '"') {
current += '"';
i += 1;
} else {
inQuotes = !inQuotes;
}
} else if (ch === ';' && !inQuotes) {
fields.push(current);
current = '';
} else {
current += ch;
}
}
fields.push(current);
return fields;
}
/** Strip zero-width word-break spaces Gaijin inserts into CJK localization strings. */
export function cleanLangText(raw: string): string {
return raw.replace(/\u200b/g, '').trim();
}
export function parseLocalizedCsvMap(csvText: string): Map<string, LocalizedCsvText> {
const lines = csvText.split(/\r?\n/);
const header = parseSemicolonCsvRow(lines[0] ?? '');
const enIdx = Math.max(1, header.findIndex((col) => col.includes('<English>')));
const zhIdx = header.findIndex((col) => col.includes('<Chinese>'));
const hzhIdx = header.findIndex((col) => col.includes('<HChinese>'));
const map = new Map<string, LocalizedCsvText>();
for (let i = 1; i < lines.length; i += 1) {
const line = lines[i];
if (!line) continue;
const cols = parseSemicolonCsvRow(line);
const id = cols[0];
if (!id) continue;
const en = cleanLangText(cols[enIdx] ?? '') || id;
const zh = cleanLangText((zhIdx >= 0 ? cols[zhIdx] : '') || (hzhIdx >= 0 ? cols[hzhIdx] : '') || '') || en;
map.set(id, { en, zh });
}
return map;
}
@@ -0,0 +1,137 @@
/**
* Dataset: the game's multiplayer missions, as the game lists and describes them.
*
* - The list: char.vromfs.bin config/mislist.blk, block "skirmish". One sub-block per
* category (e.g. air_ground_Dom, air_dom, air_naval_Dom, pve), holding the category's
* flags (isDebug, isForceHidden, …) and its mission names (repeated "m").
* - Each mission: mis.vromfs.bin gamedata/missions/…/<name lower-cased>.blk. Its
* mission_settings block names the map, the kind of game, the two sides' countries, the
* vehicle types allowed, per-difficulty overrides, and the players' spawn slots
* ("wing" entries of player / player_teamB). Its scalar parameters (and those of each
* per-difficulty "mission" sub-block) are also kept as written, with their BLK types, for
* the mission settings the local server sends when a battle starts.
*
* 2.61.0.37: 1315 missions, each name matching exactly one mission file (docs/implementation notes).
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { Dataset, DatasetSource } from './dataset.ts';
import { blockAt, boolFields, numberField, stringField, stringList } from './blk-fields.ts';
const MISSION_LIST = 'config/mislist.blk';
const MULTIPLAYER_SECTION = 'skirmish';
const MISSION_FOLDER = 'gamedata/missions/';
export interface MissionCategory {
readonly name: string;
readonly flags: Readonly<Record<string, boolean>>;
readonly missions: readonly string[];
}
export interface MissionHeader {
readonly name: string;
readonly path: string;
readonly level?: string;
readonly type?: string;
readonly environment?: string;
readonly weather?: string;
readonly locName?: string;
readonly postfix?: string;
readonly countryAxis?: string;
readonly countryAllies?: string;
readonly timeLimit?: number;
/** As written in the mission (isAirplanesAllowed, isTanksAllowed, …); empty when the mission does not say. */
readonly allowedUnitTypes: Readonly<Record<string, boolean>>;
/** Difficulties the mission has its own settings for. */
readonly difficultyOverrides: readonly string[];
/** Spawn slots per side. */
readonly playerSlots: { readonly teamA: number; readonly teamB: number };
/** String, int, real and bool parameters of mission_settings.mission, in file order. */
readonly missionParams: readonly BlkParam[];
/** The same for each per-difficulty "mission" sub-block, keyed by its `difficulty`. */
readonly difficultyParams: Readonly<Record<string, readonly BlkParam[]>>;
}
export interface MultiplayerMissions {
readonly categories: readonly MissionCategory[];
readonly missions: Readonly<Record<string, MissionHeader>>;
}
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
id: 'multiplayer-missions',
version: 3,
extract(source: DatasetSource): MultiplayerMissions {
const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION);
if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`);
const categories = section.blocks.map((block): MissionCategory => ({
name: block.name,
flags: boolFields(block),
missions: stringList(block, 'm'),
}));
const pathByName = missionPathsByLowerName(source.listFiles('mis.vromfs.bin'));
const missions: Record<string, MissionHeader> = {};
for (const name of categories.flatMap((category) => category.missions)) {
if (name in missions) continue;
const path = pathByName.get(name.toLowerCase());
if (!path) throw new Error(`mission ${name} (${MISSION_LIST}) has no file in mis.vromfs.bin`);
missions[name] = readHeader(name, path, source.readBlk('mis.vromfs.bin', path));
}
return { categories, missions };
},
};
function missionPathsByLowerName(paths: readonly string[]): Map<string, string> {
const byName = new Map<string, string>();
const repeated = new Set<string>();
for (const path of paths) {
if (!path.startsWith(MISSION_FOLDER) || !path.endsWith('.blk')) continue;
const name = path.slice(path.lastIndexOf('/') + 1, -'.blk'.length);
if (byName.has(name)) repeated.add(name);
byName.set(name, path);
}
for (const name of repeated) byName.delete(name);
return byName;
}
function readHeader(name: string, path: string, document: BlkBlock): MissionHeader {
const settings = blockAt(document, 'mission_settings');
const mission = blockAt(settings, 'mission');
const optional = {
level: stringField(mission, 'level'),
type: stringField(mission, 'type'),
environment: stringField(mission, 'environment'),
weather: stringField(mission, 'weather'),
locName: stringField(mission, 'locName'),
postfix: stringField(mission, 'postfix'),
countryAxis: stringField(mission, 'country_axis'),
countryAllies: stringField(mission, 'country_allies'),
timeLimit: numberField(mission, 'timeLimit'),
};
return {
name,
path,
...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)),
allowedUnitTypes: boolFields(blockAt(mission, 'allowedUnitTypes')),
difficultyOverrides: (mission?.blocks ?? [])
.filter((block) => block.name === 'mission')
.flatMap((block) => stringField(block, 'difficulty') ?? []),
playerSlots: {
teamA: stringList(blockAt(settings, 'player'), 'wing').length,
teamB: stringList(blockAt(settings, 'player_teamB'), 'wing').length,
},
missionParams: scalarParams(mission),
difficultyParams: Object.fromEntries((mission?.blocks ?? [])
.filter((block) => block.name === 'mission')
.flatMap((block) => {
const difficulty = stringField(block, 'difficulty');
return difficulty ? [[difficulty, scalarParams(block)]] : [];
})),
};
}
const SCALAR_TYPES = new Set(['string', 'int', 'real', 'bool']);
/** The parameters whose values survive the dataset cache's JSON unchanged. */
function scalarParams(block: BlkBlock | undefined): BlkParam[] {
return (block?.params ?? []).filter((param) => SCALAR_TYPES.has(param.value.type));
}
@@ -0,0 +1,55 @@
/**
* Datasets from char.vromfs.bin config/rank.blk.
*
* needBuyToOpenNextInEra{ <country>{ needBuyToOpenNextInEra<type><rank>:i=N } }
* how many vehicles of a rank a country's branch must own before the next rank opens; the
* stock scripts also look up the name without the type (gui.vromfs.bin
* scripts/unit/unitInfo.nut getUnitsNeedBuyToOpenNextInEra).
*
* crew_slots{ slot<N>{ cost:i costGold:i } }
* the price of a country's next crew slot when it has N crews (aces.exe 2.61.0.37
* get_crew_slot_cost, 0x90eaa0).
*/
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const RANK = 'config/rank.blk';
const SLOT = /^slot(\d+)$/;
/** country -> parameter name -> vehicles needed, as written. */
export type EraRequirements = Readonly<Record<string, Readonly<Record<string, number>>>>;
export const eraRequirements: Dataset<EraRequirements> = {
id: 'era-requirements',
version: 1,
extract: (source) => {
const block = source.readBlk('char.vromfs.bin', RANK).blocks.find((child) => child.name === 'needBuyToOpenNextInEra');
return Object.fromEntries((block?.blocks ?? []).map((country) => [
country.name,
Object.fromEntries(country.params.flatMap((param) => (param.value.type === 'int' ? [[param.name, param.value.value]] : []))),
]));
},
};
export interface CrewSlotPrice {
readonly silverLions: number;
readonly goldenEagles: number;
}
/** Indexed by the number of crews the country has; a missing index has no price (cannot be bought). */
export type CrewSlotPrices = readonly (CrewSlotPrice | null)[];
export const crewSlotPrices: Dataset<CrewSlotPrices> = {
id: 'crew-slot-prices',
version: 1,
extract: (source) => {
const block = source.readBlk('char.vromfs.bin', RANK).blocks.find((child) => child.name === 'crew_slots');
const prices: (CrewSlotPrice | null)[] = [];
for (const slot of block?.blocks ?? []) {
const index = SLOT.exec(slot.name)?.[1];
if (index === undefined) continue;
prices[Number(index)] = { silverLions: numberField(slot, 'cost') ?? 0, goldenEagles: numberField(slot, 'costGold') ?? 0 };
}
return Array.from(prices, (price) => price ?? null);
},
};
@@ -0,0 +1,82 @@
/**
* Dataset: how a battle's Research Points reach the researched vehicle (implementation notes "3e").
*
* char.vromfs.bin config/rank.blk:
* expBonusPercentForChildForMode<N> bonus when the vehicle played precedes the researched one;
* the client reads N = the difficulty's diffCode
* (gui.vromfs.bin scripts/airinfo.nut)
* expPenaltyPercentForHigherRank<N> penalty when the researched vehicle is N ranks above the one played
* expPenaltyPercentForLowerRank<N> penalty when it is N ranks below
* ExpNewNationBonus{<type>{rank<N>}} "Vehicle Research Bonus" percent by the researched vehicle's rank
* expNewNationBonusDailyBattleCount battles per nation and branch per day that get it
* char.vromfs.bin config/shop.blk:
* country{ branch{ range{ vehicle | group{ vehicle... } } } }: the last entry of each range ends a
* research line; when it is a group, its first vehicle counts (official wiki "Research Points",
* "top" vehicle definition).
*/
import type { BlkBlock } from '@wto/blk';
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
import { SHOP } from './shop-tree.ts';
export interface ResearchEfficiencyData {
/** Indexed by mode number N of expBonusPercentForChildForMode<N>. */
readonly childBonusPercent: readonly number[];
/** Indexed by the rank difference. */
readonly higherRankPenaltyPercent: readonly number[];
readonly lowerRankPenaltyPercent: readonly number[];
/** Vehicle type (rank.blk spelling: Tank, Aircraft, Helicopter, Ship, Boat) -> rank -> percent. */
readonly nationBonusPercent: Readonly<Record<string, Readonly<Record<number, number>>>>;
readonly nationBonusDailyBattles: number;
/** The vehicle that ends each research line of shop.blk. */
readonly lineEnds: readonly string[];
}
const RANK = 'config/rank.blk';
export const researchEfficiency: Dataset<ResearchEfficiencyData> = {
id: 'research-efficiency',
version: 1,
extract: (source) => {
const rank = source.readBlk('char.vromfs.bin', RANK);
const nationBonus = rank.blocks.find((block) => block.name === 'ExpNewNationBonus');
const dailyBattles = numberField(rank, 'expNewNationBonusDailyBattleCount');
if (dailyBattles === undefined) throw new Error('rank.blk: expNewNationBonusDailyBattleCount is missing');
return {
childBonusPercent: indexedSeries(rank, 'expBonusPercentForChildForMode'),
higherRankPenaltyPercent: indexedSeries(rank, 'expPenaltyPercentForHigherRank'),
lowerRankPenaltyPercent: indexedSeries(rank, 'expPenaltyPercentForLowerRank'),
nationBonusPercent: Object.fromEntries((nationBonus?.blocks ?? []).map((type) => [
type.name,
Object.fromEntries(type.params.flatMap((param) => {
const rankNumber = /^rank(\d+)$/.exec(param.name)?.[1];
return rankNumber !== undefined && param.value.type === 'int' ? [[Number(rankNumber), param.value.value]] : [];
})),
])),
nationBonusDailyBattles: dailyBattles,
lineEnds: source.readBlk('char.vromfs.bin', SHOP).blocks.flatMap((country) =>
country.blocks.flatMap((branch) => branch.blocks.filter((range) => range.name === 'range').flatMap(lineEnd))),
};
},
};
/** <prefix>0, <prefix>1, ... up to the first missing index. */
function indexedSeries(block: BlkBlock, prefix: string): number[] {
const values: number[] = [];
for (let index = 0; ; index++) {
const value = numberField(block, `${prefix}${index}`);
if (value === undefined) break;
values.push(value);
}
if (values.length === 0) throw new Error(`rank.blk: ${prefix}0 is missing`);
return values;
}
/** A vehicle entry has no child blocks; a group holds its vehicles as child blocks. */
function lineEnd(range: BlkBlock): string[] {
const last = range.blocks.at(-1);
if (!last) return [];
if (last.blocks.length === 0) return [last.name];
const first = last.blocks[0];
return first ? [first.name] : [];
}
@@ -0,0 +1,17 @@
/**
* Dataset: how many free research points one golden eagle converts into a vehicle's research
* points (implementation notes, cln_convert_exp).
*
* char.vromfs.bin config/warpoints.blk playerExpToCountryFor1Gold:i (2.61.0.37: 45). The
* client reads it in wp_get_exp_convert_exp_for_gold_rate (aces.exe 0x1052af0 -> 0x916eb0),
* defaulting to 1; the price table can override it per country (exp_to_gold_rate), which the
* local server does not send.
*/
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export const researchPointsPerGoldenEagle: Dataset<number> = {
id: 'research-point-rate',
version: 1,
extract: (source) => numberField(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'playerExpToCountryFor1Gold') ?? 1,
};
@@ -0,0 +1,64 @@
/**
* Dataset: the reserve vehicles, the free rank-I vehicles of each country and branch.
*
* The client decides what counts as a reserve vehicle with the native script function
* is_default_aircraft (aces.exe 2.61.0.37 0x17a5d50 -> 0x9640c0). It looks the vehicle up in
* char.vromfs.bin config/wpcost.blk and reads repairCostArcade, repairCostHistorical and
* repairCostSimulation: a vehicle is a reserve vehicle unless one of them is above 0 (a
* missing value counts as 0). The stock UI then only offers reserve vehicles that are also in
* the tech tree (scripts/slotbar/slotbarStateData.nut checkReserveUnit: isVisibleInShop), so
* only vehicles listed in config/shop.blk are taken; the shop also gives each one's country.
*
* 2.61.0.37: 56 vehicles; every country except Israel has reserve aircraft and ground
* vehicles, and all but China and Sweden have reserve boats and ships. No helicopter is a
* reserve vehicle.
*/
import type { BlkBlock } from '@wto/blk';
import type { Dataset } from './dataset.ts';
import { numberField } from './blk-fields.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
const SHOP = 'config/shop.blk';
const REPAIR_COSTS = ['repairCostArcade', 'repairCostHistorical', 'repairCostSimulation'] as const;
export interface ReserveVehicle {
readonly name: string;
readonly country: string;
}
export const reserveVehicles: Dataset<readonly ReserveVehicle[]> = {
id: 'reserve-vehicles',
version: 1,
extract: (source) => {
const economy = new Map(source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => [vehicle.name, vehicle]));
const result: ReserveVehicle[] = [];
for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) {
for (const name of vehiclesInTree(country)) {
const vehicle = economy.get(name);
if (vehicle && isReserve(vehicle) && !result.some((known) => known.name === name)) result.push({ name, country: country.name });
}
}
return result;
},
};
function isReserve(vehicle: BlkBlock): boolean {
return REPAIR_COSTS.every((cost) => (numberField(vehicle, cost) ?? 0) <= 0);
}
/**
* Every block name below a country's tech tree: country -> branch -> column -> vehicle, with
* grouped vehicles one level deeper. Names that are not vehicles (columns, groups) are
* dropped by the caller, which only keeps names that have an economy entry.
*/
function vehiclesInTree(country: BlkBlock): string[] {
const names: string[] = [];
const walk = (block: BlkBlock): void => {
for (const child of block.blocks) {
names.push(child.name);
walk(child);
}
};
for (const branch of country.blocks) walk(branch);
return names;
}
@@ -0,0 +1,18 @@
/**
* Dataset: the tech-tree branches of each country.
*
* char.vromfs.bin config/shop.blk has one top-level block per country, and under it one block
* per branch: army, helicopters, aviation, ships, boats (2.61.0.37: China, Sweden and Israel
* have no naval branches).
*/
import type { Dataset } from './dataset.ts';
const SHOP = 'config/shop.blk';
export type ShopBranches = Readonly<Record<string, readonly string[]>>;
export const shopBranches: Dataset<ShopBranches> = {
id: 'shop-branches',
version: 1,
extract: (source) => Object.fromEntries(source.readBlk('char.vromfs.bin', SHOP).blocks.map((country) => [country.name, country.blocks.map((branch) => branch.name)])),
};
@@ -0,0 +1,15 @@
/**
* Dataset: the countries of the game, in tech-tree order.
*
* char.vromfs.bin config/shop.blk has one top-level block per country (country_usa, …).
* The stock UI builds its own country list the same way (gui.vromfs.bin
* scripts/shop/shopCountriesList.nut, updateShopCountriesList).
*/
import type { Dataset } from './dataset.ts';
import { shopCountryNames } from './shop-tree.ts';
export const shopCountries: Dataset<readonly string[]> = {
id: 'shop-countries',
version: 1,
extract: shopCountryNames,
};
@@ -0,0 +1,27 @@
/**
* Walk char.vromfs.bin config/shop.blk: one top-level block per country, below it branches,
* columns, groups and vehicles. Shared by the datasets that need the
* per-vehicle shop entries.
*/
import type { BlkBlock } from '@wto/blk';
import type { DatasetSource } from './dataset.ts';
export const SHOP = 'config/shop.blk';
/** Every shop entry by name; the first entry wins when a name repeats. Non-vehicle entries are included and simply never looked up. */
export function shopEntriesByName(source: DatasetSource): Map<string, BlkBlock> {
const entries = new Map<string, BlkBlock>();
for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) {
for (const entry of entriesBelow(country)) if (!entries.has(entry.name)) entries.set(entry.name, entry);
}
return entries;
}
/** The countries in tech-tree order (the top-level block names). */
export function shopCountryNames(source: DatasetSource): string[] {
return source.readBlk('char.vromfs.bin', SHOP).blocks.map((block) => block.name);
}
function entriesBelow(block: BlkBlock): BlkBlock[] {
return block.blocks.flatMap((child) => [child, ...entriesBelow(child)]);
}
@@ -0,0 +1,27 @@
/**
* Dataset: entitlement-to-GUID mappings from aces.vromfs.bin config/gui.blk bundles/guid
* (gui.vromfs.bin scripts/onlineShop/onlineBundles.nut, implementation notes).
*/
import { findBlock } from '@wto/blk';
import type { Dataset } from './dataset.ts';
const GUI_CONFIG = 'config/gui.blk';
/** Entitlement name -> store item GUID (upper-case UUID string). */
export type StoreBundleGuids = Readonly<Record<string, string>>;
export const storeBundles: Dataset<StoreBundleGuids> = {
id: 'store-bundles',
version: 1,
extract: (source) => {
const gui = source.readBlk('aces.vromfs.bin', GUI_CONFIG);
const guidBlock = findBlock(findBlock(gui, 'bundles') ?? { name: '', params: [], blocks: [] }, 'guid');
const result: Record<string, string> = {};
for (const param of guidBlock?.params ?? []) {
if (param.value.type === 'string' && param.value.value) {
result[param.name] = param.value.value;
}
}
return result;
},
};
@@ -0,0 +1,27 @@
/**
* Dataset: the game's own names for countries and vehicle types, from lang.vromfs.bin
*:
* lang/_common_languages.csv: country_usa, country_germany, ... country names
* lang/menu.csv: mainmenu/type_aircraft, type_tank, ... vehicle type names
*/
import type { Dataset } from './dataset.ts';
import { parseLocalizedCsvMap, type LocalizedCsvText } from './lang-csv.ts';
const LABEL_FILES = ['lang/_common_languages.csv', 'lang/menu.csv'] as const;
const KEY_PREFIXES = ['country_', 'mainmenu/type_'];
export type UiLabels = Readonly<Record<string, LocalizedCsvText>>;
export const uiLabels: Dataset<UiLabels> = {
id: 'ui-labels',
version: 2,
extract: (source) => {
const labels: Record<string, LocalizedCsvText> = {};
for (const file of LABEL_FILES) {
for (const [key, text] of parseLocalizedCsvMap(source.readText('lang.vromfs.bin', file))) {
if (KEY_PREFIXES.some((prefix) => key.startsWith(prefix))) labels[key] = text;
}
}
return labels;
},
};
@@ -0,0 +1,58 @@
/**
* Dataset: localized vehicle names from lang.vromfs.bin lang/units.csv.
*
* Used by the local web store and generated inventory coupon definitions so players see the
* game's own English and Chinese vehicle names without shipping game text with the service.
*/
import type { Dataset } from './dataset.ts';
import { cleanLangText, parseSemicolonCsvRow, type LocalizedCsvText } from './lang-csv.ts';
const UNITS_CSV = 'lang/units.csv';
export type LocalizedText = LocalizedCsvText;
export type UnitNamesMap = Readonly<Record<string, LocalizedText>>;
export const unitNames: Dataset<UnitNamesMap> = {
id: 'unit-names',
version: 2,
extract: (source) => {
const lines = source.readText('lang.vromfs.bin', UNITS_CSV).split(/\r?\n/);
const header = parseSemicolonCsvRow(lines[0] ?? '');
const enCol = Math.max(1, header.indexOf('<English>'));
const zhCol = header.indexOf('<Chinese>');
const hzhCol = header.indexOf('<HChinese>');
const shopNames = new Map<string, LocalizedText>();
const fullNames = new Map<string, LocalizedText>();
const groupNames = new Map<string, LocalizedText>();
for (let i = 1; i < lines.length; i++) {
const line = lines[i]!;
if (!line.startsWith('"')) continue;
const firstSemi = line.indexOf(';');
if (firstSemi <= 2) continue;
const key = line.slice(1, firstSemi - 1);
const isGroup = key.startsWith('shop/group/');
const isShop = !isGroup && key.endsWith('_shop');
const isFull = !isGroup && !isShop && key.endsWith('_0');
if (!isGroup && !isShop && !isFull) continue;
const cols = parseSemicolonCsvRow(line);
const en = cleanLangText(cols[enCol] ?? '');
if (!en) continue;
const zh = cleanLangText((hzhCol >= 0 ? cols[hzhCol] : '') || (zhCol >= 0 ? cols[zhCol] : '') || en);
if (isGroup) {
groupNames.set(key, { en, zh });
} else {
const unitId = key.slice(0, isShop ? -5 : -2);
if (isShop) shopNames.set(unitId, { en, zh });
else fullNames.set(unitId, { en, zh });
}
}
const result: Record<string, LocalizedText> = {};
for (const [unitId, text] of fullNames) result[unitId] = text;
for (const [unitId, text] of shopNames) result[unitId] = text;
for (const [groupKey, text] of groupNames) result[groupKey] = text;
return result;
},
};
@@ -0,0 +1,32 @@
/**
* Dataset: the unlocks that can be bought: ship flags, profile icons
* and frames, awards, some achievements.
*
* char.vromfs.bin config/unlocks.blk: unlockable{ id:t type:t cost:i costGold:i mode{...} ... }.
* Only unlocks with a positive cost or costGold are recorded.
*/
import type { BlkBlock } from '@wto/blk';
import { numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const UNLOCKS = 'config/unlocks.blk';
export interface UnlockPrice {
readonly id: string;
readonly silverLions: number;
readonly goldenEagles: number;
}
export const unlockPrices: Dataset<readonly UnlockPrice[]> = {
id: 'unlock-prices',
version: 1,
extract: (source) => source.readBlk('char.vromfs.bin', UNLOCKS).blocks.flatMap(priceOf),
};
function priceOf(entry: BlkBlock): UnlockPrice[] {
const id = stringField(entry, 'id');
const silverLions = Math.max(0, numberField(entry, 'cost') ?? 0);
const goldenEagles = Math.max(0, numberField(entry, 'costGold') ?? 0);
if (id === undefined || (silverLions === 0 && goldenEagles === 0)) return [];
return [{ id, silverLions, goldenEagles }];
}
@@ -0,0 +1,118 @@
/**
* Dataset: every vehicle's research and purchase facts.
*
* The client takes a vehicle's economy from char.vromfs.bin config/wpcost.blk (gui.vromfs.bin
* scripts/unit/unit.nut initOnce; the native status function reads the same file,
* implementation notes): one block per vehicle with
* country:t the country whose tech tree and ranks it belongs to
* unitClass:t exp_fighter, exp_tank, ... (the vehicle type, implementation notes)
* rank:i
* reqAir:t the vehicle that has to be researched before it
* reqExp:i research points needed
* value:i price in silver lions
* costGold:i price in golden eagles
* premPackAir:b, gift:t, event:t, researchType:t premium, gift, event and squadron vehicles
* config/shop.blk places vehicles in the tech tree (country -> branch -> column -> vehicle,
* grouped vehicles one level deeper) and adds per-vehicle entries that matter here:
* reqUnlock:t an unlock from config/unlocks.blk the player must have earned first
* slaveUnit:t the separate part of a split vehicle (a launcher), which comes with it
* showOnlyWhenBought:b the stock UI only shows it to players who own it (kept by the build,
* packages/patcher reveal-hidden-vehicles.ts)
*
* Only what the files say is recorded; what it means for research is the rules layer's
* (research/tech-tree.ts).
*/
import type { BlkBlock } from '@wto/blk';
import { boolField, numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
import { shopEntriesByName } from './shop-tree.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
export interface CatalogueVehicle {
readonly name: string;
readonly country: string;
readonly unitClass: string;
readonly rank: number;
/** wpcost.blk reqAir; absent when empty or missing. */
readonly requires?: string;
/** wpcost.blk reqExp; 0 when missing. */
readonly researchPoints: number;
readonly silverLions: number;
readonly goldenEagles: number;
readonly premiumPack: boolean;
readonly gift: boolean;
readonly event: boolean;
readonly researchType?: string;
/** Listed in config/shop.blk. */
readonly inTechTree: boolean;
/** Position in config/shop.blk (countries, branches, columns top to bottom, in file order); -1 when not listed. */
readonly treeOrder: number;
/** shop.blk reqUnlock. */
readonly requiredUnlock?: string;
/** shop.blk slaveUnit, repeated. */
readonly parts: readonly string[];
/** shop.blk showOnlyWhenBought. */
readonly onlyShownWhenOwned: boolean;
/** shop.blk marketplaceItemdefId (vehicles traded as coupons on the market, implementation notes). */
readonly marketplaceItemdefId?: number;
/** wpcost.blk openCostGold (early GE buyout price for squadron vehicles, implementation notes). */
readonly openCostGold: number;
/** wpcost.blk minOpenCostGold (minimum GE buyout floor for squadron vehicles, implementation notes). */
readonly minOpenCostGold: number;
/** wpcost.blk economicRank and per-difficulty matchmaking ranks. */
readonly economicRank: number;
readonly economicRankArcade: number;
readonly economicRankHistorical: number;
readonly economicRankSimulation: number;
readonly economicRankTankHistorical?: number;
readonly economicRankTankSimulation?: number;
}
export const vehicleCatalogue: Dataset<readonly CatalogueVehicle[]> = {
id: 'vehicle-catalogue',
version: 6,
extract: (source) => {
const shopEntries = shopEntriesByName(source);
const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index]));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1));
},
};
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number): CatalogueVehicle {
const requires = stringField(vehicle, 'reqAir');
const researchType = stringField(vehicle, 'researchType');
const requiredUnlock = stringField(shopEntry, 'reqUnlock');
const marketplaceItemdefId = numberField(shopEntry, 'marketplaceItemdefId') ?? numberField(vehicle, 'marketplaceItemdefId');
const economicRank = numberField(vehicle, 'economicRank') ?? 0;
const economicRankTankHistorical = numberField(vehicle, 'economicRankTankHistorical');
const economicRankTankSimulation = numberField(vehicle, 'economicRankTankSimulation');
return {
name: vehicle.name,
country: stringField(vehicle, 'country') ?? '',
unitClass: stringField(vehicle, 'unitClass') ?? '',
rank: numberField(vehicle, 'rank') ?? 0,
...(requires ? { requires } : {}),
researchPoints: numberField(vehicle, 'reqExp') ?? 0,
silverLions: numberField(vehicle, 'value') ?? 0,
goldenEagles: numberField(vehicle, 'costGold') ?? 0,
premiumPack: boolField(vehicle, 'premPackAir') ?? false,
gift: stringField(vehicle, 'gift') !== undefined,
event: stringField(vehicle, 'event') !== undefined,
...(researchType ? { researchType } : {}),
inTechTree: shopEntry !== undefined,
treeOrder,
...(requiredUnlock ? { requiredUnlock } : {}),
parts: shopEntry ? shopEntry.params.flatMap((param) => (param.name === 'slaveUnit' && param.value.type === 'string' && param.value.value ? [param.value.value] : [])) : [],
onlyShownWhenOwned: boolField(shopEntry, 'showOnlyWhenBought') ?? false,
...(marketplaceItemdefId !== undefined ? { marketplaceItemdefId } : {}),
openCostGold: numberField(vehicle, 'openCostGold') ?? 0,
minOpenCostGold: numberField(vehicle, 'minOpenCostGold') ?? 0,
economicRank,
economicRankArcade: numberField(vehicle, 'economicRankArcade') ?? economicRank,
economicRankHistorical: numberField(vehicle, 'economicRankHistorical') ?? economicRank,
economicRankSimulation: numberField(vehicle, 'economicRankSimulation') ?? economicRank,
...(economicRankTankHistorical !== undefined ? { economicRankTankHistorical } : {}),
...(economicRankTankSimulation !== undefined ? { economicRankTankSimulation } : {}),
};
}
@@ -0,0 +1,163 @@
/**
* Dataset: every vehicle's modifications, ammunition, weapon presets and spare, with their
* research and purchase facts.
*
* char.vromfs.bin config/wpcost.blk, per vehicle:
* needBuyToOpenNextInTier<N>:i researched modifications of tier N needed to open tier N+1
* modifications{ <name>{ tier:i reqExp:i value:i costGold:i openCostGold:i
* reqModification:t (repeated) maxCount:i ammoCount:i ... } }
* Ammunition and expendables are modifications too (tier 0, maxCount, ammoCount).
* weapons{ <preset>{ value:i costGold:i maxCount:i reqModification:t ... } }
* Paid presets (bombs, rockets) are bought by the piece, up to maxCount; the rest are free,
* custom_presets (the custom preset slots) among them.
* spare{ value:i costGold:i }
*
* Only what the file says is recorded; what it means is the rules layer's (modifications/).
*/
import type { BlkBlock } from '@wto/blk';
import { findBlock } from '@wto/blk';
import { boolField, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
const MODIFICATIONS_CONFIG = 'config/modifications.blk';
/** wpcost.blk has needBuyToOpenNextInTier1..4; the modification tree has tiers 1..5 at most. */
const TIER_REQUIREMENT_COUNT = 4;
export interface ModificationFacts {
readonly name: string;
readonly tier: number;
/** reqExp; 0 when the modification is not researched (ammunition, expendables, premium). */
readonly researchPoints: number;
readonly silverLions: number;
readonly goldenEagles: number;
/** openCostGold: golden eagles to get it without the research (scaled by progress, implementation notes). */
readonly openGoldenEagles: number;
/** reqModification, repeated: modifications that must be bought first. */
readonly requires: readonly string[];
/** maxCount; 0 when the modification is not counted (bought once). */
readonly maxCount: number;
/** ammoCount present: an ammunition belt or shell type. */
readonly ammunition: boolean;
/** Initial enabled state when acquired (`turn_it_off` / `isEnabledByDefaultForAddMrank`). */
readonly defaultEnabled: boolean;
/** Non-bullet `group` name when modifications in the same group are mutually exclusive. */
readonly exclusiveGroup?: string;
}
export interface WeaponFacts {
readonly name: string;
/** value: silver lions per piece. */
readonly silverLions: number;
readonly goldenEagles: number;
/** reqModification (direct + inherited from `sum_weapons` containers, initUnitWeapons.nut). */
readonly requires: readonly string[];
/** maxCount; 0 when the preset is not bought by the piece. */
readonly maxCount: number;
}
export interface VehicleEquipment {
readonly vehicle: string;
/** needBuyToOpenNextInTier1..4 (index 0 = tier 1). */
readonly tierRequirements: readonly number[];
readonly modifications: readonly ModificationFacts[];
readonly weapons: readonly WeaponFacts[];
/** spare; absent when the vehicle has no spare price. */
readonly spare?: { readonly silverLions: number; readonly goldenEagles: number };
}
interface GlobalModificationMeta {
readonly turnOffByDefault: boolean;
readonly bulletGroup: boolean;
readonly group?: string;
}
export const vehicleEquipment: Dataset<readonly VehicleEquipment[]> = {
id: 'vehicle-equipment',
version: 3,
extract: (source) => {
const modMeta = readGlobalModificationMeta(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => equipmentOf(vehicle, modMeta));
},
};
function readGlobalModificationMeta(configRoot: BlkBlock): ReadonlyMap<string, GlobalModificationMeta> {
const modsBlock = findBlock(configRoot, 'modifications');
const map = new Map<string, GlobalModificationMeta>();
for (const entry of modsBlock?.blocks ?? []) {
const effects = findBlock(entry, 'effects');
const bulletGroup = Boolean(
effects?.params.some((p) => p.name === 'bulletMod' || p.name === 'additiveBulletMod')
|| effects?.blocks.some((b) => b.name === 'bulletMod' || b.name === 'additiveBulletMod'),
);
const group = stringField(entry, 'group');
map.set(entry.name, {
turnOffByDefault: boolField(entry, 'turn_it_off') === true,
bulletGroup,
...(group !== undefined ? { group } : {}),
});
}
return map;
}
function equipmentOf(vehicle: BlkBlock, modMeta: ReadonlyMap<string, GlobalModificationMeta>): VehicleEquipment {
const tierRequirements: number[] = [];
for (let tier = 1; tier <= TIER_REQUIREMENT_COUNT; tier++) tierRequirements.push(numberField(vehicle, `needBuyToOpenNextInTier${tier}`) ?? 0);
const spare = findBlock(vehicle, 'spare');
return {
vehicle: vehicle.name,
tierRequirements,
modifications: (findBlock(vehicle, 'modifications')?.blocks ?? []).map((mod) => modificationOf(mod, modMeta.get(mod.name))),
weapons: weaponsOf(findBlock(vehicle, 'weapons')),
...(spare ? { spare: { silverLions: numberField(spare, 'value') ?? 0, goldenEagles: numberField(spare, 'costGold') ?? 0 } } : {}),
};
}
function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | undefined): ModificationFacts {
const ammunition = numberField(modification, 'ammoCount') !== undefined;
const defaultEnabled = !(meta?.turnOffByDefault ?? false) && (boolField(modification, 'isEnabledByDefaultForAddMrank') ?? true);
const group = stringField(modification, 'group') ?? meta?.group;
const exclusiveGroup = !ammunition && !(meta?.bulletGroup ?? false) ? group : undefined;
return {
name: modification.name,
tier: numberField(modification, 'tier') ?? 0,
researchPoints: numberField(modification, 'reqExp') ?? 0,
silverLions: numberField(modification, 'value') ?? 0,
goldenEagles: numberField(modification, 'costGold') ?? 0,
openGoldenEagles: numberField(modification, 'openCostGold') ?? 0,
requires: stringList(modification, 'reqModification'),
maxCount: numberField(modification, 'maxCount') ?? 0,
ammunition,
defaultEnabled,
...(exclusiveGroup !== undefined ? { exclusiveGroup } : {}),
};
}
function weaponsOf(weaponsBlock: BlkBlock | undefined): WeaponFacts[] {
if (!weaponsBlock) return [];
const containerRequires = new Map<string, readonly string[]>();
for (const entry of weaponsBlock.blocks) {
if (boolField(entry, 'isWeaponForCustomSlot') === true) {
containerRequires.set(entry.name, stringList(entry, 'reqModification'));
}
}
return weaponsBlock.blocks
.filter((entry) => boolField(entry, 'isWeaponForCustomSlot') !== true)
.map((entry) => weaponOf(entry, containerRequires));
}
function weaponOf(entry: BlkBlock, containerRequires: ReadonlyMap<string, readonly string[]>): WeaponFacts {
const requires = [...stringList(entry, 'reqModification')];
for (const param of findBlock(entry, 'sum_weapons')?.params ?? []) {
for (const req of containerRequires.get(param.name) ?? []) {
if (!requires.includes(req)) requires.push(req);
}
}
return {
name: entry.name,
silverLions: numberField(entry, 'value') ?? 0,
goldenEagles: numberField(entry, 'costGold') ?? 0,
requires,
maxCount: numberField(entry, 'maxCount') ?? 0,
};
}
@@ -0,0 +1,120 @@
/**
* Dataset: what repairing each vehicle costs and how long a free repair takes.
*
* char.vromfs.bin config/wpcost.blk, per vehicle:
* repairCost<Mode>:i full repair cost (Mode = Arcade, Historical, Simulation)
* repairCostPerMin<Mode>:i repair cost per minute of the vehicle's lifetime in a battle
* repairTimeHrs<Mode>:r full repair time in hours with a crew
* repairTimeHrsNoCrew<Mode>:r full repair time in hours when no crew has the vehicle
* freeRepairs:i free repair allowance (falls back to warpoints.blk, then 0)
* modifications{ <mod>{ repairCostCoef:r repairCostCoef<Mode>:r } } added to the cost factor
* char.vromfs.bin config/warpoints.blk: rTimeNoCrewMul:r (no-crew time = repairTimeHrs x it when
* repairTimeHrsNoCrew<Mode> is missing).
* char.vromfs.bin config/crew_skills.blk: the crew's groundService skills that shorten the repair:
* crew_skills{ groundService{ repair{ use_specializations:b skill_level_exp{ level1..levelN } } } }
* specialization<k>_add:r (k = 1..4), repair_ranks{ rank<level>:i }.
*
* The client reads the same fields: the full cost from the price table (cln_get_price_ex,
* aircrafts/<vehicle>/repair/<mode>/cost, aces.exe 2.61.0.37 0x10517b0), times 1 + the
* repairCostCoef<Mode> (else repairCostCoef) of each modification the player has (0x964900); the
* repair time in 0x937330 (repair/repair-rules.ts fullRepairHours).
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import { blockAt, numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export const REPAIR_MODES = ['Arcade', 'Historical', 'Simulation'] as const;
export type RepairMode = (typeof REPAIR_MODES)[number];
export type PerRepairMode = Readonly<Record<RepairMode, number>>;
export interface VehicleRepair {
readonly name: string;
readonly cost: PerRepairMode;
readonly costPerMin: PerRepairMode;
/** Allowance shown by scripts/unit/unit.nut and scripts/airinfo.nut. */
readonly freeRepairs: number;
/** Hours; 0 when the data has none. */
readonly timeHours: PerRepairMode;
/** Hours; -1 when the data has none (the client's default, 0x964e30). */
readonly noCrewTimeHours: PerRepairMode;
/** Modifications with a repair cost coefficient. */
readonly modCoefs: Readonly<Record<string, PerRepairMode>>;
}
/** The crew skills that shorten a repair (crew_skills.blk). */
export interface CrewRepairSkill {
/** Levels of groundService/repair (the length of its skill_level_exp). */
readonly maxLevel: number;
readonly usesSpecializations: boolean;
/** specialization1_add .. specialization4_add (0 when missing). */
readonly specializationAdds: readonly number[];
/** repair_ranks: the highest vehicle rank a groundService/repairRank level covers, index = level - 1. */
readonly ranksByQualification: readonly number[];
/** groundService/repairRank min_skill_level. */
readonly minQualification: number;
}
export interface VehicleRepairData {
readonly vehicles: readonly VehicleRepair[];
readonly noCrewTimeMul: number;
readonly crewSkill: CrewRepairSkill;
}
const SPECIALIZATION_ADDS = 4;
export const vehicleRepair: Dataset<VehicleRepairData> = {
id: 'vehicle-repair',
version: 3,
extract: (source) => {
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
const defaultFreeRepairs = numberField(warpoints, 'freeRepairs') ?? 0;
const vehicles = source.readBlk('char.vromfs.bin', 'config/wpcost.blk').blocks.flatMap((vehicle): VehicleRepair[] => {
const cost = perMode(vehicle, 'repairCost', 0);
if (REPAIR_MODES.every((mode) => cost[mode] <= 0)) return [];
const modCoefs: Record<string, PerRepairMode> = {};
for (const mod of blockAt(vehicle, 'modifications')?.blocks ?? []) {
const base = numberField(mod, 'repairCostCoef');
const coefs = Object.fromEntries(REPAIR_MODES.map((mode) => [mode, numberField(mod, `repairCostCoef${mode}`) ?? base ?? 0])) as Record<RepairMode, number>;
if (REPAIR_MODES.some((mode) => coefs[mode] !== 0)) modCoefs[mod.name] = coefs;
}
return [{
name: vehicle.name,
cost,
costPerMin: perMode(vehicle, 'repairCostPerMin', 0),
freeRepairs: Math.max(0, Math.trunc(numberField(vehicle, 'freeRepairs') ?? defaultFreeRepairs)),
timeHours: perMode(vehicle, 'repairTimeHrs', 0),
noCrewTimeHours: perMode(vehicle, 'repairTimeHrsNoCrew', -1),
modCoefs,
}];
});
return {
vehicles,
noCrewTimeMul: numberField(warpoints, 'rTimeNoCrewMul') ?? 1,
crewSkill: crewRepairSkill(source.readBlk('char.vromfs.bin', 'config/crew_skills.blk')),
};
},
};
function crewRepairSkill(crewSkills: BlkBlock): CrewRepairSkill {
const groundService = findBlock(findBlock(crewSkills, 'crew_skills') ?? crewSkills, 'groundService');
const repair = groundService && findBlock(groundService, 'repair');
const qualification = groundService && findBlock(groundService, 'repairRank');
const levels = repair && findBlock(repair, 'skill_level_exp');
const ranks = findBlock(crewSkills, 'repair_ranks');
const ranksByQualification: number[] = [];
for (let level = 1; ranks && numberField(ranks, `rank${level}`) !== undefined; level++) ranksByQualification.push(numberField(ranks, `rank${level}`)!);
return {
maxLevel: levels?.params.length ?? numberField(crewSkills, 'max_skill_level') ?? 0,
usesSpecializations: repair?.params.some((param) => param.name === 'use_specializations' && param.value.type === 'bool' && param.value.value) ?? false,
specializationAdds: Array.from({ length: SPECIALIZATION_ADDS }, (_, index) => numberField(crewSkills, `specialization${index + 1}_add`) ?? 0),
ranksByQualification,
minQualification: (qualification && numberField(qualification, 'min_skill_level')) ?? 0,
};
}
function perMode(vehicle: BlkBlock, prefix: string, missing: number): PerRepairMode {
return Object.fromEntries(REPAIR_MODES.map((mode) => {
const value = numberField(vehicle, `${prefix}${mode}`);
return [mode, value === undefined ? missing : Math.max(0, value)];
})) as Record<RepairMode, number>;
}
@@ -0,0 +1,103 @@
/**
* Dataset: the unlocks that vehicles depend on, with their conditions.
*
* char.vromfs.bin config/unlocks.blk: unlockable{ id:t type:t mode{ type:t ... } }. The
* conditions of type char_* are checked by the char server, which then records the unlock in
* the profile. Taken here: the unlocks config/shop.blk names as a vehicle's reqUnlock, every
* unlock of type "aircraft" (earning one gives the vehicle of the same name), and every
* unlock those name in their conditions, transitively (2.61.0.37: 73 roots, 131 in all).
*
* Mode parameters kept, as written:
* char_unlocks num:i, unlock:t (repeated)
* char_aircrafts_in_era country:t, era:i, num:i, unitClass:t (repeated), rankExactly:b,
* premium:b, clanUnits:b
* char_player_era country:t, era:i, unitClass:t
* A mode with condition{} sub-blocks is marked: those conditions (first battle, login time
* ...) belong to other features.
*/
import type { BlkBlock } from '@wto/blk';
import { boolField, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const UNLOCKS = 'config/unlocks.blk';
const SHOP = 'config/shop.blk';
/** Unlocks of this type give the vehicle named by the unlock's id. */
export const VEHICLE_UNLOCK_TYPE = 'aircraft';
export interface UnlockMode {
readonly type: string;
readonly num?: number;
readonly unlocks: readonly string[];
readonly country?: string;
readonly era?: number;
readonly unitClasses: readonly string[];
readonly rankExactly?: boolean;
readonly premium?: boolean;
readonly clanUnits?: boolean;
readonly hasOtherConditions: boolean;
}
export interface UnlockDefinition {
readonly id: string;
readonly type: string;
readonly modes: readonly UnlockMode[];
}
export const vehicleUnlocks: Dataset<readonly UnlockDefinition[]> = {
id: 'vehicle-unlocks',
version: 1,
extract: (source) => {
const definitions = new Map<string, UnlockDefinition>();
for (const block of source.readBlk('char.vromfs.bin', UNLOCKS).blocks) {
if (block.name !== 'unlockable') continue;
const id = stringField(block, 'id');
if (id && !definitions.has(id)) definitions.set(id, unlockDefinition(id, block));
}
const roots = [
...requiredUnlocks(source.readBlk('char.vromfs.bin', SHOP)),
...[...definitions.values()].filter((definition) => definition.type === VEHICLE_UNLOCK_TYPE).map((definition) => definition.id),
];
const kept = new Map<string, UnlockDefinition>();
const pending = [...roots];
while (pending.length) {
const definition = definitions.get(pending.pop()!);
if (!definition || kept.has(definition.id)) continue;
kept.set(definition.id, definition);
for (const mode of definition.modes) pending.push(...mode.unlocks);
}
return [...kept.values()];
},
};
function unlockDefinition(id: string, block: BlkBlock): UnlockDefinition {
return { id, type: stringField(block, 'type') ?? '', modes: block.blocks.filter((child) => child.name === 'mode').map(unlockMode) };
}
function unlockMode(mode: BlkBlock): UnlockMode {
const optional = {
num: numberField(mode, 'num'),
country: stringField(mode, 'country'),
era: numberField(mode, 'era'),
rankExactly: boolField(mode, 'rankExactly'),
premium: boolField(mode, 'premium'),
clanUnits: boolField(mode, 'clanUnits'),
};
return {
type: stringField(mode, 'type') ?? '',
unlocks: stringList(mode, 'unlock'),
unitClasses: stringList(mode, 'unitClass'),
hasOtherConditions: mode.blocks.some((child) => child.name === 'condition'),
...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)),
};
}
function requiredUnlocks(shop: BlkBlock): string[] {
const found: string[] = [];
const walk = (block: BlkBlock): void => {
const unlock = stringField(block, 'reqUnlock');
if (unlock) found.push(unlock);
block.blocks.forEach(walk);
};
shop.blocks.forEach(walk);
return found;
}
@@ -0,0 +1,57 @@
/**
* Dataset: the game's own SVG icons that the local web pages (store and marketplace, shown in
* the in-game browser; implementation notes) display, taken from the player's
* ui/atlases.vromfs.bin at runtime. The dataset uses these entries.
* gameuiskin/<vehicle>_ico.svg the tech-tree silhouette of a vehicle
* gameuiskin/<country>.svg a country flag (country_usa, ...)
*
* All 3349 vehicle icons together are about 26 MB, so only premium and store/market vehicles
* are kept: gift vehicles (wpcost.blk gift:t), Golden Eagle premium vehicles (wpcost.blk
* costGold > 0, used by starter packs and custom multi-vehicle packs), and marketplace
* vehicles (shop.blk marketplaceItemdefId).
*/
import { numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
import { shopCountryNames, shopEntriesByName } from './shop-tree.ts';
const ATLASES = 'ui/atlases.vromfs.bin';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
const ICON_FOLDER = 'gameuiskin/';
export interface WebIcons {
/** Vehicle name -> SVG text. */
readonly vehicles: Readonly<Record<string, string>>;
/** Country (country_usa, ...) -> SVG text. */
readonly flags: Readonly<Record<string, string>>;
}
export const webIcons: Dataset<WebIcons> = {
id: 'web-icons',
version: 3,
extract: (source) => {
// Archive paths in ui/atlases.vromfs.bin are lowercase, whereas unit IDs in wpcost.blk
// mix uppercase and lowercase (e.g. germ_pzkpfw_VI_ausf_h1_tiger_east, ussr_t_26E).
const byLowerPath = new Map(source.listFiles(ATLASES).map((path) => [path.toLowerCase(), path]));
const readIcon = (name: string): string | undefined => {
const actualPath = byLowerPath.get(`${ICON_FOLDER}${name}.svg`.toLowerCase());
return actualPath ? source.readText(ATLASES, actualPath) : undefined;
};
const shopEntries = shopEntriesByName(source);
const vehicles: Record<string, string> = {};
for (const vehicle of source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks) {
const needIcon = stringField(vehicle, 'gift') !== undefined
|| (numberField(vehicle, 'costGold') ?? 0) > 0
|| numberField(shopEntries.get(vehicle.name), 'marketplaceItemdefId') !== undefined;
const icon = needIcon ? readIcon(`${vehicle.name}_ico`) : undefined;
if (icon) vehicles[vehicle.name] = icon;
}
const flags: Record<string, string> = {};
for (const country of shopCountryNames(source)) {
const flag = readIcon(country);
if (flag) flags[country] = flag;
}
return { vehicles, flags };
},
};