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

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

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

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

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

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


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

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

No files matched your search

+302
View File
@@ -0,0 +1,302 @@
/**
* 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 { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.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;
/** The mission as the game describes it, including the parameters copied into the mission settings. */
readonly mission: MissionHeader;
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 spawnScore?: BattleSpawnScore;
readonly customBots: CustomBotsPool;
readonly extraBattleSlots: readonly ExtraBattleSlot[];
}
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;
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, playerMrank, 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,
playerMrank: number,
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,
randomBattle: declaration.displayType === 'random_battle',
missionName: mission.name,
missionPath: mission.path,
...(missionLocName !== undefined ? { missionLocName } : {}),
country: input.country,
startedAtSec: serverTimeToUnixSeconds(serverTimeNow()),
});
const allowedSet = new Set(declaration.allowedClasses);
const extraBattleSlots = selectExtraBattleSlots({
country: input.country,
slotVehicles: input.slotVehicles,
declaration,
playerMrank,
sessionMaxMrank: maxMrank,
vehiclesByName: this.#vehiclesByName,
rules: this.#spawnRules,
tuning: this.#tuning,
});
const useSpawnScore = declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic';
return {
sessionId: session.sessionId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
missionName: mission.name,
mission,
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,
...(useSpawnScore ? {
spawnScore: battleSpawnScore(input.slotVehicles, extraBattleSlots, maxMrank, this.#vehiclesByName, this.#spawnRules.spawnScore),
} : {}),
customBots,
extraBattleSlots,
};
}
}
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;
}