merge(ground-ai): merge feat/tank-ai phase 1 into main

This commit is contained in:
N0VAN0M4LY committed 2026-12-04 02:50:48 +08:00
commit 0af4183cb1
58 files changed
+6900 -84

No files matched your search

@@ -19,6 +19,8 @@ export interface ResourcePaths {
readonly appIcon: string;
/** Bundled example mod templates seeded into an empty mods folder on first use. */
readonly modTemplates: string;
/** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */
readonly groundAiScripts: string;
}
export function resourcePaths(): ResourcePaths {
@@ -35,6 +37,7 @@ export function bundledResourcePaths(): ResourcePaths {
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
appIcon: join(process.resourcesPath, 'icon.ico'),
modTemplates: join(process.resourcesPath, 'mod-templates'),
groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'),
};
}
// The app path is apps/launcher; the repository is two levels up.
@@ -44,6 +47,7 @@ export function bundledResourcePaths(): ResourcePaths {
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
groundAiScripts: join(repository, 'game-ai', 'ground'),
};
}
@@ -9,6 +9,7 @@ export interface BuildRequest {
readonly port: number;
readonly patches: string;
readonly networkHookLibrary: string;
readonly groundAiScripts: string;
readonly decalCache?: string;
readonly hookLogging: boolean;
readonly acceptedUnavailable: readonly string[];
+34 -15
View File
@@ -8,15 +8,18 @@ import {
computeModsBuildFingerprint,
copyPlayerDecalCache,
CORE_BUILD_PACKS,
GAME_PACK_FILE,
isGroundAiActive,
playerDecalCacheProblem,
prepareOptionalStockPacks,
readPlayerDecalIndexFiles,
readStockGameFiles,
syncExternalModFiles,
writeGameCopy,
type GameCopyBuild,
type GameCopyFile,
} from '@wto/patcher';
import { multiVehiclePackIds } from '@wto/server';
import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
let prepared: {
@@ -61,13 +64,34 @@ function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly
return ordered;
}
function logModBuildSummary(result: GameCopyBuild): void {
if (result.gamePack) {
console.info(`[build] injected ${result.gamePack.modules.length} ground AI module(s) into ${result.gamePack.archiveFolder}`);
}
if (result.mods.enabledModIds.length === 0) return;
console.info(
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
);
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
}
}
function build(request: BuildRequest): void {
checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache);
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
const touchedPacks = touchedClientPacks(enabledMods);
const optionalPacksInBuild = touchedPacks.filter((pack) => !CORE_BUILD_PACKS.has(pack));
const groundAiConfig = loadGroundAiTuning(request.dataPath, console.info, enabledMods);
const groundAiActive = isGroundAiActive(groundAiConfig);
const touchedSet = new Set<ModdableClientPack>(
touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)),
);
if (groundAiActive) touchedSet.add(GAME_PACK_FILE);
const optionalPacksInBuild = [...touchedSet];
const extraStockPacks = optionalPacksInBuild.length > 0
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
: undefined;
@@ -83,6 +107,7 @@ function build(request: BuildRequest): void {
hookLogging: request.hookLogging,
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
...(extraStockPacks ? { extraStockPacks } : {}),
groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig },
});
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable);
@@ -91,18 +116,12 @@ function build(request: BuildRequest): void {
send({ kind: 'failed', error: 'launch_build_unavailable' });
return;
}
if (result.mods.enabledModIds.length > 0) {
console.info(
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
);
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
}
}
const fingerprint = computeModsBuildFingerprint(enabledMods, request.port, request.patches);
logModBuildSummary(result);
const fingerprint = computeModsBuildFingerprint(
enabledMods,
request.port,
`${request.patches}|groundAi=${JSON.stringify(groundAiConfig)}`,
);
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
send({ kind: 'prepared', total: prepared.files.length });
}
+9 -1
View File
@@ -19,11 +19,13 @@ import {
isModeEligibleForLineup,
lineupMrank,
selectCustomBots,
type TankLineupWeights,
type CustomBotsPool,
} from './battle-ranks.ts';
import type { BattleSessionStore } from './battle-session-store.ts';
import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts';
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
import type { BattleTuning } from './battle-tuning.ts';
export interface BattleCrewSlot {
@@ -104,6 +106,8 @@ export class BattleMatchmaker {
readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData;
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
readonly #tankWeights: TankLineupWeights | undefined;
readonly #tankLoadouts: ReadonlyMap<string, BotTankLoadout> | undefined;
readonly #filterMissions: MissionPoolFilter | undefined;
constructor(
@@ -113,6 +117,8 @@ export class BattleMatchmaker {
tuning: BattleTuning,
spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
tankWeights: TankLineupWeights | undefined,
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
filterMissions?: MissionPoolFilter,
) {
this.#gameModes = gameModes;
@@ -122,6 +128,8 @@ export class BattleMatchmaker {
this.#tuning = tuning;
this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts;
this.#tankWeights = tankWeights;
this.#tankLoadouts = tankLoadouts;
this.#filterMissions = filterMissions;
}
@@ -181,7 +189,7 @@ export class BattleMatchmaker {
minMrank,
maxMrank,
limitPerType: this.#tuning.botPoolLimitPerType,
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts);
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights, this.#tankLoadouts);
return {
ok: true,
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
@@ -130,6 +130,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
if (plan.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode));
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
@@ -140,6 +141,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts),
poolBlock('allowedShips', 'ship', plan.customBots.ships),
);
addTankAmmoParams(bots, plan.customBots.tanks);
return bots;
}
@@ -155,11 +157,26 @@ function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tan
setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset));
for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification));
}
if (entry.tankLoadout !== undefined) {
for (const modification of entry.tankLoadout.modifications) appendParam(block, 'addModification', text(modification));
}
pool.blocks.push(block);
}
return pool;
}
/** Per-tank bot ammo strings (`weapon|mod0:count0|mod1:count1`) read by local_mp_loadout.c. */
function addTankAmmoParams(bots: BlkBlock, entries: CustomBotsPool['tanks']): void {
const seen = new Set<string>();
for (const entry of entries) {
const loadout = entry.tankLoadout;
if (!loadout || loadout.bullets.length === 0 || seen.has(entry.name)) continue;
seen.add(entry.name);
const parts = [loadout.weaponName, ...loadout.bullets.slice(0, 2).map((s) => `${s.modName}:${s.count}`)];
setParam(bots, `wtoAmmo_${entry.name}`, text(parts.join('|')));
}
}
function text(value: string): BlkValue {
return { type: 'string', value };
}
+39 -4
View File
@@ -10,6 +10,7 @@ import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.t
import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
const COUNTRY_PREFIX = 'country_';
@@ -23,6 +24,7 @@ export interface BotPoolEntry {
readonly country: string;
readonly weight: number;
readonly aircraftLoadout?: BotAircraftLoadout;
readonly tankLoadout?: BotTankLoadout;
}
export interface CustomBotsPool {
@@ -31,6 +33,16 @@ export interface CustomBotsPool {
readonly ships: readonly BotPoolEntry[];
}
/** Offline tank pool weights by vehicle class (`tuning/ground-ai.jsonc` `lineupWeights`). */
export interface TankLineupWeights {
readonly spaa: number;
readonly lightTank: number;
readonly tankDestroyer: number;
readonly heavyTank: number;
readonly mediumTank: number;
readonly other: number;
}
export interface BotPoolQuery {
readonly difficulty: ModeDifficulty;
readonly requiredClass: UnitClass;
@@ -117,14 +129,25 @@ function lineupVehicleMrank(
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
}
/**
* Without `tankWeights` every pool entry keeps the stock weight of 1.
*/
export function selectCustomBots(
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
vehicles: readonly CatalogueVehicle[],
query: BotPoolQuery,
aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
tankWeights?: TankLineupWeights,
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
): CustomBotsPool {
const allowed = new Set(query.allowedClasses);
const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))];
const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [];
const rawTanks = allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query, tankWeights) : [];
return {
tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [],
tanks: tankLoadouts ? rawTanks.map((entry) => {
const tankLoadout = tankLoadouts.get(entry.name);
return tankLoadout === undefined ? entry : { ...entry, tankLoadout };
}) : rawTanks,
aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => {
const aircraftLoadout = aircraftLoadouts.get(entry.name);
return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout };
@@ -138,6 +161,7 @@ function pickCategoryPool(
orderedCountries: readonly string[],
category: 'tank' | 'aircraft' | 'ship',
query: BotPoolQuery,
tankWeights?: TankLineupWeights,
): BotPoolEntry[] {
const countrySet = new Set(orderedCountries);
const eligible = vehicles.filter((vehicle) =>
@@ -161,13 +185,14 @@ function pickCategoryPool(
return mrank >= query.minMrank && mrank <= query.maxMrank;
});
const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType);
return roundRobinByCountry(source, orderedCountries, query.limitPerType);
return roundRobinByCountry(source, orderedCountries, query.limitPerType, (vehicle) => tankPoolWeight(vehicle, tankWeights));
}
function roundRobinByCountry(
vehicles: readonly CatalogueVehicle[],
orderedCountries: readonly string[],
limit: number,
weightOf: (vehicle: CatalogueVehicle) => number,
): BotPoolEntry[] {
const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []]));
for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle);
@@ -177,7 +202,7 @@ function roundRobinByCountry(
for (const country of orderedCountries) {
const vehicle = buckets.get(country)?.[index];
if (!vehicle) continue;
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 });
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: weightOf(vehicle) });
added = true;
if (out.length >= limit) break;
}
@@ -186,6 +211,16 @@ function roundRobinByCountry(
return out;
}
function tankPoolWeight(vehicle: CatalogueVehicle, weights: TankLineupWeights | undefined): number {
if (weights === undefined) return 1;
if (vehicle.unitClass === 'exp_SPAA') return weights.spaa;
if (vehicle.isLightTank) return weights.lightTank;
if (vehicle.unitClass === 'exp_tank_destroyer') return weights.tankDestroyer;
if (vehicle.unitClass === 'exp_heavy_tank') return weights.heavyTank;
if (vehicle.unitClass === 'exp_tank') return weights.mediumTank;
return weights.other;
}
function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined {
if (type === 'Tank') return 'tank';
if (type === 'Aircraft') return 'aircraft';
+135
View File
@@ -0,0 +1,135 @@
/**
* Offline AI tank spawn ammunition selector:
* - Total carried rounds follow the vehicle's first-stage / autoloader ready rack, topped up
* when below the configured threshold (clamped to main gun capacity).
* - Primary shell prefers legal APFSDS, otherwise ranks anti-armor shells by 500 m penetration.
* - Secondary shell carries a small share of HE / HEAT / HESH when available for soft targets.
*/
import type { GroundAiLoadoutConfig } from '@wto/patcher';
import type { TankAmmoProfile, TankBotAmmoData, TankShellChoice } from '../game-data/datasets/tank-bot-ammo.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import { vehicleTypeOfClass } from '../research/vehicle-types.ts';
export interface BotTankBulletSlot {
readonly modName: string;
readonly count: number;
}
export interface BotTankLoadout {
readonly weaponName: string;
readonly bullets: readonly BotTankBulletSlot[];
readonly modifications: readonly string[];
}
export function selectBotTankLoadouts(
vehicles: readonly CatalogueVehicle[],
ammoData: TankBotAmmoData,
config: GroundAiLoadoutConfig,
): ReadonlyMap<string, BotTankLoadout> {
const result = new Map<string, BotTankLoadout>();
for (const vehicle of vehicles) {
if (vehicleTypeOfClass(vehicle.unitClass) !== 'Tank' || vehicle.unitClass === 'exp_SPAA') continue;
const profile = ammoData[vehicle.name];
if (!profile || profile.isBelt || profile.maxBullets <= 0) continue;
const loadout = chooseTankLoadout(profile, config);
if (loadout !== undefined) result.set(vehicle.name, loadout);
}
return result;
}
function chooseTankLoadout(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): BotTankLoadout | undefined {
const combatShells = profile.shells.filter((shell) => !isNonCombatShell(shell.bulletType));
if (combatShells.length === 0) return undefined;
const primary = pickPrimaryShell(combatShells);
if (!primary) return undefined;
const totalRounds = computeCarriedRounds(profile, config);
if (totalRounds <= 0) return undefined;
const secondary = pickSecondaryShell(combatShells, primary);
const bullets = splitRounds(primary, secondary, totalRounds, config);
const modSet = new Set<string>();
for (const chosen of [primary, ...(bullets.length > 1 && secondary ? [secondary] : [])]) {
if (chosen.modName) modSet.add(chosen.modName);
for (const req of chosen.requires) modSet.add(req);
}
return {
weaponName: profile.weaponName,
bullets,
modifications: [...modSet].sort(),
};
}
function computeCarriedRounds(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): number {
const want = profile.readyRack >= config.lowReadyRackThreshold
? profile.readyRack
: config.topUpAmmoCount;
return Math.max(1, Math.min(want, profile.maxBullets));
}
function pickPrimaryShell(shells: readonly TankShellChoice[]): TankShellChoice | undefined {
const ranked = [...shells].sort((a, b) => compareAntiArmor(a, b));
return ranked[0];
}
function compareAntiArmor(a: TankShellChoice, b: TankShellChoice): number {
const tierA = antiArmorTier(a.bulletType);
const tierB = antiArmorTier(b.bulletType);
if (tierA !== tierB) return tierB - tierA;
const scoreA = a.pen500Mm + (isApheFamily(a.bulletType) ? 12 : 0);
const scoreB = b.pen500Mm + (isApheFamily(b.bulletType) ? 12 : 0);
if (scoreA !== scoreB) return scoreB - scoreA;
if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps;
return a.modName.localeCompare(b.modName);
}
function antiArmorTier(bulletType: string): number {
if (bulletType.includes('apds_fs')) return 5;
if (bulletType.includes('atgm')) return 4;
if (bulletType.includes('apds')) return 3;
if (bulletType.includes('heat') || isApheFamily(bulletType) || bulletType.startsWith('ap')) return 2;
if (bulletType.includes('hesh')) return 1;
return 0;
}
function pickSecondaryShell(shells: readonly TankShellChoice[], primary: TankShellChoice): TankShellChoice | undefined {
const candidates = shells.filter((shell) => shell.modName !== primary.modName && isSoftTargetShell(shell.bulletType));
if (candidates.length === 0) return undefined;
return [...candidates].sort((a, b) => {
const heA = a.bulletType.includes('he_frag') ? 2 : (a.bulletType.includes('hesh') ? 1 : 0);
const heB = b.bulletType.includes('he_frag') ? 2 : (b.bulletType.includes('hesh') ? 1 : 0);
if (heA !== heB) return heB - heA;
if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps;
return a.modName.localeCompare(b.modName);
})[0];
}
function splitRounds(
primary: TankShellChoice,
secondary: TankShellChoice | undefined,
totalRounds: number,
config: GroundAiLoadoutConfig,
): BotTankBulletSlot[] {
if (!secondary || config.primaryAmmoPct >= 100 || config.secondaryMinRounds <= 0 || totalRounds < config.secondaryMinRounds * 2 + 2) {
return [{ modName: primary.modName, count: totalRounds }];
}
const wantSec = Math.round((totalRounds * (100 - config.primaryAmmoPct)) / 100);
const secCount = Math.min(totalRounds - 1, Math.max(config.secondaryMinRounds, wantSec));
const priCount = totalRounds - secCount;
return [
{ modName: primary.modName, count: priCount },
{ modName: secondary.modName, count: secCount },
];
}
function isNonCombatShell(bulletType: string): boolean {
return bulletType.includes('smoke') || bulletType.includes('practice') || bulletType.includes('shrapnel');
}
function isSoftTargetShell(bulletType: string): boolean {
return bulletType.includes('he_frag') || bulletType.includes('hesh') || bulletType.includes('heat');
}
function isApheFamily(bulletType: string): boolean {
return bulletType.includes('aphe') || bulletType.includes('apcbc') || bulletType.includes('apbc');
}
+23 -2
View File
@@ -7,24 +7,45 @@
* will start the service the same way. Stops on Ctrl+C.
*/
import { parseArgs } from 'node:util';
import { discoverMods, type DiscoveredMod } from '@wto/mods';
import { LOOPBACK, startServer } from './server.ts';
function resolveCliMods(modsDir: string | undefined, modIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !modIds || modIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
return modIds.map((id) => {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
return mod;
});
}
async function main(): Promise<number> {
const { values } = parseArgs({
options: {
game: { type: 'string' },
data: { type: 'string' },
port: { type: 'string' },
'mods-dir': { type: 'string' },
mod: { type: 'string', multiple: true },
},
});
const port = Number(values.port);
if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) {
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n>');
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n> [--mods-dir <dir> --mod <id>...]');
return 2;
}
let service;
try {
service = await startServer({ gameFolder: values.game, dataFolder: values.data, port, report: (line) => console.log(line) });
const mods = resolveCliMods(values['mods-dir'], values.mod);
service = await startServer({
gameFolder: values.game,
dataFolder: values.data,
port,
report: (line) => console.log(line),
...(mods.length > 0 ? { mods } : {}),
});
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error));
@@ -41,9 +41,13 @@ interface AirfieldLayoutData {
readonly airfieldLayoutProblem?: string;
}
export type GroundBattleMode = 'bttl' | 'conq' | 'dom';
export interface MissionHeader extends AirfieldLayoutData {
readonly name: string;
readonly path: string;
/** Ground mission tactical layout derived from mislist category (or suffix fallback for events). */
readonly groundMode?: GroundBattleMode;
readonly level?: string;
readonly type?: string;
readonly environment?: string;
@@ -72,7 +76,7 @@ export interface MultiplayerMissions {
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
id: 'multiplayer-missions',
version: 4,
version: 5,
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`);
@@ -82,6 +86,7 @@ export const multiplayerMissions: Dataset<MultiplayerMissions> = {
missions: stringList(block, 'm'),
}));
const groundModeByMission = indexGroundModes(categories);
const paths = source.listFiles('mis.vromfs.bin');
const pathByName = missionPathsByLowerName(paths);
const knownPaths = new Set(paths);
@@ -94,12 +99,34 @@ export const multiplayerMissions: Dataset<MultiplayerMissions> = {
const document = source.readBlk('mis.vromfs.bin', path);
const airfields = path.startsWith(AIR_HISTORICAL_MISSION_FOLDER)
? readAirfieldLayouts(source, document, knownPaths, airfieldsByPath) : { airfieldLayouts: [] };
missions[name] = readHeader(name, path, document, airfields);
const groundMode = groundModeByMission.get(name) ?? groundModeFromName(name);
missions[name] = readHeader(name, path, document, airfields, groundMode);
}
return { categories, missions };
},
};
function indexGroundModes(categories: readonly MissionCategory[]): Map<string, GroundBattleMode> {
const byName = new Map<string, GroundBattleMode>();
for (const category of categories) {
const mode: GroundBattleMode | undefined =
category.name === 'air_ground_Bttl' ? 'bttl'
: category.name === 'air_ground_Conq' ? 'conq'
: category.name === 'air_ground_Dom' ? 'dom'
: undefined;
if (!mode) continue;
for (const name of category.missions) if (!byName.has(name)) byName.set(name, mode);
}
return byName;
}
function groundModeFromName(name: string): GroundBattleMode | undefined {
if (/_Bttl\d*$/i.test(name)) return 'bttl';
if (/_Conq\d*$/i.test(name)) return 'conq';
if (/_Dom\d*$/i.test(name)) return 'dom';
return undefined;
}
function missionPathsByLowerName(paths: readonly string[]): Map<string, string> {
const byName = new Map<string, string>();
const repeated = new Set<string>();
@@ -114,11 +141,12 @@ function missionPathsByLowerName(paths: readonly string[]): Map<string, string>
}
function readHeader(
name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData,
name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData, groundMode?: GroundBattleMode,
): MissionHeader {
const settings = blockAt(document, 'mission_settings');
const mission = blockAt(settings, 'mission');
const optional = {
groundMode,
level: stringField(mission, 'level'),
type: stringField(mission, 'type'),
environment: stringField(mission, 'environment'),
@@ -0,0 +1,244 @@
/**
* Dataset: primary cannon weapon name, capacity, first-stage/autoloader ready-rack count,
* and selectable ammunition groups (with penetration and prerequisite modifications) for
* every ground tank model in `aces.vromfs.bin` + `char.vromfs.bin`.
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import type { Dataset, DatasetSource } from './dataset.ts';
import { boolField, numberField, stringField, stringList } from './blk-fields.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
const MODIFICATIONS_CONFIG = 'config/modifications.blk';
const TANK_MODELS_PREFIX = 'gamedata/units/tankmodels/';
export interface TankShellChoice {
/** Modification name expected by ChangeUnitReflection.bullets[i] (`""` for stock default). */
readonly modName: string;
readonly bulletType: string;
readonly speedMps: number;
/** Estimated normal penetration at 500 m (mm) for deterministic ranking. */
readonly pen500Mm: number;
/** Transitive prerequisite modifications needed to unlock this shell. */
readonly requires: readonly string[];
}
export interface TankAmmoProfile {
readonly weaponName: string;
readonly maxBullets: number;
readonly isBelt: boolean;
/** Total firstStage / autoLoad / ammoLoadedInGun shell slots (excluding separate charges). */
readonly readyRack: number;
readonly shells: readonly TankShellChoice[];
}
export type TankBotAmmoData = Readonly<Record<string, TankAmmoProfile>>;
interface GlobalModInfo {
readonly bulletMod?: string;
readonly requires: readonly string[];
}
interface WeaponBulletMeta {
readonly bulletType: string;
readonly speedMps: number;
readonly pen500Mm: number;
}
export const tankBotAmmo: Dataset<TankBotAmmoData> = {
id: 'tank-bot-ammo',
version: 2,
extract(source: DatasetSource): TankBotAmmoData {
const globalMods = readGlobalModInfo(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
const wpcost = source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY);
const acesPaths = new Set(source.listFiles('aces.vromfs.bin').map((p) => p.toLowerCase()));
const weaponCache = new Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>();
const out: Record<string, TankAmmoProfile> = {};
for (const vehicleBlk of wpcost.blocks) {
const unitPath = `${TANK_MODELS_PREFIX}${vehicleBlk.name.toLowerCase()}.blk`;
if (!acesPaths.has(unitPath)) continue;
const profile = extractTankProfile(source, acesPaths, weaponCache, globalMods, vehicleBlk, unitPath);
if (profile !== undefined) out[vehicleBlk.name] = profile;
}
return out;
},
};
function readGlobalModInfo(root: BlkBlock): ReadonlyMap<string, GlobalModInfo> {
const mods = findBlock(root, 'modifications');
const map = new Map<string, GlobalModInfo>();
for (const entry of mods?.blocks ?? []) {
const effects = findBlock(entry, 'effects');
const bulletMod = stringField(effects, 'additiveBulletMod') ?? stringField(effects, 'bulletMod');
map.set(entry.name, {
...(bulletMod !== undefined ? { bulletMod } : {}),
requires: stringList(entry, 'reqModification'),
});
}
return map;
}
function extractTankProfile(
source: DatasetSource,
acesPaths: ReadonlySet<string>,
weaponCache: Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>,
globalMods: ReadonlyMap<string, GlobalModInfo>,
wpcostVehicle: BlkBlock,
unitPath: string,
): TankAmmoProfile | undefined {
const unitBlk = source.readBlk('aces.vromfs.bin', unitPath);
const mainWeapon = findMainGunBlock(unitBlk);
if (!mainWeapon) return undefined;
const rawBlkPath = stringField(mainWeapon, 'blk');
const maxBullets = Math.trunc(numberField(mainWeapon, 'bullets') ?? 0);
if (!rawBlkPath || maxBullets <= 0) return undefined;
const lowerBlkPath = rawBlkPath.toLowerCase();
if (!acesPaths.has(lowerBlkPath)) return undefined;
const weaponName = basenameWithoutExt(rawBlkPath);
const weaponMeta = loadWeaponMeta(source, weaponCache, lowerBlkPath);
const readyRack = countReadyRackShells(unitBlk, stringField(mainWeapon, 'trigger') ?? 'gunner0');
const shells = collectSelectableShells(wpcostVehicle, unitBlk, globalMods, weaponMeta);
if (shells.length === 0) return undefined;
return { weaponName, maxBullets, isBelt: weaponMeta.isBelt, readyRack, shells };
}
function findMainGunBlock(unitBlk: BlkBlock): BlkBlock | undefined {
const common = findBlock(unitBlk, 'commonWeapons');
if (!common) return undefined;
return common.blocks.find((block) =>
stringField(block, 'trigger') === 'gunner0'
&& !(stringField(block, 'blk') ?? '').toLowerCase().includes('dummy_weapon'));
}
function countReadyRackShells(unitBlk: BlkBlock, mainTrigger: string): number {
const stowages = findBlock(unitBlk, 'ammoStowages');
if (!stowages) return 0;
let total = 0;
for (const stow of stowages.blocks) {
const triggers = stringList(stow, 'weaponTrigger');
if (triggers.length > 0 && !triggers.includes(mainTrigger)) continue;
for (const cluster of stow.blocks) {
if (cluster.name !== 'shells') continue;
const isReady = boolField(cluster, 'firstStage') === true
|| boolField(cluster, 'autoLoad') === true
|| boolField(cluster, 'ammoLoadedInGun') === true;
if (!isReady) continue;
for (const slot of cluster.blocks) total += Math.max(0, Math.trunc(numberField(slot, 'count') ?? 0));
}
}
return total;
}
function loadWeaponMeta(
source: DatasetSource,
cache: Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>,
lowerPath: string,
) {
const cached = cache.get(lowerPath);
if (cached) return cached;
const blk = source.readBlk('aces.vromfs.bin', lowerPath);
const isBelt = boolField(blk, 'isBulletBelt') === true;
const defaultBlock = findBlock(blk, 'bullet');
const defaultBullet = defaultBlock ? parseBulletMeta(defaultBlock) : undefined;
const sets = new Map<string, WeaponBulletMeta>();
for (const child of blk.blocks) {
if (child.name === 'bullet') continue;
const subBullet = findBlock(child, 'bullet');
if (!subBullet) continue;
const meta = parseBulletMeta(subBullet);
if (meta) sets.set(child.name, meta);
}
const entry = { isBelt, ...(defaultBullet ? { defaultBullet } : {}), sets };
cache.set(lowerPath, entry);
return entry;
}
function parseBulletMeta(bullet: BlkBlock): WeaponBulletMeta | undefined {
const bulletType = (stringField(bullet, 'bulletType') ?? '').toLowerCase();
if (!bulletType) return undefined;
const speedMps = numberField(bullet, 'speed') ?? 0;
const pen500Mm = estimatePen500Mm(bullet, bulletType, speedMps);
return { bulletType, speedMps, pen500Mm };
}
function estimatePen500Mm(bullet: BlkBlock, bulletType: string, speedMps: number): number {
const cum = numberField(findBlock(bullet, 'cumulativeDamage'), 'armorPower');
const apBlock = findBlock(bullet, 'armorpower');
const ap500 = numberField(apBlock, 'ArmorPower500m') ?? numberField(apBlock, 'ArmorPower0m') ?? 0;
if (bulletType.includes('apds_fs')) {
const dmgBlock = findBlock(bullet, 'damage');
const kinetic = dmgBlock ? findBlock(dmgBlock, 'kinetic') : undefined;
const workLen = numberField(kinetic, 'lanzOdermattWorkingLength')
?? numberField(kinetic, 'WorkingLength')
?? numberField(kinetic, 'Length')
?? 0;
const density = numberField(kinetic, 'lanzOdermattDensity') ?? numberField(kinetic, 'Density') ?? 17000;
if (workLen > 0) return Math.max(ap500, Math.round(workLen * Math.sqrt(density / 7850) * (speedMps / 1700) * 0.85));
return Math.max(ap500, Math.round(speedMps * 0.24));
}
if (cum !== undefined && cum > ap500) return cum;
if (ap500 > 0) return ap500;
const mass = numberField(bullet, 'mass') ?? 0;
const cal = numberField(bullet, 'damageCaliber') ?? numberField(bullet, 'caliber') ?? 0;
if (mass > 0 && cal > 0 && speedMps > 100 && !bulletType.includes('he_') && !bulletType.includes('smoke')) {
return Math.round(0.0022 * Math.pow(mass, 0.55) * Math.pow(speedMps, 1.43) / Math.pow(cal * 1000, 0.65));
}
return 0;
}
function collectSelectableShells(
wpcostVehicle: BlkBlock,
unitBlk: BlkBlock,
globalMods: ReadonlyMap<string, GlobalModInfo>,
weaponMeta: { defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> },
): TankShellChoice[] {
const out: TankShellChoice[] = [];
if (weaponMeta.defaultBullet) {
out.push({ modName: '', ...weaponMeta.defaultBullet, requires: [] });
}
const wpModsBlock = findBlock(wpcostVehicle, 'modifications');
const unitModsBlock = findBlock(unitBlk, 'modifications');
const reqMap = new Map<string, readonly string[]>();
for (const mod of wpModsBlock?.blocks ?? []) reqMap.set(mod.name, stringList(mod, 'reqModification'));
for (const mod of wpModsBlock?.blocks ?? []) {
if (numberField(mod, 'ammoCount') === undefined) continue;
const unitMod = unitModsBlock ? findBlock(unitModsBlock, mod.name) : undefined;
const unitModEffects = unitMod ? findBlock(unitMod, 'effects') : undefined;
const setName = stringField(unitModEffects, 'additiveBulletMod')
?? stringField(unitModEffects, 'bulletMod')
?? globalMods.get(mod.name)?.bulletMod
?? mod.name;
const meta = weaponMeta.sets.get(setName);
if (!meta) continue;
out.push({
modName: mod.name,
...meta,
requires: collectTransitiveReqs(mod.name, reqMap, globalMods),
});
}
return out;
}
function collectTransitiveReqs(
modName: string,
reqMap: ReadonlyMap<string, readonly string[]>,
globalMods: ReadonlyMap<string, GlobalModInfo>,
): string[] {
const seen = new Set<string>();
const queue = [...(reqMap.get(modName) ?? []), ...(globalMods.get(modName)?.requires ?? [])];
while (queue.length > 0) {
const next = queue.pop()!;
if (!next || next === modName || seen.has(next)) continue;
seen.add(next);
for (const parent of reqMap.get(next) ?? []) queue.push(parent);
}
return [...seen].sort();
}
function basenameWithoutExt(path: string): string {
const slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
const file = slash >= 0 ? path.slice(slash + 1) : path;
return file.endsWith('.blk') ? file.slice(0, -4) : file;
}
@@ -27,11 +27,14 @@ import type { Dataset } from './dataset.ts';
import { shopEntriesByName } from './shop-tree.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
const UNIT_TAGS = 'config/unittags.blk';
export interface CatalogueVehicle {
readonly name: string;
readonly country: string;
readonly unitClass: string;
/** True when config/unittags.blk tags the vehicle with type_light_tank. */
readonly isLightTank?: boolean;
readonly rank: number;
/** wpcost.blk reqAir; absent when empty or missing. */
readonly requires?: string;
@@ -70,15 +73,27 @@ export interface CatalogueVehicle {
export const vehicleCatalogue: Dataset<readonly CatalogueVehicle[]> = {
id: 'vehicle-catalogue',
version: 6,
version: 7,
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));
const lightTanks = lightTankNames(source.readBlk('char.vromfs.bin', UNIT_TAGS));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) =>
catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1, lightTanks.has(vehicle.name)),
);
},
};
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number): CatalogueVehicle {
function lightTankNames(unitTagsRoot: BlkBlock): ReadonlySet<string> {
const names = new Set<string>();
for (const unit of unitTagsRoot.blocks) {
const tags = unit.blocks.find((block) => block.name === 'tags');
if (tags && boolField(tags, 'type_light_tank') === true) names.add(unit.name);
}
return names;
}
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number, isLightTank: boolean): CatalogueVehicle {
const requires = stringField(vehicle, 'reqAir');
const researchType = stringField(vehicle, 'researchType');
const requiredUnlock = stringField(shopEntry, 'reqUnlock');
@@ -90,6 +105,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr
name: vehicle.name,
country: stringField(vehicle, 'country') ?? '',
unitClass: stringField(vehicle, 'unitClass') ?? '',
...(isLightTank ? { isLightTank: true } : {}),
rank: numberField(vehicle, 'rank') ?? 0,
...(requires ? { requires } : {}),
researchPoints: numberField(vehicle, 'reqExp') ?? 0,
+1
View File
@@ -11,5 +11,6 @@ export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
export { loadGroundAiTuning, type GroundAiTuning } from './tuning/ground-ai-tuning.ts';
export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts';
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
+7
View File
@@ -10,6 +10,7 @@ import { BattleEconomy } from './battle/battle-economy.ts';
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
import { BattleSessionStore } from './battle/battle-session-store.ts';
import { selectBotAircraftLoadouts } from './battle/bot-aircraft-loadouts.ts';
import { selectBotTankLoadouts } from './battle/bot-tank-loadouts.ts';
import { actionTable } from './char/actions/action-table.ts';
import { CharService } from './char/char-service.ts';
import { ClanStore } from './clans/clan-store.ts';
@@ -31,6 +32,7 @@ import { DatasetCache } from './game-data/datasets/dataset-cache.ts';
import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts';
import { externalItemSources } from './game-data/datasets/external-item-sources.ts';
import { flightModelPresets } from './game-data/datasets/flight-model-presets.ts';
import { tankBotAmmo } from './game-data/datasets/tank-bot-ammo.ts';
import { itemCatalogue } from './game-data/datasets/item-catalogue.ts';
import { multiplayerMissions, type MultiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
import { shopCountries } from './game-data/datasets/shop-countries.ts';
@@ -173,6 +175,9 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
}, report);
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork);
const botAircraftLoadouts = selectBotAircraftLoadouts(vehicles, datasets.load(flightModelPresets), equipment);
const botTankLoadouts = tuning.groundAi.mode === 'stock'
? undefined
: selectBotTankLoadouts(vehicles, datasets.load(tankBotAmmo), tuning.groundAi.loadout);
gameFiles.releasePacks();
let matching: MatchingService | undefined;
@@ -188,6 +193,8 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
tuning.battle,
spawnRules,
botAircraftLoadouts,
tuning.groundAi.mode === 'stock' ? undefined : tuning.groundAi.lineupWeights,
botTankLoadouts,
(ctx) => modRuntime.runBattleFilterMissions(ctx),
);
const economy = new BattleEconomy(
+302
View File
@@ -0,0 +1,302 @@
/**
* Typed, range-validated reader for `tuning/ground-ai.jsonc`.
*/
import type { DiscoveredMod } from '@wto/mods';
import { GROUND_AI_MODES, type GroundAiConfig, type GroundAiMode } from '@wto/patcher';
import type { TankLineupWeights } from '../battle/battle-ranks.ts';
import { tuningFiles } from './tuning-loader.ts';
import { TuningError, type TuningReader } from './tuning-reader.ts';
export interface GroundAiTuning extends GroundAiConfig {
/** Tank pool weights by class, used only when a custom ground AI mode is active. */
readonly lineupWeights: TankLineupWeights;
}
const DRIVE_MODES = new Set(['vehicle_phys', 'movesys']);
export function loadGroundAiTuning(
dataFolder: string | null,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): GroundAiTuning {
return readGroundAiTuning(tuningFiles(dataFolder, report, undefined, mods).read('ground-ai'));
}
export function readGroundAiTuning(reader: TuningReader): GroundAiTuning {
const cadence = reader.object('cadence');
const diag = reader.object('diagnostics');
return {
mode: readMode(reader),
loadout: readLoadoutSection(reader.object('loadout')),
lineupWeights: readLineupWeights(reader.object('lineupWeights')),
cadence: {
maxBots: cadence.int('maxBots', { min: 1, max: 64 }),
macroTickSec: cadence.number('macroTickSec', { min: 0.1, max: 5 }),
tacticsTickSec: cadence.number('tacticsTickSec', { min: 0.05, max: 2 }),
navTickSec: cadence.number('navTickSec', { min: 0.05, max: 2 }),
},
commander: readCommanderSection(reader.object('commander')),
macro: readMacroSection(reader.object('macro')),
crowd: readCrowdSection(reader.object('crowd')),
terrain: readTerrainSection(reader.object('terrain')),
navigation: readNavigationSection(reader.object('navigation')),
perception: readPerceptionSection(reader.object('perception')),
stateMachine: readStateMachineSection(reader.object('stateMachine')),
tactics: readTacticsSection(reader.object('tactics')),
estimation: readEstimationSection(reader.object('estimation')),
fireControl: readFireControlSection(reader.object('fireControl')),
diagnostics: {
telemetry: diag.bool('telemetry'),
telemetryIntervalSec: diag.number('telemetryIntervalSec', { min: 0.5, max: 60 }),
},
};
}
function readMode(reader: TuningReader): GroundAiMode {
const mode = reader.string('mode');
const known = GROUND_AI_MODES.find((candidate) => candidate === mode);
if (known === undefined) {
throw new TuningError(`tuning file ground-ai.jsonc: mode must be one of ${GROUND_AI_MODES.map((m) => `"${m}"`).join(', ')} (found "${mode}")`);
}
return known;
}
function readLoadoutSection(loadout: TuningReader): GroundAiTuning['loadout'] {
return {
lowReadyRackThreshold: loadout.int('lowReadyRackThreshold', { min: 1, max: 60 }),
topUpAmmoCount: loadout.int('topUpAmmoCount', { min: 4, max: 80 }),
primaryAmmoPct: loadout.int('primaryAmmoPct', { min: 50, max: 100 }),
secondaryMinRounds: loadout.int('secondaryMinRounds', { min: 0, max: 20 }),
penetrationCompareDistM: loadout.int('penetrationCompareDistM', { min: 100, max: 2000 }),
};
}
function readLineupWeights(weights: TuningReader): TankLineupWeights {
const range = { min: 0.01, max: 10 };
return {
spaa: weights.number('spaa', range),
lightTank: weights.number('lightTank', range),
tankDestroyer: weights.number('tankDestroyer', range),
heavyTank: weights.number('heavyTank', range),
mediumTank: weights.number('mediumTank', range),
other: weights.number('other', range),
};
}
function readCommanderSection(cmd: TuningReader): GroundAiTuning['commander'] {
const pct = { min: 0, max: 100 };
const bttlAssaultPct = cmd.int('bttlAssaultPct', pct);
const bttlFlankPct = cmd.int('bttlFlankPct', pct);
const bttlOverwatchPct = cmd.int('bttlOverwatchPct', pct);
if (bttlAssaultPct + bttlFlankPct + bttlOverwatchPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Bttl percentages must sum to <= 100');
}
const conqAssaultPct = cmd.int('conqAssaultPct', pct);
const conqFlankPct = cmd.int('conqFlankPct', pct);
if (conqAssaultPct + conqFlankPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Conq assault + flank percentages must sum to <= 100');
}
const conqHoldDefendPct = cmd.int('conqHoldDefendPct', pct);
const conqHoldOverwatchPct = cmd.int('conqHoldOverwatchPct', pct);
if (conqHoldDefendPct + conqHoldOverwatchPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Conq hold percentages must sum to <= 100');
}
return {
rebalanceSec: cmd.number('rebalanceSec', { min: 1.0, max: 30.0 }),
roleHoldSec: cmd.number('roleHoldSec', { min: 0.0, max: 120.0 }),
bttlAssaultPct,
bttlFlankPct,
bttlOverwatchPct,
conqAssaultPct,
conqFlankPct,
conqHoldDefendPct,
conqHoldOverwatchPct,
domAssaultPct: cmd.int('domAssaultPct', pct),
domMaxDefendersPerCap: cmd.int('domMaxDefendersPerCap', { min: 0, max: 4 }),
overwatchStandOffM: cmd.number('overwatchStandOffM', { min: 25.0, max: 350.0 }),
flankStandOffM: cmd.number('flankStandOffM', { min: 25.0, max: 300.0 }),
spaaFollowOffsetM: cmd.number('spaaFollowOffsetM', { min: 40.0, max: 500.0 }),
flankMaxLengthRatio: cmd.number('flankMaxLengthRatio', { min: 1.05, max: 3.0 }),
flankMinSeparationM: cmd.number('flankMinSeparationM', { min: 15.0, max: 200.0 }),
rallyProgressFrac: cmd.number('rallyProgressFrac', { min: 0.1, max: 0.75 }),
rallyWaitSec: cmd.number('rallyWaitSec', { min: 3.0, max: 60.0 }),
rallyMinFrac: cmd.number('rallyMinFrac', { min: 0.25, max: 1.0 }),
rallyRadiusM: cmd.number('rallyRadiusM', { min: 15.0, max: 140.0 }),
recallSafeHoldSec: cmd.number('recallSafeHoldSec', { min: 3.0, max: 60.0 }),
};
}
function readMacroSection(macro: TuningReader): GroundAiTuning['macro'] {
const recaptureMinBots = macro.int('recaptureMinBots', { min: 1, max: 8 });
const recaptureMaxBots = macro.int('recaptureMaxBots', { min: 1, max: 12 });
if (recaptureMaxBots < recaptureMinBots) {
throw new TuningError('tuning file ground-ai.jsonc: macro.recaptureMaxBots must be >= macro.recaptureMinBots');
}
return {
openingSplitSec: macro.number('openingSplitSec', { min: 0, max: 180 }),
capMaxInsiders: macro.int('capMaxInsiders', { min: 1, max: 8 }),
recaptureMinBots,
recaptureMaxBots,
capStickyBonusM: macro.number('capStickyBonusM', { min: 0, max: 800 }),
deathZoneRadiusM: macro.number('deathZoneRadiusM', { min: 10, max: 250 }),
deathZoneTtlSec: macro.number('deathZoneTtlSec', { min: 5, max: 300 }),
deathZoneMinKills: macro.int('deathZoneMinKills', { min: 1, max: 16 }),
spaaRearOffsetM: macro.number('spaaRearOffsetM', { min: 40, max: 600 }),
spaaRelocateSec: macro.number('spaaRelocateSec', { min: 5, max: 180 }),
enemySpawnAvoidM: macro.number('enemySpawnAvoidM', { min: 60, max: 600 }),
};
}
function readCrowdSection(crowd: TuningReader): GroundAiTuning['crowd'] {
return {
personalSpaceM: crowd.number('personalSpaceM', { min: 6, max: 40 }),
clusterRadiusM: crowd.number('clusterRadiusM', { min: 12, max: 80 }),
clusterMaxAllies: crowd.int('clusterMaxAllies', { min: 1, max: 10 }),
disperseStepM: crowd.number('disperseStepM', { min: 8, max: 65 }),
disperseHoldSec: crowd.number('disperseHoldSec', { min: 1, max: 15 }),
};
}
function readTerrainSection(terrain: TuningReader): GroundAiTuning['terrain'] {
return {
maxClimbSlopeDeg: terrain.number('maxClimbSlopeDeg', { min: 10, max: 42 }),
maxDropSlopeDeg: terrain.number('maxDropSlopeDeg', { min: 8, max: 40 }),
maxWaterDepthM: terrain.number('maxWaterDepthM', { min: 0.2, max: 2.5 }),
collisionMarginM: terrain.number('collisionMarginM', { min: 0.05, max: 2.0 }),
crestLookaheadM: terrain.number('crestLookaheadM', { min: 8, max: 80 }),
ridgeMaxDwellSec: terrain.number('ridgeMaxDwellSec', { min: 2, max: 60 }),
ridgeMaxShots: terrain.int('ridgeMaxShots', { min: 1, max: 10 }),
};
}
function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] {
const driveMode = nav.string('driveMode');
if (!DRIVE_MODES.has(driveMode)) {
throw new TuningError(`tuning file ground-ai.jsonc: navigation.driveMode must be "vehicle_phys" or "movesys" (found "${driveMode}")`);
}
const steerSign = nav.number('steerSign', { min: -1, max: 1 });
if (steerSign !== 1 && steerSign !== -1) {
throw new TuningError('tuning file ground-ai.jsonc: navigation.steerSign must be 1 or -1');
}
return {
driveMode,
maxPhysBots: nav.int('maxPhysBots', { min: 0, max: 64 }),
steerSign,
deadEchoSec: nav.number('deadEchoSec', { min: 0.3, max: 10 }),
controlTimeoutSec: nav.number('controlTimeoutSec', { min: 0.3, max: 10 }),
cornerBrakeAccel: nav.number('cornerBrakeAccel', { min: 0.5, max: 8 }),
pivotAngleDeg: nav.number('pivotAngleDeg', { min: 25, max: 150 }),
stuckWindowSec: nav.number('stuckWindowSec', { min: 1, max: 15 }),
stuckMinMoveM: nav.number('stuckMinMoveM', { min: 0.5, max: 10 }),
unstickReverseSec: nav.number('unstickReverseSec', { min: 0.8, max: 10 }),
tacticalReverseDistM: nav.number('tacticalReverseDistM', { min: 10, max: 90 }),
tacticalReverseMaxSec: nav.number('tacticalReverseMaxSec', { min: 2, max: 25 }),
};
}
function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception'] {
return {
foliageTransparency: perc.number('foliageTransparency', { min: 0.001, max: 1.0 }),
nearSpotRangeM: perc.number('nearSpotRangeM', { min: 20, max: 250 }),
firingSpotRangeM: perc.number('firingSpotRangeM', { min: 150, max: 1500 }),
fastSpotSec: perc.number('fastSpotSec', { min: 0.05, max: 1.5 }),
normalSpotSec: perc.number('normalSpotSec', { min: 0.1, max: 3.0 }),
farSpotSec: perc.number('farSpotSec', { min: 0.3, max: 6.0 }),
decayPerSec: perc.number('decayPerSec', { min: 0.2, max: 10.0 }),
frontConeHalfDeg: perc.number('frontConeHalfDeg', { min: 10, max: 90 }),
peripheralCloseM: perc.number('peripheralCloseM', { min: 30, max: 250 }),
};
}
function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine'] {
const coverMinDistM = sm.number('coverMinDistM', { min: 2.0, max: 30.0 });
const coverMaxDistM = sm.number('coverMaxDistM', { min: 6.0, max: 80.0 });
if (coverMaxDistM <= coverMinDistM) {
throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM');
}
return {
preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }),
shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }),
shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }),
turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }),
coverMinDistM,
coverMaxDistM,
coverRetreatBudgetSec: sm.number('coverRetreatBudgetSec', { min: 1.5, max: 20.0 }),
reloadAdvanceAngleDeg: sm.number('reloadAdvanceAngleDeg', { min: 0.0, max: 45.0 }),
hullAngleTriggerDeg: sm.number('hullAngleTriggerDeg', { min: 15.0, max: 75.0 }),
hullAngleTargetDeg: sm.number('hullAngleTargetDeg', { min: 0.0, max: 35.0 }),
maxTotalHaltSec: sm.number('maxTotalHaltSec', { min: 3.0, max: 40.0 }),
stalemateMissShots: sm.int('stalemateMissShots', { min: 1, max: 8 }),
stalemateNoShotHalts: sm.int('stalemateNoShotHalts', { min: 1, max: 6 }),
repositionMinMoveM: sm.number('repositionMinMoveM', { min: 5.0, max: 80.0 }),
repositionStepM: sm.number('repositionStepM', { min: 15.0, max: 120.0 }),
repairSafeEnemyDistM: sm.number('repairSafeEnemyDistM', { min: 30.0, max: 400.0 }),
};
}
function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] {
return {
visionRangeM: tactics.number('visionRangeM', { min: 200, max: 3500 }),
visionFovDeg: tactics.number('visionFovDeg', { min: 40, max: 180 }),
peripheralRangeM: tactics.number('peripheralRangeM', { min: 30, max: 800 }),
engineAudioRangeM: tactics.number('engineAudioRangeM', { min: 10, max: 250 }),
shotAudioRangeM: tactics.number('shotAudioRangeM', { min: 50, max: 1200 }),
radioShareRangeM: tactics.number('radioShareRangeM', { min: 50, max: 1500 }),
memoryTtlSec: tactics.number('memoryTtlSec', { min: 1, max: 45 }),
targetStickinessSec: tactics.number('targetStickinessSec', { min: 0.5, max: 20 }),
peekCooldownSec: tactics.number('peekCooldownSec', { min: 1, max: 30 }),
};
}
function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] {
const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 });
const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 });
if (watchMaxSec < watchMinSec) {
throw new TuningError('tuning file ground-ai.jsonc: estimation.watchMaxSec must be >= watchMinSec');
}
const velSampleMinSpanSec = est.number('velSampleMinSpanSec', { min: 0.05, max: 2.0 });
const velStableSpanSec = est.number('velStableSpanSec', { min: 0.2, max: 6.0 });
if (velStableSpanSec <= velSampleMinSpanSec) {
throw new TuningError('tuning file ground-ai.jsonc: estimation.velStableSpanSec must be > velSampleMinSpanSec');
}
return {
watchMinSec,
watchMaxSec,
velSampleMinSpanSec,
velStableSpanSec,
velJumpResetMps: est.number('velJumpResetMps', { min: 1.0, max: 20.0 }),
baseAimSigmaM: est.number('baseAimSigmaM', { min: 0.0, max: 2.0 }),
leadErrorFrac: est.number('leadErrorFrac', { min: 0.0, max: 1.0 }),
maxBiasM: est.number('maxBiasM', { min: 0.0, max: 6.0 }),
};
}
function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] {
const closeRangeM = fc.number('closeRangeM', { min: 30, max: 250 });
const midRangeM = fc.number('midRangeM', { min: 100, max: 600 });
const longRangeM = fc.number('longRangeM', { min: 300, max: 1500 });
if (midRangeM <= closeRangeM || longRangeM <= midRangeM) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl ranges must satisfy closeRangeM < midRangeM < longRangeM');
}
return {
maxEngageRangeM: fc.number('maxEngageRangeM', { min: 150, max: 3000 }),
closeRangeM,
midRangeM,
longRangeM,
midSlowSpeedRatio: fc.number('midSlowSpeedRatio', { min: 0.1, max: 1.0 }),
midSlowMaxMps: fc.number('midSlowMaxMps', { min: 1.0, max: 15.0 }),
stopSpeedMaxMps: fc.number('stopSpeedMaxMps', { min: 0.1, max: 2.0 }),
longRangeWindowSec: fc.number('longRangeWindowSec', { min: 1.0, max: 15.0 }),
baseAlignDeg: fc.number('baseAlignDeg', { min: 0.1, max: 3.0 }),
closeHitRadiusM: fc.number('closeHitRadiusM', { min: 0.25, max: 2.2 }),
barrelSettleDegSec: fc.number('barrelSettleDegSec', { min: 0.2, max: 12.0 }),
closeSettleHoldSec: fc.number('closeSettleHoldSec', { min: 0.02, max: 0.5 }),
settleHoldSec: fc.number('settleHoldSec', { min: 0.05, max: 1.5 }),
unstabilizedStopSpeedMps: fc.number('unstabilizedStopSpeedMps', { min: 0.1, max: 3.0 }),
stabilizedCreepSpeedMps: fc.number('stabilizedCreepSpeedMps', { min: 1.5, max: 15.0 }),
friendlyCorridorM: fc.number('friendlyCorridorM', { min: 1.0, max: 10.0 }),
ballisticStepMaxM: fc.number('ballisticStepMaxM', { min: 5.0, max: 80.0 }),
ballisticSweepRadiusM: fc.number('ballisticSweepRadiusM', { min: 0.02, max: 0.5 }),
maxPreFireChecksPerTick: fc.int('maxPreFireChecksPerTick', { min: 1, max: 16 }),
};
}
+3
View File
@@ -14,6 +14,7 @@ import { readResearchTuning, type ResearchTuning } from '../research/research-tu
import { readRedeemTuning, type RedeemTuning } from '../store/redeem-tuning.ts';
import { readStoreTuning, type StoreTuning } from '../store/store-tuning.ts';
import type { DiscoveredMod } from '@wto/mods';
import { readGroundAiTuning, type GroundAiTuning } from './ground-ai-tuning.ts';
import { readLimitsTuning, type LimitsTuning } from './limits-tuning.ts';
import { tuningFiles } from './tuning-loader.ts';
@@ -29,6 +30,7 @@ export interface Tuning {
readonly clans: ClanTuning;
readonly battle: BattleTuning;
readonly battleEconomy: BattleEconomyTuning;
readonly groundAi: GroundAiTuning;
readonly limits: LimitsTuning;
}
@@ -50,6 +52,7 @@ export function loadTuning(
clans: readClanTuning(files.read('clans')),
battle: readBattleTuning(files.read('battle')),
battleEconomy: readBattleEconomyTuning(files.read('battle-economy')),
groundAi: readGroundAiTuning(files.read('ground-ai')),
limits: readLimitsTuning(files.read('limits')),
};
}
+196
View File
@@ -0,0 +1,196 @@
// Ground battle AI configuration.
// Per-client overrides live in <dataDir>/tuning/ground-ai.jsonc. The game copy build compiles the
// layer settings into game/wtoai/wto_ai_config_common.das; the local server reads lineupWeights.
{
// "full": every custom layer (default).
// "fire": stock movement and destinations, custom perception and fire permission.
// "drive": custom team orders and driving, stock aiming and firing (debugging).
// "stock": stock AI only, no scripts packed, stock lineup weights (troubleshooting).
"mode": "full",
// AI tank spawn ammunition selection (offline values; ignored in "stock" mode).
// Carries first-stage / autoloader ready-rack capacity, topped up when below threshold,
// split between best anti-armor primary (APFSDS preferred) and HE/HEAT secondary when available.
"loadout": {
"lowReadyRackThreshold": 15,
"topUpAmmoCount": 22,
"primaryAmmoPct": 80,
"secondaryMinRounds": 3,
"penetrationCompareDistM": 500
},
// Relative pick weights of AI tank classes in a battle's bot pool. Offline values; ignored in
// "stock" mode, where every vehicle keeps the stock weight of 1.
"lineupWeights": {
"spaa": 0.12,
"lightTank": 0.45,
"tankDestroyer": 0.55,
"heavyTank": 0.85,
"mediumTank": 1.15,
"other": 1.0
},
"cadence": {
"maxBots": 64,
"macroTickSec": 0.5,
"tacticsTickSec": 0.25,
"navTickSec": 0.2
},
// Team commander role quotas and timing (offline values).
"commander": {
"rebalanceSec": 5.0,
"roleHoldSec": 20.0,
"bttlAssaultPct": 45,
"bttlFlankPct": 15,
"bttlOverwatchPct": 20,
"conqAssaultPct": 50,
"conqFlankPct": 20,
"conqHoldDefendPct": 30,
"conqHoldOverwatchPct": 30,
"domAssaultPct": 70,
"domMaxDefendersPerCap": 1,
"overwatchStandOffM": 95.0,
"flankStandOffM": 75.0,
"spaaFollowOffsetM": 160.0,
"flankMaxLengthRatio": 1.6,
"flankMinSeparationM": 45.0,
"rallyProgressFrac": 0.40,
"rallyWaitSec": 25.0,
"rallyMinFrac": 0.66,
"rallyRadiusM": 55.0,
"recallSafeHoldSec": 15.0
},
"macro": {
"openingSplitSec": 40.0,
"capMaxInsiders": 2,
"recaptureMinBots": 2,
"recaptureMaxBots": 4,
"capStickyBonusM": 165.0,
"deathZoneRadiusM": 55.0,
"deathZoneTtlSec": 60.0,
"deathZoneMinKills": 3,
"spaaRearOffsetM": 185.0,
"spaaRelocateSec": 28.0,
"enemySpawnAvoidM": 180.0
},
"crowd": {
"personalSpaceM": 14.0,
"clusterRadiusM": 28.0,
"clusterMaxAllies": 2,
"disperseStepM": 24.0,
"disperseHoldSec": 4.2
},
"terrain": {
"maxClimbSlopeDeg": 25.0,
"maxDropSlopeDeg": 20.0,
"maxWaterDepthM": 0.6,
"collisionMarginM": 0.3,
"crestLookaheadM": 28.0,
"ridgeMaxDwellSec": 10.0,
"ridgeMaxShots": 2
},
"navigation": {
// "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement.
"driveMode": "vehicle_phys",
"maxPhysBots": 64,
"steerSign": 1.0,
"deadEchoSec": 1.2,
"controlTimeoutSec": 1.0,
"cornerBrakeAccel": 1.75,
"pivotAngleDeg": 75.0,
"stuckWindowSec": 3.6,
"stuckMinMoveM": 2.0,
"unstickReverseSec": 3.0,
"tacticalReverseDistM": 34.0,
"tacticalReverseMaxSec": 9.5
},
// Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI).
"perception": {
"foliageTransparency": 0.01,
"nearSpotRangeM": 90.0,
"firingSpotRangeM": 650.0,
"fastSpotSec": 0.25,
"normalSpotSec": 0.60,
"farSpotSec": 1.45,
"decayPerSec": 1.5,
"frontConeHalfDeg": 30.0,
"peripheralCloseM": 100.0
},
// Per-bot hull state machine timings and thresholds (offline values).
"stateMachine": {
"preaimAngleDeg": 8.0,
"shortHaltMaxSec": 3.0,
"shortHaltCooldownSec": 4.0,
"turnLaunchSpeedMps": 2.1,
"coverMinDistM": 6.0,
"coverMaxDistM": 24.0,
"coverRetreatBudgetSec": 6.0,
"reloadAdvanceAngleDeg": 18.0,
"hullAngleTriggerDeg": 30.0,
"hullAngleTargetDeg": 15.0,
"maxTotalHaltSec": 12.0,
"stalemateMissShots": 2,
"stalemateNoShotHalts": 2,
"repositionMinMoveM": 20.0,
"repositionStepM": 48.0,
"repairSafeEnemyDistM": 140.0
},
"tactics": {
"visionRangeM": 1250.0,
"visionFovDeg": 115.0,
"peripheralRangeM": 230.0,
"engineAudioRangeM": 65.0,
"shotAudioRangeM": 380.0,
"radioShareRangeM": 450.0,
"memoryTtlSec": 12.0,
"targetStickinessSec": 4.5,
"peekCooldownSec": 6.0
},
// Target velocity estimation from own visual samples, last-seen watch, and bounded shot bias.
"estimation": {
"watchMinSec": 2.0,
"watchMaxSec": 5.0,
"velSampleMinSpanSec": 0.25,
"velStableSpanSec": 1.2,
"velJumpResetMps": 4.5,
"baseAimSigmaM": 0.28,
"leadErrorFrac": 0.26,
"maxBiasM": 2.2
},
"fireControl": {
"maxEngageRangeM": 1250.0,
"closeRangeM": 100.0,
"midRangeM": 300.0,
"longRangeM": 800.0,
"midSlowSpeedRatio": 0.45,
"midSlowMaxMps": 5.5,
"stopSpeedMaxMps": 0.45,
"longRangeWindowSec": 4.0,
"baseAlignDeg": 0.42,
"closeHitRadiusM": 0.85,
"barrelSettleDegSec": 1.8,
"closeSettleHoldSec": 0.08,
"settleHoldSec": 0.20,
"unstabilizedStopSpeedMps": 0.45,
"stabilizedCreepSpeedMps": 5.5,
"friendlyCorridorM": 3.2,
"ballisticStepMaxM": 25.0,
"ballisticSweepRadiusM": 0.12,
"maxPreFireChecksPerTick": 2
},
"diagnostics": {
"telemetry": false,
"telemetryIntervalSec": 5.0
}
}