chore(battle): snapshot the LocalMP rework baseline

Records the uncommitted battle-session work exactly as it was left
(local service matchmaking, settlement, chat, native LocalMP hooks,
battle gui/exe patches) so the following review and rework commits
show every correction as a diff against this state.

This commit is not reviewed and is known to be incomplete: in-game
testing reported wrong settlement rewards, single-country teams,
missing random/fixed supplement slots, misattributed hit messages and
other regressions. Do not merge this branch before the rework lands.
This commit is contained in:
N0VAN0M4LY committed 2026-11-28 03:15:47 +08:00
1 parent 5c9204c031
commit b260d2899e
97 files changed
+7676 -396

No files matched your search

@@ -0,0 +1,227 @@
/**
* Authentic nation coalition pairing for Arcade, Realistic, and Simulator battles.
*
* Filters eligible countries by tech-tree vehicle availability in the match's BR window,
* assigns the player uniformly to Team 1 (`allies`) or Team 2 (`axis`), and builds
* per-team bare country lists (`"usa"`, `"germany"`, ...) with `playerCountry` at index 0
* of the player's team array.
*/
import { randomInt } from 'node:crypto';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
import { stripCountryPrefix, unitClassOfExpClass, vehicleMrank } from './battle-ranks.ts';
import type { BattleTuning } from './battle-tuning.ts';
const SIM_WW2_ALLIES: readonly string[] = ['usa', 'ussr', 'britain', 'china', 'france', 'israel'];
const SIM_WW2_AXIS: readonly string[] = ['germany', 'japan', 'italy', 'sweden'];
const SIM_CW_WEST: readonly string[] = ['usa', 'germany', 'britain', 'japan', 'italy', 'france', 'sweden', 'israel'];
const SIM_CW_EAST: readonly string[] = ['ussr', 'china'];
export interface CoalitionPairingInput {
readonly vehicles: readonly CatalogueVehicle[];
readonly knownCountries: readonly string[];
readonly playerCountry: string;
readonly difficulty: ModeDifficulty;
readonly requiredClass: UnitClass;
readonly playerMrank: number;
readonly minMrank: number;
readonly maxMrank: number;
readonly tuning: BattleTuning;
}
export interface CoalitionPairing {
readonly playerTeam: 1 | 2;
readonly countryAllies: string;
readonly countryAxis: string;
readonly countriesAllies: readonly string[];
readonly countriesAxis: readonly string[];
readonly symmetricTeams: boolean;
}
export function selectBattleCoalitions(input: CoalitionPairingInput): CoalitionPairing {
const playerCountry = stripCountryPrefix(input.playerCountry);
const eligible = eligibleCountriesForBracket(input, playerCountry);
const playerTeam: 1 | 2 = randomInt(2) === 0 ? 1 : 2;
const sides = input.difficulty === 'arcade'
? buildArcadeSides(eligible, playerCountry)
: input.difficulty === 'simulator'
? buildSimulatorSides(eligible, playerCountry, input.playerMrank, input.tuning.simColdWarMinMrank)
: buildRealisticSides(eligible, playerCountry, input.requiredClass, input.tuning);
const countriesAllies = playerTeam === 1 ? sides.playerSide : sides.enemySide;
const countriesAxis = playerTeam === 2 ? sides.playerSide : sides.enemySide;
return {
playerTeam,
countryAllies: countriesAllies[0] ?? playerCountry,
countryAxis: countriesAxis[0] ?? playerCountry,
countriesAllies,
countriesAxis,
symmetricTeams: sides.symmetricTeams,
};
}
interface TeamSides {
readonly playerSide: readonly string[];
readonly enemySide: readonly string[];
readonly symmetricTeams: boolean;
}
function eligibleCountriesForBracket(input: CoalitionPairingInput, playerCountry: string): string[] {
const knownBare = [...new Set(input.knownCountries.map(stripCountryPrefix).filter((c) => c.length > 0))];
const knownSet = new Set(knownBare);
const inWindow = new Set<string>();
const inClass = new Set<string>();
for (const vehicle of input.vehicles) {
if (!isStandardTreeVehicle(vehicle, input.requiredClass)) continue;
const bare = stripCountryPrefix(vehicle.country);
if (!knownSet.has(bare)) continue;
inClass.add(bare);
const mrank = vehicleMrank(vehicle, input.difficulty, input.requiredClass);
if (mrank >= input.minMrank && mrank <= input.maxMrank) inWindow.add(bare);
}
inWindow.add(playerCountry);
if (inWindow.size >= 2) return knownBare.filter((c) => inWindow.has(c));
inClass.add(playerCountry);
if (inClass.size >= 2) return knownBare.filter((c) => inClass.has(c));
return knownBare.includes(playerCountry) ? knownBare : [playerCountry, ...knownBare];
}
function isStandardTreeVehicle(vehicle: CatalogueVehicle, requiredClass: UnitClass): boolean {
return vehicle.inTechTree
&& !vehicle.onlyShownWhenOwned
&& !vehicle.premiumPack
&& !vehicle.gift
&& !vehicle.event
&& vehicle.researchType === undefined
&& unitClassOfExpClass(vehicle.unitClass) === requiredClass;
}
function buildArcadeSides(eligible: readonly string[], playerCountry: string): TeamSides {
const playerSide = placeFirst(shuffle(eligible), playerCountry);
const enemySide = shuffle(eligible);
return { playerSide, enemySide, symmetricTeams: true };
}
function buildSimulatorSides(
eligible: readonly string[],
playerCountry: string,
playerMrank: number,
coldWarMinMrank: number,
): TeamSides {
const eligibleSet = new Set(eligible);
const blocA = (playerMrank < coldWarMinMrank ? SIM_WW2_ALLIES : SIM_CW_WEST).filter((c) => eligibleSet.has(c));
const blocB = (playerMrank < coldWarMinMrank ? SIM_WW2_AXIS : SIM_CW_EAST).filter((c) => eligibleSet.has(c));
const playerInB = blocB.includes(playerCountry);
const rawPlayerBloc = playerInB ? [...blocB] : [...blocA];
const rawEnemyBloc = playerInB ? [...blocA] : [...blocB];
if (!rawPlayerBloc.includes(playerCountry)) rawPlayerBloc.unshift(playerCountry);
const playerOthers = shuffle(rawPlayerBloc.filter((c) => c !== playerCountry));
let enemySide = shuffle(rawEnemyBloc.filter((c) => c !== playerCountry));
if (enemySide.length === 0 && playerOthers.length > 0) {
enemySide = [playerOthers.pop()!];
}
if (enemySide.length === 0) {
const fallback = eligible.find((c) => c !== playerCountry) ?? playerCountry;
enemySide = [fallback];
}
return {
playerSide: [playerCountry, ...playerOthers],
enemySide,
symmetricTeams: false,
};
}
function buildRealisticSides(
eligible: readonly string[],
playerCountry: string,
requiredClass: UnitClass,
tuning: BattleTuning,
): TeamSides {
const mixedChance = requiredClass === 'tank'
? tuning.rbGroundMixedChance
: requiredClass === 'ship'
? tuning.rbNavalMixedChance
: tuning.rbAirMixedChance;
const roll = randomInt(1_000_000) / 1_000_000;
if (roll >= mixedChance && eligible.length >= 2) {
return buildDisjointRealisticSides(eligible, playerCountry, tuning);
}
return buildMixedRealisticSides(eligible, playerCountry, tuning);
}
function buildDisjointRealisticSides(
eligible: readonly string[],
playerCountry: string,
tuning: BattleTuning,
): TeamSides {
const others = shuffle(eligible.filter((c) => c !== playerCountry));
const total = eligible.length;
const minC = tuning.rbCoalitionMinCountries;
const maxC = tuning.rbCoalitionMaxCountries;
const playerMax = total >= minC * 2 ? Math.min(maxC, total - minC) : Math.min(maxC, total - 1);
const playerMin = total >= minC * 2 ? Math.min(minC, playerMax) : 1;
const playerCount = randomRangeInclusive(playerMin, playerMax);
const remaining = total - playerCount;
const enemyMax = Math.min(maxC, remaining);
const enemyMin = Math.min(minC, enemyMax);
const enemyCount = randomRangeInclusive(enemyMin, enemyMax);
return {
playerSide: [playerCountry, ...others.slice(0, playerCount - 1)],
enemySide: others.slice(playerCount - 1, playerCount - 1 + enemyCount),
symmetricTeams: false,
};
}
function buildMixedRealisticSides(
eligible: readonly string[],
playerCountry: string,
tuning: BattleTuning,
): TeamSides {
if (eligible.length < 2 || randomInt(2) === 0) {
return buildArcadeSides(eligible, playerCountry);
}
const total = eligible.length;
const minCount = Math.min(tuning.rbCoalitionMinCountries, total);
const maxCount = Math.min(tuning.rbCoalitionMaxCountries, total);
const playerCount = randomRangeInclusive(minCount, maxCount);
const enemyCount = randomRangeInclusive(minCount, maxCount);
const others = shuffle(eligible.filter((c) => c !== playerCountry));
const playerSide = [playerCountry, ...others.slice(0, playerCount - 1)];
const shared = playerSide[randomInt(playerSide.length)]!;
const enemyPool = shuffle(eligible.filter((c) => c !== shared));
const enemySide = shuffle([shared, ...enemyPool.slice(0, enemyCount - 1)]);
return {
playerSide,
enemySide,
symmetricTeams: sameCountrySet(playerSide, enemySide),
};
}
function placeFirst(countries: readonly string[], first: string): string[] {
return [first, ...countries.filter((c) => c !== first)];
}
function sameCountrySet(a: readonly string[], b: readonly string[]): boolean {
if (a.length !== b.length) return false;
const setB = new Set(b);
return a.every((item) => setB.has(item));
}
function randomRangeInclusive(min: number, max: number): number {
return max <= min ? min : min + randomInt(max - min + 1);
}
function shuffle<T>(items: readonly T[]): T[] {
const copy = [...items];
for (let i = copy.length - 1; i > 0; i--) {
const j = randomInt(i + 1);
const tmp = copy[i]!;
copy[i] = copy[j]!;
copy[j] = tmp;
}
return copy;
}
@@ -0,0 +1,257 @@
/**
* Session-level extra crew slot selection for Ground RB killstreak aircraft
* (nuclear bombers from `gameplay.blk/missionSupportPlane`, strike UCAVs from `wpcost.blk`)
* and `gameplay.blk/RandomSpawnUnits` auto-supplemented lineup slots.
*/
import { randomInt } from 'node:crypto';
import type {
BattleSpawnRulesData,
NuclearAircraftEntry,
NuclearPresetBracket,
RandomSpawnCandidate,
RandomSpawnGroupRule,
} from '../game-data/datasets/battle-spawn-rules.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { GameModeDeclaration } from '../game-modes/catalogue/game-mode-declaration.ts';
import { unitClassOfExpClass, vehicleMrank } from './battle-ranks.ts';
/** Ground RB persistent spawn-point cost for strike UCAVs (`ucav_*_killstreak`). */
const STRIKE_UCAV_SPAWN_SCORE = 750;
/** Standard maximum rank spread below `economicRankHistorical` where strike UCAVs appear. */
const STRIKE_UCAV_MAX_RANK_DIFF = 2;
/** Engine bitmask limit on crew slots (`LMP_MP_OFF_BROKEN_SLOTS_MASK` is `uint32_t`). */
const MAX_BATTLE_CREW_SLOTS = 32;
export interface ExtraBattleSlot {
readonly unitName: string;
readonly persistentCost: number;
readonly spaded: boolean;
readonly forceWeapon?: string;
readonly groupName?: string;
}
export interface ExtraBattleSlotsInput {
readonly country: string;
readonly slotVehicles: readonly string[];
readonly declaration: GameModeDeclaration;
readonly sessionMaxMrank: number;
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
readonly rules?: BattleSpawnRulesData;
}
export interface ExtraBattleSlotsPlan {
readonly extraBattleSlots: readonly ExtraBattleSlot[];
readonly randomUnits: Readonly<Record<string, readonly string[]>>;
readonly randomUnitsEventName?: string;
}
export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): ExtraBattleSlotsPlan {
const { rules, declaration, slotVehicles } = input;
const maxExtra = Math.max(0, MAX_BATTLE_CREW_SLOTS - slotVehicles.length);
if (!rules || declaration.multiSlot === false || maxExtra === 0) {
return { extraBattleSlots: [], randomUnits: {} };
}
const slots: ExtraBattleSlot[] = [];
if (declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic') {
const nuclear = pickNuclearSlot(input.country, input.sessionMaxMrank, rules.nuclearBrackets);
if (nuclear) slots.push(nuclear);
const ucav = pickStrikeUcavSlot(input.country, input.sessionMaxMrank, rules);
if (ucav) slots.push(ucav);
}
const randomPlan = pickRandomSpawnSlots(input, rules);
slots.push(...randomPlan.slots);
return {
extraBattleSlots: slots.slice(0, maxExtra),
randomUnits: randomPlan.randomUnits,
...(randomPlan.eventName ? { randomUnitsEventName: randomPlan.eventName } : {}),
};
}
function pickNuclearSlot(
country: string,
sessionMaxMrank: number,
brackets: readonly NuclearPresetBracket[],
): ExtraBattleSlot | undefined {
if (brackets.length === 0) return undefined;
const minNuclearRank = brackets[0]!.minMrank;
if (sessionMaxMrank < minNuclearRank) return undefined;
const matchingBracket = brackets.find((b) => sessionMaxMrank >= b.minMrank && sessionMaxMrank <= b.maxMrank)
?? (sessionMaxMrank > brackets[brackets.length - 1]!.maxMrank ? brackets[brackets.length - 1] : undefined);
if (!matchingBracket) return undefined;
const countryEntries = matchingBracket.entries.filter((entry) => entry.country === country);
if (countryEntries.length === 0) return undefined;
const chosen = chooseBestNuclearEntry(countryEntries, sessionMaxMrank);
return {
unitName: chosen.unitName,
persistentCost: matchingBracket.spawnScore,
spaded: true,
forceWeapon: chosen.weapon,
};
}
function chooseBestNuclearEntry(
entries: readonly NuclearAircraftEntry[],
sessionMaxMrank: number,
): NuclearAircraftEntry {
const withinRank = entries.filter((entry) => entry.tankRealisticMrank <= sessionMaxMrank);
if (withinRank.length > 0) {
const highestRank = withinRank.reduce((max, entry) => Math.max(max, entry.tankRealisticMrank), 0);
const tied = withinRank.filter((entry) => entry.tankRealisticMrank === highestRank);
return tied[randomInt(tied.length)]!;
}
const lowestRank = entries.reduce((min, entry) => Math.min(min, entry.tankRealisticMrank), Infinity);
const fallback = entries.filter((entry) => entry.tankRealisticMrank === lowestRank);
return fallback[randomInt(fallback.length)]!;
}
function pickStrikeUcavSlot(
country: string,
sessionMaxMrank: number,
rules: BattleSpawnRulesData,
): ExtraBattleSlot | undefined {
const ucav = rules.strikeUcavs.find((entry) => entry.country === country);
if (!ucav) return undefined;
const minSessionRank = Math.max(0, ucav.historicalMrank - STRIKE_UCAV_MAX_RANK_DIFF);
if (sessionMaxMrank < minSessionRank) return undefined;
return {
unitName: ucav.unitName,
persistentCost: STRIKE_UCAV_SPAWN_SCORE,
spaded: true,
...(ucav.weapon ? { forceWeapon: ucav.weapon } : {}),
};
}
function pickRandomSpawnSlots(
input: ExtraBattleSlotsInput,
rules: BattleSpawnRulesData,
): {
readonly eventName?: string;
readonly slots: readonly ExtraBattleSlot[];
readonly randomUnits: Readonly<Record<string, readonly string[]>>;
} {
const eventName = resolveRandomSpawnEventName(input.declaration);
if (!eventName) return { slots: [], randomUnits: {} };
const eventRule = rules.randomSpawnEvents.find((entry) => entry.eventName === eventName);
const groups = eventRule?.countries[input.country];
if (!groups || groups.length === 0) return { slots: [], randomUnits: {} };
const playerTopMrank = topAllowedLineupMrank(input.slotVehicles, input.declaration, input.vehiclesByName);
const equipped = new Set(input.slotVehicles);
const slots: ExtraBattleSlot[] = [];
const randomUnits: Record<string, readonly string[]> = {};
for (const group of groups) {
if (playerTopMrank < group.minPlayerMRank) continue;
if (input.sessionMaxMrank - playerTopMrank > group.maxDiffBetweenTopUnitAndSessionRank) continue;
const minWindowRank = Math.max(0, playerTopMrank - group.mRanksCount);
if (!lineupNeedsRandomGroup(group.groupName, input.slotVehicles, minWindowRank, input.declaration, input.vehiclesByName)) {
continue;
}
const candidates = filterGroupCandidates(group, minWindowRank, playerTopMrank, equipped, input.declaration, input.vehiclesByName);
if (candidates.length === 0) continue;
const chosen = candidates[randomInt(candidates.length)]!;
randomUnits[group.groupName] = candidates.map((candidate) => candidate.unitName);
slots.push({
unitName: chosen.unitName,
persistentCost: 0,
spaded: true,
groupName: group.groupName,
...(chosen.forceWeapon ? { forceWeapon: chosen.forceWeapon } : {}),
});
}
if (slots.length === 0) return { slots: [], randomUnits: {} };
return { eventName, slots, randomUnits };
}
function resolveRandomSpawnEventName(declaration: GameModeDeclaration): string | undefined {
if (declaration.requiredClass === 'tank') {
if (declaration.difficulty === 'realistic') return 'tank_random_battles_historical_base';
if (declaration.difficulty === 'arcade') return 'tank_event_in_random_battles_arcade';
}
if (declaration.requiredClass === 'ship') {
if (declaration.difficulty === 'realistic') return 'ship_event_in_random_battles_realistic';
if (declaration.difficulty === 'arcade') return 'ship_event_in_random_battles_arcade';
}
return undefined;
}
function topAllowedLineupMrank(
slotVehicles: readonly string[],
declaration: GameModeDeclaration,
byName: ReadonlyMap<string, CatalogueVehicle>,
): number {
const allowed = new Set(declaration.allowedClasses);
let top = 0;
for (const name of slotVehicles) {
const vehicle = byName.get(name);
const cls = vehicle && unitClassOfExpClass(vehicle.unitClass);
if (!vehicle || !cls || !allowed.has(cls)) continue;
top = Math.max(top, vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass));
}
return top;
}
function lineupNeedsRandomGroup(
groupName: string,
slotVehicles: readonly string[],
minWindowRank: number,
declaration: GameModeDeclaration,
byName: ReadonlyMap<string, CatalogueVehicle>,
): boolean {
let matching = 0;
for (const name of slotVehicles) {
const vehicle = byName.get(name);
if (!vehicle) continue;
const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass);
if (groupName === 'spaa') {
if (vehicle.unitClass === 'exp_SPAA' && rank >= minWindowRank) matching++;
} else if (groupName === 'tank') {
if (unitClassOfExpClass(vehicle.unitClass) === 'tank' && vehicle.unitClass !== 'exp_SPAA' && rank >= minWindowRank) {
matching++;
}
} else if (groupName === 'bomber') {
if (vehicle.unitClass === 'exp_bomber' || vehicle.unitClass === 'exp_assault') matching++;
} else if (groupName === 'fighter') {
if (vehicle.unitClass === 'exp_fighter') matching++;
}
}
return groupName === 'tank' ? matching < 2 : matching < 1;
}
function filterGroupCandidates(
group: RandomSpawnGroupRule,
minWindowRank: number,
maxWindowRank: number,
equipped: ReadonlySet<string>,
declaration: GameModeDeclaration,
byName: ReadonlyMap<string, CatalogueVehicle>,
): RandomSpawnCandidate[] {
const inWindow = group.units.filter((candidate) => {
if (equipped.has(candidate.unitName)) return false;
const vehicle = byName.get(candidate.unitName);
if (!vehicle) return false;
const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass);
return rank >= minWindowRank && rank <= maxWindowRank;
});
if (inWindow.length > 0) return inWindow;
const lowerCandidates = group.units
.flatMap((candidate) => {
if (equipped.has(candidate.unitName)) return [];
const vehicle = byName.get(candidate.unitName);
if (!vehicle) return [];
const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass);
return rank <= maxWindowRank ? [{ candidate, rank }] : [];
});
if (lowerCandidates.length === 0) return [];
const bestRank = lowerCandidates.reduce((max, item) => Math.max(max, item.rank), 0);
return lowerCandidates.filter((item) => item.rank === bestRank).map((item) => item.candidate);
}
@@ -0,0 +1,293 @@
/**
* Pure local-battle matchmaking rules (`match.enqueue`):
* validates the chosen PvP mode and country, computes the player's lineup BR, selects a
* two-sided multiplayer mission honoring banned/disliked map preferences, pairs AB/RB/SB
* nation coalitions, builds the `customBots` pool and extra battle slots, and records a
* `BattleSession`.
*/
import { randomInt } from 'node:crypto';
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { MISSION_DIFFICULTY } from '../game-modes/mode-definition.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
import {
lineupMrank,
selectCustomBots,
unitClassOfExpClass,
vehicleMrank,
type CustomBotsPool,
} from './battle-ranks.ts';
import type { BattleSessionStore } from './battle-session-store.ts';
import type { BattleTuning } from './battle-tuning.ts';
export interface EnqueueBattleInput {
readonly userId: string;
readonly mode: OfferedGameMode;
readonly modes?: readonly OfferedGameMode[];
readonly country: string;
readonly slotVehicles: readonly string[];
readonly selectedSlotVehicle?: string;
readonly bannedMissions: ReadonlySet<string>;
readonly dislikedMissions: ReadonlySet<string>;
}
export interface BattleLaunchPlan {
readonly sessionId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly missionName: string;
readonly missionFile: string;
readonly missionType: string;
readonly level?: string;
readonly environment?: string;
readonly weather?: string;
readonly difficulty: string;
readonly country: string;
readonly playerTeam: 1 | 2;
readonly countryAllies: string;
readonly countryAxis: string;
readonly countriesAllies: readonly string[];
readonly countriesAxis: readonly string[];
readonly symmetricTeams: boolean;
readonly minMrank: number;
readonly maxMrank: number;
readonly maxPlayers: number;
readonly maxBots: number;
readonly tankBotRespawns: number;
readonly airBotRespawns: number;
readonly useTankBots: boolean;
readonly useShipBots: boolean;
readonly useSpawnScore: boolean;
readonly customBots: CustomBotsPool;
readonly extraBattleSlots: readonly ExtraBattleSlot[];
readonly randomUnits: Readonly<Record<string, readonly string[]>>;
readonly randomUnitsEventName?: string;
}
export type MatchmakeOutcome =
| { readonly ok: true; readonly launch: BattleLaunchPlan }
| { readonly ok: false; readonly error: string };
export class BattleMatchmaker {
readonly #gameModes: GameModes;
readonly #vehicles: readonly CatalogueVehicle[];
readonly #vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
readonly #sessions: BattleSessionStore;
readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData | undefined;
constructor(
gameModes: GameModes,
vehicles: readonly CatalogueVehicle[],
sessions: BattleSessionStore,
tuning: BattleTuning,
spawnRules?: BattleSpawnRulesData,
) {
this.#gameModes = gameModes;
this.#vehicles = vehicles;
this.#vehiclesByName = new Map(vehicles.map((vehicle) => [vehicle.name, vehicle]));
this.#sessions = sessions;
this.#tuning = tuning;
this.#spawnRules = spawnRules;
}
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
const knownCountries = this.#gameModes.countries();
if (!knownCountries.includes(input.country)) return { ok: false, error: 'BAD_PARAMS' };
const candidates = input.modes && input.modes.length > 0 ? input.modes : [input.mode];
const chosenMode = this.#pickQueuedMode(candidates, input.slotVehicles, input.selectedSlotVehicle);
if (!chosenMode) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
const { declaration } = chosenMode;
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlotVehicle, this.#vehiclesByName);
const playerMrank = lineupMrank(
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
);
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
const maxMrank = Math.max(minMrank, playerMrank + this.#tuning.brSpreadMrank);
const mission = pickMission(twoSidedMissionsOf(chosenMode), input.bannedMissions, input.dislikedMissions);
const coalitions = selectBattleCoalitions({
vehicles: this.#vehicles,
knownCountries,
playerCountry: input.country,
difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass,
playerMrank,
minMrank,
maxMrank,
tuning: this.#tuning,
});
const customBots = selectCustomBots(this.#vehicles, {
difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass,
allowedClasses: declaration.allowedClasses,
countries: [...coalitions.countriesAllies, ...coalitions.countriesAxis],
centerMrank: playerMrank,
minMrank,
maxMrank,
limitPerType: this.#tuning.botPoolLimitPerType,
});
return {
ok: true,
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, minMrank, maxMrank, customBots),
};
}
#pickQueuedMode(
candidates: readonly OfferedGameMode[],
slotVehicles: readonly string[],
selectedSlotVehicle: string | undefined,
): OfferedGameMode | undefined {
const pvpModes = candidates.filter(
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
);
if (pvpModes.length === 0) return undefined;
const eligible = pvpModes.filter((mode) =>
isModeEligibleForLineup(mode.declaration, slotVehicles, selectedSlotVehicle, this.#vehiclesByName));
const pool = eligible.length > 0 ? eligible : pvpModes.filter((mode) => !mode.declaration.tag);
if (pool.length === 0) return pvpModes[0];
const classics = pool.filter((mode) => !mode.declaration.tag);
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
if (subModes.length > 0 && classics.length > 0) {
const useSubMode = randomInt(1_000_000) < Math.round(this.#tuning.subModeChance * 1_000_000);
const bucket = useSubMode ? subModes : classics;
return bucket[randomInt(bucket.length)];
}
return pool[randomInt(pool.length)];
}
#buildLaunchPlan(
input: EnqueueBattleInput,
chosenMode: OfferedGameMode,
mission: MissionHeader,
coalitions: CoalitionPairing,
minMrank: number,
maxMrank: number,
customBots: CustomBotsPool,
): BattleLaunchPlan {
const { declaration } = chosenMode;
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
const missionLocName = resolveMissionLocName(mission);
const environment = declaration.environmentOverride ?? mission.environment;
const session = this.#sessions.create({
userId: input.userId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass,
missionName: mission.name,
missionPath: mission.path,
...(missionLocName !== undefined ? { missionLocName } : {}),
country: input.country,
startedAtSec: serverTimeToUnixSeconds(serverTimeNow()),
});
const allowedSet = new Set(declaration.allowedClasses);
const extraPlan = selectExtraBattleSlots({
country: input.country,
slotVehicles: input.slotVehicles,
declaration,
sessionMaxMrank: maxMrank,
vehiclesByName: this.#vehiclesByName,
...(this.#spawnRules ? { rules: this.#spawnRules } : {}),
});
return {
sessionId: session.sessionId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
missionName: mission.name,
missionFile: mission.path,
missionType: mission.type ?? 'domination',
...(mission.level !== undefined ? { level: mission.level } : {}),
...(environment !== undefined ? { environment } : {}),
...(mission.weather !== undefined ? { weather: mission.weather } : {}),
difficulty: MISSION_DIFFICULTY[declaration.difficulty],
country: input.country,
playerTeam: coalitions.playerTeam,
countryAllies: coalitions.countryAllies,
countryAxis: coalitions.countryAxis,
countriesAllies: coalitions.countriesAllies,
countriesAxis: coalitions.countriesAxis,
symmetricTeams: coalitions.symmetricTeams,
minMrank,
maxMrank,
maxPlayers,
maxBots,
tankBotRespawns: this.#tuning.tankBotRespawns,
airBotRespawns: this.#tuning.airBotRespawns,
useTankBots: allowedSet.has('tank'),
useShipBots: allowedSet.has('ship'),
useSpawnScore: declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic',
customBots,
extraBattleSlots: extraPlan.extraBattleSlots,
randomUnits: extraPlan.randomUnits,
...(extraPlan.randomUnitsEventName ? { randomUnitsEventName: extraPlan.randomUnitsEventName } : {}),
};
}
}
function twoSidedMissionsOf(mode: OfferedGameMode): MissionHeader[] {
return mode.missions.filter((m) => m.playerSlots.teamA > 0 && m.playerSlots.teamB > 0);
}
function activeVehiclesForMode(
declaration: OfferedGameMode['declaration'],
slotVehicles: readonly string[],
selectedSlotVehicle: string | undefined,
byName: ReadonlyMap<string, CatalogueVehicle>,
): readonly string[] {
if (declaration.multiSlot !== false || !selectedSlotVehicle) return slotVehicles;
const selected = byName.get(selectedSlotVehicle);
return selected && unitClassOfExpClass(selected.unitClass) === declaration.requiredClass
? [selectedSlotVehicle]
: slotVehicles;
}
function isModeEligibleForLineup(
declaration: OfferedGameMode['declaration'],
slotVehicles: readonly string[],
selectedSlotVehicle: string | undefined,
byName: ReadonlyMap<string, CatalogueVehicle>,
): boolean {
if (!declaration.tag) return true;
const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName);
const minMrank = declaration.minQueueMrank ?? 0;
const minCrafts = declaration.minCraftsToPlay ?? 1;
const matchingCount = active.filter((name) => {
const vehicle = byName.get(name);
if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false;
return vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass) >= minMrank;
}).length;
return matchingCount >= minCrafts;
}
function pickMission(missions: readonly MissionHeader[], banned: ReadonlySet<string>, disliked: ReadonlySet<string>): MissionHeader {
const unbanned = missions.filter((mission) => !banned.has(mission.name));
const poolAfterBan = unbanned.length > 0 ? unbanned : missions;
const preferred = poolAfterBan.filter((mission) => !disliked.has(mission.name));
const pool = preferred.length > 0 ? preferred : poolAfterBan;
return pool[randomInt(pool.length)]!;
}
function maxSlotsForMission(mission: MissionHeader, desiredMaxPlayers: number): number {
const { teamA, teamB } = mission.playerSlots;
return Math.max(2, Math.min(desiredMaxPlayers, Math.min(teamA, teamB) * 2));
}
function resolveMissionLocName(mission: MissionHeader): string | undefined {
if (mission.locName && mission.locName.length > 0) return mission.locName;
if (mission.postfix && mission.postfix.length > 0 && mission.name.endsWith(mission.postfix)) {
const baseName = mission.name.slice(0, -mission.postfix.length);
if (baseName.length > 0) return `missions/${mission.postfix};missions/${baseName}`;
}
return undefined;
}
@@ -0,0 +1,177 @@
/**
* Pure matchmaking rank (`mrank`) calculation and deterministic BR-matched `customBots`
* vehicle-pool selection (`scripts/slotbar/slotbarpresets/calcranks.nut`).
*
* `BotSystem` (`aces.exe` `0x11af3f0`) reads `MissionSettings.customBots` using bare country
* names (`"usa"`, `"germany"`, ...) and three sub-blocks: `allowedTanks` (`tank`),
* `allowedAircrafts` (`aircraft`), and `allowedShips` (`ship`).
*/
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
const COUNTRY_PREFIX = 'country_';
export interface CraftRankEntry {
readonly unitClass: UnitClass | undefined;
readonly mrank: number;
}
export interface BotPoolEntry {
readonly name: string;
readonly country: string;
readonly weight: number;
}
export interface CustomBotsPool {
readonly tanks: readonly BotPoolEntry[];
readonly aircrafts: readonly BotPoolEntry[];
readonly ships: readonly BotPoolEntry[];
}
export interface BotPoolQuery {
readonly difficulty: ModeDifficulty;
readonly requiredClass: UnitClass;
readonly allowedClasses: readonly UnitClass[];
readonly countries: readonly string[];
readonly centerMrank: number;
readonly minMrank: number;
readonly maxMrank: number;
readonly limitPerType: number;
}
export function stripCountryPrefix(country: string): string {
return country.startsWith(COUNTRY_PREFIX) ? country.slice(COUNTRY_PREFIX.length) : country;
}
export function unitClassOfExpClass(expClass: string): UnitClass | undefined {
return unitClassOfVehicleType(vehicleTypeOfClass(expClass));
}
export function unitClassOfTypeCode(unitTypeCode: number): UnitClass | undefined {
return unitClassOfVehicleType(vehicleTypeById(unitTypeCode));
}
export function vehicleMrank(vehicle: CatalogueVehicle, difficulty: ModeDifficulty, requiredClass: UnitClass): number {
if (difficulty === 'arcade') return vehicle.economicRankArcade;
if (difficulty === 'simulator') {
return requiredClass === 'tank' && vehicle.economicRankTankSimulation !== undefined
? vehicle.economicRankTankSimulation
: vehicle.economicRankSimulation;
}
return requiredClass === 'tank' && vehicle.economicRankTankHistorical !== undefined
? vehicle.economicRankTankHistorical
: vehicle.economicRankHistorical;
}
/**
* Maximum `mrank` among crafts allowed in the mode (`calcranks.nut` `filterCrafts` +
* `specialShipsFilter`: in naval modes, aircraft above `maxShipMrank + 1` are ignored).
*/
export function maxModeMrank(
crafts: readonly CraftRankEntry[],
requiredClass: UnitClass,
allowedClasses: readonly UnitClass[],
): number {
const allowedSet = new Set(allowedClasses);
const matching = crafts.filter((craft) => craft.unitClass !== undefined && allowedSet.has(craft.unitClass));
if (!matching.some((craft) => craft.unitClass === requiredClass)) return 0;
let filtered = matching;
if (requiredClass === 'ship') {
const maxShip = matching
.filter((craft) => craft.unitClass === 'ship')
.reduce((max, craft) => Math.max(max, craft.mrank), 0);
filtered = matching.filter((craft) => craft.unitClass !== 'aircraft' || craft.mrank <= maxShip + 1);
}
return filtered.reduce((max, craft) => Math.max(max, Math.max(0, Math.trunc(craft.mrank))), 0);
}
export function lineupMrank(
vehicleNames: readonly string[],
byName: ReadonlyMap<string, CatalogueVehicle>,
difficulty: ModeDifficulty,
requiredClass: UnitClass,
allowedClasses: readonly UnitClass[],
): number {
const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => {
const vehicle = byName.get(name);
if (!vehicle) return [];
return [{
unitClass: unitClassOfExpClass(vehicle.unitClass),
mrank: vehicleMrank(vehicle, difficulty, requiredClass),
}];
});
return maxModeMrank(crafts, requiredClass, allowedClasses);
}
export function selectCustomBots(vehicles: readonly CatalogueVehicle[], query: BotPoolQuery): CustomBotsPool {
const allowed = new Set(query.allowedClasses);
const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))];
return {
tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [],
aircrafts: allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [],
ships: allowed.has('ship') ? pickCategoryPool(vehicles, orderedCountries, 'ship', query) : [],
};
}
function pickCategoryPool(
vehicles: readonly CatalogueVehicle[],
orderedCountries: readonly string[],
category: 'tank' | 'aircraft' | 'ship',
query: BotPoolQuery,
): BotPoolEntry[] {
const countrySet = new Set(orderedCountries);
const eligible = vehicles.filter((vehicle) =>
vehicle.inTechTree
&& !vehicle.onlyShownWhenOwned
&& !vehicle.premiumPack
&& !vehicle.gift
&& !vehicle.event
&& vehicle.researchType === undefined
&& countrySet.has(vehicle.country)
&& unitClassOfExpClass(vehicle.unitClass) === category);
if (eligible.length === 0) return [];
const sortedByCloseness = [...eligible].sort((a, b) => {
const distA = Math.abs(vehicleMrank(a, query.difficulty, query.requiredClass) - query.centerMrank);
const distB = Math.abs(vehicleMrank(b, query.difficulty, query.requiredClass) - query.centerMrank);
return distA !== distB ? distA - distB : a.name.localeCompare(b.name);
});
const inWindow = sortedByCloseness.filter((vehicle) => {
const mrank = vehicleMrank(vehicle, query.difficulty, query.requiredClass);
return mrank >= query.minMrank && mrank <= query.maxMrank;
});
const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType);
return roundRobinByCountry(source, orderedCountries, query.limitPerType);
}
function roundRobinByCountry(
vehicles: readonly CatalogueVehicle[],
orderedCountries: readonly string[],
limit: number,
): BotPoolEntry[] {
const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []]));
for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle);
const out: BotPoolEntry[] = [];
for (let index = 0; out.length < limit; index++) {
let added = false;
for (const country of orderedCountries) {
const vehicle = buckets.get(country)?.[index];
if (!vehicle) continue;
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 });
added = true;
if (out.length >= limit) break;
}
if (!added) break;
}
return out;
}
function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined {
if (type === 'Tank') return 'tank';
if (type === 'Aircraft') return 'aircraft';
if (type === 'Helicopter') return 'helicopter';
if (type === 'Ship' || type === 'Boat') return 'ship';
return undefined;
}
@@ -0,0 +1,179 @@
/**
* Battle debriefing report schema and DataBlock parser for `cln_wto_finish_battle`,
* including per-unit and top-level reward categories mapped to `EULT_SESSION_RESULT`
* `body/container` event blocks (`scripts/userlog/getuserlogbattlerewardstable.nut`).
*/
import { findBlock, type BlkBlock } from '@wto/blk';
export type BattleOutcomeKind = 'win' | 'lose' | 'running';
export interface RewardCategoryStat {
readonly count: number;
readonly wp: number;
readonly exp: number;
}
export interface RewardCategorySpec {
readonly category: string;
readonly containerId: string;
readonly victimUnitFileName?: string;
readonly singleSummaryEvent?: boolean;
}
export const REWARD_CATEGORY_SPECS: readonly RewardCategorySpec[] = [
{ category: 'AirKills', containerId: 'eventKill' },
{ category: 'GroundKills', containerId: 'eventKillGround' },
{ category: 'NavalKills', containerId: 'eventKillGround', victimUnitFileName: 'ships/' },
{ category: 'HumanKills', containerId: 'eventKillHuman' },
{ category: 'Assist', containerId: 'eventAssist' },
{ category: 'AirSevereDamage', containerId: 'eventSevereDamage' },
{ category: 'ShipSevereDamage', containerId: 'eventSevereDamage' },
{ category: 'Critical', containerId: 'eventCriticalHit' },
{ category: 'Hit', containerId: 'eventHit' },
{ category: 'Takeoffs', containerId: 'eventTakeoff' },
{ category: 'Landings', containerId: 'eventLanding' },
{ category: 'MissileEvade', containerId: 'eventMissileEvade' },
{ category: 'ShellInterception', containerId: 'eventShellInterception' },
{ category: 'Captures', containerId: 'eventCaptureZone' },
{ category: 'SectorCapture', containerId: 'eventSectorCapture' },
{ category: 'SuppliesDelivery', containerId: 'eventSuppliesDelivery' },
{ category: 'SuppliesReturn', containerId: 'eventSuppliesReturn' },
{ category: 'SuppliesDestroy', containerId: 'eventSuppliesDestroy' },
{ category: 'SuppliesEscort', containerId: 'eventSuppliesEscort' },
{ category: 'Destruction', containerId: 'eventDestroyZone' },
{ category: 'Damage', containerId: 'eventDamageZone' },
{ category: 'Scout', containerId: 'eventScout' },
{ category: 'ScoutCriticalHit', containerId: 'eventScoutCriticalHit' },
{ category: 'ScoutKill', containerId: 'eventScoutKill' },
{ category: 'ScoutKillUnknown', containerId: 'eventScoutKill' },
{ category: 'TimedAward', containerId: 'eventTimedAward' },
{ category: 'Unlocks', containerId: 'eventStreak' },
{ category: 'BattleTime', containerId: 'eventBattletime', singleSummaryEvent: true },
];
export interface VehicleBattleStats {
readonly vehicle: string;
readonly wpTotal: number;
readonly expTotal: number;
readonly expModsTotal: number;
readonly expUnitTotal: number;
readonly wpMission: number;
readonly expSkillBonusTotal: number;
readonly expSkillBonusLevel: number;
readonly sessionTime: number;
readonly battleTime: number;
readonly rewards: Readonly<Record<string, RewardCategoryStat>>;
}
export interface BattleReport {
readonly sessionId: string;
readonly country: string;
readonly outcome: BattleOutcomeKind;
readonly localTeam: number;
readonly teamAScore: number;
readonly teamBScore: number;
readonly teamAKills: number;
readonly teamBKills: number;
readonly wpTotal: number;
readonly expTotal: number;
readonly expFree: number;
readonly wpMission: number;
readonly wpTeamKills: number;
readonly expSkillBonusTotal: number;
readonly expSkillBonusLevel: number;
readonly activity: number;
readonly sessionTime: number;
readonly battleTime: number;
readonly rewards: Readonly<Record<string, RewardCategoryStat>>;
readonly usedSpares: Readonly<Record<string, number>>;
readonly vehicles: readonly VehicleBattleStats[];
}
export function parseBattleReport(payload: BlkBlock): BattleReport | undefined {
const sessionId = strOf(payload, 'sessionId');
if (!sessionId || !/^[0-9a-f]{16}$/i.test(sessionId)) return undefined;
const rawOutcome = strOf(payload, 'outcome');
const outcome: BattleOutcomeKind = rawOutcome === 'win' || rawOutcome === 'lose' ? rawOutcome : 'running';
const vehiclesBlock = findBlock(payload, 'vehicles');
const vehicles: VehicleBattleStats[] = (vehiclesBlock?.blocks ?? [])
.filter((block) => block.name.length > 0)
.map((block) => ({
vehicle: block.name,
wpTotal: intOf(block, 'wpTotal'),
expTotal: intOf(block, 'expTotal'),
expModsTotal: intOf(block, 'expModsTotal'),
expUnitTotal: intOf(block, 'expUnitTotal'),
wpMission: intOf(block, 'wpMission'),
expSkillBonusTotal: intOf(block, 'expSkillBonusTotal'),
expSkillBonusLevel: intOf(block, 'expSkillBonusLevel'),
sessionTime: realOf(block, 'sessionTime'),
battleTime: realOf(block, 'battleTime'),
rewards: parseRewardMap(findBlock(block, 'rewards')),
}));
return {
sessionId: sessionId.toLowerCase(),
country: strOf(payload, 'country') ?? '',
outcome,
localTeam: intOf(payload, 'localTeam', 1),
teamAScore: intOf(payload, 'teamAScore'),
teamBScore: intOf(payload, 'teamBScore'),
teamAKills: intOf(payload, 'teamAKills'),
teamBKills: intOf(payload, 'teamBKills'),
wpTotal: intOf(payload, 'wpTotal'),
expTotal: intOf(payload, 'expTotal'),
expFree: intOf(payload, 'expFree'),
wpMission: intOf(payload, 'wpMission'),
wpTeamKills: intOf(payload, 'wpTeamKills'),
expSkillBonusTotal: intOf(payload, 'expSkillBonusTotal'),
expSkillBonusLevel: intOf(payload, 'expSkillBonusLevel'),
activity: realOf(payload, 'activity'),
sessionTime: realOf(payload, 'sessionTime'),
battleTime: realOf(payload, 'battleTime'),
rewards: parseRewardMap(findBlock(payload, 'rewards')),
usedSpares: parseSpareMap(findBlock(payload, 'spares')),
vehicles,
};
}
function parseRewardMap(rewardsBlk: BlkBlock | undefined): Record<string, RewardCategoryStat> {
const out: Record<string, RewardCategoryStat> = {};
if (!rewardsBlk) return out;
for (const catBlk of rewardsBlk.blocks) {
if (!catBlk.name) continue;
const count = Math.max(0, intOf(catBlk, 'count'));
const wp = Math.max(0, intOf(catBlk, 'wp'));
const exp = Math.max(0, intOf(catBlk, 'exp'));
if (count > 0 || wp > 0 || exp > 0) out[catBlk.name] = { count, wp, exp };
}
return out;
}
function parseSpareMap(sparesBlk: BlkBlock | undefined): Record<string, number> {
const out: Record<string, number> = {};
if (!sparesBlk) return out;
for (const param of sparesBlk.params) {
if (!param.name) continue;
const count = param.value.type === 'int' ? param.value.value : param.value.type === 'int64' ? Number(param.value.value) : 0;
if (count > 0) out[param.name] = count;
}
return out;
}
function strOf(block: BlkBlock, name: string): string | undefined {
const value = block.params.find((p) => p.name === name)?.value;
return value?.type === 'string' ? value.value : undefined;
}
function intOf(block: BlkBlock, name: string, fallback = 0): number {
const value = block.params.find((p) => p.name === name)?.value;
if (value?.type === 'int') return value.value;
if (value?.type === 'int64') return Number(value.value);
return fallback;
}
function realOf(block: BlkBlock, name: string): number {
const value = block.params.find((p) => p.name === name)?.value;
if (value?.type === 'real') return value.value;
if (value?.type === 'int') return value.value;
return 0;
}
@@ -0,0 +1,280 @@
/**
* Assemble and append full `EULT_SESSION_RESULT` (`type = 2`) battle mail entries into
* `profile.userlogs` matching `scripts/userlog/userlogviewdata.nut` and
* `scripts/userlog/getuserlogbattlerewardstable.nut`.
*/
import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { REWARD_CATEGORY_SPECS, type BattleReport, type RewardCategorySpec } from './battle-report.ts';
import type { BattleSession } from './battle-session-store.ts';
export interface EarnedRpItem {
readonly unit: string;
readonly modification?: string;
readonly rp: number;
readonly excessRp?: number;
}
export interface BattleResultSummary {
readonly win: boolean;
readonly country: string;
readonly wpEarned: number;
readonly xpEarned: number;
readonly activity: number;
readonly slMul: number;
readonly rpMul: number;
readonly weaponRefillSl: number;
readonly friendlyFirePenalty: number;
readonly report: BattleReport;
readonly rpItems: readonly EarnedRpItem[];
}
export function mergeEarnedRpItems(items: readonly EarnedRpItem[]): EarnedRpItem[] {
const byKey = new Map<string, EarnedRpItem>();
for (const item of items) {
if (item.rp <= 0 && (item.excessRp ?? 0) <= 0) continue;
const key = `${item.unit}\0${item.modification ?? ''}`;
const existing = byKey.get(key);
if (existing) {
const mergedExcess = (existing.excessRp ?? 0) + (item.excessRp ?? 0);
byKey.set(key, {
unit: existing.unit,
...(existing.modification ? { modification: existing.modification } : {}),
rp: existing.rp + item.rp,
...(mergedExcess > 0 ? { excessRp: mergedExcess } : {}),
});
} else {
byKey.set(key, item);
}
}
return [...byKey.values()];
}
export function appendBattleResultLog(
profile: BlkBlock,
session: BattleSession,
summary: BattleResultSummary,
): void {
const bodyParams: BlkParam[] = [
{ name: 'win', value: { type: 'bool', value: summary.win } },
{ name: 'mission', value: { type: 'string', value: session.missionName } },
...(session.missionLocName ? [{ name: 'locName', value: { type: 'string' as const, value: session.missionLocName } }] : []),
{ name: 'country', value: { type: 'string', value: summary.country } },
{ name: 'eventId', value: { type: 'string', value: session.modeName } },
{ name: 'wpEarned', value: { type: 'int', value: summary.wpEarned } },
{ name: 'xpEarned', value: { type: 'int', value: summary.xpEarned } },
{ name: 'activity', value: { type: 'real', value: summary.activity } },
...(summary.friendlyFirePenalty !== 0
? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: summary.friendlyFirePenalty } }]
: []),
{ name: 'wtoSessionId', value: { type: 'string', value: session.sessionId } },
{ name: 'wtoSlMul', value: { type: 'real', value: summary.slMul } },
{ name: 'wtoRpMul', value: { type: 'real', value: summary.rpMul } },
];
const bodyBlocks: BlkBlock[] = [buildContainerBlock(summary)];
const aircrafts = buildAircraftsBlock(summary.report);
if (aircrafts) bodyBlocks.push(aircrafts);
const spare = buildSpareBlock(summary.report);
if (spare) bodyBlocks.push(spare);
const rpEarned = buildRpEarnedBlock(summary.rpItems);
if (rpEarned) bodyBlocks.push(rpEarned);
appendUserLog(profile, {
type: EULT_SESSION_RESULT,
timeSec: serverTimeToUnixSeconds(serverTimeNow()),
roomId: session.roomId,
bodyParams,
bodyBlocks,
});
}
function buildContainerBlock(summary: BattleResultSummary): BlkBlock {
const container = emptyBlock('container');
const { report, slMul, rpMul } = summary;
if (summary.weaponRefillSl > 0) {
setParam(container, 'wpCostWeaponRefill', { type: 'int', value: summary.weaponRefillSl });
}
const wpMission = scalePositive(
Math.max(report.wpMission, report.vehicles.reduce((s, v) => s + Math.max(0, v.wpMission), 0)),
slMul,
);
if (wpMission > 0) {
setParam(container, 'wpMissionEndAward', { type: 'int', value: wpMission });
}
const eventLists = new Map<string, BlkBlock[]>();
for (const spec of REWARD_CATEGORY_SPECS) {
appendCategoryEvents(eventLists, spec, report, slMul, rpMul);
}
for (const [containerId, events] of eventLists) {
if (events.length > 0) {
container.blocks.push({ name: containerId, params: [], blocks: events });
}
}
const sessionAward = buildUnitSessionAwardBlock(report);
if (sessionAward) container.blocks.push(sessionAward);
const skillBonus = buildSkillBonusBlock(report, rpMul);
if (skillBonus) container.blocks.push(skillBonus);
return container;
}
function appendCategoryEvents(
eventLists: Map<string, BlkBlock[]>,
spec: RewardCategorySpec,
report: BattleReport,
slMul: number,
rpMul: number,
): void {
let unitWpSum = 0;
let unitExpSum = 0;
let hasUnitEntries = false;
for (const vehicle of report.vehicles) {
const stat = vehicle.rewards[spec.category];
if (!stat) continue;
hasUnitEntries = true;
const wp = scalePositive(stat.wp, slMul);
const exp = scalePositive(stat.exp, rpMul);
unitWpSum += stat.wp;
unitExpSum += stat.exp;
pushSplitEvents(eventLists, spec, vehicle.vehicle, stat.count, wp, exp);
}
const rootStat = report.rewards[spec.category];
if (!rootStat) return;
if (!hasUnitEntries) {
const fallbackUnit = report.vehicles[0]?.vehicle ?? '';
pushSplitEvents(
eventLists,
spec,
fallbackUnit,
rootStat.count,
scalePositive(rootStat.wp, slMul),
scalePositive(rootStat.exp, rpMul),
);
return;
}
const extraWp = scalePositive(rootStat.wp - unitWpSum, slMul);
const extraExp = scalePositive(rootStat.exp - unitExpSum, rpMul);
if (extraWp > 0 || extraExp > 0) {
pushSplitEvents(eventLists, spec, report.vehicles[0]?.vehicle ?? '', 1, extraWp, extraExp);
}
}
function pushSplitEvents(
eventLists: Map<string, BlkBlock[]>,
spec: RewardCategorySpec,
offenderUnit: string,
rawCount: number,
totalWp: number,
totalExp: number,
): void {
if (rawCount <= 0 && totalWp <= 0 && totalExp <= 0) return;
const count = spec.singleSummaryEvent ? 1 : Math.min(64, Math.max(1, rawCount));
let list = eventLists.get(spec.containerId);
if (!list) {
list = [];
eventLists.set(spec.containerId, list);
}
let prevWp = 0;
let prevExp = 0;
for (let i = 0; i < count; i++) {
const nextWp = Math.round((totalWp * (i + 1)) / count);
const nextExp = Math.round((totalExp * (i + 1)) / count);
const ev = emptyBlock('event');
if (offenderUnit) setParam(ev, 'offenderUnit', { type: 'string', value: offenderUnit });
if (spec.victimUnitFileName) setParam(ev, 'victimUnitFileName', { type: 'string', value: spec.victimUnitFileName });
setParam(ev, 'wpNoBonus', { type: 'int', value: nextWp - prevWp });
setParam(ev, 'expNoBonus', { type: 'int', value: nextExp - prevExp });
list.push(ev);
prevWp = nextWp;
prevExp = nextExp;
}
}
function buildUnitSessionAwardBlock(report: BattleReport): BlkBlock | undefined {
const events: BlkBlock[] = [];
for (const v of report.vehicles) {
const sec = Math.round(v.sessionTime > 0 ? v.sessionTime : v.battleTime);
if (sec <= 0) continue;
const ev = emptyBlock('event');
setParam(ev, 'unit', { type: 'string', value: v.vehicle });
setParam(ev, 'lifetime', { type: 'int', value: sec });
setParam(ev, 'wpNoBonus', { type: 'int', value: 0 });
setParam(ev, 'expNoBonus', { type: 'int', value: 0 });
events.push(ev);
}
if (events.length === 0) {
const rootSec = Math.round(report.sessionTime > 0 ? report.sessionTime : report.battleTime);
if (rootSec <= 0) return undefined;
const ev = emptyBlock('event');
setParam(ev, 'lifetime', { type: 'int', value: rootSec });
setParam(ev, 'wpNoBonus', { type: 'int', value: 0 });
setParam(ev, 'expNoBonus', { type: 'int', value: 0 });
events.push(ev);
}
return { name: 'unitSessionAward', params: [], blocks: events };
}
function buildSkillBonusBlock(report: BattleReport, rpMul: number): BlkBlock | undefined {
const units: BlkBlock[] = [];
for (const v of report.vehicles) {
const exp = scalePositive(v.expSkillBonusTotal, rpMul);
if (exp <= 0) continue;
const uBlk = emptyBlock('unit');
setParam(uBlk, 'unit', { type: 'string', value: v.vehicle });
setParam(uBlk, 'bonusLevel', { type: 'int', value: Math.max(1, v.expSkillBonusLevel || report.expSkillBonusLevel) });
setParam(uBlk, 'exp', { type: 'int', value: exp });
units.push(uBlk);
}
if (units.length === 0 && report.expSkillBonusTotal > 0) {
const exp = scalePositive(report.expSkillBonusTotal, rpMul);
if (exp > 0) {
const uBlk = emptyBlock('unit');
setParam(uBlk, 'unit', { type: 'string', value: report.vehicles[0]?.vehicle ?? '' });
setParam(uBlk, 'bonusLevel', { type: 'int', value: Math.max(1, report.expSkillBonusLevel) });
setParam(uBlk, 'exp', { type: 'int', value: exp });
units.push(uBlk);
}
}
return units.length > 0 ? { name: 'expSkillBonus', params: [], blocks: units } : undefined;
}
function buildAircraftsBlock(report: BattleReport): BlkBlock | undefined {
if (report.vehicles.length === 0) return undefined;
const blk = emptyBlock('aircrafts');
for (const v of report.vehicles) {
setParam(blk, v.vehicle, { type: 'real', value: 1.0 });
}
return blk;
}
function buildSpareBlock(report: BattleReport): BlkBlock | undefined {
const entries = Object.entries(report.usedSpares).filter(([unit, cnt]) => unit.length > 0 && cnt > 0);
if (entries.length === 0) return undefined;
const blk = emptyBlock('spare');
for (const [unit, count] of entries) {
setParam(blk, unit, { type: 'int', value: Math.trunc(count) });
}
return blk;
}
function buildRpEarnedBlock(items: readonly EarnedRpItem[]): BlkBlock | undefined {
if (items.length === 0) return undefined;
const rpEarned = emptyBlock('rpEarned');
items.forEach((item, index) => {
setParam(rpEarned, `aname${index}`, { type: 'string', value: item.unit });
if (item.modification) setParam(rpEarned, `mname${index}`, { type: 'string', value: item.modification });
setParam(rpEarned, `mrp${index}`, { type: 'int', value: item.rp });
if (item.excessRp && item.excessRp > 0) {
setParam(rpEarned, `merp${index}`, { type: 'int', value: item.excessRp });
}
});
return rpEarned;
}
function scalePositive(base: number, mul: number): number {
if (!Number.isFinite(base) || base <= 0) return 0;
return Math.min(0x7fffffff, Math.max(0, Math.round(base * mul)));
}
@@ -0,0 +1,266 @@
/**
* Post-battle Modification RP and Vehicle RP investment with overflow banking:
* - Modification RP completes at most the vehicle's active `investMode` modification, sets
* `investModePrev = <completedMod>`, clears `investMode = ""`, and banks remaining RP into
* `hangar/<unit>/excessExp:i64` (unless all modifications on the vehicle are researched).
* - Vehicle RP aggregates per `(country, branchType)` before investing, completes at most the
* active `currUnit` once, sets `prevUnit = <completedUnit>`, clears `currUnit = ""`, and
* banks remaining RP into `researchUnits.<country>.exp<Branch>:i64`.
*/
import type { BlkBlock } from '@wto/blk';
import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts';
import type { UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
import { isResearchable, type EquipmentCatalogue } from '../modifications/equipment-catalogue.ts';
import { pickDefaultResearchableModule } from '../modifications/module-state.ts';
import { isModuleResearched, ModuleStatus, vehicleModuleState } from '../modifications/module-status.ts';
import { addExpertToAceRp, specializationOf } from '../profile/profile-crew-skills.ts';
import { crewForVehicleInCountry } from '../profile/profile-crews.ts';
import { readRedirectedResearchDomain, type VehicleDomain } from '../profile/profile-dest-rp.ts';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { moduleResearchPoints, setModuleResearchPoints } from '../profile/profile-module-research.ts';
import {
branchExcessRp,
finishedResearch,
researchTarget,
setBranchExcessRp,
setFinishedResearch,
setResearchTarget,
} from '../profile/profile-research-targets.ts';
import { researchPointsOf } from '../profile/profile-vehicle-research.ts';
import {
finishedModuleResearch,
moduleResearchTarget,
setFinishedModuleResearch,
setModuleResearchTarget,
setVehicleExcessRp,
vehicleExcessRp,
} from '../profile/profile-vehicle-state.ts';
import { addResearchPoints } from '../research/research-progress.ts';
import type { ResearchRules } from '../research/research-rules.ts';
import { currentStatus, refreshResearchState } from '../research/research-state.ts';
import { VehicleStatus } from '../research/vehicle-status.ts';
import type { BattleReport } from './battle-report.ts';
import type { EarnedRpItem } from './battle-result-log.ts';
import type { BattleSession } from './battle-session-store.ts';
export interface BattleRpDeps {
readonly research: ResearchRules;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
}
export function collectEarnedBattleRp(
profile: BlkBlock,
report: BattleReport,
session: BattleSession,
deps: BattleRpDeps,
rpMul: number,
earnedTotalRp: number,
): EarnedRpItem[] {
const rpItems: EarnedRpItem[] = [];
const owned = ownedVehicles(profile);
const branchTotals = new Map<string, { readonly country: string; readonly branchType: string; amount: number }>();
refreshResearchState(profile, deps.research);
for (const stat of report.vehicles) {
const modRp = scaleRp(stat.expModsTotal > 0 ? stat.expModsTotal : stat.expTotal, rpMul);
const unitRp = scaleRp(stat.expUnitTotal > 0 ? stat.expUnitTotal : stat.expTotal, rpMul);
if (modRp > 0 && owned.has(stat.vehicle)) {
const modItem = investModificationRp(profile, deps.equipment, stat.vehicle, modRp);
if (modItem) rpItems.push(modItem);
}
if (unitRp > 0) {
if (owned.has(stat.vehicle)) investAceCrewRp(profile, deps.crew, session.country, stat.vehicle, unitRp);
accumulateBranchRp(branchTotals, profile, deps.research, stat.vehicle, session, unitRp);
}
}
if (report.vehicles.length === 0 && earnedTotalRp > 0) {
const fallbackBranch = resolveFallbackBranch(profile, session.country, session.requiredClass);
if (fallbackBranch) addToBranchMap(branchTotals, session.country, fallbackBranch, earnedTotalRp);
}
for (const entry of branchTotals.values()) {
const item = investIntoBranch(profile, deps.research, entry.country, entry.branchType, entry.amount);
if (item) rpItems.push(item);
}
return rpItems;
}
function accumulateBranchRp(
branchTotals: Map<string, { readonly country: string; readonly branchType: string; amount: number }>,
profile: BlkBlock,
research: ResearchRules,
playedVehicleName: string,
session: BattleSession,
amount: number,
): void {
const played = research.techTree.vehicle(playedVehicleName);
if (played) {
const targetBranch = readRedirectedResearchDomain(profile, played.country, played.type);
addToBranchMap(branchTotals, played.country, targetBranch, amount);
return;
}
const fallbackBranch = resolveFallbackBranch(profile, session.country, session.requiredClass);
if (fallbackBranch) {
const targetBranch = readRedirectedResearchDomain(profile, session.country, fallbackBranch);
addToBranchMap(branchTotals, session.country, targetBranch, amount);
}
}
function addToBranchMap(
map: Map<string, { readonly country: string; readonly branchType: string; amount: number }>,
country: string,
branchType: string,
amount: number,
): void {
const key = `${country}\0${branchType}`;
const existing = map.get(key);
if (existing) existing.amount += amount;
else map.set(key, { country, branchType, amount });
}
function resolveFallbackBranch(profile: BlkBlock, country: string, requiredClass: UnitClass): VehicleDomain | undefined {
const preferred: Readonly<Record<UnitClass, readonly VehicleDomain[]>> = {
tank: ['Tank', 'Aircraft', 'Helicopter', 'Boat', 'Ship'],
aircraft: ['Aircraft', 'Helicopter', 'Tank', 'Boat', 'Ship'],
helicopter: ['Helicopter', 'Aircraft', 'Tank', 'Boat', 'Ship'],
ship: ['Ship', 'Boat', 'Aircraft', 'Tank', 'Helicopter'],
};
return preferred[requiredClass].find((branch) => Boolean(researchTarget(profile, country, branch)))
?? preferred[requiredClass][0];
}
function investModificationRp(
profile: BlkBlock,
catalogue: EquipmentCatalogue,
vehicleName: string,
amount: number,
): EarnedRpItem | undefined {
const equipment = catalogue.vehicle(vehicleName);
if (!equipment || amount <= 0) return undefined;
const state = vehicleModuleState(profile, equipment);
let targetName = moduleResearchTarget(profile, vehicleName);
if (targetName && state.statuses.get(targetName) !== ModuleStatus.CAN_RESEARCH) {
targetName = '';
setModuleResearchTarget(profile, vehicleName, '');
}
if (!targetName && finishedModuleResearch(profile, vehicleName) === '' && vehicleExcessRp(profile, vehicleName) === 0) {
targetName = pickDefaultResearchableModule(equipment, state);
if (targetName) setModuleResearchTarget(profile, vehicleName, targetName);
}
if (!targetName) {
if (!hasUnresearchedModification(profile, vehicleName, equipment.modifications)) return undefined;
setVehicleExcessRp(profile, vehicleName, vehicleExcessRp(profile, vehicleName) + amount);
return { unit: vehicleName, rp: 0, excessRp: amount };
}
const modFacts = catalogue.modification(vehicleName, targetName);
if (!modFacts || modFacts.researchPoints <= 0) return undefined;
const before = moduleResearchPoints(profile, vehicleName, targetName);
const invested = Math.min(amount, Math.max(0, modFacts.researchPoints - before));
const leftover = amount - invested;
if (invested > 0) setModuleResearchPoints(profile, vehicleName, targetName, before + invested);
let bankedExcess = 0;
if (before + invested >= modFacts.researchPoints) {
setModuleResearchTarget(profile, vehicleName, '');
setFinishedModuleResearch(profile, vehicleName, targetName);
if (hasUnresearchedModification(profile, vehicleName, equipment.modifications)) {
if (leftover > 0) {
setVehicleExcessRp(profile, vehicleName, vehicleExcessRp(profile, vehicleName) + leftover);
bankedExcess = leftover;
}
} else {
setVehicleExcessRp(profile, vehicleName, 0);
}
}
return {
unit: vehicleName,
modification: targetName,
rp: invested,
...(bankedExcess > 0 ? { excessRp: bankedExcess } : {}),
};
}
function investIntoBranch(
profile: BlkBlock,
research: ResearchRules,
country: string,
branchType: string,
amount: number,
): EarnedRpItem | undefined {
if (amount <= 0) return undefined;
const targetName = researchTarget(profile, country, branchType);
const target = targetName ? research.techTree.vehicle(targetName) : undefined;
if (!target || target.researchPoints <= 0 || currentStatus(profile, research, target.name) !== VehicleStatus.CAN_RESEARCH) {
if (!hasUnresearchedBranchVehicle(profile, research, country, branchType)) return undefined;
setBranchExcessRp(profile, country, branchType, branchExcessRp(profile, country, branchType) + amount);
const labelUnit = finishedResearch(profile, country, branchType);
return labelUnit ? { unit: labelUnit, rp: 0, excessRp: amount } : undefined;
}
const before = researchPointsOf(profile, target.name);
const invested = Math.min(amount, Math.max(0, target.researchPoints - before));
const remaining = amount - invested;
if (invested > 0) addResearchPoints(profile, target, invested);
let bankedExcess = 0;
if (before + invested >= target.researchPoints) {
setResearchTarget(profile, country, branchType, '');
setFinishedResearch(profile, country, branchType, target.name);
if (hasUnresearchedBranchVehicle(profile, research, country, branchType)) {
if (remaining > 0) {
setBranchExcessRp(profile, country, branchType, branchExcessRp(profile, country, branchType) + remaining);
bankedExcess = remaining;
}
} else {
setBranchExcessRp(profile, country, branchType, 0);
}
}
return {
unit: target.name,
rp: invested,
...(bankedExcess > 0 ? { excessRp: bankedExcess } : {}),
};
}
function hasUnresearchedModification(
profile: BlkBlock,
vehicle: string,
modifications: readonly Parameters<typeof isModuleResearched>[2][],
): boolean {
return modifications.some((mod) => isResearchable(mod) && !isModuleResearched(profile, vehicle, mod));
}
function hasUnresearchedBranchVehicle(
profile: BlkBlock,
research: ResearchRules,
country: string,
branchType: string,
): boolean {
const owned = ownedVehicles(profile);
for (const vehicle of research.techTree.all()) {
if (vehicle.kind !== 'research' || vehicle.country !== country || vehicle.type !== branchType) continue;
if (!owned.has(vehicle.name) && researchPointsOf(profile, vehicle.name) < vehicle.researchPoints) return true;
}
return false;
}
function investAceCrewRp(
profile: BlkBlock,
catalogue: CrewSkillCatalogue,
country: string,
vehicleName: string,
amount: number,
): void {
const targetRp = catalogue.training(vehicleName)?.aceResearchPoints ?? 0;
if (targetRp <= 0) return;
const crew = crewForVehicleInCountry(profile, country, vehicleName);
if (crew && specializationOf(crew, vehicleName) === 1) {
addExpertToAceRp(crew, vehicleName, amount, targetRp);
}
}
function scaleRp(base: number, multiplier: number): number {
if (!Number.isFinite(base) || base <= 0) return 0;
return Math.min(0x7fffffff, Math.max(0, Math.round(base * multiplier)));
}
@@ -0,0 +1,105 @@
/**
* In-memory registry of battle sessions created by `match.enqueue` and settled once by
* `cln_wto_finish_battle`.
*
* Each session gets a non-zero positive 63-bit integer `roomId` formatted as a 16-character
* lowercase hexadecimal `sessionId`, matching `userlogs` `roomId:i64` (`aces.exe` `0x1799d30`).
*/
import { randomBytes } from 'node:crypto';
import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
export interface BattleSession {
readonly sessionId: string;
readonly roomId: bigint;
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly difficulty: ModeDifficulty;
readonly requiredClass: UnitClass;
readonly missionName: string;
readonly missionPath: string;
readonly missionLocName?: string;
readonly country: string;
readonly startedAtSec: number;
settled: boolean;
}
export interface NewBattleSession {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly difficulty: ModeDifficulty;
readonly requiredClass: UnitClass;
readonly missionName: string;
readonly missionPath: string;
readonly missionLocName?: string;
readonly country: string;
readonly startedAtSec: number;
}
export class BattleSessionStore {
readonly #sessions = new Map<string, BattleSession>();
readonly #pendingByUser = new Map<string, string>();
readonly #maxRetained: number;
constructor(maxRetained: number) {
this.#maxRetained = Math.max(1, maxRetained);
}
create(input: NewBattleSession): BattleSession {
const roomId = generateRoomId(this.#sessions);
const sessionId = roomId.toString(16).padStart(16, '0');
const session: BattleSession = { ...input, sessionId, roomId, settled: false };
this.#sessions.set(sessionId, session);
this.#pendingByUser.set(input.userId, sessionId);
this.#trim();
return session;
}
/** Cancel a queued session if the player leaves the queue before entering flight. */
cancelPendingForUser(userId: string): void {
this.#pendingByUser.delete(userId);
}
isPending(userId: string, sessionId: string): boolean {
return this.#pendingByUser.get(userId) === sessionId;
}
clearPending(userId: string, sessionId: string): void {
if (this.#pendingByUser.get(userId) === sessionId) {
this.#pendingByUser.delete(userId);
}
}
findForUser(sessionId: string, userId: string): BattleSession | undefined {
const session = this.#sessions.get(sessionId);
return session && session.userId === userId ? session : undefined;
}
markSettled(sessionId: string): void {
const session = this.#sessions.get(sessionId);
if (session) {
session.settled = true;
this.clearPending(session.userId, sessionId);
}
}
#trim(): void {
while (this.#sessions.size > this.#maxRetained) {
const oldestKey = this.#sessions.keys().next().value;
if (oldestKey === undefined) break;
this.#sessions.delete(oldestKey);
}
}
}
function generateRoomId(existing: ReadonlyMap<string, BattleSession>): bigint {
for (;;) {
const raw = randomBytes(8).readBigUInt64BE(0) & 0x7fffffffffffffffn;
const roomId = raw === 0n ? 1n : raw;
const hex = roomId.toString(16).padStart(16, '0');
if (!existing.has(hex)) return roomId;
}
}
@@ -0,0 +1,117 @@
/**
* Post-battle settlement rules (`cln_wto_finish_battle`):
* - Resolves battle win/loss (direct outcome when finished, weighted ticket + kill ratio on
* early leave).
* - Applies offline multipliers (`tuning/battle.jsonc`) to Silver Lions, Free RP, Modification
* RP, and Vehicle RP, runs `autoRefillWeapons` equipment top-ups, and appends the full
* `EULT_SESSION_RESULT` battle mail log.
*/
import type { BlkBlock } from '@wto/blk';
import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts';
import { stockAndRefillEquipment } from '../modifications/ammo-refill.ts';
import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts';
import { isAutoRefillWeaponsEnabled } from '../profile/profile-client-settings.ts';
import { addSilverLions, balanceOf, pay } from '../profile/profile-currency.ts';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { addFreeResearchPoints } from '../profile/profile-research-points.ts';
import type { ResearchRules } from '../research/research-rules.ts';
import type { BattleReport } from './battle-report.ts';
import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts';
import { collectEarnedBattleRp } from './battle-rp-investment.ts';
import type { BattleSession } from './battle-session-store.ts';
import type { BattleTuning } from './battle-tuning.ts';
export type { BattleOutcomeKind, BattleReport, VehicleBattleStats } from './battle-report.ts';
export interface BattleSettlementDeps {
readonly research: ResearchRules;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
readonly tuning: BattleTuning;
}
export function settleBattle(
profile: BlkBlock,
report: BattleReport,
session: BattleSession,
deps: BattleSettlementDeps,
): void {
const win = resolveWin(report, deps.tuning);
const slMul = deps.tuning.rewardMultiplierSilverLions;
const rpMul = deps.tuning.rewardMultiplierResearchPoints;
const earnedSilverLions = scaleNonNegative(report.wpTotal, slMul);
const friendlyFirePenalty = report.wpTeamKills !== 0
? -scaleNonNegative(Math.abs(report.wpTeamKills), slMul)
: 0;
const baseTotalRp = Math.max(
report.expTotal,
report.vehicles.reduce((sum, vehicle) => sum + Math.max(0, vehicle.expTotal), 0),
);
const earnedTotalRp = scaleNonNegative(baseTotalRp, rpMul);
const earnedFreeRp = scaleNonNegative(report.expFree > 0 ? report.expFree : baseTotalRp, rpMul);
applyNetSilverLions(profile, earnedSilverLions + friendlyFirePenalty);
if (earnedFreeRp > 0) addFreeResearchPoints(profile, earnedFreeRp);
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
const rpItems = collectEarnedBattleRp(profile, report, session, deps, rpMul, earnedTotalRp);
const country = report.country.startsWith('country_') ? report.country : session.country;
appendBattleResultLog(profile, session, {
win,
country,
wpEarned: earnedSilverLions,
xpEarned: earnedTotalRp,
activity: clampActivity(report.activity),
slMul,
rpMul,
weaponRefillSl,
friendlyFirePenalty,
report,
rpItems: mergeEarnedRpItems(rpItems),
});
}
function applyNetSilverLions(profile: BlkBlock, netDelta: number): void {
if (netDelta > 0) {
addSilverLions(profile, netDelta);
} else if (netDelta < 0) {
const deduction = Math.min(balanceOf(profile).silverLions, -netDelta);
if (deduction > 0) pay(profile, { silverLions: deduction, goldenEagles: 0 });
}
}
function refillOwnedEquipment(profile: BlkBlock, catalogue: EquipmentCatalogue): number {
if (!isAutoRefillWeaponsEnabled(profile)) return 0;
const owned = [...ownedVehicles(profile)].sort((a, b) => a.localeCompare(b));
let totalSpent = 0;
for (const vehicle of owned) {
const eq = catalogue.vehicle(vehicle);
if (eq) totalSpent += stockAndRefillEquipment(profile, eq, true).silverLionsSpent;
}
return totalSpent;
}
function resolveWin(report: BattleReport, tuning: BattleTuning): boolean {
if (report.outcome === 'win') return true;
if (report.outcome === 'lose') return false;
const isTeamB = report.localTeam === 2;
const myTickets = Math.max(0, isTeamB ? report.teamBScore : report.teamAScore);
const enemyTickets = Math.max(0, isTeamB ? report.teamAScore : report.teamBScore);
const myKills = Math.max(0, isTeamB ? report.teamBKills : report.teamAKills);
const enemyKills = Math.max(0, isTeamB ? report.teamAKills : report.teamBKills);
const ticketShare = myTickets + enemyTickets > 0 ? myTickets / (myTickets + enemyTickets) : 0.5;
const killShare = myKills + enemyKills > 0 ? myKills / (myKills + enemyKills) : 0.5;
const totalWeight = tuning.earlyLeaveTicketWeight + tuning.earlyLeaveKillWeight;
return (ticketShare * tuning.earlyLeaveTicketWeight + killShare * tuning.earlyLeaveKillWeight) / totalWeight >= 0.5;
}
function scaleNonNegative(base: number, multiplier: number): number {
if (!Number.isFinite(base) || base <= 0) return 0;
return Math.min(0x7fffffff, Math.max(0, Math.round(base * multiplier)));
}
function clampActivity(activity: number): number {
if (!Number.isFinite(activity)) return 0;
return Math.min(1, Math.max(0, activity));
}
@@ -0,0 +1,73 @@
/**
* Typed reader for `tuning/battle.jsonc`: offline Silver Lions and Research Points
* multipliers, LocalMP slot and bot counts, matchmaking BR window, coalition pairing
* rules, and early-leave win-inference weights.
*/
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
export interface BattleTuning {
readonly rewardMultiplierSilverLions: number;
readonly rewardMultiplierResearchPoints: number;
readonly maxPlayers: number;
readonly maxBots: number;
readonly smallTeamsMaxPlayers: number;
readonly subModeChance: number;
readonly brSpreadMrank: number;
readonly botPoolLimitPerType: number;
readonly rbCoalitionMinCountries: number;
readonly rbCoalitionMaxCountries: number;
readonly rbGroundMixedChance: number;
readonly rbAirMixedChance: number;
readonly rbNavalMixedChance: number;
readonly simColdWarMinMrank: number;
readonly tankBotRespawns: number;
readonly airBotRespawns: number;
readonly earlyLeaveTicketWeight: number;
readonly earlyLeaveKillWeight: number;
}
export function readBattleTuning(reader: TuningReader): BattleTuning {
const maxPlayers = reader.int('maxPlayers', { min: 2, max: 64 });
const maxBots = reader.int('maxBots', { min: 1, max: 63 });
if (maxBots >= maxPlayers) {
throw new TuningError(`tuning file battle.jsonc: maxBots (${maxBots}) must be less than maxPlayers (${maxPlayers})`);
}
const smallTeamsMaxPlayers = reader.int('smallTeamsMaxPlayers', { min: 2, max: 64 });
if (smallTeamsMaxPlayers > maxPlayers) {
throw new TuningError(
`tuning file battle.jsonc: smallTeamsMaxPlayers (${smallTeamsMaxPlayers}) must not exceed maxPlayers (${maxPlayers})`,
);
}
const rbCoalitionMinCountries = reader.int('rbCoalitionMinCountries', { min: 1, max: 10 });
const rbCoalitionMaxCountries = reader.int('rbCoalitionMaxCountries', { min: 1, max: 10 });
if (rbCoalitionMaxCountries < rbCoalitionMinCountries) {
throw new TuningError(
`tuning file battle.jsonc: rbCoalitionMaxCountries (${rbCoalitionMaxCountries}) must be at least rbCoalitionMinCountries (${rbCoalitionMinCountries})`,
);
}
const earlyLeaveTicketWeight = reader.number('earlyLeaveTicketWeight', { min: 0, max: 1 });
const earlyLeaveKillWeight = reader.number('earlyLeaveKillWeight', { min: 0, max: 1 });
if (earlyLeaveTicketWeight + earlyLeaveKillWeight <= 0) {
throw new TuningError('tuning file battle.jsonc: earlyLeaveTicketWeight + earlyLeaveKillWeight must be positive');
}
return {
rewardMultiplierSilverLions: reader.number('rewardMultiplierSilverLions', { min: 0, max: 100 }),
rewardMultiplierResearchPoints: reader.number('rewardMultiplierResearchPoints', { min: 0, max: 100 }),
maxPlayers,
maxBots,
smallTeamsMaxPlayers,
subModeChance: reader.number('subModeChance', { min: 0, max: 1 }),
brSpreadMrank: reader.int('brSpreadMrank', { min: 0, max: 12 }),
botPoolLimitPerType: reader.int('botPoolLimitPerType', { min: 4, max: 200 }),
rbCoalitionMinCountries,
rbCoalitionMaxCountries,
rbGroundMixedChance: reader.number('rbGroundMixedChance', { min: 0, max: 1 }),
rbAirMixedChance: reader.number('rbAirMixedChance', { min: 0, max: 1 }),
rbNavalMixedChance: reader.number('rbNavalMixedChance', { min: 0, max: 1 }),
simColdWarMinMrank: reader.int('simColdWarMinMrank', { min: 0, max: 40 }),
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
earlyLeaveTicketWeight,
earlyLeaveKillWeight,
};
}
@@ -1,4 +1,4 @@
/** Char action names mapped to their handlers (full list of names: research-data/char_actions_37.json). */
/** Char action names mapped to their protocol handlers. */
import type { AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
@@ -66,11 +66,13 @@ import { entitlementsFull, initialMeta, legacyUserData } from './online-init-act
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
import { priceEx } from './price-actions.ts';
import { buyAircraft, buySlot } from './purchase-actions.ts';
import { convertExp, resetResearchable, setResearchable } from './research-actions.ts';
import { convertExp, moveExpToModuleAction, moveExpToUnitAction, resetResearchable, setResearchable } from './research-actions.ts';
import { buyNotResearchedClanUnitAction, flushClanExpToUnitAction, setResearchClanUnitAction } from './squadron-research-actions.ts';
import { setStartingInfo } from './starting-info-actions.ts';
import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts';
import { buyUnlockAction } from './unlock-actions.ts';
import { finishBattleAction, type BattleActionDependencies } from './battle-actions.ts';
import { hangarMiscActionEntries } from './hangar-misc-actions.ts';
export interface ClanActionDependencies {
readonly store: ClanStore;
@@ -91,14 +93,17 @@ export interface ActionDependencies {
readonly trophies: TrophyCatalogue;
readonly clans?: ClanActionDependencies;
readonly cloudSettings?: CloudSettingsStore;
readonly battle?: BattleActionDependencies;
readonly notifyInventoryChanged?: () => void;
}
export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharActionHandler> {
const entries: Array<[string, CharActionHandler]> = [
...coreActionEntries(deps),
...hangarMiscActionEntries(deps),
...(deps.clans ? clanActionEntries(deps, deps.clans) : []),
...(deps.cloudSettings ? cloudActionEntries(deps.accounts, deps.cloudSettings) : []),
...(deps.battle ? [['cln_wto_finish_battle', finishBattleAction(deps, deps.battle)] as [string, CharActionHandler]] : []),
];
return new Map<string, CharActionHandler>(entries);
}
@@ -118,6 +123,8 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
['cln_set_researchable', setResearchable(deps.profiles, deps.accounts, deps.research, deps.equipment)],
['cln_reset_researchable', resetResearchable(deps.profiles, deps.accounts, deps.research)],
['cln_convert_exp', convertExp(deps.profiles, deps.accounts, deps.research)],
['cln_move_exp_to_unit', moveExpToUnitAction(deps.profiles, deps.accounts, deps.research)],
['cln_move_exp_to_module', moveExpToModuleAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_aircraft', buyAircraft(deps.profiles, deps.accounts, deps.research)],
['cln_buy_slot', buySlot(deps.profiles, deps.accounts, deps.research)],
['cln_get_price_ex', priceEx({ techTree, equipment: deps.equipment, decor: deps.decor, crew: deps.crew, unlocks: deps.unlocks, items: deps.items, trophies: deps.trophies })],
@@ -0,0 +1,53 @@
/**
* Char action `cln_wto_finish_battle`: receives the client's local-battle debriefing stats
* (`stat_get_exp()`), settles Silver Lions, Research Points, equipment refills, and
* `EULT_SESSION_RESULT` into the player's save, and answers the updated profile.
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
import type { BattleTuning } from '../../battle/battle-tuning.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
export interface BattleActionDependencies {
readonly sessions: BattleSessionStore;
readonly tuning: BattleTuning;
}
export interface FinishBattleContext {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
}
export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler {
const settlementDeps: BattleSettlementDeps = {
research: ctx.research,
equipment: ctx.equipment,
crew: ctx.crew,
tuning: battle.tuning,
};
return (context) => withAccount(context, ctx.accounts, (account) => {
const report = context.payload && parseBattleReport(context.payload);
if (!report) return { kind: 'error', code: 'BAD_PARAMS' };
const session = battle.sessions.findForUser(report.sessionId, account.userId);
if (!session) return { kind: 'error', code: 'BAD_PARAMS' };
if (session.settled) {
return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) };
}
const updated = ctx.profiles.update(account.userId, (profile) => {
settleBattle(profile, report, session, settlementDeps);
});
battle.sessions.markSettled(session.sessionId);
return { kind: 'data', blk: clientProfile(updated, account) };
});
}
@@ -0,0 +1,232 @@
/**
* Miscellaneous hangar char actions that mutate the player's profile and return the full
* updated clientProfile:
* - GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.37 0xeb5f60, profile mask
* 0x301800822fbf at 0xeb61c4) applies both job type 13 (char_send_blk, 0x2991f0) and job
* type 7 (shop_repair_all 0x29a370 / shop_repair_aircraft 0x29a610) as full profile updates.
*
* Covered actions:
* - cln_set_dest_rp_unit_type (scripts/shop/shop.nut:2353, job type 13)
* - cln_unlock_crew (scripts/crew/crewActions.nut:18, job type 13)
* - cln_prepare_aircraft (scripts/unit/unitActions.nut:147 job 13; 0x29a610 job 7)
* - cln_repair_all (shop_repair_all 0x29a370, job type 7)
* - cln_repair_all_in_slots (shop_repair_all 0x29a370, job type 7)
* - cln_add_to_wish_list (scripts/wishlist/wishlistManager.nut:39, job type 13)
* - cln_remove_from_wish_list (scripts/wishlist/wishlistManager.nut:48, job type 13)
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { int64Field, removeParam } from '../../profile/blk-fields.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { allCrews, crewOf, crewVehiclesOfCountry } from '../../profile/profile-crews.ts';
import { canAfford, pay } from '../../profile/profile-currency.ts';
import { applySetDestinationRpRule } from '../../profile/profile-dest-rp.ts';
import { ownsVehicle } from '../../profile/profile-hangar.ts';
import {
addWishlistUnit,
DEFAULT_WISHLIST_LIMITS,
removeWishlistUnit,
type WishlistLimits,
} from '../../profile/profile-wishlist.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../../profile/server-time.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../../research/rule-outcome.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { CharActionContext, CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import {
headerOrPayloadBool,
headerOrPayloadInt,
headerOrPayloadString,
realParam,
} from './payload-params.ts';
export type ActionEntry = [string, CharActionHandler];
export interface HangarMiscActionDependencies {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly wishlistLimits?: WishlistLimits;
}
const HANGAR_BLOCK = 'hangar';
const ALL_COUNTRIES = 'all';
const WISHLIST_UNIT_TYPE = 'unit';
const FULL_VEHICLE_HP = 1.0;
export function hangarMiscActionEntries(deps: HangarMiscActionDependencies): ActionEntry[] {
const { profiles, accounts, research } = deps;
const { techTree } = research;
const limits = deps.wishlistLimits ?? DEFAULT_WISHLIST_LIMITS;
return [
['cln_set_dest_rp_unit_type', setDestRpUnitTypeAction(profiles, accounts, techTree)],
['cln_unlock_crew', unlockCrewAction(profiles, accounts)],
['cln_prepare_aircraft', prepareAircraftAction(profiles, accounts)],
['cln_repair_all', repairVehiclesAction(profiles, accounts, techTree, false)],
['cln_repair_all_in_slots', repairVehiclesAction(profiles, accounts, techTree, true)],
['cln_add_to_wish_list', addToWishlistAction(profiles, accounts, techTree, limits)],
['cln_remove_from_wish_list', removeFromWishlistAction(profiles, accounts)],
];
}
function runProfileRule(
context: CharActionContext,
profiles: PlayerProfiles,
accounts: AccountStore,
rule: (profile: BlkBlock) => RuleOutcome,
) {
return withAccount(context, accounts, (account) => {
let outcome: RuleOutcome = refused('BAD_PARAMS');
const updated = profiles.updateWhen(account.userId, (saved) => {
outcome = rule(saved);
return outcome.ok;
});
if (updated) return { kind: 'data', blk: clientProfile(updated, account) };
return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
});
}
function setDestRpUnitTypeAction(profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree): CharActionHandler {
return (context) => {
const country = headerOrPayloadString(context, 'country');
const srcType = headerOrPayloadInt(context, 'srcType');
const destType = headerOrPayloadInt(context, 'destType');
if (!country || srcType === undefined || destType === undefined) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) =>
applySetDestinationRpRule(saved, techTree, country, srcType, destType));
};
}
function unlockCrewAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => {
const crewId = headerOrPayloadInt(context, 'crew');
const byGold = headerOrPayloadBool(context, 'gold') ?? false;
const cost = headerOrPayloadInt(context, 'cost') ?? 0;
const costGold = headerOrPayloadInt(context, 'costGold') ?? 0;
if (crewId === undefined || crewId < 0 || cost < 0 || costGold < 0) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
const crew = crewOf(saved, crewId);
if (!crew) return refused('BAD_PARAMS');
const nowSec = BigInt(serverTimeToUnixSeconds(serverTimeNow()));
const lockedTill = int64Field(crew, 'lockedTill', 0n);
if (lockedTill > nowSec) {
const price = { silverLions: byGold ? 0 : cost, goldenEagles: byGold ? costGold : 0 };
if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY');
pay(saved, price);
}
// Crew lock state in profile.blk (aces.exe 0x8fa632, 0x93ae07..0x93ae1b): lockedTill:i64, lockedRoomId:i64.
removeParam(crew, 'lockedTill');
removeParam(crew, 'lockedRoomId');
return ACCEPTED;
});
};
}
function prepareAircraftAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => {
const unit = headerOrPayloadString(context, 'name') ?? headerOrPayloadString(context, 'aircraft');
const cost = headerOrPayloadInt(context, 'cost') ?? 0;
const costGold = headerOrPayloadInt(context, 'costGold') ?? 0;
if (!unit || cost < 0 || costGold < 0) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
if (!ownsVehicle(saved, unit)) return refused('NOT_AVAILABLE');
const hangar = findBlock(saved, HANGAR_BLOCK);
const unitBlock = hangar && findBlock(hangar, unit);
if (unitBlock && isDamagedVehicleBlock(unitBlock) && (cost > 0 || costGold > 0)) {
const price = { silverLions: cost, goldenEagles: costGold };
if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY');
pay(saved, price);
}
if (unitBlock) clearVehicleDamage(unitBlock);
return ACCEPTED;
});
};
}
function repairVehiclesAction(
profiles: PlayerProfiles,
accounts: AccountStore,
techTree: TechTree,
inSlotsOnly: boolean,
): CharActionHandler {
return (context) => {
const rawCountry = headerOrPayloadString(context, 'country');
const country = rawCountry && rawCountry.length > 0 ? rawCountry : ALL_COUNTRIES;
if (country !== ALL_COUNTRIES && !techTree.hasCountry(country)) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
const hangar = findBlock(saved, HANGAR_BLOCK);
if (!hangar) return ACCEPTED;
const targets = collectRepairTargetUnits(saved, hangar, techTree, country, inSlotsOnly);
for (const unitBlock of hangar.blocks) {
if (targets.has(unitBlock.name)) clearVehicleDamage(unitBlock);
}
return ACCEPTED;
});
};
}
function collectRepairTargetUnits(
profile: BlkBlock,
hangar: BlkBlock,
techTree: TechTree,
country: string,
inSlotsOnly: boolean,
): Set<string> {
if (inSlotsOnly) {
if (country !== ALL_COUNTRIES) return new Set(crewVehiclesOfCountry(profile, country));
const slotted = new Set<string>();
for (const crew of allCrews(profile)) {
const current = findBlock(crew, 'aircrafts')?.params.find((param) => param.name === 'current')?.value;
if (current?.type === 'string' && current.value.length > 0) slotted.add(current.value);
}
return slotted;
}
if (country === ALL_COUNTRIES) return new Set(hangar.blocks.map((entry) => entry.name));
return new Set(
hangar.blocks
.filter((entry) => techTree.vehicle(entry.name)?.country === country)
.map((entry) => entry.name),
);
}
/** AircraftInfo::serialize (aces.exe 0x94061f..0x940abc): hp:r (default 1.0f) and time:i64. */
function isDamagedVehicleBlock(unitBlock: BlkBlock): boolean {
const hp = realParam(unitBlock, 'hp');
return hp !== undefined && hp < FULL_VEHICLE_HP;
}
function clearVehicleDamage(unitBlock: BlkBlock): void {
removeParam(unitBlock, 'hp');
removeParam(unitBlock, 'time');
}
function addToWishlistAction(
profiles: PlayerProfiles,
accounts: AccountStore,
techTree: TechTree,
limits: WishlistLimits,
): CharActionHandler {
return (context) => {
const itemType = headerOrPayloadString(context, 'type') ?? WISHLIST_UNIT_TYPE;
const unit = headerOrPayloadString(context, 'unit');
const comment = headerOrPayloadString(context, 'comment') ?? '';
if (itemType !== WISHLIST_UNIT_TYPE || !unit) return { kind: 'error', code: 'BAD_PARAMS' };
const nowSec = serverTimeToUnixSeconds(serverTimeNow());
return runProfileRule(context, profiles, accounts, (saved) =>
addWishlistUnit(saved, techTree, unit, comment, nowSec, limits));
};
}
function removeFromWishlistAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => {
const itemType = headerOrPayloadString(context, 'type') ?? WISHLIST_UNIT_TYPE;
const unit = headerOrPayloadString(context, 'unit');
if (itemType !== WISHLIST_UNIT_TYPE || !unit) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => removeWishlistUnit(saved, unit));
};
}
@@ -12,6 +12,14 @@ export function intParam(payload: BlkBlock, name: string): number | undefined {
return param?.type === 'int' ? param.value : undefined;
}
export function realParam(payload: BlkBlock, name: string): number | undefined {
const param = findParam(payload, name)?.value;
if (param?.type === 'real' || param?.type === 'int') {
return Number.isFinite(param.value) ? param.value : undefined;
}
return undefined;
}
export function boolParam(payload: BlkBlock, name: string): boolean | undefined {
const param = findParam(payload, name)?.value;
return param?.type === 'bool' ? param.value : undefined;
@@ -1,6 +1,5 @@
/**
* The price table the char server sends for cln_get_price_ex (implementation notes,
* implementation notes).
* The price table the char server sends for cln_get_price_ex.
*
* The client keeps the answer whole as its price table (aces.exe 2.61.0.37 0xeb7a88, job type
* 0x21; stored in the save-data object at +0x3f5c0, which warpoints::init makes the price
@@ -16,6 +15,7 @@
* mods{ <modification>{ cost:i costGold:i openCostGold:i } }
* weapons{ <preset>{ cost:i costGold:i } }
* spare{ cost:i costGold:i }
* specialization{ spec_expert{ cost:i } spec_ace{ costGold:i } }
* }
* }
* skins{ "<vehicle>/<skin>"{ cost:i costGold:i } } decorations (get_skin_cost_*, 0x17a8910...)
@@ -24,7 +24,7 @@
* skills{ <pack>{ costGold:i } } skill point packs (0x916380)
* unlocks{ <unlock>{ cost:i costGold:i } } unlocks for sale (0x9170c0)
* items{ <item>{ cost:i costGold:i } } classic items for sale, price per piece
* (wp_get_item_cost, 0x10531e0; implementation notes)
* (wp_get_item_cost, 0x10531e0)
* trophy{ <id>{ cost:i costGold:i } } classic trophy prices
* }
* trophy{ <id>{ ... } } classic trophy definitions & drop weights
@@ -32,8 +32,8 @@
* Every entry is read as cost:i (silver lions), costGold:i (golden eagles), discount:i (percent
* off, not sent: no discounts), each 0 when missing (so zero prices are left out); openCostGold
* is the outright price of a modification before research progress (0xec0910). Anything the
* lookup does not find costs 0 for the client, which then offers it at 0 (lab round 20). The
* prices are config/wpcost.blk value and costGold (decorations: config/skins.blk, decals.blk,
* lookup does not find costs 0 for the client, which then offers it at 0. The prices are
* config/wpcost.blk value and costGold (decorations: config/skins.blk, decals.blk,
* attachable.blk; unlocks: config/unlocks.blk), the same the purchase rules charge.
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
@@ -67,7 +67,7 @@ export function priceTable(sources: PriceTableSources): BlkBlock {
name: COMMON_SECTION,
params: [],
blocks: [
vehicleSection(sources.techTree, sources.equipment),
vehicleSection(sources.techTree, sources.equipment, sources.crew),
...decorSections(sources.decor),
skillPackSection(sources.crew),
unlockSection(sources.unlocks),
@@ -80,7 +80,7 @@ export function priceTable(sources: PriceTableSources): BlkBlock {
};
}
function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue): BlkBlock {
function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue, crew: CrewSkillCatalogue): BlkBlock {
const vehicles: BlkBlock[] = [];
for (const vehicle of techTree.all()) {
const entry: BlkBlock = { name: vehicle.name, params: priceParams(vehicle.silverLions, vehicle.goldenEagles), blocks: [] };
@@ -97,6 +97,13 @@ function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue): BlkB
if (weapons.length) entry.blocks.push({ name: 'weapons', params: [], blocks: weapons });
if (fitted.spare) entry.blocks.push({ name: 'spare', params: priceParams(fitted.spare.silverLions, fitted.spare.goldenEagles), blocks: [] });
}
const training = crew.training(vehicle.name);
if (training && (training.expert > 0 || training.aceGoldenEagles > 0)) {
const specBlocks: BlkBlock[] = [];
if (training.expert > 0) specBlocks.push({ name: 'spec_expert', params: priceParams(training.expert, 0), blocks: [] });
if (training.aceGoldenEagles > 0) specBlocks.push({ name: 'spec_ace', params: priceParams(0, training.aceGoldenEagles), blocks: [] });
entry.blocks.push({ name: 'specialization', params: [], blocks: specBlocks });
}
if (entry.blocks.length || vehicle.silverLions > 0 || vehicle.goldenEagles > 0) vehicles.push(entry);
}
return { name: 'aircrafts', params: [], blocks: vehicles };
@@ -1,25 +1,18 @@
/**
* Research actions. All are sent with char_send_blk (job type 13),
* so the client applies each answer as a profile update and each answers the whole profile.
* Vehicle and modification research char actions. Sent via `char_send_blk` (job type 13),
* each updates the profile and answers the updated client profile:
*
* cln_set_researchable (shop_set_researchable_unit, aces.exe 2.61.0.37 0x17a3e80):
* unit:t the vehicle to research
* type:i its vehicle type number
* or, for a modification (shop_set_researchable_unit_module, 0x17a3e00; implementation notes):
* unit:t the owned vehicle
* mod:t the modification to research
* cln_reset_researchable (shop_reset_researchable_unit, 0x17a3f00): the player closed the
* "research finished" prompt without choosing.
* country:t, type:i
* cln_convert_exp (shop_convert_free_exp_for_unit, 0x17a4ec0): free research points into a
* vehicle, paid with golden eagles.
* unit:t, amount:i research points
* - `cln_set_researchable` (`shop_set_researchable_unit` `0x17a3e80` /
* `shop_set_researchable_unit_module` `0x17a3e00`): `unit:t, type:i` or `unit:t, mod:t`.
* - `cln_reset_researchable` (`shop_reset_researchable_unit` `0x17a3f00`): `country:t, type:i`.
* - `cln_convert_exp` (`shop_convert_free_exp_for_unit` `0x17a4ec0`): `unit:t, amount:i`.
* - `cln_move_exp_to_unit` / `cln_move_exp_to_module`: spend banked excess RP.
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { chooseModuleResearch } from '../../modifications/module-research-target.ts';
import { chooseModuleResearch, moveExcessExpToModule } from '../../modifications/module-research-target.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { chooseResearchTarget, convertFreeResearchPoints, dismissFinishedResearch } from '../../research/research-progress.ts';
import { chooseResearchTarget, convertFreeResearchPoints, dismissFinishedResearch, moveExcessExpToUnit } from '../../research/research-progress.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
@@ -58,3 +51,24 @@ export function convertExp(profiles: PlayerProfiles, accounts: AccountStore, rul
return (profile) => convertFreeResearchPoints(profile, rules, vehicle, amount);
});
}
export function moveExpToUnitAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
if (vehicle === undefined) return undefined;
return (profile) => moveExcessExpToUnit(profile, rules, vehicle);
});
}
export function moveExpToModuleAction(
profiles: PlayerProfiles,
accounts: AccountStore,
equipment: EquipmentCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const modification = stringParam(payload, 'mod');
if (vehicle === undefined || modification === undefined) return undefined;
return (profile) => moveExcessExpToModule(profile, equipment, vehicle, modification);
});
}
@@ -0,0 +1,88 @@
/**
* RFC 1459 + Gaijin IRC wire parser and line formatters used by the local chat server.
*/
export const IRC_SERVER_HOST = 'wt.local';
export interface IrcCommand {
readonly verb: string;
readonly params: readonly string[];
}
const HANDSHAKE_PREFIX = /^(?:PASS |NICK |USER |CAP |PING |QUIT(?: |\r|\n|$))/i;
export function startsIrcHandshake(firstChunk: Buffer): boolean {
if (firstChunk.length < 4) return false;
const head = firstChunk.subarray(0, Math.min(firstChunk.length, 16)).toString('latin1');
return HANDSHAKE_PREFIX.test(head);
}
export function parseIrcLine(rawLine: string): IrcCommand | undefined {
let rest = rawLine.replace(/[\r\n]+$/, '');
if (rest.length === 0) return undefined;
if (rest.startsWith(':')) {
const space = rest.indexOf(' ');
if (space < 0) return undefined;
rest = rest.slice(space + 1).trimStart();
}
if (rest.length === 0) return undefined;
const verbEnd = rest.indexOf(' ');
if (verbEnd < 0) {
return { verb: rest.toUpperCase(), params: [] };
}
const verb = rest.slice(0, verbEnd).toUpperCase();
let cursor = rest.slice(verbEnd + 1);
const params: string[] = [];
while (cursor.length > 0) {
while (cursor.startsWith(' ')) cursor = cursor.slice(1);
if (cursor.length === 0) break;
if (cursor.startsWith(':')) {
params.push(cursor.slice(1));
break;
}
const nextSpace = cursor.indexOf(' ');
if (nextSpace < 0) {
params.push(cursor);
break;
}
params.push(cursor.slice(0, nextSpace));
cursor = cursor.slice(nextSpace + 1);
}
return { verb, params };
}
export function formatServerNumeric(code: string, nick: string, params: readonly string[], trailing?: string): string {
const target = sanitizeToken(nick || '*');
const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : '';
const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : '';
return `:${IRC_SERVER_HOST} ${code} ${target}${middle}${suffix}\r\n`;
}
export function formatServerCommand(verb: string, params: readonly string[], trailing?: string): string {
const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : '';
const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : '';
return `:${IRC_SERVER_HOST} ${verb}${middle}${suffix}\r\n`;
}
export function formatUserEvent(nick: string, user: string, verb: string, params: readonly string[], trailing?: string): string {
const safeNick = sanitizeToken(nick || 'Player');
const safeUser = sanitizeToken(user || '0');
const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : '';
const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : '';
return `:${safeNick}!${safeUser}@127.0.0.1 ${verb}${middle}${suffix}\r\n`;
}
export function sanitizeChannelName(raw: string): string {
const trimmed = sanitizeToken(raw);
if (trimmed.length === 0) return '#general';
return trimmed.startsWith('#') || trimmed.startsWith('&') ? trimmed : `#${trimmed}`;
}
function sanitizeToken(text: string): string {
return text.replace(/[\r\n\0 ]+/g, '');
}
function sanitizeTrailing(text: string): string {
return text.replace(/[\r\n\0]+/g, ' ');
}
@@ -0,0 +1,284 @@
/**
* In-process RFC 1459 + Gaijin IRC chat server (`IRCClient` in `aces.exe` 0x133c5e0).
*
* Serves hangar general rooms, custom player rooms, discussion threads (`XTJOIN` / `XTMETA`),
* private messages, and session presence so `gchat_is_connected()` and `gchat_is_enabled()`
* evaluate `true` natively in both hangar and battle.
*/
import type { Duplex } from 'node:stream';
import {
formatServerCommand,
formatServerNumeric,
formatUserEvent,
IRC_SERVER_HOST,
parseIrcLine,
sanitizeChannelName,
type IrcCommand,
} from './irc-protocol.ts';
interface IrcSession {
readonly socket: Duplex;
nick: string;
user: string;
realName: string;
registered: boolean;
buffer: string;
readonly channels: Set<string>;
}
interface IrcChannel {
readonly name: string;
topic: string;
readonly members: Set<IrcSession>;
}
const MAX_BUFFER_CHARS = 65_536;
export class IrcServer {
readonly #sessions = new Set<IrcSession>();
readonly #channels = new Map<string, IrcChannel>();
#nextThreadId = 1;
accept(socket: Duplex): void {
const session: IrcSession = {
socket, nick: '', user: '', realName: '', registered: false, buffer: '', channels: new Set(),
};
this.#sessions.add(session);
socket.on('data', (chunk: Buffer | string) => {
session.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
if (session.buffer.length > MAX_BUFFER_CHARS) {
socket.destroy();
return;
}
let nl = session.buffer.indexOf('\n');
while (nl >= 0) {
const rawLine = session.buffer.slice(0, nl);
session.buffer = session.buffer.slice(nl + 1);
const cmd = parseIrcLine(rawLine);
if (cmd) this.#handleCommand(session, cmd);
nl = session.buffer.indexOf('\n');
}
});
socket.once('close', () => this.#removeSession(session, 'Client disconnected'));
socket.once('error', () => socket.destroy());
}
#handleCommand(session: IrcSession, cmd: IrcCommand): void {
const [p0 = '', p1 = ''] = cmd.params;
switch (cmd.verb) {
case 'CAP': if (p0.toUpperCase() === 'LS') this.#send(session, formatServerCommand('CAP', ['*', 'LS'], '')); return;
case 'PASS':
case 'PONG': return;
case 'NICK': this.#handleNick(session, p0); return;
case 'USER':
session.user = p0 || '0';
session.realName = cmd.params[3] ?? session.user;
this.#tryCompleteRegistration(session);
return;
case 'PING': this.#send(session, formatServerCommand('PONG', [IRC_SERVER_HOST], p0 || IRC_SERVER_HOST)); return;
case 'JOIN': this.#handleJoin(session, p0); return;
case 'PART': this.#handlePart(session, p0, p1); return;
case 'PRIVMSG':
case 'NOTICE': this.#handleMessage(session, cmd.verb, p0, p1); return;
case 'NAMES': this.#sendNames(session, sanitizeChannelName(p0 || '#general')); return;
case 'LIST': this.#handleList(session); return;
case 'TOPIC': this.#handleTopic(session, cmd.params); return;
case 'MODE': this.#handleMode(session, p0); return;
case 'WHO': this.#handleWho(session, p0); return;
case 'WHOIS': this.#handleWhois(session, p0); return;
case 'XTJOIN': this.#handleXtJoin(session, cmd.params); return;
case 'XTMETA': this.#handleXtMeta(session, cmd.params); return;
case 'QUIT':
this.#removeSession(session, p0 || 'Quit');
session.socket.end();
return;
default: return;
}
}
#handleNick(session: IrcSession, rawNick: string): void {
const nextNick = rawNick.trim() || `Player${this.#sessions.size}`;
const prevNick = session.nick;
session.nick = nextNick;
if (session.registered && prevNick && prevNick !== nextNick) {
this.#send(session, formatUserEvent(prevNick, session.user, 'NICK', [], nextNick));
return;
}
this.#tryCompleteRegistration(session);
}
#tryCompleteRegistration(session: IrcSession): void {
if (session.registered || !session.nick || !session.user) return;
session.registered = true;
const { nick, user } = session;
this.#send(session, formatServerNumeric('001', nick, [], `Welcome to the War Thunder Local Chat Network ${nick}!${user}@127.0.0.1`));
this.#send(session, formatServerNumeric('002', nick, [], `Your host is ${IRC_SERVER_HOST}, running version 1.0`));
this.#send(session, formatServerNumeric('003', nick, [], 'This server was created locally'));
this.#send(session, formatServerNumeric('004', nick, [IRC_SERVER_HOST, '1.0', 'iow', 'ntov']));
this.#send(session, formatServerNumeric('375', nick, [], `- ${IRC_SERVER_HOST} Message of the Day -`));
this.#send(session, formatServerNumeric('372', nick, [], '- Local offline chat service active'));
this.#send(session, formatServerNumeric('376', nick, [], 'End of /MOTD command.'));
}
#handleJoin(session: IrcSession, rawTargets: string): void {
if (!rawTargets) return;
if (rawTargets === '0') {
for (const chan of [...session.channels]) this.#partOne(session, chan, '');
return;
}
for (const raw of rawTargets.split(',')) {
if (!raw.trim()) continue;
this.#joinChannel(session, sanitizeChannelName(raw), '');
}
}
#joinChannel(session: IrcSession, channelName: string, initialTopic: string): void {
let channel = this.#channels.get(channelName);
if (!channel) {
channel = { name: channelName, topic: initialTopic, members: new Set() };
this.#channels.set(channelName, channel);
} else if (initialTopic && !channel.topic) {
channel.topic = initialTopic;
}
channel.members.add(session);
session.channels.add(channelName);
const joinLine = formatUserEvent(session.nick, session.user, 'JOIN', [], channelName);
for (const member of channel.members) this.#send(member, joinLine);
if (channel.topic) {
this.#send(session, formatServerNumeric('332', session.nick, [channelName], channel.topic));
} else {
this.#send(session, formatServerNumeric('331', session.nick, [channelName], 'No topic is set'));
}
this.#sendNames(session, channelName);
}
#handlePart(session: IrcSession, rawTargets: string, reason: string): void {
for (const raw of rawTargets.split(',')) {
if (!raw.trim()) continue;
this.#partOne(session, sanitizeChannelName(raw), reason);
}
}
#partOne(session: IrcSession, channelName: string, reason: string): void {
const channel = this.#channels.get(channelName);
if (!channel || !channel.members.has(session)) return;
const partLine = formatUserEvent(session.nick, session.user, 'PART', [channelName], reason || undefined);
for (const member of channel.members) this.#send(member, partLine);
channel.members.delete(session);
session.channels.delete(channelName);
if (channel.members.size === 0) this.#channels.delete(channelName);
}
#handleMessage(session: IrcSession, verb: 'PRIVMSG' | 'NOTICE', target: string, text: string): void {
if (!target) return;
if (target.startsWith('#') || target.startsWith('&')) {
const channel = this.#channels.get(sanitizeChannelName(target));
if (!channel) {
if (verb === 'PRIVMSG') this.#send(session, formatServerNumeric('403', session.nick, [target], 'No such channel'));
return;
}
const line = formatUserEvent(session.nick, session.user, verb, [channel.name], text);
for (const member of channel.members) {
if (member !== session) this.#send(member, line);
}
return;
}
const recipient = [...this.#sessions].find((peer) => peer.registered && peer.nick === target);
if (!recipient) {
if (verb === 'PRIVMSG') this.#send(session, formatServerNumeric('401', session.nick, [target], 'No such nick/channel'));
return;
}
this.#send(recipient, formatUserEvent(session.nick, session.user, verb, [recipient.nick], text));
}
#sendNames(session: IrcSession, channelName: string): void {
const channel = this.#channels.get(channelName);
const nicks = channel ? [...channel.members].map((m) => m.nick).filter(Boolean).join(' ') : session.nick;
this.#send(session, formatServerNumeric('353', session.nick, ['=', channelName], nicks));
this.#send(session, formatServerNumeric('366', session.nick, [channelName], 'End of /NAMES list.'));
}
#handleList(session: IrcSession): void {
this.#send(session, formatServerNumeric('321', session.nick, ['Channel'], 'Users Name'));
for (const channel of this.#channels.values()) {
if (channel.name === '#___empty___') continue;
this.#send(session, formatServerNumeric('322', session.nick, [channel.name, String(channel.members.size)], channel.topic));
}
this.#send(session, formatServerNumeric('323', session.nick, [], 'End of /LIST'));
}
#handleTopic(session: IrcSession, params: readonly string[]): void {
const channelName = sanitizeChannelName(params[0] ?? '');
const channel = this.#channels.get(channelName);
if (!channel) {
this.#send(session, formatServerNumeric('403', session.nick, [channelName], 'No such channel'));
return;
}
if (params.length >= 2) {
channel.topic = params[1] ?? '';
const line = formatUserEvent(session.nick, session.user, 'TOPIC', [channelName], channel.topic);
for (const member of channel.members) this.#send(member, line);
return;
}
if (channel.topic) this.#send(session, formatServerNumeric('332', session.nick, [channelName], channel.topic));
else this.#send(session, formatServerNumeric('331', session.nick, [channelName], 'No topic is set'));
}
#handleMode(session: IrcSession, target: string): void {
if (target.startsWith('#') || target.startsWith('&')) {
this.#send(session, formatServerNumeric('324', session.nick, [sanitizeChannelName(target), '+nt']));
} else this.#send(session, formatServerNumeric('221', session.nick, ['+i']));
}
#handleWho(session: IrcSession, target: string): void {
const channel = target.startsWith('#') ? this.#channels.get(sanitizeChannelName(target)) : undefined;
for (const m of channel?.members ?? []) {
this.#send(session, formatServerNumeric('352', session.nick, [channel!.name, m.user, '127.0.0.1', IRC_SERVER_HOST, m.nick, 'H'], `0 ${m.realName}`));
}
this.#send(session, formatServerNumeric('315', session.nick, [target || '*'], 'End of /WHO list.'));
}
#handleWhois(session: IrcSession, targetNick: string): void {
const found = [...this.#sessions].find((peer) => peer.nick === targetNick);
if (found) this.#send(session, formatServerNumeric('311', session.nick, [found.nick, found.user, '127.0.0.1', '*'], found.realName));
this.#send(session, formatServerNumeric('318', session.nick, [targetNick || '*'], 'End of /WHOIS list.'));
}
#handleXtJoin(session: IrcSession, params: readonly string[]): void {
this.#joinChannel(session, `#___xthread_${this.#nextThreadId++}`, params[1] ?? params[0] ?? 'Discussion');
}
#handleXtMeta(session: IrcSession, params: readonly string[]): void {
const channelName = sanitizeChannelName(params[0] ?? '');
const channel = this.#channels.get(channelName);
if (!channel || params[1]?.toLowerCase() !== 'topic') return;
channel.topic = params[2] ?? '';
const line = formatUserEvent(session.nick, session.user, 'TOPIC', [channelName], channel.topic);
for (const member of channel.members) this.#send(member, line);
}
#removeSession(session: IrcSession, reason: string): void {
if (!this.#sessions.delete(session)) return;
const quitLine = session.registered ? formatUserEvent(session.nick, session.user, 'QUIT', [], reason) : '';
const notified = new Set<IrcSession>();
for (const channelName of session.channels) {
const channel = this.#channels.get(channelName);
if (!channel) continue;
channel.members.delete(session);
for (const peer of quitLine ? channel.members : []) {
if (!notified.has(peer)) {
notified.add(peer);
this.#send(peer, quitLine);
}
}
if (channel.members.size === 0) this.#channels.delete(channelName);
}
session.channels.clear();
}
#send(session: IrcSession, line: string): void {
if (!session.socket.destroyed && session.socket.writable) session.socket.write(line);
}
}
@@ -1,9 +1,15 @@
/**
* Per-player cloud settings persistence inside `<data>/saves/<userId>/cloud-settings/`
*. Keeping cloud settings inside each player's save directory means
* copying `saves/<userId>/` to another machine or fresh client folder carries all game
* options, keybinds, HUD settings, presets, and map preferences along automatically.
* Per-player cloud settings persistence inside `<data>/saves/<userId>/cloud-settings/`.
* Keeping cloud settings inside each player's save directory means copying `saves/<userId>/`
* to another machine or fresh client folder carries all game options, keybinds, HUD settings,
* presets, and map preferences along automatically.
*
* When an account has no saved `GBT_GENERAL_SETTINGS.blk` yet, version 1 is seeded once with
* `hudShowFuel = 2` and `hudShowAmmo = 2` ("Always", `aces.exe` 0xf4cc1f..0xf4cc55) so the
* top-left ground/air weapon and fuel HUD indicators are visible out of the box without
* overriding any subsequent change the player makes in the in-game Options menu.
*/
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, setParam, type BlkBlock } from '@wto/blk';
@@ -27,6 +33,7 @@ export const GENERAL_BLK_TYPES = [
export const SUPPORTED_CLOUD_COMPRESSIONS = 'zstd;zlib;gzip';
const SUPPORTED_BLK_TYPE_SET: ReadonlySet<string> = new Set(GENERAL_BLK_TYPES);
const HUD_SHOW_ALWAYS = 2;
export interface ParsedGblkUpload {
readonly blkType: string;
@@ -54,6 +61,7 @@ export class CloudSettingsStore {
}
buildMetaBlk(userId?: string, blockName?: string): BlkBlock {
if (userId && isValidUserId(userId)) this.#ensureDefaultGeneralSettings(userId);
const meta = blockName ? emptyBlock(blockName) : emptyBlock();
setParam(meta, 'machineHash', { type: 'string', value: `hhh${userId ?? '0'}` });
setParam(meta, 'compressionSupported', { type: 'string', value: SUPPORTED_CLOUD_COMPRESSIONS });
@@ -78,6 +86,7 @@ export class CloudSettingsStore {
loadContainer(userId: string, blkType: string): BlkBlock | undefined {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined;
if (blkType === 'GBT_GENERAL_SETTINGS') this.#ensureDefaultGeneralSettings(userId);
const blkPath = this.#blkPath(userId, blkType);
if (!existsSync(blkPath)) return undefined;
try {
@@ -111,6 +120,18 @@ export class CloudSettingsStore {
return savedCount;
}
#ensureDefaultGeneralSettings(userId: string): void {
const blkPath = this.#blkPath(userId, 'GBT_GENERAL_SETTINGS');
if (existsSync(blkPath)) return;
const { container, contentHash } = buildDefaultGeneralSettings();
this.saveUpload(userId, {
blkType: 'GBT_GENERAL_SETTINGS',
version: 1,
contentHash,
container,
});
}
#loadMeta(userId: string): CloudSettingsMetaFile {
const metaPath = this.#metaPath(userId);
if (!existsSync(metaPath)) return { formatVersion: 1, blocks: {} };
@@ -138,6 +159,24 @@ export class CloudSettingsStore {
}
}
function buildDefaultGeneralSettings(): { readonly container: BlkBlock; readonly contentHash: string } {
const content = emptyBlock('content');
const profile = ensureBlock(content, 'profile');
const settings = ensureBlock(profile, 'settings');
setParam(settings, 'hudShowFuel', { type: 'int', value: HUD_SHOW_ALWAYS });
setParam(settings, 'hudShowAmmo', { type: 'int', value: HUD_SHOW_ALWAYS });
const hashRoot = emptyBlock();
hashRoot.params.push(...content.params);
hashRoot.blocks.push(...content.blocks);
const contentHash = createHash('md5').update(encodeBlk(hashRoot)).digest('hex');
const container = emptyBlock();
setParam(container, 'version', { type: 'int', value: 1 });
container.blocks.push(content);
return { container, contentHash };
}
function isValidUserId(userId: string): boolean {
return /^\d+$/.test(userId);
}
@@ -1,5 +1,5 @@
/**
* Crew skill upgrades, skill point packs and specializations.
* Crew skill upgrades, skill point packs and specializations:
*
* cln_upgrade_crew raise skills: <page>{ <skill>:i=levels to add } id:i
* cost = sum of the per-level costs of the new levels
@@ -7,12 +7,21 @@
* cln_purchase_skill_points id:i pack:t: warpoints.blk crewSkillPointsCost, golden eagles
* cln_specialize_crew id:i aircraft:t: one step up for a trained vehicle,
* expert (wpcost.blk train2Cost, silver lions) then
* ace (train3Cost_gold, golden eagles)
* ace (train3Cost_gold discounted by expert_to_ace_cost_reduce)
*/
import type { BlkBlock } from '@wto/blk';
import type { CrewSkillData, CrewTrainingPrices, SkillFacts, SkillPointPack } from '../game-data/datasets/crew-skills.ts';
import type { AceDiscountStage, CrewSkillData, CrewTrainingPrices, SkillFacts, SkillPointPack } from '../game-data/datasets/crew-skills.ts';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { addSkillPoints, isTrainedFor, setSkillLevel, setSpecialization, skillLevel, skillPoints, specializationOf } from '../profile/profile-crew-skills.ts';
import {
addSkillPoints,
expertToAceRp,
isTrainedFor,
setSkillLevel,
setSpecialization,
skillLevel,
skillPoints,
specializationOf,
} from '../profile/profile-crew-skills.ts';
import { crewOf } from '../profile/profile-crews.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
@@ -22,11 +31,13 @@ export class CrewSkillCatalogue {
readonly #skills = new Map<string, SkillFacts>();
readonly #packs: ReadonlyMap<string, SkillPointPack>;
readonly #training: ReadonlyMap<string, CrewTrainingPrices>;
readonly #aceDiscountStages: readonly AceDiscountStage[];
constructor(data: CrewSkillData) {
for (const page of data.pages) for (const skill of page.skills) this.#skills.set(`${page.name}/${skill.name}`, skill);
this.#packs = new Map(data.packs.map((pack) => [pack.name, pack]));
this.#training = new Map(data.training.map((prices) => [prices.vehicle, prices]));
this.#aceDiscountStages = data.aceDiscountStages;
}
skill(page: string, skill: string): SkillFacts | undefined {
@@ -44,6 +55,21 @@ export class CrewSkillCatalogue {
training(vehicle: string): CrewTrainingPrices | undefined {
return this.#training.get(vehicle);
}
aceGoldenEaglesPrice(vehicle: string, earnedAceRp: number): number {
const prices = this.#training.get(vehicle);
if (!prices) return 0;
const baseGold = Math.max(0, prices.aceGoldenEagles);
const targetRp = prices.aceResearchPoints;
if (baseGold === 0 || targetRp <= 0 || earnedAceRp <= 0) return baseGold;
if (earnedAceRp >= targetRp) return 0;
const progressPercent = Math.floor((earnedAceRp * 100) / targetRp);
let discount = 0;
for (const stage of this.#aceDiscountStages) {
if (progressPercent >= stage.percent && stage.discount > discount) discount = stage.discount;
}
return Math.max(0, baseGold - Math.floor((baseGold * discount) / 100));
}
}
export interface SkillRaise {
@@ -89,7 +115,9 @@ export function specializeCrew(profile: BlkBlock, catalogue: CrewSkillCatalogue,
if (!crew || !prices || !isTrainedFor(crew, vehicle)) return refused('BAD_PARAMS');
const spec = specializationOf(crew, vehicle);
if (spec >= ACE) return refused('NOT_AVAILABLE');
const price: Price = spec === 0 ? { silverLions: prices.expert, goldenEagles: 0 } : { silverLions: 0, goldenEagles: prices.aceGoldenEagles };
const price: Price = spec === 0
? { silverLions: prices.expert, goldenEagles: 0 }
: { silverLions: 0, goldenEagles: catalogue.aceGoldenEaglesPrice(vehicle, expertToAceRp(crew, vehicle)) };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
setSpecialization(crew, vehicle, spec + 1);
@@ -1,13 +1,23 @@
/**
* The indexes of downloadable skins and decals (user-made content fetched from Gaijin's CDN).
* The local service offers none, so both indexes are empty.
* Downloadable skin and decal indexes served on the dldata CDN hosts.
*
* Why they are served at all: the client waits up to 60 seconds, twice, for these indexes
* before giving up (aces.exe 2.61.0.37 0xd3fa20, "webcache: downloadable ... index hasn't
* arrived yet"); with dldata_s.info missing, start-up took two minutes longer
*.
* Why both indexes are served:
* - Startup waits up to 60 seconds per index before giving up (aces.exe 2.61.0.37 0xd3fa20,
* "webcache: downloadable ... index hasn't arrived yet").
* - For decals, webdlcontent::getDecalsBlk (0xd41050) merges downloadable_decals.<hash>.blk
* into sharedDecalsBlk (0xd47e20), overlays char.vromfs.bin config/decals.blk (0xd48380),
* and deletes any block lacking both lod0:t and a "<name>*" managed texture (0xd415d6..0xd4183d).
* Populating downloadable_decals.<hash>.blk from config/decals.blk + local DXP2 decal textures
* keeps all 1,598 Hangar Customization decals and Marketplace decal coupons active offline:
* 0xd44fc0 resolves "<lod>*?" via get_managed_texture_id (0x31aec00) directly to the local DXP
* texture without registering webcache HTTP downloads.
*/
import { emptyBlock, encodeBlk } from '@wto/blk';
import { emptyBlock, encodeBlk, type BlkBlock } from '@wto/blk';
import {
makeDdsxDxt5HeaderBase64,
type DecalConfigEntry,
type DxpDecalTexture,
} from '../game-data/datasets/decal-textures.ts';
import { contentHash } from './content-hash.ts';
export type IndexKind = 'skins' | 'decals';
@@ -19,9 +29,77 @@ export interface ContentIndex {
readonly hash: string;
}
/** Stock decals.dxp.bin built-in texture names and dimensions when no DXP pack is scanned. */
const DEFAULT_SQUARE_TEX: DxpDecalTexture = {
name: 'star',
width: 512,
height: 512,
aspectRatio: 1,
ddsxHeaderBase64: makeDdsxDxt5HeaderBase64(512, 512),
};
const DEFAULT_WIDE_TEX: DxpDecalTexture = {
name: 'panther',
width: 512,
height: 256,
aspectRatio: 2,
ddsxHeaderBase64: makeDdsxDxt5HeaderBase64(512, 256),
};
const WIDE_ASPECT_THRESHOLD = 1.5;
export function buildContentIndexes(
decals: readonly DecalConfigEntry[] = [],
localDxp: ReadonlyMap<string, DxpDecalTexture> = new Map(),
): ReadonlyMap<IndexKind, ContentIndex> {
const skinsBytes = encodeBlk(emptyBlock());
const decalsBytes = encodeBlk(decals.length > 0 ? buildDecalsIndexBlk(decals, localDxp) : emptyBlock());
return new Map<IndexKind, ContentIndex>([
['skins', { kind: 'skins', bytes: skinsBytes, hash: contentHash(skinsBytes) }],
['decals', { kind: 'decals', bytes: decalsBytes, hash: contentHash(decalsBytes) }],
]);
}
export function emptyContentIndexes(): ReadonlyMap<IndexKind, ContentIndex> {
return new Map((['skins', 'decals'] as const).map((kind) => {
const bytes = encodeBlk(emptyBlock());
return [kind, { kind, bytes, hash: contentHash(bytes) }];
}));
return buildContentIndexes();
}
function buildDecalsIndexBlk(
decals: readonly DecalConfigEntry[],
localDxp: ReadonlyMap<string, DxpDecalTexture>,
): BlkBlock {
const squareFallback = localDxp.get('star') ?? firstDxpTexture(localDxp) ?? DEFAULT_SQUARE_TEX;
const wideFallback = localDxp.get('panther') ?? widestDxpTexture(localDxp) ?? DEFAULT_WIDE_TEX;
return {
name: '',
params: [],
blocks: decals.map((entry) => {
const target = localDxp.get(entry.name.toLowerCase())
?? (entry.aspectRatio >= WIDE_ASPECT_THRESHOLD ? wideFallback : squareFallback);
return {
name: entry.name,
params: [
{ name: 'category', value: { type: 'string', value: '' } },
{ name: 'aspect_ratio', value: { type: 'real', value: entry.aspectRatio } },
{ name: 'hdr0', value: { type: 'string', value: target.ddsxHeaderBase64 } },
{ name: 'lod0', value: { type: 'string', value: target.name } },
{ name: 'hdr1', value: { type: 'string', value: target.ddsxHeaderBase64 } },
{ name: 'lod1', value: { type: 'string', value: target.name } },
],
blocks: [],
};
}),
};
}
function firstDxpTexture(localDxp: ReadonlyMap<string, DxpDecalTexture>): DxpDecalTexture | undefined {
return localDxp.values().next().value;
}
function widestDxpTexture(localDxp: ReadonlyMap<string, DxpDecalTexture>): DxpDecalTexture | undefined {
let best: DxpDecalTexture | undefined;
for (const candidate of localDxp.values()) {
if (!best || candidate.aspectRatio > best.aspectRatio) best = candidate;
}
return best;
}
@@ -10,8 +10,9 @@
* checks size and SHA-1 against the hash (content-hash.ts).
*/
import { emptyBlock, encodeBlk, formatBlkText, setParam } from '@wto/blk';
import { scanLocalDecalDxp, type DecalConfigEntry } from '../game-data/datasets/decal-textures.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import { emptyContentIndexes, type ContentIndex } from './content-indexes.ts';
import { buildContentIndexes, type ContentIndex, type IndexKind } from './content-indexes.ts';
const INFO_HOST = /^public-configs[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/;
const INFO_PATH = /^\/[a-z0-9_-]+\/dldata_s\.info$/;
@@ -22,8 +23,15 @@ const BINARY = { 'content-type': 'application/octet-stream' };
export class DownloadableContentService implements Service {
readonly name = 'dldata';
readonly #indexes = emptyContentIndexes();
readonly #info = this.#infoBlk();
readonly #indexes: ReadonlyMap<IndexKind, ContentIndex>;
readonly #decalCount: number;
readonly #info: { readonly bytes: Uint8Array; readonly text: string };
constructor(decals: readonly DecalConfigEntry[] = [], gameFolder?: string) {
this.#indexes = buildContentIndexes(decals, scanLocalDecalDxp(gameFolder));
this.#decalCount = decals.length;
this.#info = this.#infoBlk();
}
accepts(request: ServiceRequest): boolean {
const host = request.originalHost;
@@ -40,7 +48,8 @@ export class DownloadableContentService implements Service {
if (!index || index.hash !== match?.[2]) {
return { status: 404, body: 'unknown index', logNotes: { summary: `index ${request.path}: not one this service listed` } };
}
return { status: 200, headers: BINARY, body: index.bytes, logNotes: { summary: `downloadable_${index.kind} (empty)` } };
const detail = index.kind === 'decals' && this.#decalCount > 0 ? `${this.#decalCount} decals` : 'empty';
return { status: 200, headers: BINARY, body: index.bytes, logNotes: { summary: `downloadable_${index.kind} (${detail})` } };
}
#infoBlk(): { readonly bytes: Uint8Array; readonly text: string } {
@@ -0,0 +1,184 @@
/**
* Dataset: Ground RB special spawn aircraft (`missionSupportPlane` nuclear bombers and
* `ucav_*_killstreak` strike UCAVs) and `RandomSpawnUnits` auto-supplemented vehicle pools.
*
* aces.vromfs.bin config/gameplay.blk
* missionSupportPlane{ tank_event_in_random_battles_historical{ UnitPreset{ ... } } }
* RandomSpawnUnits{ <eventName>{ <country>{ <group>{ minPlayerMRank:i ... <unit>{ ... } } } } }
* char.vromfs.bin config/wpcost.blk
* <unit>_killstreak{ country:t economicRankHistorical:i economicRankTankHistorical:i weapons{ ... } }
*/
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
import { numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export interface NuclearAircraftEntry {
readonly country: string;
readonly unitName: string;
readonly weapon: string;
readonly tankRealisticMrank: number;
}
export interface NuclearPresetBracket {
readonly minMrank: number;
readonly maxMrank: number;
readonly spawnScore: number;
readonly entries: readonly NuclearAircraftEntry[];
}
export interface StrikeUcavEntry {
readonly country: string;
readonly unitName: string;
readonly weapon: string;
readonly historicalMrank: number;
}
export interface RandomSpawnCandidate {
readonly unitName: string;
readonly forceWeapon?: string;
}
export interface RandomSpawnGroupRule {
readonly groupName: string;
readonly minPlayerMRank: number;
readonly maxDiffBetweenTopUnitAndSessionRank: number;
readonly mRanksCount: number;
readonly units: readonly RandomSpawnCandidate[];
}
export interface RandomSpawnEventRule {
readonly eventName: string;
readonly countries: Readonly<Record<string, readonly RandomSpawnGroupRule[]>>;
}
export interface BattleSpawnRulesData {
readonly nuclearBrackets: readonly NuclearPresetBracket[];
readonly strikeUcavs: readonly StrikeUcavEntry[];
readonly randomSpawnEvents: readonly RandomSpawnEventRule[];
}
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
id: 'battle-spawn-rules',
version: 1,
extract: (source) => {
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
const wpcostByUnit = new Map(wpcost.blocks.map((block) => [block.name, block]));
return {
nuclearBrackets: extractNuclearBrackets(gameplay, wpcostByUnit),
strikeUcavs: extractStrikeUcavs(wpcost.blocks),
randomSpawnEvents: extractRandomSpawnEvents(gameplay),
};
},
};
function extractNuclearBrackets(
gameplay: BlkBlock,
wpcostByUnit: ReadonlyMap<string, BlkBlock>,
): NuclearPresetBracket[] {
const msp = findBlock(gameplay, 'missionSupportPlane');
const tankRb = msp && findBlock(msp, 'tank_event_in_random_battles_historical');
if (!tankRb) return [];
const brackets: NuclearPresetBracket[] = [];
for (const preset of tankRb.blocks) {
if (preset.name !== 'UnitPreset') continue;
if (stringField(preset, 'killStreakTagName') !== 'bomber_nuclear') continue;
const range = ipoint2Field(preset, 'rankRange');
const spawnScore = numberField(preset, 'spawnScoreToUse');
if (!range || spawnScore === undefined || spawnScore <= 0) continue;
const entries: NuclearAircraftEntry[] = [];
for (const countryBlk of preset.blocks) {
if (!countryBlk.name.startsWith('country_')) continue;
const unitName = stringField(countryBlk, 'unitName') ?? '';
const weapon = stringField(countryBlk, 'weapon') ?? '';
if (!unitName || !weapon) continue;
const costBlk = wpcostByUnit.get(unitName);
const tankRealisticMrank = (costBlk && (
numberField(costBlk, 'economicRankTankHistorical')
?? numberField(costBlk, 'economicRankHistorical')
?? numberField(costBlk, 'economicRank')
)) ?? range[0];
entries.push({ country: countryBlk.name, unitName, weapon, tankRealisticMrank });
}
if (entries.length > 0) {
brackets.push({ minMrank: range[0], maxMrank: range[1], spawnScore, entries });
}
}
return brackets.sort((a, b) => a.minMrank - b.minMrank);
}
function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcavEntry[] {
const entries: StrikeUcavEntry[] = [];
for (const unitBlk of wpcostBlocks) {
if (!STRIKE_UCAV_PATTERN.test(unitBlk.name)) continue;
const country = stringField(unitBlk, 'country') ?? '';
if (!country.startsWith('country_')) continue;
const historicalMrank = numberField(unitBlk, 'economicRankTankHistorical')
?? numberField(unitBlk, 'economicRankHistorical')
?? numberField(unitBlk, 'economicRank')
?? 0;
const weapon = pickArmedUcavWeapon(unitBlk);
entries.push({ country, unitName: unitBlk.name, weapon, historicalMrank });
}
return entries;
}
function pickArmedUcavWeapon(unitBlk: BlkBlock): string {
const weaponsBlk = findBlock(unitBlk, 'weapons');
const presets = (weaponsBlk?.blocks ?? []).filter((b) =>
b.name !== 'custom_presets'
&& !b.name.startsWith('bombguns_')
&& !b.name.startsWith('containers_')
&& !b.name.startsWith('rocketguns_'));
const armed = presets.find((preset) =>
(numberField(preset, 'atgmMaxDistance') ?? 0) > 0
|| (numberField(preset, 'totalBombRocketMass') ?? 0) > 0
|| (numberField(preset, 'totalGuidedBombMass') ?? 0) > 0);
return armed?.name ?? presets[0]?.name ?? '';
}
function extractRandomSpawnEvents(gameplay: BlkBlock): RandomSpawnEventRule[] {
const root = findBlock(gameplay, 'RandomSpawnUnits');
if (!root) return [];
const events: RandomSpawnEventRule[] = [];
for (const eventBlk of root.blocks) {
const countries: Record<string, RandomSpawnGroupRule[]> = {};
for (const countryBlk of eventBlk.blocks) {
if (!countryBlk.name.startsWith('country_')) continue;
const groups: RandomSpawnGroupRule[] = [];
for (const groupBlk of countryBlk.blocks) {
const minPlayerMRank = numberField(groupBlk, 'minPlayerMRank') ?? 0;
const maxDiff = numberField(groupBlk, 'maxDiffBetweenTopUnitAndSessionRank') ?? 0;
const mRanksCount = numberField(groupBlk, 'mRanksCount') ?? 0;
const units: RandomSpawnCandidate[] = groupBlk.blocks
.filter((u) => u.name.length > 0)
.map((u) => {
const forceWeapon = stringField(u, 'forceWeapon');
return forceWeapon ? { unitName: u.name, forceWeapon } : { unitName: u.name };
});
if (units.length > 0) {
groups.push({
groupName: groupBlk.name,
minPlayerMRank,
maxDiffBetweenTopUnitAndSessionRank: maxDiff,
mRanksCount,
units,
});
}
}
if (groups.length > 0) countries[countryBlk.name] = groups;
}
events.push({ eventName: eventBlk.name, countries });
}
return events;
}
function ipoint2Field(block: BlkBlock, name: string): readonly [number, number] | undefined {
const value = findParam(block, name)?.value;
if (value?.type === 'ipoint2') return value.value;
return undefined;
}
@@ -1,15 +1,16 @@
/**
* Dataset: crew skills, skill point packs and per-vehicle crew training prices
*.
* 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_gold:i (ace, golden eagles), train3Cost_exp:i (free ace RP threshold)
*/
import type { BlkBlock } from '@wto/blk';
import { findBlock } from '@wto/blk';
@@ -34,33 +35,48 @@ export interface SkillPointPack {
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: 1,
version: 2,
extract: (source) => {
const skills = findBlock(source.readBlk('char.vromfs.bin', 'config/crew_skills.blk'), 'crew_skills');
const packs = findBlock(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'crewSkillPointsCost');
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,
})),
};
},
@@ -0,0 +1,198 @@
/**
* Dataset and local DXP2 scanner for Hangar and Marketplace decals.
*
* Why this exists:
* - char.vromfs.bin config/decals.blk lists all stock and marketplace decals (1,598 blocks)
* with category, group, costGold, unlock, marketplaceItemdefId, and aspect_ratio, but omits
* lod0 / lod1 texture fields because the online client merges downloadable_decals.<hash>.blk
* into sharedDecalsBlk first (aces.exe 2.61.0.37 0xd41050 -> 0xd47e20 -> 0xd48380).
* - In webdlcontent::getDecalsBlk (0xd415d6..0xd4183d), any decal block without a lod0 string
* and without a local managed texture "<name>*" (get_managed_texture_id, 0x31aec00) is
* deleted from sharedDecalsBlk ("failed to find texture for decal '%s', skipping it").
* - Stock client installations only ship built-in decal textures in content/base/res/decals.dxp.bin
* (DxP2 v2 pack: lang, panther, star). Extracting the decal list via DatasetCache and scanning
* any local *decal*.dxp.bin headers lets DownloadableContentService populate every decal block
* with valid lod0/lod1 and 32-byte DDSx headers without outbound CDN requests.
*/
import { closeSync, existsSync, openSync, readdirSync, readSync } from 'node:fs';
import { join } from 'node:path';
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const DECALS_CONFIG_PATH = 'config/decals.blk';
/** DxP2 v2 pack header constants (verified on content/base/res/decals.dxp.bin). */
const DXP2_MAGIC = 0x32507844; // "DxP2"
const DXP2_VERSION = 2;
const DXP2_PREAMBLE_BYTES = 0x10;
const DXP2_MAX_HEADER_BYTES = 4 * 1024 * 1024;
/** Dagor ddsx::Header binary layout constants (32 bytes, verified at aces.exe 0xd49e00). */
const DDSX_HEADER_BYTES = 32;
const DDSX_MAGIC = 0x78534444; // "DDSx"
const DDSX_DXT5_FOURCC = 0x35545844; // "DXT5"
const DDSX_COMPRESSION_MASK = 0x0fffffff;
const DDSX_UNPACKED_DECAL_FLAGS = 0x00000044;
const DDSX_DECAL_QUALITY_WORD = 0x7401;
const DXT5_BLOCK_BYTES = 16;
export interface DecalConfigEntry {
readonly name: string;
readonly aspectRatio: number;
}
export interface DxpDecalTexture {
readonly name: string;
readonly width: number;
readonly height: number;
readonly aspectRatio: number;
/** Base64-encoded 32-byte unpacked ddsx::Header expected in hdr0 / hdr1 (0xd49e00). */
readonly ddsxHeaderBase64: string;
}
export const decalTextures: Dataset<readonly DecalConfigEntry[]> = {
id: 'decal-textures',
version: 1,
extract: (source) =>
source.readBlk('char.vromfs.bin', DECALS_CONFIG_PATH).blocks.map((entry) => {
const ratio = numberField(entry, 'aspect_ratio');
return {
name: entry.name,
aspectRatio: ratio !== undefined && Number.isFinite(ratio) && ratio > 0 ? ratio : 1,
};
}),
};
/** Scan local *decal*.dxp.bin headers inside the game folder, keyed by lowercase texture name. */
export function scanLocalDecalDxp(gameFolder?: string): ReadonlyMap<string, DxpDecalTexture> {
const found = new Map<string, DxpDecalTexture>();
if (!gameFolder || !existsSync(gameFolder)) return found;
for (const dxpPath of candidateDecalDxpPaths(gameFolder)) {
for (const entry of readDxp2DecalHeaders(dxpPath)) {
const key = entry.name.toLowerCase();
if (!found.has(key)) found.set(key, entry);
}
}
return found;
}
/** Synthesize a 32-byte Dagor DXT5 ddsx::Header (base64) matching downloadable_decals.blk. */
export function makeDdsxDxt5HeaderBase64(width: number, height: number): string {
const header = Buffer.alloc(DDSX_HEADER_BYTES);
header.writeUInt32LE(DDSX_MAGIC, 0);
header.writeUInt32LE(DDSX_DXT5_FOURCC, 4);
header.writeUInt32LE(DDSX_UNPACKED_DECAL_FLAGS, 8);
header.writeUInt16LE(width, 12);
header.writeUInt16LE(height, 14);
const { levels, memSize } = dxt5MipChainSize(width, height);
header[16] = levels;
header.writeUInt16LE(DDSX_DECAL_QUALITY_WORD, 22);
header.writeUInt32LE(memSize, 24);
return header.toString('base64');
}
function dxt5MipChainSize(width: number, height: number): { readonly levels: number; readonly memSize: number } {
let w = Math.max(1, Math.trunc(width));
let h = Math.max(1, Math.trunc(height));
let levels = 0;
let memSize = 0;
for (;;) {
levels += 1;
memSize += Math.max(1, Math.ceil(w / 4)) * Math.max(1, Math.ceil(h / 4)) * DXT5_BLOCK_BYTES;
if (w === 1 && h === 1) break;
w = Math.max(1, w >> 1);
h = Math.max(1, h >> 1);
}
return { levels, memSize };
}
function candidateDecalDxpPaths(gameFolder: string): string[] {
const paths = new Set<string>();
const addResFolder = (resFolder: string): void => {
if (!existsSync(resFolder)) return;
try {
for (const item of readdirSync(resFolder, { withFileTypes: true })) {
if (item.isFile() && /decal.*\.dxp\.bin$/i.test(item.name)) paths.add(join(resFolder, item.name));
}
} catch { /* unreadable optional pack folder */ }
};
addResFolder(join(gameFolder, 'res'));
addResFolder(join(gameFolder, 'content', 'base', 'res'));
const contentRoot = join(gameFolder, 'content');
if (existsSync(contentRoot)) {
try {
for (const pkg of readdirSync(contentRoot, { withFileTypes: true })) {
if (pkg.isDirectory() && pkg.name !== 'base') addResFolder(join(contentRoot, pkg.name, 'res'));
}
} catch { /* unreadable optional content root */ }
}
return [...paths];
}
function readDxp2DecalHeaders(dxpPath: string): DxpDecalTexture[] {
const headerBuf = readDxp2HeaderSlice(dxpPath);
if (!headerBuf) return [];
const count = headerBuf.readUInt32LE(0x08);
const namesTable = DXP2_PREAMBLE_BYTES + headerBuf.readUInt32LE(0x10);
const ddsxTable = DXP2_PREAMBLE_BYTES + headerBuf.readUInt32LE(0x20);
if (namesTable + count * 8 > headerBuf.length || ddsxTable + count * DDSX_HEADER_BYTES > headerBuf.length) {
return [];
}
const textures: DxpDecalTexture[] = [];
for (let i = 0; i < count; i++) {
const nameOffset = DXP2_PREAMBLE_BYTES + Number(headerBuf.readBigUInt64LE(namesTable + i * 8));
const rawName = readNullTerminatedAscii(headerBuf, nameOffset);
const starIndex = rawName.indexOf('*');
const cleanName = (starIndex >= 0 ? rawName.slice(0, starIndex) : rawName).trim();
const ddsxSlice = headerBuf.subarray(ddsxTable + i * DDSX_HEADER_BYTES, ddsxTable + (i + 1) * DDSX_HEADER_BYTES);
if (!cleanName || ddsxSlice.readUInt32LE(0) !== DDSX_MAGIC) continue;
const width = ddsxSlice.readUInt16LE(12);
const height = ddsxSlice.readUInt16LE(14);
if (width === 0 || height === 0) continue;
textures.push({
name: cleanName,
width,
height,
aspectRatio: width / height,
ddsxHeaderBase64: normalizeDdsxHeader(ddsxSlice),
});
}
return textures;
}
function readDxp2HeaderSlice(dxpPath: string): Buffer | undefined {
let fd: number | undefined;
try {
fd = openSync(dxpPath, 'r');
const preamble = Buffer.alloc(DXP2_PREAMBLE_BYTES);
if (readSync(fd, preamble, 0, DXP2_PREAMBLE_BYTES, 0) < DXP2_PREAMBLE_BYTES) return undefined;
if (preamble.readUInt32LE(0) !== DXP2_MAGIC || preamble.readUInt32LE(4) !== DXP2_VERSION) return undefined;
const hdrSize = preamble.readUInt32LE(0x0c);
if (hdrSize === 0 || hdrSize > DXP2_MAX_HEADER_BYTES) return undefined;
const total = DXP2_PREAMBLE_BYTES + hdrSize;
const full = Buffer.alloc(total);
preamble.copy(full, 0);
if (readSync(fd, full, DXP2_PREAMBLE_BYTES, hdrSize, DXP2_PREAMBLE_BYTES) < hdrSize) return undefined;
return full;
} catch {
return undefined;
} finally {
if (fd !== undefined) {
try { closeSync(fd); } catch { /* ignore close failure */ }
}
}
}
function normalizeDdsxHeader(rawHeader: Uint8Array): string {
const unpacked = Buffer.from(rawHeader);
unpacked.writeUInt32LE(unpacked.readUInt32LE(8) & DDSX_COMPRESSION_MASK, 8);
unpacked.writeUInt32LE(0, 28);
return unpacked.toString('base64');
}
function readNullTerminatedAscii(buffer: Buffer, offset: number): string {
if (offset < 0 || offset >= buffer.length) return '';
let end = offset;
while (end < buffer.length && buffer[end] !== 0) end += 1;
return buffer.subarray(offset, end).toString('ascii');
}
@@ -32,6 +32,8 @@ export interface MissionHeader {
readonly type?: string;
readonly environment?: string;
readonly weather?: string;
readonly locName?: string;
readonly postfix?: string;
readonly countryAxis?: string;
readonly countryAllies?: string;
readonly timeLimit?: number;
@@ -50,7 +52,7 @@ export interface MultiplayerMissions {
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
id: 'multiplayer-missions',
version: 1,
version: 2,
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`);
@@ -93,6 +95,8 @@ function readHeader(name: string, path: string, document: BlkBlock): MissionHead
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'),
@@ -60,11 +60,18 @@ export interface CatalogueVehicle {
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: 5,
version: 6,
extract: (source) => {
const shopEntries = shopEntriesByName(source);
const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index]));
@@ -77,6 +84,9 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr
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') ?? '',
@@ -98,5 +108,11 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr
...(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 } : {}),
};
}
@@ -4,21 +4,29 @@ import { PVE_BATTLES } from './pve-battles.ts';
import { RANDOM_BATTLES } from './random-battles.ts';
import { SIMULATOR_BATTLES } from './simulator-battles.ts';
import { SPECIAL_EVENTS } from './special-events.ts';
import { SUB_GAME_MODES } from './sub-game-modes.ts';
export const GAME_MODE_CATALOGUE: readonly GameModeDeclaration[] = checked([
...RANDOM_BATTLES,
...SUB_GAME_MODES,
...SIMULATOR_BATTLES,
...PVE_BATTLES,
...SPECIAL_EVENTS,
]);
function checked(modes: readonly GameModeDeclaration[]): readonly GameModeDeclaration[] {
for (const key of ['gameModeId', 'name'] as const) {
const seen = new Set<unknown>();
for (const mode of modes) {
if (seen.has(mode[key])) throw new Error(`game-mode catalogue: ${key} ${String(mode[key])} is used twice`);
seen.add(mode[key]);
const seenIds = new Set<number>();
const seenNameTags = new Set<string>();
for (const mode of modes) {
if (seenIds.has(mode.gameModeId)) {
throw new Error(`game-mode catalogue: gameModeId ${mode.gameModeId} is used twice`);
}
seenIds.add(mode.gameModeId);
const nameTag = `${mode.name}\0${mode.tag ?? ''}`;
if (seenNameTags.has(nameTag)) {
throw new Error(`game-mode catalogue: (${mode.name}, tag="${mode.tag ?? ''}") is used twice`);
}
seenNameTags.add(nameTag);
}
return modes;
}
@@ -31,6 +31,12 @@ export interface GameModeDeclaration {
readonly gameModeId: number;
/** The stock name where the game has one (docs/implementation notes). */
readonly name: string;
/**
* Sub-mode tag prefix recognized by `scripts/matching/matchinggamemodes.nut:28-42`
* (`regular_with_night_`, `small_teams_`, `bullet_hell_`, `nuclear_escalation_`,
* `naval_ec_ab_`, `naval_ec_rb_`). Empty or omitted for primary modes.
*/
readonly tag?: string;
readonly economicName: string;
/** A single key of the game's localization (a composite key makes the stock UI log an error). */
readonly locName: string;
@@ -38,6 +44,27 @@ export interface GameModeDeclaration {
readonly displayType: DisplayType;
/** Events-window chapter; only for modes shown there. */
readonly chapter?: string;
/**
* Whether multiple crew slots participate (`scripts/events/eventsstate.nut:76`). Defaults to
* `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode).
*/
readonly multiSlot?: boolean;
/** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */
readonly minMRankForNightBattles?: number;
/** Minimum `mrank` exposed on the parent mode for Tactical Skies (`scripts/events/eventinfo.nut:137`). */
readonly minMRankForSmallTeamsBattles?: number;
/** Minimum suitable vehicles required in the crew bar (`scripts/events/secondgamemodesutils.nut:70-71`). */
readonly minCraftsToPlay?: number;
/** Minimum `mrank` per vehicle class emitted into `teamA`/`teamB.allowedCrafts` (`mranks.min`). */
readonly allowedCraftMinMrank?: Partial<Readonly<Record<UnitClass, number>>>;
/** Explicit `minTeamSize` / `maxTeamSize` override (`scripts/events/secondgamemodesutils.nut:40-54`). */
readonly teamSizeOverride?: { readonly min: number; readonly max: number };
/** Minimum `mrank` enforced by local matchmaking before selecting this sub-mode. */
readonly minQueueMrank?: number;
/** Mission time-of-day override applied when launching this mode (e.g. `"Night"`). */
readonly environmentOverride?: string;
/** Uses `BattleTuning.smallTeamsMaxPlayers` instead of `BattleTuning.maxPlayers` when true. */
readonly isSmallTeams?: boolean;
/** The vehicle class a player must bring; the mode is greyed out without one. */
readonly requiredClass: UnitClass;
readonly allowedClasses: readonly UnitClass[];
@@ -27,3 +27,18 @@ export const NAVAL_BATTLE_MISSIONS: MissionSelection = {
requireAllowed: ['ship'],
exclude: NEWBIE_MISSIONS,
};
export const BULLET_HELL_MISSIONS: MissionSelection = {
categories: ['bullet_hell'],
requireAllowed: ['aircraft'],
};
export const NUCLEAR_ESCALATION_MISSIONS: MissionSelection = {
categories: ['nuclear_escalation'],
requireAllowed: ['aircraft'],
};
export const NAVAL_EC_MISSIONS: MissionSelection = {
categories: ['naval_n2m'],
requireAllowed: ['ship'],
};
@@ -5,10 +5,17 @@
* names are the game's "missions/<mode>_event_<difficulty>" texts (lang menu_events.csv);
* economic names of ground and naval modes are the ones the leaderboard scripts use
* (scripts/leaderboard/leaderboardCategoryType.nut).
*
* `minMRankForSmallTeamsBattles` (27 = BR 10.0, Air RB) and `minMRankForNightBattles`
* (27 = BR 10.0, Ground RB) come from `scripts/events/secondgamemodesutils.nut:25-26`,
* `scripts/unlocks/personalunlocks.nut:12`, and `config/unlocks.blk` (`title_prowler_in_the_night`).
*/
import type { GameModeDeclaration } from './game-mode-declaration.ts';
import { AIR_BATTLE_MISSIONS, GROUND_BATTLE_MISSIONS, NAVAL_BATTLE_MISSIONS } from './mission-pools.ts';
const AIR_REALISTIC_SMALL_TEAMS_MIN_MRANK = 27;
const GROUND_REALISTIC_NIGHT_MIN_MRANK = 27;
const AIR = { requiredClass: 'aircraft', allowedClasses: ['aircraft'], missions: AIR_BATTLE_MISSIONS } as const;
const GROUND = { requiredClass: 'tank', allowedClasses: ['tank', 'aircraft', 'helicopter'], missions: GROUND_BATTLE_MISSIONS } as const;
const NAVAL = { requiredClass: 'ship', allowedClasses: ['ship', 'aircraft'], missions: NAVAL_BATTLE_MISSIONS } as const;
@@ -20,7 +27,8 @@ export const RANDOM_BATTLES: readonly GameModeDeclaration[] = [
},
{
gameModeId: 2, name: 'air_realistic', economicName: 'air_realistic', locName: 'missions/air_event_historical',
difficulty: 'realistic', displayType: 'random_battle', ...AIR,
difficulty: 'realistic', displayType: 'random_battle', multiSlot: false,
minMRankForSmallTeamsBattles: AIR_REALISTIC_SMALL_TEAMS_MIN_MRANK, ...AIR,
},
{
gameModeId: 3, name: 'tank_event_in_random_battles_arcade', economicName: 'tank_arcade',
@@ -28,7 +36,8 @@ export const RANDOM_BATTLES: readonly GameModeDeclaration[] = [
},
{
gameModeId: 4, name: 'tank_event_in_random_battles_historical', economicName: 'tank_realistic',
locName: 'missions/tank_event_in_random_battles_historical', difficulty: 'realistic', displayType: 'random_battle', ...GROUND,
locName: 'missions/tank_event_in_random_battles_historical', difficulty: 'realistic', displayType: 'random_battle',
minMRankForNightBattles: GROUND_REALISTIC_NIGHT_MIN_MRANK, ...GROUND,
},
{
gameModeId: 5, name: 'ship_event_in_random_battles_arcade', economicName: 'test_ship_arcade',
@@ -0,0 +1,119 @@
/**
* Stock 2.61.0.37 sub-game-modes (`secondGameModesPanel`, `scripts/matching/matchinggamemodes.nut:28-42`
* and `scripts/events/secondgamemodesutils.nut:25-30, 355-390, 606-654`):
*
* Each sub-mode shares its parent mode's `name` and `economicName` (`matchinggamemodes.nut:74-77, 93`
* and `config/unlocks.blk` `title_prowler_in_the_night`), while carrying its stock `tag` prefix so:
* - `matchingGameModes.notifyGmChanged()` excludes it from the top-level mode drawer (`isSubGameMode`);
* - `mapPreferencesParams.getMapsListImpl()` excludes it from the parent mode's map-ban list;
* - `secondGameModesUtils.nut` binds each toggle strictly to the matching `economicName` (Ground RB
* only gets Night Battles; Air RB gets Nuclear Escalation, Tactical Skies, and Bullet Hell; Naval
* AB/RB get Enduring Confrontation; Ground AB and Air AB get none);
* - `queueEvent.nut` includes or excludes its `gameModeId` in `match.enqueue` `game_modes_list`.
*/
import type { GameModeDeclaration } from './game-mode-declaration.ts';
import {
AIR_BATTLE_MISSIONS,
BULLET_HELL_MISSIONS,
GROUND_BATTLE_MISSIONS,
NAVAL_EC_MISSIONS,
NUCLEAR_ESCALATION_MISSIONS,
} from './mission-pools.ts';
/** Protocol thresholds defined in `scripts/events/secondgamemodesutils.nut:25-30`. */
const MIN_MRANK_NIGHT_BATTLES = 27;
const MIN_MRANK_SMALL_TEAMS = 27;
const MIN_MRANK_BULLET_HELL = 22;
const MIN_CRAFTS_BULLET_HELL = 2;
const MIN_MRANK_NUCLEAR_ESCALATION = 23;
const MIN_MRANK_NAVAL_EC = 7;
export const SUB_GAME_MODES: readonly GameModeDeclaration[] = [
{
gameModeId: 101,
name: 'tank_event_in_random_battles_historical',
tag: 'regular_with_night_tank_realistic',
economicName: 'tank_realistic',
locName: 'missions/tank_event_in_random_battles_historical',
difficulty: 'realistic',
displayType: 'random_battle',
minQueueMrank: MIN_MRANK_NIGHT_BATTLES,
environmentOverride: 'Night',
requiredClass: 'tank',
allowedClasses: ['tank', 'aircraft', 'helicopter'],
missions: GROUND_BATTLE_MISSIONS,
},
{
gameModeId: 102,
name: 'air_realistic',
tag: 'small_teams_air_realistic',
economicName: 'air_realistic',
locName: 'missions/air_event_historical',
difficulty: 'realistic',
displayType: 'random_battle',
multiSlot: false,
teamSizeOverride: { min: 6, max: 12 },
minQueueMrank: MIN_MRANK_SMALL_TEAMS,
isSmallTeams: true,
requiredClass: 'aircraft',
allowedClasses: ['aircraft'],
missions: AIR_BATTLE_MISSIONS,
},
{
gameModeId: 103,
name: 'air_realistic',
tag: 'nuclear_escalation_air_realistic',
economicName: 'air_realistic',
locName: 'missions/air_event_historical',
difficulty: 'realistic',
displayType: 'random_battle',
allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION },
minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION,
requiredClass: 'aircraft',
allowedClasses: ['aircraft'],
missions: NUCLEAR_ESCALATION_MISSIONS,
},
{
gameModeId: 104,
name: 'air_realistic',
tag: 'bullet_hell_air_realistic',
economicName: 'air_realistic',
locName: 'missions/air_event_historical',
difficulty: 'realistic',
displayType: 'random_battle',
minCraftsToPlay: MIN_CRAFTS_BULLET_HELL,
allowedCraftMinMrank: { aircraft: MIN_MRANK_BULLET_HELL },
minQueueMrank: MIN_MRANK_BULLET_HELL,
requiredClass: 'aircraft',
allowedClasses: ['aircraft'],
missions: BULLET_HELL_MISSIONS,
},
{
gameModeId: 105,
name: 'ship_event_in_random_battles_arcade',
tag: 'naval_ec_ab_ship_arcade',
economicName: 'test_ship_arcade',
locName: 'missions/ship_event_arcade',
difficulty: 'arcade',
displayType: 'random_battle',
allowedCraftMinMrank: { ship: MIN_MRANK_NAVAL_EC },
minQueueMrank: MIN_MRANK_NAVAL_EC,
requiredClass: 'ship',
allowedClasses: ['ship', 'aircraft'],
missions: NAVAL_EC_MISSIONS,
},
{
gameModeId: 106,
name: 'ship_event_in_random_battles_realistic',
tag: 'naval_ec_rb_ship_realistic',
economicName: 'test_ship_realistic',
locName: 'missions/ship_event_historical',
difficulty: 'realistic',
displayType: 'random_battle',
allowedCraftMinMrank: { ship: MIN_MRANK_NAVAL_EC },
minQueueMrank: MIN_MRANK_NAVAL_EC,
requiredClass: 'ship',
allowedClasses: ['ship', 'aircraft'],
missions: NAVAL_EC_MISSIONS,
},
];
@@ -6,37 +6,72 @@
* The same object will serve the battle flow later (docs/implementation notes): which missions
* and team rules a chosen mode has.
*/
import type { MultiplayerMissions } from '../game-data/datasets/multiplayer-missions.ts';
import type { MissionHeader, MultiplayerMissions } from '../game-data/datasets/multiplayer-missions.ts';
import { GAME_MODE_CATALOGUE } from './catalogue/catalogue.ts';
import type { GameModeDeclaration } from './catalogue/game-mode-declaration.ts';
import { selectMissions } from './mission-pool.ts';
import { buildModeDefinition, type ModeDefinition } from './mode-definition.ts';
export interface OfferedGameMode {
readonly declaration: GameModeDeclaration;
readonly missions: readonly MissionHeader[];
readonly definition: ModeDefinition;
}
export class GameModes {
readonly #definitions = new Map<number, ModeDefinition>();
readonly #byId = new Map<number, OfferedGameMode>();
readonly #byName = new Map<string, OfferedGameMode>();
readonly #byEconomicName = new Map<string, OfferedGameMode[]>();
readonly #countries: readonly string[];
constructor(missions: MultiplayerMissions, countries: readonly string[], report: (line: string) => void,
catalogue: readonly GameModeDeclaration[] = GAME_MODE_CATALOGUE) {
this.#countries = [...countries];
for (const mode of catalogue) {
const selected = selectMissions(mode.missions, missions);
if (selected.length === 0) {
report(`game mode ${mode.name}: no missions in the game files, left out`);
report(`game mode ${mode.name}${mode.tag ? `.${mode.tag}` : ''}: no missions in the game files, left out`);
continue;
}
this.#definitions.set(mode.gameModeId, buildModeDefinition(mode, selected, countries));
const offered: OfferedGameMode = {
declaration: mode,
missions: selected,
definition: buildModeDefinition(mode, selected, countries),
};
this.#byId.set(mode.gameModeId, offered);
if (!mode.tag) this.#byName.set(mode.name, offered);
const group = this.#byEconomicName.get(mode.economicName) ?? [];
group.push(offered);
this.#byEconomicName.set(mode.economicName, group);
}
report(`game modes: ${this.#definitions.size} of ${catalogue.length} offered`);
report(`game modes: ${this.#byId.size} of ${catalogue.length} offered`);
}
ids(): number[] {
return [...this.#definitions.keys()];
return [...this.#byId.keys()];
}
countries(): readonly string[] {
return this.#countries;
}
byId(id: number): OfferedGameMode | undefined {
return this.#byId.get(id);
}
byName(name: string): OfferedGameMode | undefined {
return this.#byName.get(name);
}
byEconomicName(economicName: string): readonly OfferedGameMode[] {
return this.#byEconomicName.get(economicName) ?? [];
}
/** Definitions of the known ids among those asked for, in the order asked. */
definitions(ids: readonly number[]): ModeDefinition[] {
return ids.flatMap((id): ModeDefinition[] => {
const definition = this.#definitions.get(id);
return definition ? [definition] : [];
const offered = this.#byId.get(id);
return offered ? [offered.definition] : [];
});
}
}
@@ -12,10 +12,10 @@
* createEventGameMode).
* - mission_decl.missions_list: mission name -> {} (a value may carry "enableIf" rank
* limits, scripts/missions/mapPreferencesParams.nut; none are set).
* - tag: required, the script reads it unguarded (scripts/matching/matchingGameModes.nut,
* - tag: required, the script reads it unguarded (scripts/matching/matchingGameModes.nut,
* onGameModesUpdated; local verification stopped there without it). Tag prefixes mark sub-modes
* (night battles, small teams, …, SUB_GAME_MODE_TAG_PREFIXES); our modes have none, so
* the tag is empty.
* (night battles, small teams, bullet hell, nuclear escalation, naval EC;
* SUB_GAME_MODE_TAG_PREFIXES in matchingGameModes.nut:28-42).
* - rankCalcMode: required, read unguarded when the slotbar computes the lineup's battle
* rating (scripts/slotbar/slotbarPresets/calcRanks.nut calculateBR; local verification).
* "average" or "maximum" (lang: multiplayer/battleRatingCalcHint/*); random battles
@@ -34,7 +34,7 @@ const MATCHING_DIFFICULTY: Readonly<Record<ModeDifficulty, string>> = {
simulator: 'simulation',
};
const MISSION_DIFFICULTY: Readonly<Record<ModeDifficulty, string>> = {
export const MISSION_DIFFICULTY: Readonly<Record<ModeDifficulty, string>> = {
arcade: 'arcade',
realistic: 'realistic',
simulator: 'hardcore',
@@ -44,23 +44,35 @@ export type ModeDefinition = Readonly<Record<string, unknown>>;
export function buildModeDefinition(mode: GameModeDeclaration, missions: readonly MissionHeader[],
countries: readonly string[]): ModeDefinition {
const minTeamSize = mode.teamSizeOverride?.min ?? 1;
const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions);
const team = {
countries: [...countries],
allowedCrafts: mode.allowedClasses.map((unitClass) => ({ class: unitClass })),
allowedCrafts: mode.allowedClasses.map((unitClass) => {
const minMrank = mode.allowedCraftMinMrank?.[unitClass];
return minMrank === undefined
? { class: unitClass }
: { class: unitClass, mranks: { min: minMrank } };
}),
requiredCrafts: [{ class: mode.requiredClass }],
minTeamSize: 1,
maxTeamSize: teamSize(mode, missions),
minTeamSize,
maxTeamSize,
};
return {
gameModeId: mode.gameModeId,
name: mode.name,
tag: '',
tag: mode.tag ?? '',
economicName: mode.economicName,
loc_name: mode.locName,
difficulty: MATCHING_DIFFICULTY[mode.difficulty],
rankCalcMode: 'maximum',
displayType: mode.displayType,
multiSlot: mode.multiSlot ?? true,
minTeamSize,
...(mode.chapter === undefined ? {} : { chapter: mode.chapter }),
...(mode.minCraftsToPlay === undefined ? {} : { minCraftsToPlay: mode.minCraftsToPlay }),
...(mode.minMRankForNightBattles === undefined ? {} : { minMRankForNightBattles: mode.minMRankForNightBattles }),
...(mode.minMRankForSmallTeamsBattles === undefined ? {} : { minMRankForSmallTeamsBattles: mode.minMRankForSmallTeamsBattles }),
visible: true,
disabled: false,
teamA: team,
+28 -4
View File
@@ -1,9 +1,11 @@
/**
* Assemble the local service: data layer, save layer, rules, the
* protocol-layer services, and the listening port.
* Assemble the local service: data layer, save layer, rules, protocol-layer services,
* and the single loopback listening port.
*/
import type { Server } from 'node:net';
import { AccountStore } from './accounts/account-store.ts';
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
import { BattleSessionStore } from './battle/battle-session-store.ts';
import { actionTable } from './char/actions/action-table.ts';
import { CharService } from './char/char-service.ts';
import { ClanStore } from './clans/clan-store.ts';
@@ -11,9 +13,11 @@ import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts';
import { DecorShop } from './decor/decor-purchase.ts';
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts';
import { clanEconomy } from './game-data/datasets/clan-economy.ts';
import { crewSkillData } from './game-data/datasets/crew-skills.ts';
import { DatasetCache } from './game-data/datasets/dataset-cache.ts';
import { decalTextures } from './game-data/datasets/decal-textures.ts';
import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts';
import { externalItemSources } from './game-data/datasets/external-item-sources.ts';
import { itemCatalogue } from './game-data/datasets/item-catalogue.ts';
@@ -75,6 +79,8 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
const clans = new ClanStore(options.dataFolder, tuning.clans);
const cloudSettings = new CloudSettingsStore(options.dataFolder);
const vehicles = datasets.load(vehicleCatalogue);
const spawnRules = datasets.load(battleSpawnRules);
const decals = datasets.load(decalTextures);
const labels = datasets.load(uiLabels);
const { profiles, research, equipment } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels);
@@ -89,6 +95,8 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
let matching: MatchingService | undefined;
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules);
const router = new Router([
webUi,
@@ -104,12 +112,28 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
...catalogues,
clans: { store: clans, economy: squadronEconomy },
cloudSettings,
battle: { sessions: battleSessions, tuning: tuning.battle },
notifyInventoryChanged,
})),
new DownloadableContentService(),
new DownloadableContentService(decals, options.gameFolder),
]);
const log = new TrafficLog(options.dataFolder);
const listener = createPortListener(router, matchingRequests({ gameModes }), log, loadOrCreateCredentials(options.dataFolder));
const listener = createPortListener(
router,
matchingRequests({
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
},
}),
log,
loadOrCreateCredentials(options.dataFolder),
);
matching = listener.matching;
await listen(listener.server, options.port);
return {
@@ -0,0 +1,180 @@
/**
* Matching-server RPC handlers for hangar battle-rating display and battle queueing
*:
* - `wtmm_static.calc_ranks` (scripts/battlerating.nut:179)
* - `match.enqueue` (scripts/matching/servicenotifications/match.nut:75)
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
import type { BattleLaunchPlan, BattleMatchmaker } from '../battle/battle-matchmaker.ts';
import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts';
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import type { MatchingRequestHandler } from './matching-requests.ts';
export interface BattleLaunchNotifyPayload extends BattleLaunchPlan, Record<string, unknown> {
readonly from: 'wto_battle';
readonly func: 'launch';
}
export interface BattleQueueDependencies {
readonly gameModes: GameModes;
readonly profiles: PlayerProfiles;
readonly matchmaker: BattleMatchmaker;
readonly sessions: BattleSessionStore;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotifyPayload) => void;
}
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
return [
['wtmm_static.calc_ranks', (request) => answerCalcRanks(request.params, deps.gameModes)],
['match.enqueue', (request, session) => handleEnqueue(request.params, session, deps)],
['match.leave_queue', (_request, session) => {
const userId = session.authenticatedUserId();
if (userId) deps.sessions.cancelPendingForUser(userId);
return {};
}],
['match.check_reconnect', () => ({})],
];
}
function answerCalcRanks(params: Readonly<Record<string, unknown>>, gameModes: GameModes): Record<string, unknown> {
const mode = typeof params.gameModeId === 'number' ? gameModes.byId(params.gameModeId) : undefined;
const players = Array.isArray(params.players) ? params.players : [];
const answer: Record<string, Array<{ mrank: number }>> = {};
for (const rawPlayer of players) {
if (!isRecord(rawPlayer) || typeof rawPlayer.name !== 'string' || !rawPlayer.name) continue;
const crafts = parsePlayerCrafts(rawPlayer.crafts);
const slot = typeof rawPlayer.slot === 'number' && Number.isInteger(rawPlayer.slot) ? rawPlayer.slot : -1;
const singleSlotCraft = mode?.declaration.multiSlot === false && slot >= 0 && slot < crafts.length
? crafts[slot]
: undefined;
const scopedCrafts = singleSlotCraft && singleSlotCraft.unitClass === mode?.declaration.requiredClass
? [singleSlotCraft]
: crafts;
const mrank = mode
? maxModeMrank(scopedCrafts, mode.declaration.requiredClass, mode.declaration.allowedClasses)
: scopedCrafts.reduce((max, craft) => Math.max(max, craft.mrank), 0);
answer[rawPlayer.name] = [{ mrank }];
}
return answer;
}
function handleEnqueue(
params: Readonly<Record<string, unknown>>,
session: { authenticatedUserId(): string | undefined; note(text: string): void },
deps: BattleQueueDependencies,
): Record<string, unknown> {
const userId = session.authenticatedUserId();
if (!userId) {
session.note('rejected: matching session is not authenticated');
return { error: 'AUTH_REQ_ERROR' };
}
const modes = resolveQueuedModes(params, deps.gameModes);
if (modes.length === 0) {
session.note('rejected: unknown game mode');
return { error: 'UNKNOWN_GAME_MODE' };
}
const playerEntry = extractPlayerEntry(params, userId);
if (!playerEntry) {
session.note('rejected: missing player country in match.enqueue');
return { error: 'BAD_PARAMS' };
}
const profile = deps.profiles.profileOf(userId);
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
const selectedSlotVehicle = playerEntry.selectedSlot !== undefined
? crewSlotVehicleOfCountry(profile, playerEntry.country, playerEntry.selectedSlot)
: undefined;
const outcome = deps.matchmaker.enqueue({
userId,
mode: modes[0]!,
modes,
country: playerEntry.country,
slotVehicles,
...(selectedSlotVehicle !== undefined ? { selectedSlotVehicle } : {}),
bannedMissions: playerEntry.bannedMissions,
dislikedMissions: playerEntry.dislikedMissions,
});
if (!outcome.ok) {
session.note(`rejected: ${outcome.error}`);
return { error: outcome.error };
}
const { launch } = outcome;
session.note(`mode=${launch.modeName}, mission=${launch.missionName}, mrank=${launch.minMrank}..${launch.maxMrank}`);
setImmediate(() => {
if (!deps.sessions.isPending(userId, launch.sessionId)) return;
deps.sessions.clearPending(userId, launch.sessionId);
deps.notifyLaunch(userId, { from: 'wto_battle', func: 'launch', ...launch });
});
return {};
}
function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] {
if (!Array.isArray(rawCrafts)) return [];
return rawCrafts.flatMap((craft): CraftRankEntry[] => {
if (!isRecord(craft) || typeof craft.mrank !== 'number' || !Number.isFinite(craft.mrank)) return [];
const fromExp = typeof craft.craftType === 'string' ? unitClassOfExpClass(craft.craftType) : undefined;
const fromCode = typeof craft.unitTypeCode === 'number' ? unitClassOfTypeCode(craft.unitTypeCode) : undefined;
return [{ unitClass: fromExp ?? fromCode, mrank: Math.max(0, Math.trunc(craft.mrank)) }];
});
}
/**
* Resolve every candidate `OfferedGameMode` allowed by `match.enqueue` (`scripts/queue/queue/queueevent.nut:191-207`):
* - `game_mode_id`: explicit single mode ID;
* - `game_modes_list`: filtered IDs after applying `onlyTags` / `excludedTags`;
* - `mode`: sent when `onlyTags` and `excludedTags` are both empty (classic mode plus every
* sub-mode of that `economicName` is enabled; server-side BR/craft guards still apply).
*/
function resolveQueuedModes(params: Readonly<Record<string, unknown>>, gameModes: GameModes): OfferedGameMode[] {
if (typeof params.game_mode_id === 'number') {
const found = gameModes.byId(params.game_mode_id);
return found ? [found] : [];
}
if (Array.isArray(params.game_modes_list)) {
return params.game_modes_list.flatMap((id) => (typeof id === 'number' ? gameModes.byId(id) ?? [] : []));
}
if (typeof params.mode === 'string' && params.mode) {
const primary = gameModes.byName(params.mode);
if (!primary) return [];
const family = gameModes.byEconomicName(primary.declaration.economicName);
return family.length > 0 ? [...family] : [primary];
}
return [];
}
function extractPlayerEntry(
params: Readonly<Record<string, unknown>>,
userId: string,
): {
readonly country: string;
readonly selectedSlot?: number;
readonly bannedMissions: Set<string>;
readonly dislikedMissions: Set<string>;
} | undefined {
const players = isRecord(params.players) ? params.players : undefined;
const entry = players && isRecord(players[userId]) ? players[userId] : undefined;
const rawCountry = typeof entry?.country === 'string' ? entry.country.trim() : '';
if (!rawCountry) return undefined;
const country = rawCountry.startsWith('country_') ? rawCountry : `country_${rawCountry}`;
const slots = isRecord(entry?.slots) ? entry.slots : undefined;
const rawSlot = slots?.[country] ?? slots?.[rawCountry];
const selectedSlot = typeof rawSlot === 'number' && Number.isInteger(rawSlot) && rawSlot >= 0 ? rawSlot : undefined;
return {
country,
...(selectedSlot !== undefined ? { selectedSlot } : {}),
bannedMissions: toStringSet(entry?.bannedMissions),
dislikedMissions: toStringSet(entry?.dislikedMissions),
};
}
function toStringSet(raw: unknown): Set<string> {
if (!Array.isArray(raw)) return new Set();
return new Set(raw.filter((item): item is string => typeof item === 'string' && item.length > 0));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -0,0 +1,22 @@
/**
* Static matching-server feature flags (`wtmm_static.fetch_game_settings`,
* `scripts/matching/matchinggamesettings.nut` -> `scripts/user/matchingfeature.nut`).
*
* Stock `matchingfeature.nut` defaults `hasChat`, `hasBattleChatModeAll`, and
* `hasBattleChatModeTeam` to `false` until `wtmm_static.fetch_game_settings` returns
* `features.<key> = true`. Enabling them lets DaRG `hudLogs.nut` and the built-in
* LocalMP host chat dispatcher (`aces.exe` 0x154f540 -> 0x133ba10) accept in-battle
* All/Team/Squad chat and quick-radio voice messages.
*/
import type { MatchingRequestHandler } from './matching-requests.ts';
export const fetchGameSettings: MatchingRequestHandler = () => ({
features: {
hasChat: true,
hasMenuChat: true,
hasBattleChatModeAll: true,
hasBattleChatModeTeam: true,
hasBattleChatModeSquad: true,
hasMenuChatMPlobby: true,
},
});
@@ -8,9 +8,12 @@
* Nothing local checks the credentials (single-player machine); the session key is needed
* because the client encrypts everything after this request.
*/
import type { AccountStore } from '../accounts/account-store.ts';
import type { GameModes } from '../game-modes/game-modes.ts';
import { battleQueueRequests, type BattleQueueDependencies } from './battle-queue-requests.ts';
import { fetchClustersList } from './cluster-list.ts';
import { gameModeRequests } from './game-modes-requests.ts';
import { fetchGameSettings } from './game-settings.ts';
import type { MatchingRequest } from './matching-message.ts';
import { jwtDecryptsWith, unwrapSessionKey } from './session-crypto/session-key.ts';
@@ -18,6 +21,10 @@ import { jwtDecryptsWith, unwrapSessionKey } from './session-crypto/session-key.
export interface MatchingSessionControl {
/** Encrypt this connection from the answer to the current request on. */
useSessionKey(key: Buffer): void;
/** Bind this matching connection to a verified local account. */
authenticateUser(userId: string): void;
/** The local account bound during `mlogin.login`, or undefined when unauthenticated. */
authenticatedUserId(): string | undefined;
/** Add a line to the traffic log entry of the current request. */
note(text: string): void;
}
@@ -28,18 +35,23 @@ export type MatchingRequestTable = ReadonlyMap<string, MatchingRequestHandler>;
export interface MatchingRules {
readonly gameModes: GameModes;
readonly accounts?: AccountStore;
readonly battle?: BattleQueueDependencies;
}
export function matchingRequests({ gameModes }: MatchingRules): MatchingRequestTable {
export function matchingRequests({ gameModes, accounts, battle }: MatchingRules): MatchingRequestTable {
return new Map<string, MatchingRequestHandler>([
['mlogin.login', signIn],
['mlogin.login', (request, session) => signIn(request, session, accounts)],
['wtmm_static.fetch_clusters_list', fetchClustersList],
['wtmm_static.fetch_game_settings', fetchGameSettings],
['mrooms.leave_room', () => ({})],
...gameModeRequests(gameModes),
...(battle ? battleQueueRequests(battle) : []),
]);
}
function signIn(request: MatchingRequest, session: MatchingSessionControl): Record<string, unknown> {
const { login, auth_jwt_enc: authJwtEnc } = request.params;
function signIn(request: MatchingRequest, session: MatchingSessionControl, accounts?: AccountStore): Record<string, unknown> {
const { login, auth_jwt_enc: authJwtEnc, user_id: rawUserId } = request.params;
if (typeof login === 'string') {
const { sessionKey, fields } = unwrapSessionKey(login);
const verified = typeof authJwtEnc === 'string' && jwtDecryptsWith(sessionKey, authJwtEnc);
@@ -48,5 +60,14 @@ function signIn(request: MatchingRequest, session: MatchingSessionControl): Reco
} else {
session.note('no sealed login field: the connection stays unencrypted');
}
const userIdText = typeof rawUserId === 'number' && Number.isSafeInteger(rawUserId)
? String(rawUserId)
: typeof rawUserId === 'string' ? rawUserId.trim() : '';
const account = userIdText && accounts ? accounts.byUserId(userIdText) : undefined;
if (account) {
session.authenticateUser(account.userId);
session.note(`authenticated user ${account.userId} (${account.nick})`);
}
return {};
}
@@ -49,6 +49,16 @@ export class MatchingService {
const message = notifyMessage(name, data);
for (const session of this.#sessions) session.pushNotify(message, name);
}
/** Push a matching notification only to active sessions authenticated as `userId`. */
notifyUser(userId: string, name: string, data: Record<string, unknown>): boolean {
const message = notifyMessage(name, data);
let sent = false;
for (const session of this.#sessions) {
if (session.userId() === userId && session.pushNotify(message, name)) sent = true;
}
return sent;
}
}
class MatchingSession {
@@ -59,6 +69,7 @@ class MatchingSession {
readonly #packets = new PacketReader();
#sessionKey: Buffer | undefined;
#envelopes: EnvelopeReader | undefined;
#userId: string | undefined;
constructor(socket: Socket, connectionId: number, requests: MatchingRequestTable, log: TrafficLog) {
this.#socket = socket;
@@ -67,6 +78,10 @@ class MatchingSession {
this.#log = log;
}
userId(): string | undefined {
return this.#userId;
}
receive(chunk: Buffer): void {
if (this.#envelopes) {
for (const plaintext of this.#envelopes.push(chunk)) this.#readPackets(plaintext);
@@ -109,6 +124,10 @@ class MatchingSession {
this.#sessionKey = key;
this.#envelopes = new EnvelopeReader(key);
},
authenticateUser: (userId) => {
this.#userId = userId;
},
authenticatedUserId: () => this.#userId,
note: (text) => notes.push(text),
};
const data = handler ? handler(request, control) : {};
@@ -123,10 +142,11 @@ class MatchingSession {
this.#socket.write(this.#sessionKey ? sealEnvelope(this.#sessionKey, packet) : packet);
}
pushNotify(message: MatchingMessage, summaryName: string): void {
if (!this.#sessionKey || this.#socket.destroyed) return;
pushNotify(message: MatchingMessage, summaryName: string): boolean {
if (!this.#sessionKey || this.#socket.destroyed) return false;
this.#record('out', message, `notify ${summaryName} (encrypted)`, false);
this.#send(message);
return true;
}
#record(direction: 'in' | 'out', message: MatchingMessage, summary: string, unhandled: boolean): void {
@@ -1,25 +1,10 @@
/**
* Initial full stocking and `autoRefillWeapons` Silver-Lion top-up for an owned vehicle's
* modifications, ammunition belts/shells, expendables (`tank_medical_kit_expendable`), and
* secondary weapon presets.
* modifications, ammunition belts/shells, expendables, and secondary weapon presets.
*
* Rules:
* 1. Zero-cost modifications (`isFree`) whose `requires` are all owned cannot be bought by the
* client (`weaponsPurchase.nut` `canBuyItem` rejects zero cost) and receive `count = 1` in
* name + topological order, honoring `defaultEnabled` and non-bullet `exclusiveGroup` mutual
* exclusion.
* 2. Free secondary weapon presets (`isFreeWeapon`, excluding `isWeaponForCustomSlot` containers)
* whose `requires` (direct + `sum_weapons` container inheritance) are all owned receive
* `count = 1` so `shop_is_weapon_purchased` allows selecting them.
* 3. Silver-Lion counted modifications (`isCounted` with `goldenEagles === 0`, covering all
* 12,800 shells, gun belts, and `tank_medical_kit_expendable`) and paid weapon presets
* (`isPaidWeapon` with `goldenEagles === 0`) whose `requires` are all owned:
* - When no profile record exists yet (`record === undefined`, i.e. newly acquired vehicle or
* newly unlocked prerequisite modification), receive their initial full load (`maxCount`)
* at no extra Silver-Lion charge (`itemInfo.nut` `getAllModsCost` skips `maxAmount > 1`).
* - When a record already exists with `count < maxCount` (consumed in battle) and hangar
* `autoRefillWeapons` is enabled, buy as many missing pieces with Silver Lions in
* deterministic name order as the player's balance affords.
* Returns the total Silver Lions spent on refilling consumed ammunition, expendables, and
* paid weapon presets during this call (`0` on initial free stocking or when `autoRefill`
* is disabled).
*/
import type { BlkBlock } from '@wto/blk';
import type { ModificationFacts, VehicleEquipment, WeaponFacts } from '../game-data/datasets/vehicle-equipment.ts';
@@ -29,17 +14,27 @@ import { weaponRecord, writeWeaponRecord } from '../profile/profile-weapons.ts';
import { isCounted, isFree, isFreeWeapon, isPaidWeapon } from './equipment-catalogue.ts';
import { arePrerequisitesOwned } from './module-status.ts';
export function stockAndRefillEquipment(profile: BlkBlock, equipment: VehicleEquipment, autoRefill: boolean): void {
export interface EquipmentRefillResult {
readonly silverLionsSpent: number;
}
export function stockAndRefillEquipment(
profile: BlkBlock,
equipment: VehicleEquipment,
autoRefill: boolean,
): EquipmentRefillResult {
const modifications = [...equipment.modifications].sort((a, b) => a.name.localeCompare(b.name));
const weapons = [...equipment.weapons].sort((a, b) => a.name.localeCompare(b.name));
grantUnlockedFreeModifications(profile, equipment.vehicle, modifications);
grantUnlockedFreeWeapons(profile, equipment.vehicle, weapons);
let silverLionsSpent = 0;
for (const modification of modifications) {
stockOrRefillCountedModification(profile, equipment.vehicle, modification, autoRefill);
silverLionsSpent += stockOrRefillCountedModification(profile, equipment.vehicle, modification, autoRefill);
}
for (const weapon of weapons) {
stockOrRefillPaidWeapon(profile, equipment.vehicle, weapon, autoRefill);
silverLionsSpent += stockOrRefillPaidWeapon(profile, equipment.vehicle, weapon, autoRefill);
}
return { silverLionsSpent };
}
function grantUnlockedFreeModifications(profile: BlkBlock, vehicle: string, modifications: readonly ModificationFacts[]): void {
@@ -84,9 +79,9 @@ function stockOrRefillCountedModification(
vehicle: string,
modification: ModificationFacts,
autoRefill: boolean,
): void {
if (!isCounted(modification) || modification.goldenEagles > 0) return;
if (!arePrerequisitesOwned(profile, vehicle, modification.requires)) return;
): number {
if (!isCounted(modification) || modification.goldenEagles > 0) return 0;
if (!arePrerequisitesOwned(profile, vehicle, modification.requires)) return 0;
const record = modificationRecord(profile, vehicle, modification.name);
if (record === undefined) {
writeModificationRecord(profile, vehicle, modification.name, {
@@ -95,11 +90,11 @@ function stockOrRefillCountedModification(
enabled: modification.defaultEnabled,
count: modification.maxCount,
});
return;
return 0;
}
if (!autoRefill || record.count >= modification.maxCount) return;
if (!autoRefill || record.count >= modification.maxCount) return 0;
const toBuy = affordableUnits(profile, modification.maxCount - record.count, modification.silverLions);
if (toBuy <= 0) return;
if (toBuy <= 0) return 0;
const cost = toBuy * modification.silverLions;
if (cost > 0) pay(profile, { silverLions: cost, goldenEagles: 0 });
writeModificationRecord(profile, vehicle, modification.name, {
@@ -107,19 +102,25 @@ function stockOrRefillCountedModification(
silverLionsSpent: record.silverLionsSpent + cost,
count: record.count + toBuy,
});
return cost;
}
function stockOrRefillPaidWeapon(profile: BlkBlock, vehicle: string, weapon: WeaponFacts, autoRefill: boolean): void {
if (!isPaidWeapon(weapon) || weapon.goldenEagles > 0) return;
if (!arePrerequisitesOwned(profile, vehicle, weapon.requires)) return;
function stockOrRefillPaidWeapon(
profile: BlkBlock,
vehicle: string,
weapon: WeaponFacts,
autoRefill: boolean,
): number {
if (!isPaidWeapon(weapon) || weapon.goldenEagles > 0) return 0;
if (!arePrerequisitesOwned(profile, vehicle, weapon.requires)) return 0;
const record = weaponRecord(profile, vehicle, weapon.name);
if (record === undefined) {
writeWeaponRecord(profile, vehicle, weapon.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, count: weapon.maxCount });
return;
return 0;
}
if (!autoRefill || record.count >= weapon.maxCount) return;
if (!autoRefill || record.count >= weapon.maxCount) return 0;
const toBuy = affordableUnits(profile, weapon.maxCount - record.count, weapon.silverLions);
if (toBuy <= 0) return;
if (toBuy <= 0) return 0;
const cost = toBuy * weapon.silverLions;
if (cost > 0) pay(profile, { silverLions: cost, goldenEagles: 0 });
writeWeaponRecord(profile, vehicle, weapon.name, {
@@ -127,6 +128,7 @@ function stockOrRefillPaidWeapon(profile: BlkBlock, vehicle: string, weapon: Wea
goldenEaglesSpent: record.goldenEaglesSpent,
count: record.count + toBuy,
});
return cost;
}
function affordableUnits(profile: BlkBlock, missing: number, unitSilverCost: number): number {
@@ -1,19 +1,67 @@
/**
* Choosing the modification a vehicle researches: cln_set_researchable
* with unit:t and mod:t (script shop_set_researchable_unit_module). The modification has to be
* researchable now; it goes into hangar/<vehicle>/investMode, and the client shows it as "in
* research" from there.
* Choosing the modification an owned vehicle researches (`cln_set_researchable` with
* `unit:t` and `mod:t`) and pouring banked `excessExp` into a modification
* (`cln_move_exp_to_module`).
*/
import type { BlkBlock } from '@wto/blk';
import { setModuleResearchTarget } from '../profile/profile-vehicle-state.ts';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { moduleResearchPoints, setModuleResearchPoints } from '../profile/profile-module-research.ts';
import {
setFinishedModuleResearch,
setModuleResearchTarget,
setVehicleExcessRp,
vehicleExcessRp,
} from '../profile/profile-vehicle-state.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
import { currentModuleStatus } from './module-state.ts';
import { ModuleStatus } from './module-status.ts';
export function chooseModuleResearch(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, modification: string): RuleOutcome {
export function chooseModuleResearch(
profile: BlkBlock,
catalogue: EquipmentCatalogue,
vehicle: string,
modification: string,
): RuleOutcome {
if (modification === '') {
if (!catalogue.vehicle(vehicle) || !ownedVehicles(profile).has(vehicle)) return refused('BAD_PARAMS');
setModuleResearchTarget(profile, vehicle, '');
setFinishedModuleResearch(profile, vehicle, '');
return ACCEPTED;
}
if (!catalogue.modification(vehicle, modification)) return refused('BAD_PARAMS');
if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) {
return refused('NOT_AVAILABLE');
}
setModuleResearchTarget(profile, vehicle, modification);
setFinishedModuleResearch(profile, vehicle, '');
return ACCEPTED;
}
export function moveExcessExpToModule(
profile: BlkBlock,
catalogue: EquipmentCatalogue,
vehicle: string,
modification: string,
): RuleOutcome {
const modFacts = catalogue.modification(vehicle, modification);
if (!modFacts || modFacts.researchPoints <= 0) return refused('BAD_PARAMS');
if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) {
return refused('NOT_AVAILABLE');
}
const available = vehicleExcessRp(profile, vehicle);
const before = moduleResearchPoints(profile, vehicle, modification);
const moved = Math.min(available, Math.max(0, modFacts.researchPoints - before));
if (moved <= 0) return ACCEPTED;
const remaining = available - moved;
setVehicleExcessRp(profile, vehicle, remaining);
setModuleResearchPoints(profile, vehicle, modification, before + moved);
if (before + moved >= modFacts.researchPoints) {
setModuleResearchTarget(profile, vehicle, '');
setFinishedModuleResearch(profile, vehicle, '');
} else {
setModuleResearchTarget(profile, vehicle, modification);
setFinishedModuleResearch(profile, vehicle, '');
}
return ACCEPTED;
}
@@ -1,23 +1,30 @@
/**
* Bringing the modification state of a profile up to date, like research/research-state.ts does
* for vehicles: whenever a profile is handed out or changed (profiles-setup.ts), for every owned
* vehicle (sorted by name for deterministic auto-refill deduction):
* modifications & weapons unlocked free items, initial full stock of newly unlocked
* ammunition / expendables / paid presets, and Silver-Lion
* top-ups when `autoRefillWeapons` is enabled (ammo-refill.ts)
* hangar/<vehicle>/tierNumber the highest open tier
* modsResearch the status of every modification not owned yet; locked ones
* only keep an entry while they hold research points
* hangar/<vehicle>/investMode cleared when that modification is no longer researchable
* Keeping every owned vehicle's modification state synchronized with its owned equipment
* and modification research points:
* - grants newly unlocked free items, stocks newly unlocked counted items, and runs SL
* top-ups when `autoRefillWeapons` is enabled;
* - writes `hangar/<vehicle>/tierNumber` and `modsResearch` statuses;
* - maintains `investMode` so finished-modification prompts (`investModePrev != ""`) open
* `WeaponsModalHandler` in `researchMode` when researchable modifications remain (or signal
* `isResearchLast` with `investMode = ""` when the vehicle is spaded), without overwriting
* an intentionally empty `investMode` while `excessExp > 0` inside the modal.
*/
import type { BlkBlock } from '@wto/blk';
import type { VehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts';
import { isAutoRefillWeaponsEnabled } from '../profile/profile-client-settings.ts';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { moduleResearchPoints, removeModuleResearch, setModuleStatus } from '../profile/profile-module-research.ts';
import { moduleResearchTarget, setModuleResearchTarget, setOpenTier } from '../profile/profile-vehicle-state.ts';
import {
finishedModuleResearch,
moduleResearchTarget,
setModuleResearchTarget,
setOpenTier,
setVehicleExcessRp,
vehicleExcessRp,
} from '../profile/profile-vehicle-state.ts';
import { stockAndRefillEquipment } from './ammo-refill.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
import { ModuleStatus, vehicleModuleState } from './module-status.ts';
import { isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
import { isModuleResearched, ModuleStatus, vehicleModuleState, type VehicleModuleState } from './module-status.ts';
export function refreshModuleState(profile: BlkBlock, catalogue: EquipmentCatalogue): void {
const autoRefill = isAutoRefillWeaponsEnabled(profile);
@@ -32,16 +39,51 @@ export function refreshModuleState(profile: BlkBlock, catalogue: EquipmentCatalo
const status = state.statuses.get(modification.name);
if (status === undefined || (status === ModuleStatus.LOCKED && moduleResearchPoints(profile, vehicle, modification.name) === 0)) {
removeModuleResearch(profile, vehicle, modification.name);
} else {
setModuleStatus(profile, vehicle, modification.name, status);
}
else setModuleStatus(profile, vehicle, modification.name, status);
}
const target = moduleResearchTarget(profile, vehicle);
if (target && state.statuses.get(target) !== ModuleStatus.CAN_RESEARCH) setModuleResearchTarget(profile, vehicle, '');
syncVehicleInvestMode(profile, equipment, state);
}
}
/** The status of one modification the player does not own; undefined when owned, unknown or the vehicle is not owned. */
export function currentModuleStatus(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, modification: string): ModuleStatus | undefined {
function syncVehicleInvestMode(profile: BlkBlock, equipment: VehicleEquipment, state: VehicleModuleState): void {
const vehicle = equipment.vehicle;
const target = moduleResearchTarget(profile, vehicle);
if (target && state.statuses.get(target) === ModuleStatus.CAN_RESEARCH) return;
const hasAnyUnresearched = equipment.modifications.some(
(mod) => isResearchable(mod) && !isModuleResearched(profile, vehicle, mod),
);
if (!hasAnyUnresearched) {
setModuleResearchTarget(profile, vehicle, '');
setVehicleExcessRp(profile, vehicle, 0);
return;
}
const nextMod = pickDefaultResearchableModule(equipment, state);
const prevMod = finishedModuleResearch(profile, vehicle);
const excess = vehicleExcessRp(profile, vehicle);
if (prevMod !== '' || excess === 0) {
setModuleResearchTarget(profile, vehicle, nextMod);
} else {
setModuleResearchTarget(profile, vehicle, '');
}
}
export function pickDefaultResearchableModule(equipment: VehicleEquipment, state: VehicleModuleState): string {
const ordered = [...equipment.modifications]
.filter((mod) => isResearchable(mod) && state.statuses.get(mod.name) === ModuleStatus.CAN_RESEARCH)
.sort((a, b) => (a.tier !== b.tier ? a.tier - b.tier : a.name.localeCompare(b.name)));
return ordered[0]?.name ?? '';
}
export function currentModuleStatus(
profile: BlkBlock,
catalogue: EquipmentCatalogue,
vehicle: string,
modification: string,
): ModuleStatus | undefined {
const equipment = catalogue.vehicle(vehicle);
if (!equipment || !ownedVehicles(profile).has(vehicle)) return undefined;
return vehicleModuleState(profile, equipment).statuses.get(modification);
@@ -1,7 +1,7 @@
/**
* The status of each modification of an owned vehicle. The client
* works out "owned" and "mounted" from the modifications records and "in research" from
* investMode itself; the server supplies the rest through modsResearch:
* The status of each modification of an owned vehicle. The client works out "owned" and
* "mounted" from the modifications records and "in research" from `investMode` itself; the
* server supplies the rest through `modsResearch`:
*
* researchable modification (tier 1+, research points)
* tier not open LOCKED
@@ -1,10 +1,11 @@
/**
* Crew skills, skill points and specializations inside a crew block:
* Crew skills, skill points, specializations, and Expert-to-Ace RP inside a crew block:
*
* crews{
* c0{
* country:t="country_usa"
* aircrafts{ trained:t="us_m2a4" spec:i=1 trained:t="us_m22_locust" spec:i=0 current:t="us_m2a4" }
* expertToAceProgress{ us_m2a4:i=12000 }
* commander{ crewMember_0{ eyesight:i64=5 field_repair:i64=2 } }
* skillPointsStat:i64=0
* skillPointsManualChanges:i64=150000
@@ -15,7 +16,8 @@
* kept times 100: the client shows (skillPointsStat + skillPointsManualChanges) / 100
* (get_crew_info, 0x179dbac); the local service books what the player buys and spends in
* skillPointsManualChanges. Every trained vehicle is followed by its spec (0 none, 1 expert,
* 2 ace), as the client writes them (0x939ed0..0x939f55).
* 2 ace), as the client writes them (0x939ed0..0x939f55), and per-vehicle Expert-to-Ace RP sits
* in expertToAceProgress/<vehicle>:i (0x93b0d0..0x93b4eb).
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
@@ -26,6 +28,7 @@ const POINTS_SCALE = 100;
const VEHICLES = 'aircrafts';
const TRAINED = 'trained';
const SPEC = 'spec';
const ACE_PROGRESS = 'expertToAceProgress';
export function skillLevel(crew: BlkBlock, page: string, skill: string): number {
const pageBlock = findBlock(crew, page);
@@ -78,6 +81,18 @@ export function trainedPairs(crew: BlkBlock): { vehicle: string; spec: number }[
return pairs;
}
export function expertToAceRp(crew: BlkBlock, vehicle: string): number {
const progress = findBlock(crew, ACE_PROGRESS);
return progress ? intOf(progress, vehicle) : 0;
}
export function addExpertToAceRp(crew: BlkBlock, vehicle: string, deltaRp: number, maxRp: number): void {
if (deltaRp <= 0 || maxRp <= 0) return;
const current = expertToAceRp(crew, vehicle);
const next = Math.min(maxRp, Math.max(0, current + Math.trunc(deltaRp)));
if (next !== current) setParam(ensureBlock(crew, ACE_PROGRESS), vehicle, { type: 'int', value: next });
}
function intOf(block: BlkBlock, name: string): number {
const value = findParam(block, name)?.value;
if (value?.type === 'int64') return Number(value.value);
@@ -33,6 +33,38 @@ export function crewCountOf(profile: BlkBlock, country: string): number {
return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => crewCountry(crew) === country).length;
}
/** Non-empty vehicles currently slotted in the country's crews, in profile order. */
export function crewVehiclesOfCountry(profile: BlkBlock, country: string): string[] {
return allCrews(profile)
.filter((crew) => crewCountry(crew) === country)
.flatMap((crew) => {
const current = crew.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value.length > 0 ? [current.value] : [];
});
}
/** Vehicle slotted in the country's `slotIndex`-th crew (`idInCountry`), if non-empty. */
export function crewSlotVehicleOfCountry(profile: BlkBlock, country: string, slotIndex: number): string | undefined {
if (!Number.isInteger(slotIndex) || slotIndex < 0) return undefined;
const crew = allCrews(profile).filter((entry) => crewCountry(entry) === country)[slotIndex];
const current = crew?.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value.length > 0 ? current.value : undefined;
}
/** Crew block in `country` currently equipping `vehicle` (or trained for it as fallback). */
export function crewForVehicleInCountry(profile: BlkBlock, country: string, vehicle: string): BlkBlock | undefined {
const crews = allCrews(profile).filter((entry) => crewCountry(entry) === country);
const slotted = crews.find((entry) => {
const current = entry.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value === vehicle;
});
if (slotted) return slotted;
return crews.find((entry) =>
(entry.blocks.find((block) => block.name === VEHICLES)?.params ?? []).some(
(param) => param.name === TRAINED && param.value.type === 'string' && param.value.value === vehicle,
));
}
/** Add an empty crew for the country, numbered after every existing crew; returns its id. */
export function addCrew(profile: BlkBlock, country: string): number {
const crews = ensureBlock(profile, CREWS);
@@ -0,0 +1,96 @@
/**
* Cross-branch research-point redirection in profile.blk ("Research helicopters by playing
* ground vehicles", gui.vromfs.bin scripts/shop/shop.nut:2341-2354).
*
* Profile contract (verified in aces.exe 2.61.0.37 0x930150..0x93082a & 0x903ca0):
* researchUnits{
* country_usa{
* destTypeRPTank:t="Helicopter"
* }
* }
* - Reader (0x93020e..0x930247): reads "destTypeRP<SrcType>" inside researchUnits.<country>
* and maps it against VEHICLE_TYPES (0..6); missing or unrecognized values become -1
* (ES_UNIT_TYPE_INVALID), exposed to Squirrel by getDestinationRPUnitType (0x15532f0).
* - Writer (0x9307eb..0x93082a): writes "destTypeRP<SrcType>" only when 0 <= destType <= 6
* and omits the parameter when disabled (-1).
*/
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { TechTree } from '../research/tech-tree.ts';
import { VEHICLE_TYPES, vehicleTypeById, type VehicleType } from '../research/vehicle-types.ts';
import { removeParam, stringField } from './blk-fields.ts';
import { researchTarget } from './profile-research-targets.ts';
const RESEARCH_UNITS = 'researchUnits';
const DEST_TYPE_PREFIX = 'destTypeRP';
const INVALID_UNIT_TYPE = -1;
export type VehicleDomain = VehicleType;
const VALID_DOMAINS: ReadonlySet<string> = new Set<string>(VEHICLE_TYPES);
export function destinationRpDomain(
profile: BlkBlock,
country: string,
sourceDomain: VehicleDomain,
): VehicleDomain | undefined {
const countryBlock = findBlock(findBlock(profile, RESEARCH_UNITS) ?? { name: '', params: [], blocks: [] }, country);
const raw = stringField(countryBlock, `${DEST_TYPE_PREFIX}${sourceDomain}`);
if (!raw || !VALID_DOMAINS.has(raw) || raw === sourceDomain) return undefined;
return raw as VehicleDomain;
}
export function setDestinationRpDomain(
profile: BlkBlock,
country: string,
sourceDomain: VehicleDomain,
destinationDomain: VehicleDomain | undefined,
): void {
const countryBlock = ensureBlock(ensureBlock(profile, RESEARCH_UNITS), country);
const paramName = `${DEST_TYPE_PREFIX}${sourceDomain}`;
if (!destinationDomain || destinationDomain === sourceDomain) {
removeParam(countryBlock, paramName);
return;
}
removeParam(countryBlock, paramName);
countryBlock.params.push({ name: paramName, value: { type: 'string', value: destinationDomain } });
}
/** Validate and apply cln_set_dest_rp_unit_type (country:t, srcType:i, destType:i). */
export function applySetDestinationRpRule(
profile: BlkBlock,
techTree: TechTree,
country: string,
srcTypeId: number,
destTypeId: number,
): RuleOutcome {
const sourceDomain = vehicleTypeById(srcTypeId);
if (!country || !techTree.hasCountry(country) || !sourceDomain) return refused('BAD_PARAMS');
if (destTypeId === INVALID_UNIT_TYPE) {
setDestinationRpDomain(profile, country, sourceDomain, undefined);
return ACCEPTED;
}
const destinationDomain = vehicleTypeById(destTypeId);
if (!destinationDomain || destinationDomain === sourceDomain) return refused('BAD_PARAMS');
const hasDestinationBranch = techTree.branches().some(
(branch) => branch.country === country && branch.type === destinationDomain,
);
if (!hasDestinationBranch) return refused('NOT_AVAILABLE');
setDestinationRpDomain(profile, country, sourceDomain, destinationDomain);
return ACCEPTED;
}
/**
* Resolve the effective research branch for battle settlement: returns the redirected domain
* (such as 'Helicopter' when playing 'Tank') when configured and that branch still has an
* active currUnit research target, otherwise falls back to sourceDomain.
*/
export function readRedirectedResearchDomain(
profile: BlkBlock,
country: string,
sourceDomain: VehicleDomain,
): VehicleDomain {
const redirected = destinationRpDomain(profile, country, sourceDomain);
if (!redirected) return sourceDomain;
return researchTarget(profile, country, redirected) !== '' ? redirected : sourceDomain;
}
@@ -23,6 +23,12 @@ export function spendFreeResearchPoints(profile: BlkBlock, amount: number): void
setCounter(profile, SPENT, counter(profile, SPENT) + amount);
}
/** Credit convertible (free) research points earned in battle (`experience:i64`). */
export function addFreeResearchPoints(profile: BlkBlock, amount: number): void {
if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`);
if (amount > 0) setCounter(profile, EARNED, counter(profile, EARNED) + amount);
}
/** Make the free research points this amount (the save editor). */
export function setFreeResearchPoints(profile: BlkBlock, amount: number): void {
if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`);
@@ -1,6 +1,6 @@
/**
* The current research target and the just-finished research of each country and vehicle
* type.
* Current research target, just-finished research vehicle, and banked excess RP per country
* and vehicle branch (`aces.exe` `0x930150`):
*
* researchUnits{
* country_usa{
@@ -24,6 +24,7 @@ import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto
const RESEARCH_UNITS = 'researchUnits';
const CURRENT = 'currUnit';
const FINISHED = 'prevUnit';
const EXCESS_EXP = 'exp';
export function researchTarget(profile: BlkBlock, country: string, vehicleType: string): string {
return field(profile, country, `${CURRENT}${vehicleType}`);
@@ -41,6 +42,22 @@ export function setFinishedResearch(profile: BlkBlock, country: string, vehicleT
setField(profile, country, `${FINISHED}${vehicleType}`, vehicle);
}
export function branchExcessRp(profile: BlkBlock, country: string, vehicleType: string): number {
const units = findBlock(profile, RESEARCH_UNITS);
const block = units && findBlock(units, country);
const value = block && findParam(block, `${EXCESS_EXP}${vehicleType}`)?.value;
if (value?.type === 'int64') return Math.max(0, Number(value.value));
return value?.type === 'int' ? Math.max(0, value.value) : 0;
}
export function setBranchExcessRp(profile: BlkBlock, country: string, vehicleType: string, amount: number): void {
const clamped = Math.max(0, Math.trunc(amount));
setParam(ensureBlock(ensureBlock(profile, RESEARCH_UNITS), country), `${EXCESS_EXP}${vehicleType}`, {
type: 'int64',
value: BigInt(clamped),
});
}
function field(profile: BlkBlock, country: string, name: string): string {
const units = findBlock(profile, RESEARCH_UNITS);
const block = units && findBlock(units, country);
@@ -12,7 +12,8 @@ const TROPHIES = 'trophies';
const USERLOGS = 'userlogs';
const PURCHASE_RECEIPT = 'purchaseReceipt';
// Registered by the client at 0x1a5569e (2.61.0.37).
// Registered by the client at 0x1a554dc / 0x1a5569e / 0x1a5599b (2.61.0.37).
export const EULT_SESSION_RESULT = 2;
const EULT_BUYENTITLEMENT = 13;
export const EULT_OPEN_TROPHY = 30;
export const EULT_BUY_TROPHY = 20;
@@ -32,6 +33,7 @@ export function incrementTrophyOpenCount(profile: BlkBlock, trophyId: string, de
export interface NewUserLogEntry {
readonly type: number;
readonly timeSec: number;
readonly roomId?: bigint;
readonly bodyParams: readonly BlkParam[];
readonly bodyBlocks?: readonly BlkBlock[];
}
@@ -53,7 +55,7 @@ export function appendUserLog(profile: BlkBlock, entry: NewUserLogEntry): string
params: [
{ name: 'type', value: { type: 'int', value: entry.type } },
{ name: 'time', value: { type: 'int', value: entry.timeSec } },
{ name: 'roomId', value: { type: 'int64', value: 0n } },
{ name: 'roomId', value: { type: 'int64', value: entry.roomId ?? 0n } },
],
blocks: [{
name: 'body',
@@ -1,17 +1,20 @@
/**
* Per-vehicle fields of owned vehicles: hangar{ <vehicle>{ ... } },
* read by name by AircraftInfo::serialize (aces.exe 0x940510). Only the fields the local
* service maintains are handled here:
* investMode:t the modification being researched (empty = none)
* tierNumber:i the highest open modification tier (script is_tier_available)
* spareAircraftsCount:i spares the player has for this vehicle
* Per-vehicle fields of owned vehicles under `hangar{ <vehicle>{ ... } }`, read by name in
* `AircraftInfo::serialize` (`aces.exe` `0x940510`):
* investMode:t the modification currently selected for research (`+0x100`)
* investModePrev:t the modification whose research just finished (`+0x108`)
* tierNumber:i the highest open modification tier
* spareAircraftsCount:i vehicle-specific backups owned
* excessExp:i64 banked modification overflow RP (`+0x70`)
*/
import { findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const HANGAR = 'hangar';
const RESEARCH_TARGET = 'investMode';
const FINISHED_TARGET = 'investModePrev';
const OPEN_TIER = 'tierNumber';
const SPARES = 'spareAircraftsCount';
const EXCESS_EXP = 'excessExp';
export function moduleResearchTarget(profile: BlkBlock, vehicle: string): string {
const value = fieldOf(profile, vehicle, RESEARCH_TARGET);
@@ -23,6 +26,16 @@ export function setModuleResearchTarget(profile: BlkBlock, vehicle: string, modi
if (entry) setParam(entry, RESEARCH_TARGET, { type: 'string', value: modification });
}
export function finishedModuleResearch(profile: BlkBlock, vehicle: string): string {
const value = fieldOf(profile, vehicle, FINISHED_TARGET);
return value?.type === 'string' ? value.value : '';
}
export function setFinishedModuleResearch(profile: BlkBlock, vehicle: string, modification: string): void {
const entry = vehicleEntry(profile, vehicle);
if (entry) setParam(entry, FINISHED_TARGET, { type: 'string', value: modification });
}
export function setOpenTier(profile: BlkBlock, vehicle: string, tier: number): void {
const entry = vehicleEntry(profile, vehicle);
if (entry) setParam(entry, OPEN_TIER, { type: 'int', value: tier });
@@ -38,6 +51,17 @@ export function setSpareCount(profile: BlkBlock, vehicle: string, count: number)
if (entry) setParam(entry, SPARES, { type: 'int', value: count });
}
export function vehicleExcessRp(profile: BlkBlock, vehicle: string): number {
const value = fieldOf(profile, vehicle, EXCESS_EXP);
if (value?.type === 'int64') return Math.max(0, Number(value.value));
return value?.type === 'int' ? Math.max(0, value.value) : 0;
}
export function setVehicleExcessRp(profile: BlkBlock, vehicle: string, amount: number): void {
const entry = vehicleEntry(profile, vehicle);
if (entry) setParam(entry, EXCESS_EXP, { type: 'int64', value: BigInt(Math.max(0, Math.trunc(amount))) });
}
function fieldOf(profile: BlkBlock, vehicle: string, name: string) {
const entry = vehicleEntry(profile, vehicle);
return entry && findParam(entry, name)?.value;
@@ -0,0 +1,98 @@
/**
* Vehicle wishlist persistence in profile.blk (cln_add_to_wish_list / cln_remove_from_wish_list).
*
* Binary & script contract (verified in aces.exe 2.61.0.37 0x967c30..0x96891b, getWishList
* 0x1553470, and gui.vromfs.bin scripts/wishlist/wishlistManager.nut):
* wishList{
* units{
* us_m1_abrams{
* cmnts:t="optional note"
* ts:i64=1764260000
* }
* }
* }
* - When reading profile.blk (0x967c40..0x967d8a), if top-level "wishList" is absent the client
* returns early without clearing its in-memory wishlist vector ([econ + 0xe868]). Keeping an
* empty wishList { units {} } block on removal ensures 0x967ebd..0x967f19 clears the client's
* vector immediately upon profile sync.
* - Static limits come from char.vromfs.bin config/warpoints.blk: maxWishListSize:i=100 and
* maxWishListCommentSize:i=100 (exposed via getMaxWishListSize 0x1553450 and
* getMaxWishListCommentSize 0x1553460).
*/
import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { TechTree } from '../research/tech-tree.ts';
import { int64Field, stringField } from './blk-fields.ts';
import { ownsVehicle } from './profile-hangar.ts';
const WISH_LIST_BLOCK = 'wishList';
const UNITS_BLOCK = 'units';
const COMMENT_PARAM = 'cmnts';
const TIMESTAMP_PARAM = 'ts';
/** Limits defined in char.vromfs.bin config/warpoints.blk (maxWishListSize / maxWishListCommentSize). */
export const DEFAULT_WISHLIST_LIMITS: WishlistLimits = {
maxSize: 100,
maxCommentLength: 100,
};
export interface WishlistLimits {
readonly maxSize: number;
readonly maxCommentLength: number;
}
export interface WishlistEntry {
readonly unit: string;
readonly comment: string;
readonly timestampSec: number;
}
export function readWishlist(profile: BlkBlock): WishlistEntry[] {
const unitsBlock = findBlock(findBlock(profile, WISH_LIST_BLOCK) ?? { name: '', params: [], blocks: [] }, UNITS_BLOCK);
if (!unitsBlock) return [];
return unitsBlock.blocks
.filter((entry) => entry.name.length > 0)
.map((entry) => ({
unit: entry.name,
comment: stringField(entry, COMMENT_PARAM),
timestampSec: Number(int64Field(entry, TIMESTAMP_PARAM, 0n)),
}));
}
export function hasWishlistUnit(profile: BlkBlock, unit: string): boolean {
const unitsBlock = findBlock(findBlock(profile, WISH_LIST_BLOCK) ?? { name: '', params: [], blocks: [] }, UNITS_BLOCK);
return unitsBlock !== undefined && unitsBlock.blocks.some((entry) => entry.name === unit);
}
export function addWishlistUnit(
profile: BlkBlock,
techTree: TechTree,
unit: string,
comment: string,
timestampSec: number,
limits: WishlistLimits = DEFAULT_WISHLIST_LIMITS,
): RuleOutcome {
if (!unit || [...comment].length > limits.maxCommentLength) return refused('BAD_PARAMS');
const vehicle = techTree.vehicle(unit);
if (!vehicle || vehicle.kind === 'part' || vehicle.kind === 'hidden') return refused('BAD_PARAMS');
if (ownsVehicle(profile, unit) || hasWishlistUnit(profile, unit)) return refused('NOT_AVAILABLE');
const unitsBlock = ensureWishlistUnitsBlock(profile);
if (unitsBlock.blocks.length >= limits.maxSize) return refused('NOT_AVAILABLE');
const params: BlkParam[] = [];
if (comment.length > 0) params.push({ name: COMMENT_PARAM, value: { type: 'string', value: comment } });
params.push({ name: TIMESTAMP_PARAM, value: { type: 'int64', value: BigInt(Math.max(0, Math.trunc(timestampSec))) } });
unitsBlock.blocks.push({ name: unit, params, blocks: [] });
return ACCEPTED;
}
export function removeWishlistUnit(profile: BlkBlock, unit: string): RuleOutcome {
if (!unit) return refused('BAD_PARAMS');
const unitsBlock = ensureWishlistUnitsBlock(profile);
unitsBlock.blocks = unitsBlock.blocks.filter((entry) => entry.name !== unit);
return ACCEPTED;
}
function ensureWishlistUnitsBlock(profile: BlkBlock): BlkBlock {
return ensureBlock(ensureBlock(profile, WISH_LIST_BLOCK), UNITS_BLOCK);
}
@@ -1,31 +1,32 @@
/**
* Choosing what to research and putting research points into a vehicle (implementation notes
* sections 1.2, 4.3 and 5).
*
* - Choosing a research target (cln_set_researchable) makes a researchable vehicle the
* target of its country and type and closes the "research finished" prompt.
* - Dismissing that prompt (cln_reset_researchable) only closes it.
* - Converting free research points (cln_convert_exp) costs the points and golden eagles:
* one golden eagle per researchPointsPerGoldenEagle points, rounded up. The stock window
* (scripts/convertExp/convertExpHandler.nut) never asks for more than the vehicle still
* needs; more is cut down to that.
* - When a vehicle's research points reach what it needs and it is the target, the target is
* cleared and the vehicle recorded as just finished, which makes the client offer the next
* research; the refresh after the change (research-state.ts) then picks the next target.
* Choosing a vehicle research target (`cln_set_researchable`), dismissing a finished-research
* prompt (`cln_reset_researchable`), converting free RP (`cln_convert_exp`), and investing
* banked branch excess RP (`cln_move_exp_to_unit`).
*/
import type { BlkBlock } from '@wto/blk';
import { balanceOf, pay } from '../profile/profile-currency.ts';
import { freeResearchPoints, spendFreeResearchPoints } from '../profile/profile-research-points.ts';
import { researchTarget, setFinishedResearch, setResearchTarget } from '../profile/profile-research-targets.ts';
import {
branchExcessRp,
researchTarget,
setBranchExcessRp,
setFinishedResearch,
setResearchTarget,
} from '../profile/profile-research-targets.ts';
import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts';
import { currentStatus } from './research-state.ts';
import type { ResearchRules } from './research-rules.ts';
import { currentStatus } from './research-state.ts';
import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts';
import type { TreeVehicle } from './tech-tree.ts';
import { VehicleStatus } from './vehicle-status.ts';
import { vehicleTypeById } from './vehicle-types.ts';
export function chooseResearchTarget(profile: BlkBlock, rules: ResearchRules, vehicleName: string, typeId: number): RuleOutcome {
export function chooseResearchTarget(
profile: BlkBlock,
rules: ResearchRules,
vehicleName: string,
typeId: number,
): RuleOutcome {
const vehicle = rules.techTree.vehicle(vehicleName);
if (!vehicle || vehicleTypeById(typeId) !== vehicle.type) return refused('BAD_PARAMS');
if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
@@ -34,14 +35,24 @@ export function chooseResearchTarget(profile: BlkBlock, rules: ResearchRules, ve
return ACCEPTED;
}
export function dismissFinishedResearch(profile: BlkBlock, rules: ResearchRules, country: string, typeId: number): RuleOutcome {
export function dismissFinishedResearch(
profile: BlkBlock,
rules: ResearchRules,
country: string,
typeId: number,
): RuleOutcome {
const type = vehicleTypeById(typeId);
if (!type || !rules.techTree.hasCountry(country)) return refused('BAD_PARAMS');
setFinishedResearch(profile, country, type, '');
return ACCEPTED;
}
export function convertFreeResearchPoints(profile: BlkBlock, rules: ResearchRules, vehicleName: string, requested: number): RuleOutcome {
export function convertFreeResearchPoints(
profile: BlkBlock,
rules: ResearchRules,
vehicleName: string,
requested: number,
): RuleOutcome {
const vehicle = rules.techTree.vehicle(vehicleName);
if (!vehicle || !Number.isSafeInteger(requested) || requested <= 0) return refused('BAD_PARAMS');
if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
@@ -55,7 +66,28 @@ export function convertFreeResearchPoints(profile: BlkBlock, rules: ResearchRule
return ACCEPTED;
}
/** Add research points to a vehicle; finishing the research target opens the next-research prompt. */
export function moveExcessExpToUnit(profile: BlkBlock, rules: ResearchRules, vehicleName: string): RuleOutcome {
const vehicle = rules.techTree.vehicle(vehicleName);
if (!vehicle) return refused('BAD_PARAMS');
if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE');
const available = branchExcessRp(profile, vehicle.country, vehicle.type);
const before = researchPointsOf(profile, vehicle.name);
const needed = Math.max(0, vehicle.researchPoints - before);
const moved = Math.min(available, needed);
if (moved <= 0) return ACCEPTED;
const remaining = available - moved;
setBranchExcessRp(profile, vehicle.country, vehicle.type, remaining);
setResearchPoints(profile, vehicle.name, before + moved);
if (before + moved >= vehicle.researchPoints) {
setResearchTarget(profile, vehicle.country, vehicle.type, '');
setFinishedResearch(profile, vehicle.country, vehicle.type, remaining > 0 ? '' : vehicle.name);
} else {
setResearchTarget(profile, vehicle.country, vehicle.type, vehicle.name);
setFinishedResearch(profile, vehicle.country, vehicle.type, '');
}
return ACCEPTED;
}
export function addResearchPoints(profile: BlkBlock, vehicle: TreeVehicle, amount: number): void {
const before = researchPointsOf(profile, vehicle.name);
setResearchPoints(profile, vehicle.name, before + amount);
@@ -1,6 +1,6 @@
/**
* The static facts vehicle research and purchase rules use, loaded once at start-up from
* the player's game files (implementation notes; implementation notes).
* Static facts used by vehicle research and purchase rules, loaded once at startup from game
* files.
*/
import type { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import { crewSlotPrices, eraRequirements, type CrewSlotPrices, type EraRequirements } from '../game-data/datasets/rank-settings.ts';
@@ -16,7 +16,6 @@ export interface ResearchRules {
readonly vehicleUnlocks: readonly UnlockDefinition[];
readonly crewSlotPrices: CrewSlotPrices;
readonly researchPointsPerGoldenEagle: number;
/** How a branch without a research target gets one (tuning/research.jsonc; implementation notes). */
readonly researchTuning: ResearchTuning;
}
@@ -1,30 +1,32 @@
/**
* Bringing the research state of a profile up to date. The char
* server keeps it current online; the local service does it whenever a profile is handed out
* or changed (profile/player-profiles.ts), so the state always follows from the facts:
* owned vehicles, research points, earned unlocks.
*
* 1. Open ranks and earn unlocks until neither changes anything (an unlock can give a vehicle,
* a vehicle can open a rank, a rank can earn an unlock).
* 2. Write every vehicle's status into unitResearch: owned vehicles have no entry, locked
* vehicles only keep one while they hold research points.
* 3. Keep every branch researching while it can: a target that is no
* longer researchable (bought, researched, ...) is replaced, and a branch without one gets
* one, picked by auto-research-target.ts; "" only when nothing can be researched.
* Keeping a player's vehicle research state consistent with owned vehicles, earned unlocks,
* and branch research progress:
* 1. Open ranks and earn unlocks until neither changes anything.
* 2. Write every non-owned vehicle's status into `unitResearch`.
* 3. Maintain `currUnit<Branch>` without overwriting an intentionally empty target while
* banked `exp<Branch>` is being spent inside `ShopCheckResearch`, while seeding a default
* target on brand-new branches (`currUnit === "" && prevUnit === "" && excessRp === 0`)
* and autosetting a 0-RP cursor candidate when `prevUnit !== ""` so stock
* `researchActions.nut` (`checkNonApprovedResearches`) opens `ShopCheckResearch`.
*/
import type { BlkBlock } from '@wto/blk';
import { pickResearchTarget } from './auto-research-target.ts';
import type { TreeVehicle } from './tech-tree.ts';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { finishedResearch, researchTarget, setResearchTarget } from '../profile/profile-research-targets.ts';
import {
branchExcessRp,
finishedResearch,
researchTarget,
setBranchExcessRp,
setResearchTarget,
} from '../profile/profile-research-targets.ts';
import { earnedUnlocks } from '../profile/profile-unlocks.ts';
import { removeVehicleResearch, researchPointsOf, setVehicleStatus } from '../profile/profile-vehicle-research.ts';
import { pickResearchTarget } from './auto-research-target.ts';
import { openEarnedRanks } from './era-progress.ts';
import type { ResearchRules } from './research-rules.ts';
import { earnVehicleUnlocks } from './vehicle-unlock-rules.ts';
import type { TreeVehicle } from './tech-tree.ts';
import { VehicleStatus, vehicleStatuses } from './vehicle-status.ts';
import { earnVehicleUnlocks } from './vehicle-unlock-rules.ts';
/** More rounds than any chain in the game data needs; stops a faulty data loop. */
const MAX_ROUNDS = 16;
export function refreshResearchState(profile: BlkBlock, rules: ResearchRules): void {
@@ -39,26 +41,33 @@ export function refreshResearchState(profile: BlkBlock, rules: ResearchRules): v
const statuses = vehicleStatuses({ profile, owned, earnedUnlocks: earned, techTree: rules.techTree });
for (const vehicle of rules.techTree.all()) {
const status = statuses.get(vehicle.name);
if (status === undefined || (status === VehicleStatus.LOCKED && researchPointsOf(profile, vehicle.name) === 0)) removeVehicleResearch(profile, vehicle.name);
else setVehicleStatus(profile, vehicle.name, status);
if (status === undefined || (status === VehicleStatus.LOCKED && researchPointsOf(profile, vehicle.name) === 0)) {
removeVehicleResearch(profile, vehicle.name);
} else {
setVehicleStatus(profile, vehicle.name, status);
}
}
const candidates = researchCandidates(rules, statuses);
const unresearchedBranches = branchesWithUnresearchedTreeVehicles(rules, statuses);
for (const { country, type } of rules.techTree.branches()) {
const key = `${country}/${type}`;
if (!unresearchedBranches.has(key)) {
setBranchExcessRp(profile, country, type, 0);
}
const target = researchTarget(profile, country, type);
if (target && statuses.get(target) === VehicleStatus.CAN_RESEARCH) continue;
const previous = target || finishedResearch(profile, country, type);
const next = pickResearchTarget(candidates.get(`${country}/${type}`) ?? [], rules.researchTuning, previous);
setResearchTarget(profile, country, type, next?.name ?? '');
if (target) setResearchTarget(profile, country, type, '');
const prev = finishedResearch(profile, country, type);
const excess = branchExcessRp(profile, country, type);
if (prev !== '' || excess === 0) {
const next = pickResearchTarget(candidates.get(key) ?? [], rules.researchTuning, target || prev);
setResearchTarget(profile, country, type, next?.name ?? '');
}
}
}
/**
* The vehicles a branch target can be chosen from, by "country/type": what the stock scripts
* offer as a research target (scripts/unit/unitStatus.nut canResearchUnit; squadron vehicles
* have their own target, implementation notes, and are left out as scripts/shop/shopCheckResearch.nut
* getMaxRankResearchingUnitByCountry does).
*/
function researchCandidates(rules: ResearchRules, statuses: ReadonlyMap<string, VehicleStatus>): Map<string, TreeVehicle[]> {
const byBranch = new Map<string, TreeVehicle[]>();
for (const vehicle of rules.techTree.all()) {
@@ -71,7 +80,26 @@ function researchCandidates(rules: ResearchRules, statuses: ReadonlyMap<string,
return byBranch;
}
/** The current status of one vehicle the player does not own; undefined when it is owned or unknown. */
function branchesWithUnresearchedTreeVehicles(
rules: ResearchRules,
statuses: ReadonlyMap<string, VehicleStatus>,
): Set<string> {
const branches = new Set<string>();
for (const vehicle of rules.techTree.all()) {
if (vehicle.kind !== 'research') continue;
const status = statuses.get(vehicle.name);
if (status === VehicleStatus.CAN_RESEARCH || status === VehicleStatus.LOCKED) {
branches.add(`${vehicle.country}/${vehicle.type}`);
}
}
return branches;
}
export function currentStatus(profile: BlkBlock, rules: ResearchRules, vehicle: string): VehicleStatus | undefined {
return vehicleStatuses({ profile, owned: ownedVehicles(profile), earnedUnlocks: earnedUnlocks(profile), techTree: rules.techTree }).get(vehicle);
return vehicleStatuses({
profile,
owned: ownedVehicles(profile),
earnedUnlocks: earnedUnlocks(profile),
techTree: rules.techTree,
}).get(vehicle);
}
@@ -1,14 +1,17 @@
/**
* The local service's one listening port. Every address in the game's network.blk points
* here, and the network hook library sends every other connection of the
* game here too (5.1), so connections arrive in several protocols. The first bytes of a
* connection decide where it goes: the matching protocol (first byte 1, see
* matching/matching-frame.ts) to the matching service; a TLS handshake (record type 0x16) is
* answered with the local certificate and the decrypted stream goes to the HTTP server;
* everything else (HTTP, other) goes to the HTTP server directly.
* The local service's single listening port. Every address in the game's network.blk points
* here, and the network hook library routes all other outbound game connections here as well.
* The first bytes of a connection decide which protocol handler accepts it:
* - Matching binary packet (first byte 1) -> MatchingService;
* - Plaintext IRC handshake (`PASS` / `NICK` / `USER` / `CAP` / `PING`) -> IrcServer;
* - TLS ClientHello (record type 0x16) -> decrypted with the local certificate, then routed
* to IrcServer or the HTTP server based on the first decrypted bytes;
* - Everything else -> HTTP server directly.
*/
import { createServer, type Server, type Socket } from 'node:net';
import { createSecureContext, TLSSocket } from 'node:tls';
import { startsIrcHandshake } from '../chat/irc-protocol.ts';
import { IrcServer } from '../chat/irc-server.ts';
import type { TlsCredentials } from './tls/tls-certificate.ts';
import type { MatchingRequestTable } from '../matching/matching-requests.ts';
import { MatchingService } from '../matching/matching-service.ts';
@@ -34,6 +37,7 @@ export function createPortListener(router: Router, matchingRequests: MatchingReq
let lastNumber = 0;
const http = createHttpServer(router, log, (socket) => numbers.get(socket) ?? 0);
const matching = new MatchingService(matchingRequests, log);
const irc = new IrcServer();
const server = createServer((socket) => {
lastNumber += 1;
@@ -51,11 +55,18 @@ export function createPortListener(router: Router, matchingRequests: MatchingReq
socket.pause();
socket.unshift(first);
if (startsMatchingPacket(first)) matching.accept(socket, number);
else if (startsIrcHandshake(first)) irc.accept(socket);
else if (first[0] === TLS_HANDSHAKE) {
const secure = new TLSSocket(socket, { isServer: true, secureContext });
numbers.set(secure, number);
secure.on('error', () => socket.destroy());
http.emit('connection', secure);
secure.once('data', (innerFirst: Buffer) => {
secure.pause();
secure.unshift(innerFirst);
if (startsIrcHandshake(innerFirst)) irc.accept(secure);
else http.emit('connection', secure);
process.nextTick(() => secure.resume());
});
} else http.emit('connection', socket);
process.nextTick(() => socket.resume());
});
@@ -1,6 +1,5 @@
/**
* The JSON requests of the local store page (/store, shown in the game's built-in browser;
* implementation notes):
* The JSON requests of the local store page (/store, shown in the game's built-in browser):
* GET /store/api/state?userId= balances, products and redeem code help for one account
* POST /store/api/buy { userId, productId }
* POST /store/api/cart { userId, productId, action }
+115 -89
View File
@@ -2,6 +2,7 @@
'use strict';
const galleryPlayers = new WeakMap();
const CLIP_TIMEOUT_MS = 23_000;
function stopStoreGallery(root) {
const stage = root.querySelector('.media-stage');
@@ -29,8 +30,7 @@ function galleryItems(product) {
return entries;
}
function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable) {
galleryPlayers.get(stage)?.();
function createClipVideoElement(poster, autoplay) {
const video = document.createElement('video');
video.controls = true;
video.playsInline = true;
@@ -41,6 +41,12 @@ function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable)
video.loop = true;
}
if (poster) video.poster = poster;
return video;
}
function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable) {
galleryPlayers.get(stage)?.();
const video = createClipVideoElement(poster, autoplay);
const playable = sources.filter((url) => video.canPlayType(/\.webm(?:$|\?)/i.test(url) ? 'video/webm' : 'video/mp4'));
let nextSource = 0;
let timer;
@@ -64,34 +70,125 @@ function playStoreClip(stage, sources, poster, autoplay, onReady, onUnavailable)
return;
}
video.src = url;
timer = setTimeout(attempt, 23_000);
timer = setTimeout(attempt, CLIP_TIMEOUT_MS);
void video.play().catch(() => {});
}
video.onerror = attempt;
video.oncanplay = () => {
clearTimeout(timer);
onReady();
};
video.oncanplay = () => { clearTimeout(timer); onReady(); };
stage.replaceChildren(video);
galleryPlayers.set(stage, dispose);
attempt();
}
function appendScreenshot(container, item, loaded, eager = false) {
const candidates = storeImageCandidates(item.screenshot);
const image = makeElement('img', 'gallery-screenshot');
image.alt = eager ? item.label : '';
image.loading = eager ? 'eager' : 'lazy';
image.crossOrigin = 'anonymous';
image.referrerPolicy = 'no-referrer';
let index = 0;
function tryNext() {
const nextUrl = candidates[index++];
if (!nextUrl) {
image.onload = image.onerror = null;
image.remove();
loaded(false);
return;
}
image.src = nextUrl;
}
image.onload = () => {
image.onload = image.onerror = null;
image.classList.add('ready');
loaded(true);
};
image.onerror = () => loaded(false);
image.src = item.screenshot;
image.onerror = tryNext;
container.append(image);
tryNext();
return image;
}
function renderStageScreenshot(stage, status, product, item) {
const gameArt = WtoUi.tieredImg([], productArtwork(product), '');
gameArt.loading = 'eager';
stage.append(gameArt);
status.textContent = t('screenshotLoading');
status.hidden = false;
const image = appendScreenshot(stage, item, (ok) => {
if (image.parentNode !== stage) return;
if (ok) {
gameArt.remove();
status.hidden = true;
} else {
status.textContent = t('screenshotUnavailable');
}
}, true);
}
function renderStageMedia(stage, status, product, item, showPlay, onPlay) {
stage.replaceChildren();
if (item.screenshot) {
renderStageScreenshot(stage, status, product, item);
return;
}
const image = item.image();
image.loading = 'eager';
image.alt = item.label;
stage.append(image);
if (!showPlay) return;
const play = storeButton('media-play', '▶ ' + t('playVideo'));
play.onclick = () => onPlay(item, false);
stage.append(play);
}
function startStageVideo(stage, status, product, item, autoplay) {
const image = stage.querySelector('img');
const poster = image?.currentSrc || image?.getAttribute('src');
status.textContent = t('videoLoading');
status.hidden = false;
playStoreClip(stage, item.sources, poster, autoplay, () => { status.hidden = true; }, () => {
renderStageMedia(stage, status, product, item, true, (target, auto) => startStageVideo(stage, status, product, target, auto));
status.textContent = t('videoUnavailable');
status.hidden = false;
});
}
function createGalleryThumb(item, index, onSelect) {
const button = storeButton('media-thumb');
button.setAttribute('aria-label', item.label);
button.setAttribute('aria-pressed', 'false');
button.title = item.label;
if (item.screenshot) {
const label = makeElement('span', 'media-placeholder', item.label);
button.append(label);
appendScreenshot(button, item, (ok) => { if (ok) label.remove(); });
} else {
button.append(item.image());
}
if (item.sources) button.append(makeElement('span', 'thumb-play', '▶'));
button.onclick = () => onSelect(index, true);
return button;
}
function bindGalleryControls(nav, rail, prev, next, buttons, itemsLength, getActive, onSelect) {
prev.setAttribute('aria-label', t('previousMedia'));
next.setAttribute('aria-label', t('nextMedia'));
prev.onclick = () => onSelect(getActive() - 1);
next.onclick = () => onSelect(getActive() + 1);
rail.append(...buttons);
rail.onkeydown = (event) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
event.preventDefault();
onSelect(getActive() + (event.key === 'ArrowRight' ? 1 : -1));
buttons[getActive()].focus({ preventScroll: true });
};
nav.hidden = itemsLength === 1;
}
function mountStoreGallery(root, product, autoplay) {
const items = galleryItems(product);
root.innerHTML = '<div class="media-stage"></div><div class="media-navigation"><button type="button">‹</button>'
@@ -106,51 +203,7 @@ function mountStoreGallery(root, product, autoplay) {
const caption = root.querySelector('.media-caption');
const status = root.querySelector('.media-status');
let active = 0;
function showImage(item, showPlay) {
stage.replaceChildren();
if (item.screenshot) {
showScreenshot(item);
return;
}
const image = item.image();
image.loading = 'eager';
image.alt = item.label;
stage.append(image);
if (!showPlay) return;
const play = storeButton('media-play', '▶ ' + t('playVideo'));
play.onclick = () => playItem(item);
stage.append(play);
}
function showScreenshot(item) {
const gameArt = WtoUi.tieredImg([], productArtwork(product), '');
gameArt.loading = 'eager';
stage.append(gameArt);
status.textContent = t('screenshotLoading');
status.hidden = false;
const image = appendScreenshot(stage, item, (ok) => {
if (image.parentNode !== stage) return;
if (ok) {
gameArt.remove();
status.hidden = true;
} else {
status.textContent = t('screenshotUnavailable');
}
}, true);
}
function playItem(item, autoplay = false) {
const image = stage.querySelector('img');
const poster = image?.currentSrc || image?.getAttribute('src');
status.textContent = t('videoLoading');
status.hidden = false;
playStoreClip(stage, item.sources, poster, autoplay, () => { status.hidden = true; }, () => {
showImage(item, true);
status.textContent = t('videoUnavailable');
status.hidden = false;
});
}
const playItem = (item, auto = false) => startStageVideo(stage, status, product, item, auto);
function select(index, play = false, scroll = true) {
if (index < 0 || index >= items.length) return;
@@ -158,47 +211,20 @@ function mountStoreGallery(root, product, autoplay) {
buttons[active].setAttribute('aria-pressed', 'false');
active = index;
const item = items[index];
const button = buttons[index];
button.setAttribute('aria-pressed', 'true');
if (scroll) button.scrollIntoView({ block: 'nearest', inline: 'nearest' });
buttons[index].setAttribute('aria-pressed', 'true');
if (scroll) buttons[index].scrollIntoView({ block: 'nearest', inline: 'nearest' });
prev.disabled = index === 0;
next.disabled = index === items.length - 1;
caption.querySelector('.media-label').textContent = item.label;
caption.querySelector('.media-position').textContent = (index + 1) + ' / ' + items.length;
status.hidden = true;
showImage(item, !!item.sources);
if (play && item.sources) playItem(item);
renderStageMedia(stage, status, product, item, !!item.sources, playItem);
if (play && item.sources) playItem(item, false);
}
const buttons = items.map((item, index) => {
const button = storeButton('media-thumb');
button.setAttribute('aria-label', item.label);
button.setAttribute('aria-pressed', 'false');
button.title = item.label;
if (item.screenshot) {
const label = makeElement('span', 'media-placeholder', item.label);
button.append(label);
appendScreenshot(button, item, (ok) => { if (ok) label.remove(); });
} else {
button.append(item.image());
}
if (item.sources) button.append(makeElement('span', 'thumb-play', '▶'));
button.onclick = () => select(index, true);
return button;
});
prev.setAttribute('aria-label', t('previousMedia'));
next.setAttribute('aria-label', t('nextMedia'));
prev.onclick = () => select(active - 1);
next.onclick = () => select(active + 1);
rail.append(...buttons);
rail.onkeydown = (event) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
event.preventDefault();
select(active + (event.key === 'ArrowRight' ? 1 : -1));
buttons[active].focus({ preventScroll: true });
};
nav.hidden = caption.hidden = items.length === 1;
const buttons = items.map((item, index) => createGalleryThumb(item, index, select));
bindGalleryControls(nav, rail, prev, next, buttons, items.length, () => active, select);
caption.hidden = items.length === 1;
select(0, false, false);
const initial = items[0];
if (autoplay && initial.sources) playItem(initial, true);
if (autoplay && items[0].sources) playItem(items[0], true);
}
@@ -24,19 +24,31 @@ function rankLabel(rank) {
return t('rank', { rank: ROMAN[rank] || rank });
}
const LOCAL_STORE_MEDIA_PREFIX = '/_wto/ui/store-media/';
const PUBLIC_STORE_CDN = 'https://static-store.gaijin.net/';
function storeImageCandidates(localUrl) {
if (!localUrl) return [];
if (!localUrl.startsWith(LOCAL_STORE_MEDIA_PREFIX)) return [localUrl];
return [localUrl, PUBLIC_STORE_CDN + localUrl.slice(LOCAL_STORE_MEDIA_PREFIX.length)];
}
function productArtwork(product) {
const image = product.unitName ? WtoUi.artworkUrl('vehicle', product.unitName) : WtoUi.artworkUrl('product', product.kind);
return product.artworkGroup ? [WtoUi.artworkUrl('group', product.artworkGroup), image] : [image];
const fallbacks = product.artworkGroup ? [WtoUi.artworkUrl('group', product.artworkGroup), image] : [image];
if (product.unitName) fallbacks.push('/_wto/ui/vehicle/' + encodeURIComponent(product.unitName) + '.svg');
return fallbacks;
}
function productImage(product, className = '') {
const { cover } = WtoUi.storeMedia(product.id);
const urls = product.unitName ? [cover, ...WtoUi.vehicleUrls(product.unitName)] : [cover];
const candidates = storeImageCandidates(cover);
const urls = product.unitName ? [...candidates, ...WtoUi.vehicleUrls(product.unitName)] : candidates;
return WtoUi.tieredImg(urls, productArtwork(product), className);
}
function productScreenshot(product, url, className = '') {
return WtoUi.tieredImg([url], productArtwork(product), className);
return WtoUi.tieredImg(storeImageCandidates(url), productArtwork(product), className);
}
function vehicleMeta(vehicle) {
@@ -4,11 +4,13 @@ import type { TuningReader } from './tuning-reader.ts';
export interface LimitsTuning {
readonly itemPiecesPerPurchase: number;
readonly userLogsKept: number;
readonly battleSessionsKept: number;
}
export function readLimitsTuning(file: TuningReader): LimitsTuning {
return {
itemPiecesPerPurchase: file.int('itemPiecesPerPurchase', { min: 1 }),
userLogsKept: file.int('userLogsKept', { min: 1 }),
battleSessionsKept: file.int('battleSessionsKept', { min: 1 }),
};
}
@@ -4,6 +4,7 @@
* limits, preset content). Values the game data already has are read from the game files
* instead, and protocol constants stay in the code next to their source.
*/
import { readBattleTuning, type BattleTuning } from '../battle/battle-tuning.ts';
import { readClanTuning, type ClanTuning } from '../clans/clan-tuning.ts';
import { readMarketplaceTuning, type MarketplaceTuning } from '../inventory/marketplace-tuning.ts';
import { readRecyclingTuning, type RecyclingTuning } from '../inventory/recycling-tuning.ts';
@@ -26,6 +27,7 @@ export interface Tuning {
readonly recycling: RecyclingTuning;
readonly trophies: TrophyTuning;
readonly clans: ClanTuning;
readonly battle: BattleTuning;
readonly limits: LimitsTuning;
}
@@ -41,6 +43,7 @@ export function loadTuning(dataFolder: string, report: (line: string) => void):
recycling: readRecyclingTuning(files.read('recycling')),
trophies: readTrophyTuning(files.read('trophies')),
clans: readClanTuning(files.read('clans')),
battle: readBattleTuning(files.read('battle')),
limits: readLimitsTuning(files.read('limits')),
};
}
@@ -1,12 +1,18 @@
/** Fetch and cache only public media named in the bundled store manifest. */
/**
* Serve pre-cached store covers, screenshots, and demo clips from local disk only.
*
* The local service listens strictly on loopback and never initiates outbound network
* requests: files present in the player's offline asset pack or local media cache are
* served directly (with HTTP byte-range support for video playback), while uncached
* paths immediately return 404 so the browser UI falls back without stalling.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { ServiceResponse } from '../server/exchange.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts';
export const STORE_MEDIA_PREFIX = 'store-media/';
const CDN = 'https://static-store.gaijin.net/';
const STORE_HOST = 'static-store.gaijin.net';
const MANIFEST = new URL('./web/official-store-media.json', import.meta.url);
const CONTENT_TYPES: Readonly<Record<string, string>> = {
jpg: 'image/jpeg', webm: 'video/webm', mp4: 'video/mp4',
@@ -32,28 +38,30 @@ function knownAssets(): ReadonlyMap<string, string> {
export class StoreMediaCache {
readonly #assets = knownAssets();
readonly #packFolder: string;
readonly #cacheFolder: string;
readonly #pending = new Map<string, Promise<Buffer | undefined>>();
readonly #retryAfter = new Map<string, number>();
readonly #roots: readonly string[];
constructor(dataFolder: string) {
this.#packFolder = join(dataFolder, 'asset-pack', new URL(CDN).hostname);
this.#cacheFolder = join(dataFolder, 'cache', 'store-media');
this.#roots = [
join(dataFolder, 'asset-pack', STORE_HOST),
join(dataFolder, 'cache', 'store-media'),
join(dataFolder, 'store-media-cache'),
join(dataFolder, 'store-assets'),
];
}
async serve(path: string, range: string | undefined): Promise<ServiceResponse> {
serve(path: string, range: string | undefined): ServiceResponse {
const type = this.#assets.get(path);
if (!type) return { status: 404, logNotes: { summary: 'unknown store media' } };
const cachedPath = join(this.#cacheFolder, path);
const bytes = readCached(join(this.#packFolder, path)) ?? readCached(cachedPath)
?? await this.#downloadOnce(path, type, cachedPath);
const logNotes = { summary: 'store media: ' + path, omitResponseBody: true };
const bytes = this.#readLocal(path);
if (!bytes) {
return { status: 503, headers: { 'cache-control': 'no-store' }, logNotes: { ...logNotes, summary: 'store media unavailable: ' + path } };
return {
status: 404,
headers: { 'cache-control': 'no-store' },
logNotes: { summary: 'store media not cached: ' + path },
};
}
const logNotes = { summary: 'store media: ' + path, omitResponseBody: true };
const headers = { 'content-type': type, 'cache-control': 'public, max-age=86400', 'accept-ranges': 'bytes' };
if (!range) return { status: 200, headers: { ...headers, 'content-length': String(bytes.length) }, body: bytes, logNotes };
const span = parseRange(range, bytes.length);
@@ -68,22 +76,12 @@ export class StoreMediaCache {
};
}
async #downloadOnce(path: string, type: string, cachedPath: string): Promise<Buffer | undefined> {
if ((this.#retryAfter.get(path) ?? 0) > Date.now()) return undefined;
const pending = this.#pending.get(path);
if (pending) return pending;
const work = downloadAsset(path, type).then((bytes) => {
if (bytes) {
this.#retryAfter.delete(path);
try { writeFileAtomic(cachedPath, bytes); } catch { /* The response is usable even if the disk cache is unavailable. */ }
} else {
this.#retryAfter.set(path, Date.now() + 30_000);
}
return bytes;
}).finally(() => { this.#pending.delete(path); });
this.#pending.set(path, work);
return work;
#readLocal(path: string): Buffer | undefined {
for (const root of this.#roots) {
const bytes = readCached(join(root, path));
if (bytes) return bytes;
}
return undefined;
}
}
@@ -97,49 +95,6 @@ function readCached(path: string): Buffer | undefined {
}
}
async function downloadAsset(path: string, type: string): Promise<Buffer | undefined> {
const video = type.startsWith('video/');
const signal = AbortSignal.timeout(video ? 20_000 : 7_500);
for (let attempt = 0; attempt < 2 && !signal.aborted; attempt++) {
try {
const response = await fetch(new URL(path, CDN), { signal, redirect: 'error' });
if (response.ok && response.headers.get('content-type')?.split(';', 1)[0] === type) {
return await readMediaBody(response, (video ? 64 : 8) * 1024 * 1024);
}
await response.body?.cancel();
if (response.status < 500) return undefined;
} catch {
// Retry a transient connection error within the original time limit.
}
}
return undefined;
}
async function readMediaBody(response: Response, limit: number): Promise<Buffer | undefined> {
const reader = response.body?.getReader();
if (!reader) return undefined;
try {
if (Number(response.headers.get('content-length')) > limit) {
await reader.cancel();
return undefined;
}
const chunks: Uint8Array[] = [];
let bytes = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) return bytes ? Buffer.concat(chunks, bytes) : undefined;
bytes += value.length;
if (bytes > limit) {
await reader.cancel();
return undefined;
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
}
function parseRange(range: string, size: number): readonly [number, number] | undefined {
const match = /^bytes=(\d*)-(\d*)$/.exec(range);
if (!match || (!match[1] && !match[2])) return undefined;
@@ -0,0 +1,41 @@
// Offline battle session capacity, AI bot pool rules, nation coalitions, and post-battle multipliers.
{
// Global post-battle Silver Lions and Research Points multipliers (1.0 matches stock rates).
"rewardMultiplierSilverLions": 1.0,
"rewardMultiplierResearchPoints": 1.0,
// LocalMP session capacity (16v16 = 32 total slots: 1 local player + up to 31 AI bots).
"maxPlayers": 32,
"maxBots": 31,
// Reduced LocalMP session capacity when Tactical Skies (`small_teams_`) is selected (8v8 = 16).
"smallTeamsMaxPlayers": 16,
// Chance (0..1) of rolling an enabled sub-mode (Night Battles, Tactical Skies, Bullet Hell,
// Nuclear Escalation, Naval EC) when queued alongside the classic mode; 1.0 when classic is off.
"subModeChance": 0.5,
// Matchmaking economic-rank spread around the player's lineup mrank (3 steps = +/- 1.0 BR).
"brSpreadMrank": 3,
// Maximum vehicles per unit category (tanks, aircraft, ships) emitted into customBots.
"botPoolLimitPerType": 80,
// Realistic Battles multi-nation coalition size bounds and mixed-battle probabilities.
"rbCoalitionMinCountries": 2,
"rbCoalitionMaxCountries": 5,
"rbGroundMixedChance": 0.08,
"rbAirMixedChance": 0.25,
"rbNavalMixedChance": 0.70,
// Simulator Battles Cold War / modern bloc cutoff mrank (18 = BR 7.0).
"simColdWarMinMrank": 18,
// AI bot respawn limits per battle in multi-slot versus modes.
"tankBotRespawns": 3,
"airBotRespawns": 2,
// Team win-inference weights when the player leaves while the battle is still running.
"earlyLeaveTicketWeight": 0.7,
"earlyLeaveKillWeight": 0.3
}
+3 -1
View File
@@ -3,5 +3,7 @@
// Maximum classic item quantity per cln_buy_item purchase.
"itemPiecesPerPurchase": 1000,
// Number of recent user logs to retain. Older unread purchase receipts are kept until acknowledged.
"userLogsKept": 80
"userLogsKept": 80,
// Number of recent in-memory battle sessions retained for idempotent settlement checks.
"battleSessionsKept": 256
}