diff --git a/packages/blk/src/binary/name-table.ts b/packages/blk/src/binary/name-table.ts index b26fdb9..cc8fdec 100644 --- a/packages/blk/src/binary/name-table.ts +++ b/packages/blk/src/binary/name-table.ts @@ -4,14 +4,12 @@ * Layout (DagorEngine blk_serialize.cpp, dblk::write_names_base / read_names_base): * varUint count * varUint total byte size of the names (only when count > 0) - * names, each UTF-8 and NUL-terminated + * names, each UTF-8 and NUL-terminated (invalid bytes kept, text-bytes.ts) */ import { BlkFormatError } from '../errors.ts'; import type { ByteReader } from './byte-reader.ts'; import type { ByteWriter } from './byte-writer.ts'; - -const utf8Decoder = new TextDecoder('utf-8', { fatal: true }); -const utf8Encoder = new TextEncoder(); +import { decodeText, encodeText } from './text-bytes.ts'; export function readNameTable(reader: ByteReader): string[] { const count = reader.varUint(); @@ -25,7 +23,7 @@ export function readNameTable(reader: ByteReader): string[] { while (names.length < count) { const end = blob.indexOf(0, start); if (end < 0) throw new BlkFormatError(`name table ends after ${names.length} of ${count} names`); - names.push(utf8Decoder.decode(blob.subarray(start, end))); + names.push(decodeText(blob.subarray(start, end))); start = end + 1; } return names; @@ -34,7 +32,7 @@ export function readNameTable(reader: ByteReader): string[] { export function writeNameTable(writer: ByteWriter, names: readonly string[]): void { writer.varUint(names.length); if (names.length === 0) return; - const encoded = names.map((name) => utf8Encoder.encode(name)); + const encoded = names.map(encodeText); writer.varUint(encoded.reduce((total, bytes) => total + bytes.length + 1, 0)); for (const bytes of encoded) { if (bytes.includes(0)) throw new BlkFormatError('a name cannot contain a NUL character'); diff --git a/packages/blk/src/binary/param-values.ts b/packages/blk/src/binary/param-values.ts index 42165cb..0262694 100644 --- a/packages/blk/src/binary/param-values.ts +++ b/packages/blk/src/binary/param-values.ts @@ -11,11 +11,10 @@ import type { BlkValue } from '../model.ts'; import { BlkFormatError } from '../errors.ts'; import { isInline, typeById, typeByName } from '../param-types.ts'; import type { ByteWriter } from './byte-writer.ts'; +import { decodeText, encodeText } from './text-bytes.ts'; export const NAME_TABLE_STRING_FLAG = 0x8000_0000; -const utf8Decoder = new TextDecoder('utf-8', { fatal: true }); -const utf8Encoder = new TextEncoder(); const bits = new DataView(new ArrayBuffer(4)); export interface DecodeContext { @@ -68,7 +67,7 @@ export function storesInline(value: BlkValue): boolean { /** Append a string to the complex-data area; returns its offset. */ export function appendString(complex: ByteWriter, text: string): number { - const encoded = utf8Encoder.encode(text); + const encoded = encodeText(text); if (encoded.includes(0)) throw new BlkFormatError('a string value cannot contain a NUL character'); const offset = complex.length; complex.bytes(encoded); @@ -110,7 +109,7 @@ function decodeString(v: number, { names, complex }: DecodeContext): string { } const end = complex.indexOf(0, v); if (v >= complex.length || end < 0) throw new BlkFormatError(`string at complex offset ${v} is not terminated`); - return utf8Decoder.decode(complex.subarray(v, end)); + return decodeText(complex.subarray(v, end)); } function decodeInline(type: BlkValue['type'], v: number): BlkValue { diff --git a/packages/blk/src/binary/text-bytes.ts b/packages/blk/src/binary/text-bytes.ts new file mode 100644 index 0000000..7f04499 --- /dev/null +++ b/packages/blk/src/binary/text-bytes.ts @@ -0,0 +1,104 @@ +/** + * Names and string values: bytes in the file, JavaScript strings in memory. + * + * BLK text is UTF-8, but the engine treats it as plain bytes and never checks it, and some + * stock data is not valid UTF-8: the shared name map of 2.61.0.37 mis.vromfs.bin holds 3 + * such names among 103183 (mission-trigger comments whose first byte is damaged). Rejecting + * them would make the whole pack unreadable, and replacing them would change the bytes. + * + * So invalid bytes are kept with the "surrogateescape" scheme (Python, PEP 383): each byte + * that is not part of a valid UTF-8 sequence becomes the lone low surrogate U+DC00 + byte, + * and encoding turns such a lone surrogate back into that byte. Valid UTF-8 can never + * produce a lone surrogate, so the mapping is unambiguous and a document read and written + * back keeps every byte. + */ + +const strictUtf8 = new TextDecoder('utf-8', { fatal: true }); +const utf8Encoder = new TextEncoder(); + +const ESCAPE_BASE = 0xdc00; +/** Only bytes 0x80..0xFF can be invalid; ASCII always decodes. */ +const ESCAPE_FIRST = ESCAPE_BASE + 0x80; +const ESCAPE_LAST = ESCAPE_BASE + 0xff; + +export function decodeText(bytes: Uint8Array): string { + try { + return strictUtf8.decode(bytes); + } catch { + return decodeWithEscapes(bytes); + } +} + +export function encodeText(text: string): Uint8Array { + if (!hasEscapes(text)) return utf8Encoder.encode(text); + const parts: Uint8Array[] = []; + let runStart = 0; + for (let i = 0; i < text.length; i += 1) { + const unit = text.charCodeAt(i); + if (!isEscape(text, i, unit)) continue; + if (i > runStart) parts.push(utf8Encoder.encode(text.slice(runStart, i))); + parts.push(Uint8Array.of(unit - ESCAPE_BASE)); + runStart = i + 1; + } + if (runStart < text.length) parts.push(utf8Encoder.encode(text.slice(runStart))); + return concat(parts); +} + +function decodeWithEscapes(bytes: Uint8Array): string { + let text = ''; + let i = 0; + while (i < bytes.length) { + const length = sequenceLength(bytes[i]!); + const sequence = length > 0 && i + length <= bytes.length ? decodeSequence(bytes.subarray(i, i + length)) : undefined; + if (sequence === undefined) { + text += String.fromCharCode(ESCAPE_BASE + bytes[i]!); + i += 1; + } else { + text += sequence; + i += length; + } + } + return text; +} + +/** Length of the UTF-8 sequence a lead byte announces; 0 when it cannot start one. */ +function sequenceLength(lead: number): number { + if (lead < 0x80) return 1; + if (lead >= 0xc2 && lead <= 0xdf) return 2; + if (lead >= 0xe0 && lead <= 0xef) return 3; + if (lead >= 0xf0 && lead <= 0xf4) return 4; + return 0; +} + +/** The one character a candidate sequence encodes, or undefined when it is not valid UTF-8. */ +function decodeSequence(candidate: Uint8Array): string | undefined { + try { + return strictUtf8.decode(candidate); + } catch { + return undefined; + } +} + +function hasEscapes(text: string): boolean { + for (let i = 0; i < text.length; i += 1) { + if (isEscape(text, i, text.charCodeAt(i))) return true; + } + return false; +} + +/** A low surrogate in the escape range that does not complete a surrogate pair. */ +function isEscape(text: string, index: number, unit: number): boolean { + if (unit < ESCAPE_FIRST || unit > ESCAPE_LAST) return false; + const previous = index > 0 ? text.charCodeAt(index - 1) : 0; + return !(previous >= 0xd800 && previous <= 0xdbff); +} + +function concat(parts: readonly Uint8Array[]): Uint8Array { + const result = new Uint8Array(parts.reduce((total, part) => total + part.length, 0)); + let offset = 0; + for (const part of parts) { + result.set(part, offset); + offset += part.length; + } + return result; +} diff --git a/packages/local-service/src/cli.ts b/packages/local-service/src/cli.ts index 5977ad9..b4d765f 100644 --- a/packages/local-service/src/cli.ts +++ b/packages/local-service/src/cli.ts @@ -24,7 +24,7 @@ async function main(): Promise { } let service; try { - service = await startLocalService({ gameFolder: values.game, dataFolder: values.data, port }); + service = await startLocalService({ gameFolder: values.game, dataFolder: values.data, port, report: (line) => console.log(line) }); } catch (error) { const code = (error as NodeJS.ErrnoException).code; console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error)); diff --git a/packages/local-service/src/game-data/datasets/blk-fields.ts b/packages/local-service/src/game-data/datasets/blk-fields.ts new file mode 100644 index 0000000..95118d4 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/blk-fields.ts @@ -0,0 +1,31 @@ +/** Typed reads of BLK parameters for dataset extraction; a missing or differently typed parameter reads as undefined. */ +import { findBlock, findParam, type BlkBlock } from '@wto/blk'; + +export function stringField(block: BlkBlock | undefined, name: string): string | undefined { + const value = block && findParam(block, name)?.value; + return value?.type === 'string' ? value.value : undefined; +} + +export function numberField(block: BlkBlock | undefined, name: string): number | undefined { + const value = block && findParam(block, name)?.value; + return value?.type === 'int' || value?.type === 'real' ? value.value : undefined; +} + +/** Every string value of a repeated parameter, in order. */ +export function stringList(block: BlkBlock | undefined, name: string): string[] { + if (!block) return []; + return block.params.flatMap((param) => param.name === name && param.value.type === 'string' ? [param.value.value] : []); +} + +/** Every bool parameter of a block, by name. */ +export function boolFields(block: BlkBlock | undefined): Record { + if (!block) return {}; + return Object.fromEntries(block.params.flatMap((param) => param.value.type === 'bool' ? [[param.name, param.value.value]] : [])); +} + +/** Follow a path of first-found sub-blocks. */ +export function blockAt(block: BlkBlock | undefined, ...names: string[]): BlkBlock | undefined { + let current = block; + for (const name of names) current = current && findBlock(current, name); + return current; +} diff --git a/packages/local-service/src/game-data/datasets/dataset-cache.ts b/packages/local-service/src/game-data/datasets/dataset-cache.ts new file mode 100644 index 0000000..93c4ff3 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/dataset-cache.ts @@ -0,0 +1,155 @@ +/** + * Extract datasets once and reuse the result while the game files stay the same + *: + * + * 1. every pack the dataset read has the same size and modification time as when it was + * extracted: use the cached result; + * 2. otherwise compare the SHA-1 of the files the dataset actually read (and of the file + * listings it used): all equal, the result still holds, so only the pack stamps are + * updated (the build rewrites char.vromfs.bin on every launch without touching what + * the datasets read); + * 3. otherwise extract again. + * + * Cache entries live in /cache/datasets/.json. + */ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { BlkBlock } from '@wto/blk'; +import { writeFileAtomic } from '../../storage/atomic-file.ts'; +import type { GameFiles, GamePackName, PackStamp } from '../game-files.ts'; +import type { Dataset, DatasetSource } from './dataset.ts'; + +interface FileInput { + readonly pack: GamePackName; + readonly path: string; + readonly sha1: string; +} + +interface ListingInput { + readonly pack: GamePackName; + readonly sha1: string; +} + +interface CacheEntry { + readonly id: string; + readonly version: number; + readonly packs: Partial>; + readonly files: readonly FileInput[]; + readonly listings: readonly ListingInput[]; + readonly data: unknown; +} + +export type DatasetOrigin = 'cache' | 'cache, verified by content' | 'extracted'; + +export class DatasetCache { + readonly #folder: string; + readonly #gameFiles: GameFiles; + readonly #report: (line: string) => void; + + constructor(dataFolder: string, gameFiles: GameFiles, report: (line: string) => void) { + this.#folder = join(dataFolder, 'cache', 'datasets'); + this.#gameFiles = gameFiles; + this.#report = report; + } + + load(dataset: Dataset): T { + const entryPath = join(this.#folder, `${dataset.id}.json`); + const cached = readEntry(entryPath); + if (cached && cached.id === dataset.id && cached.version === dataset.version) { + if (this.#stampsMatch(cached)) return this.#use(dataset, cached, 'cache'); + if (this.#contentMatches(cached)) { + writeEntry(entryPath, { ...cached, packs: this.#stamps(Object.keys(cached.packs) as GamePackName[]) }); + return this.#use(dataset, cached, 'cache, verified by content'); + } + } + const started = Date.now(); + const tracked = new TrackedSource(this.#gameFiles); + const data = dataset.extract(tracked); + const entry: CacheEntry = { + id: dataset.id, + version: dataset.version, + packs: this.#stamps(tracked.packs()), + files: tracked.files(), + listings: tracked.listings(), + data, + }; + writeEntry(entryPath, entry); + this.#report(`dataset ${dataset.id}: extracted in ${Date.now() - started} ms (${entry.files.length} files)`); + return data; + } + + #use(dataset: Dataset, entry: CacheEntry, origin: DatasetOrigin): T { + this.#report(`dataset ${dataset.id}: ${origin}`); + return entry.data as T; + } + + #stamps(packs: readonly GamePackName[]): Partial> { + return Object.fromEntries(packs.map((pack) => [pack, this.#gameFiles.packStamp(pack)])); + } + + #stampsMatch(entry: CacheEntry): boolean { + return Object.entries(entry.packs).every(([pack, stamp]) => { + const current = this.#gameFiles.packStamp(pack as GamePackName); + return stamp !== undefined && current.size === stamp.size && current.mtimeMs === stamp.mtimeMs; + }); + } + + #contentMatches(entry: CacheEntry): boolean { + return entry.files.every(({ pack, path, sha1 }) => this.#gameFiles.pack(pack).fileDigest(path) === sha1) + && entry.listings.every(({ pack, sha1 }) => listingDigest(this.#gameFiles.pack(pack).paths()) === sha1); + } +} + +/** Reads through to the game files and remembers every input. */ +class TrackedSource implements DatasetSource { + readonly #gameFiles: GameFiles; + readonly #files = new Map(); + readonly #listings = new Map(); + + constructor(gameFiles: GameFiles) { + this.#gameFiles = gameFiles; + } + + readBlk(pack: GamePackName, path: string): BlkBlock { + const gamePack = this.#gameFiles.pack(pack); + const sha1 = gamePack.fileDigest(path); + if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`); + this.#files.set(`${pack}/${path}`, { pack, path, sha1 }); + return gamePack.readBlk(path); + } + + listFiles(pack: GamePackName): readonly string[] { + const paths = this.#gameFiles.pack(pack).paths(); + this.#listings.set(pack, { pack, sha1: listingDigest(paths) }); + return paths; + } + + packs(): GamePackName[] { + return [...new Set([...this.#files.values(), ...this.#listings.values()].map((input) => input.pack))]; + } + + files(): FileInput[] { + return [...this.#files.values()]; + } + + listings(): ListingInput[] { + return [...this.#listings.values()]; + } +} + +function listingDigest(paths: readonly string[]): string { + return createHash('sha1').update(paths.join('\n')).digest('hex'); +} + +function readEntry(path: string): CacheEntry | undefined { + try { + return JSON.parse(readFileSync(path, 'utf8')) as CacheEntry; + } catch { + return undefined; + } +} + +function writeEntry(path: string, entry: CacheEntry): void { + writeFileAtomic(path, JSON.stringify(entry)); +} diff --git a/packages/local-service/src/game-data/datasets/dataset.ts b/packages/local-service/src/game-data/datasets/dataset.ts new file mode 100644 index 0000000..3f51a81 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/dataset.ts @@ -0,0 +1,25 @@ +/** + * A dataset: a set of static facts extracted from the player's game files (implementation notes + * 3.4). Each dataset declares what it produces and reads its inputs only through the source + * it is given, so the cache knows exactly which files the result depends on. + * + * A dataset only records what the game files say; deciding what the facts mean for a game + * rule belongs to the rules layer. + */ +import type { BlkBlock } from '@wto/blk'; +import type { GamePackName } from '../game-files.ts'; + +export interface DatasetSource { + readBlk(pack: GamePackName, path: string): BlkBlock; + /** Every file path in a pack, sorted. */ + listFiles(pack: GamePackName): readonly string[]; +} + +export interface Dataset { + /** File name of the cache entry; unique among datasets. */ + readonly id: string; + /** Raise when the extraction code or the shape of the result changes: old cache entries are then ignored. */ + readonly version: number; + /** The result must survive JSON.stringify / JSON.parse unchanged. */ + extract(source: DatasetSource): T; +} diff --git a/packages/local-service/src/game-data/datasets/multiplayer-missions.ts b/packages/local-service/src/game-data/datasets/multiplayer-missions.ts new file mode 100644 index 0000000..72b8938 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/multiplayer-missions.ts @@ -0,0 +1,113 @@ +/** + * Dataset: the game's multiplayer missions, as the game lists and describes them. + * + * - The list: char.vromfs.bin config/mislist.blk, block "skirmish". One sub-block per + * category (e.g. air_ground_Dom, air_dom, air_naval_Dom, pve), holding the category's + * flags (isDebug, isForceHidden, …) and its mission names (repeated "m"). + * - Each mission: mis.vromfs.bin gamedata/missions/…/.blk. Its + * mission_settings block names the map, the kind of game, the two sides' countries, the + * vehicle types allowed, per-difficulty overrides, and the players' spawn slots + * ("wing" entries of player / player_teamB). + * + * 2.61.0.37: 1315 missions, each name matching exactly one mission file (docs/implementation notes). + */ +import type { BlkBlock } from '@wto/blk'; +import type { Dataset, DatasetSource } from './dataset.ts'; +import { blockAt, boolFields, numberField, stringField, stringList } from './blk-fields.ts'; + +const MISSION_LIST = 'config/mislist.blk'; +const MULTIPLAYER_SECTION = 'skirmish'; +const MISSION_FOLDER = 'gamedata/missions/'; + +export interface MissionCategory { + readonly name: string; + readonly flags: Readonly>; + readonly missions: readonly string[]; +} + +export interface MissionHeader { + readonly name: string; + readonly path: string; + readonly level?: string; + readonly type?: string; + readonly environment?: string; + readonly weather?: string; + readonly countryAxis?: string; + readonly countryAllies?: string; + readonly timeLimit?: number; + /** As written in the mission (isAirplanesAllowed, isTanksAllowed, …); empty when the mission does not say. */ + readonly allowedUnitTypes: Readonly>; + /** Difficulties the mission has its own settings for. */ + readonly difficultyOverrides: readonly string[]; + /** Spawn slots per side. */ + readonly playerSlots: { readonly teamA: number; readonly teamB: number }; +} + +export interface MultiplayerMissions { + readonly categories: readonly MissionCategory[]; + readonly missions: Readonly>; +} + +export const multiplayerMissions: Dataset = { + id: 'multiplayer-missions', + version: 1, + extract(source: DatasetSource): MultiplayerMissions { + const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION); + if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`); + const categories = section.blocks.map((block): MissionCategory => ({ + name: block.name, + flags: boolFields(block), + missions: stringList(block, 'm'), + })); + + const pathByName = missionPathsByLowerName(source.listFiles('mis.vromfs.bin')); + const missions: Record = {}; + for (const name of categories.flatMap((category) => category.missions)) { + if (name in missions) continue; + const path = pathByName.get(name.toLowerCase()); + if (!path) throw new Error(`mission ${name} (${MISSION_LIST}) has no file in mis.vromfs.bin`); + missions[name] = readHeader(name, path, source.readBlk('mis.vromfs.bin', path)); + } + return { categories, missions }; + }, +}; + +function missionPathsByLowerName(paths: readonly string[]): Map { + const byName = new Map(); + const repeated = new Set(); + for (const path of paths) { + if (!path.startsWith(MISSION_FOLDER) || !path.endsWith('.blk')) continue; + const name = path.slice(path.lastIndexOf('/') + 1, -'.blk'.length); + if (byName.has(name)) repeated.add(name); + byName.set(name, path); + } + for (const name of repeated) byName.delete(name); + return byName; +} + +function readHeader(name: string, path: string, document: BlkBlock): MissionHeader { + const settings = blockAt(document, 'mission_settings'); + const mission = blockAt(settings, 'mission'); + const optional = { + level: stringField(mission, 'level'), + type: stringField(mission, 'type'), + environment: stringField(mission, 'environment'), + weather: stringField(mission, 'weather'), + countryAxis: stringField(mission, 'country_axis'), + countryAllies: stringField(mission, 'country_allies'), + timeLimit: numberField(mission, 'timeLimit'), + }; + return { + name, + path, + ...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)), + allowedUnitTypes: boolFields(blockAt(mission, 'allowedUnitTypes')), + difficultyOverrides: (mission?.blocks ?? []) + .filter((block) => block.name === 'mission') + .flatMap((block) => stringField(block, 'difficulty') ?? []), + playerSlots: { + teamA: stringList(blockAt(settings, 'player'), 'wing').length, + teamB: stringList(blockAt(settings, 'player_teamB'), 'wing').length, + }, + }; +} diff --git a/packages/local-service/src/game-data/datasets/shop-countries.ts b/packages/local-service/src/game-data/datasets/shop-countries.ts new file mode 100644 index 0000000..db49b51 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/shop-countries.ts @@ -0,0 +1,16 @@ +/** + * Dataset: the countries of the game, in tech-tree order. + * + * char.vromfs.bin config/shop.blk has one top-level block per country (country_usa, …). + * The stock UI builds its own country list the same way (gui.vromfs.bin + * scripts/shop/shopCountriesList.nut, updateShopCountriesList). + */ +import type { Dataset } from './dataset.ts'; + +const SHOP = 'config/shop.blk'; + +export const shopCountries: Dataset = { + id: 'shop-countries', + version: 1, + extract: (source) => source.readBlk('char.vromfs.bin', SHOP).blocks.map((block) => block.name), +}; diff --git a/packages/local-service/src/game-data/game-files.ts b/packages/local-service/src/game-data/game-files.ts index a899ed2..ded3edb 100644 --- a/packages/local-service/src/game-data/game-files.ts +++ b/packages/local-service/src/game-data/game-files.ts @@ -1,27 +1,55 @@ /** * The game files the local service reads, opened lazily from the player's game folder. */ +import { statSync } from 'node:fs'; import { join } from 'node:path'; import type { BlkBlock } from '@wto/blk'; import { GamePack } from './game-pack.ts'; +/** The data packs the local service reads (file names in the game folder). */ +export type GamePackName = 'char.vromfs.bin' | 'mis.vromfs.bin'; + +/** What identifies one version of a pack file cheaply (implementation notes, first check). */ +export interface PackStamp { + readonly size: number; + readonly mtimeMs: number; +} + /** Gaijin's template for a new account's profile. */ const NEW_ACCOUNT_TEMPLATE = 'config/default_user.blk'; export class GameFiles { readonly #gameFolder: string; - #charPack: GamePack | undefined; + readonly #packs = new Map(); constructor(gameFolder: string) { this.#gameFolder = gameFolder; } newAccountTemplate(): BlkBlock { - return this.#char().readBlk(NEW_ACCOUNT_TEMPLATE); + return this.pack('char.vromfs.bin').readBlk(NEW_ACCOUNT_TEMPLATE); } - #char(): GamePack { - this.#charPack ??= GamePack.open(join(this.#gameFolder, 'char.vromfs.bin')); - return this.#charPack; + pack(name: GamePackName): GamePack { + let pack = this.#packs.get(name); + if (!pack) { + pack = GamePack.open(this.#packPath(name)); + this.#packs.set(name, pack); + } + return pack; + } + + /** Drop the opened packs (they are reopened on demand); called after start-up extraction. */ + releasePacks(): void { + this.#packs.clear(); + } + + packStamp(name: GamePackName): PackStamp { + const { size, mtimeMs } = statSync(this.#packPath(name)); + return { size, mtimeMs }; + } + + #packPath(name: GamePackName): string { + return join(this.#gameFolder, name); } } diff --git a/packages/local-service/src/game-data/game-pack.ts b/packages/local-service/src/game-data/game-pack.ts index 9894e79..1bba607 100644 --- a/packages/local-service/src/game-data/game-pack.ts +++ b/packages/local-service/src/game-data/game-pack.ts @@ -2,6 +2,7 @@ * Read BLK documents out of one of the player's game data packs (implementation notes: the * game's own files are the source of every static fact; nothing is shipped with us). */ +import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { decodeBlk, parseSharedNameMap, type BlkBlock, type SharedNameContext } from '@wto/blk'; import { getFile, NAME_MAP_PATH, readArchive, type Archive } from '@wto/vromfs'; @@ -24,6 +25,17 @@ export class GamePack { readBlk(pathInPack: string): BlkBlock { return decodeBlk(getFile(this.#archive, pathInPack), this.#shared); } + + /** Every file path in the pack, sorted. */ + paths(): string[] { + return [...this.#archive.files.keys()].sort(); + } + + /** SHA-1 of one file's content, hex; undefined when the pack has no such file. */ + fileDigest(pathInPack: string): string | undefined { + const content = this.#archive.files.get(pathInPack); + return content ? createHash('sha1').update(content).digest('hex') : undefined; + } } function findDictionary(archive: Archive): Uint8Array | undefined { diff --git a/packages/local-service/src/game-modes/catalogue/catalogue.ts b/packages/local-service/src/game-modes/catalogue/catalogue.ts new file mode 100644 index 0000000..3935099 --- /dev/null +++ b/packages/local-service/src/game-modes/catalogue/catalogue.ts @@ -0,0 +1,24 @@ +/** The offline version's game modes (docs/implementation notes; implementation notes J). */ +import type { GameModeDeclaration } from './game-mode-declaration.ts'; +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'; + +export const GAME_MODE_CATALOGUE: readonly GameModeDeclaration[] = checked([ + ...RANDOM_BATTLES, + ...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(); + 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]); + } + } + return modes; +} diff --git a/packages/local-service/src/game-modes/catalogue/game-mode-declaration.ts b/packages/local-service/src/game-modes/catalogue/game-mode-declaration.ts new file mode 100644 index 0000000..449b669 --- /dev/null +++ b/packages/local-service/src/game-modes/catalogue/game-mode-declaration.ts @@ -0,0 +1,45 @@ +/** + * What the offline game-mode catalogue declares about one mode (docs/implementation notes, + * 3.3). Everything else in a mode definition is derived from the game's own files. + */ + +/** Vehicle classes, named as the stock UI names unit types in event craft rules (scripts/unit/baseUnitTypes.nut). */ +export type UnitClass = 'aircraft' | 'tank' | 'ship' | 'helicopter'; + +export type ModeDifficulty = 'arcade' | 'realistic' | 'simulator'; + +/** + * Where the stock UI shows the mode (scripts/events/eventDisplayType.nut): random_battle + * and pve_battle in the game-mode selection, regular in the events window. + */ +export type DisplayType = 'random_battle' | 'pve_battle' | 'regular'; + +/** Which multiplayer missions (game-data/datasets/multiplayer-missions.ts) the mode rotates. */ +export interface MissionSelection { + /** Categories of config/mislist.blk; only listed categories are used, whatever their flags. */ + readonly categories: readonly string[]; + /** The mission must state that these vehicle classes are allowed. */ + readonly requireAllowed: readonly UnitClass[]; + /** Keep only missions whose name matches. */ + readonly include?: RegExp; + /** Drop missions whose name matches. */ + readonly exclude?: RegExp; +} + +export interface GameModeDeclaration { + /** Fixed forever: the client remembers modes by it. */ + readonly gameModeId: number; + /** The stock name where the game has one (docs/implementation notes). */ + readonly name: 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; + readonly difficulty: ModeDifficulty; + readonly displayType: DisplayType; + /** Events-window chapter; only for modes shown there. */ + readonly chapter?: string; + /** The vehicle class a player must bring; the mode is greyed out without one. */ + readonly requiredClass: UnitClass; + readonly allowedClasses: readonly UnitClass[]; + readonly missions: MissionSelection; +} diff --git a/packages/local-service/src/game-modes/catalogue/mission-pools.ts b/packages/local-service/src/game-modes/catalogue/mission-pools.ts new file mode 100644 index 0000000..3993e2f --- /dev/null +++ b/packages/local-service/src/game-modes/catalogue/mission-pools.ts @@ -0,0 +1,29 @@ +/** + * The mission pools of the regular battle modes, by vehicle class. Categories come from + * char.vromfs.bin config/mislist.blk ("skirmish"); the vehicle-type requirement keeps only + * missions that say the class is allowed. + * + * Missions made for the newbie modes (names containing "newbie") stay out: the offline + * version has no newbie restriction (local verification, docs/implementation notes). + */ +import type { MissionSelection } from './game-mode-declaration.ts'; + +const NEWBIE_MISSIONS = /newbie/i; + +export const AIR_BATTLE_MISSIONS: MissionSelection = { + categories: ['air_dom', 'airfield_dom', 'ground_strike', 'base_dom', 'air_conq'], + requireAllowed: ['aircraft'], + exclude: NEWBIE_MISSIONS, +}; + +export const GROUND_BATTLE_MISSIONS: MissionSelection = { + categories: ['air_ground_Dom', 'air_ground_Conq', 'air_ground_Bttl'], + requireAllowed: ['tank'], + exclude: NEWBIE_MISSIONS, +}; + +export const NAVAL_BATTLE_MISSIONS: MissionSelection = { + categories: ['air_naval_Dom', 'air_naval_Conq', 'air_naval_Tdm'], + requireAllowed: ['ship'], + exclude: NEWBIE_MISSIONS, +}; diff --git a/packages/local-service/src/game-modes/catalogue/pve-battles.ts b/packages/local-service/src/game-modes/catalogue/pve-battles.ts new file mode 100644 index 0000000..df39148 --- /dev/null +++ b/packages/local-service/src/game-modes/catalogue/pve-battles.ts @@ -0,0 +1,32 @@ +/** + * Player-versus-AI modes, shown in the game-mode selection (display type pve_battle). + * + * The game has no stock mode names for these; the display names are the game's own texts: + * "chapters/assault" (Air Assault), "chapters/air_ground_PvE" (Assault) and + * "missions/helicopter_event_arcade". Missions: + * - air assault: the "*_survive_arcade_pve" missions of the "pve" category; + * - ground assault: the "*battle_for_survival_8_players_pve" missions of the same category + * (they do not state their vehicle types, so none is required of them); + * - helicopters: the "air_h2m" category (helicopter PvE missions). + */ +import type { GameModeDeclaration } from './game-mode-declaration.ts'; + +const PVE = { difficulty: 'arcade', displayType: 'pve_battle' } as const; + +export const PVE_BATTLES: readonly GameModeDeclaration[] = [ + { + gameModeId: 21, name: 'air_assault_pve', economicName: 'air_assault_pve', locName: 'chapters/assault', ...PVE, + requiredClass: 'aircraft', allowedClasses: ['aircraft'], + missions: { categories: ['pve'], requireAllowed: ['aircraft'], include: /_survive_arcade_pve$/i }, + }, + { + gameModeId: 22, name: 'tank_assault_pve', economicName: 'tank_assault_pve', locName: 'chapters/air_ground_PvE', ...PVE, + requiredClass: 'tank', allowedClasses: ['tank'], + missions: { categories: ['pve'], requireAllowed: [], include: /battle_for_survival_8_players_pve$/i }, + }, + { + gameModeId: 23, name: 'helicopter_pve_arcade', economicName: 'helicopter_pve_arcade', locName: 'missions/helicopter_event_arcade', ...PVE, + requiredClass: 'helicopter', allowedClasses: ['helicopter'], + missions: { categories: ['air_h2m'], requireAllowed: ['helicopter'] }, + }, +]; diff --git a/packages/local-service/src/game-modes/catalogue/random-battles.ts b/packages/local-service/src/game-modes/catalogue/random-battles.ts new file mode 100644 index 0000000..878f5d7 --- /dev/null +++ b/packages/local-service/src/game-modes/catalogue/random-battles.ts @@ -0,0 +1,41 @@ +/** + * Random battles: shown in the game-mode selection. Names are the stock ones the UI scripts + * know (scripts/events/eventInfo.nut eventIdsForMainGameModeList, + * scripts/gameModes/gameModeManagerState.nut, scripts/gameModes/psnActivities.nut); display + * names are the game's "missions/_event_" texts (lang menu_events.csv); + * economic names of ground and naval modes are the ones the leaderboard scripts use + * (scripts/leaderboard/leaderboardCategoryType.nut). + */ +import type { GameModeDeclaration } from './game-mode-declaration.ts'; +import { AIR_BATTLE_MISSIONS, GROUND_BATTLE_MISSIONS, NAVAL_BATTLE_MISSIONS } from './mission-pools.ts'; + +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; + +export const RANDOM_BATTLES: readonly GameModeDeclaration[] = [ + { + gameModeId: 1, name: 'air_arcade', economicName: 'air_arcade', locName: 'missions/air_event_arcade', + difficulty: 'arcade', displayType: 'random_battle', ...AIR, + }, + { + gameModeId: 2, name: 'air_realistic', economicName: 'air_realistic', locName: 'missions/air_event_historical', + difficulty: 'realistic', displayType: 'random_battle', ...AIR, + }, + { + gameModeId: 3, name: 'tank_event_in_random_battles_arcade', economicName: 'tank_arcade', + locName: 'missions/tank_event_in_random_battles_arcade', difficulty: 'arcade', displayType: 'random_battle', ...GROUND, + }, + { + 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, + }, + { + gameModeId: 5, name: 'ship_event_in_random_battles_arcade', economicName: 'test_ship_arcade', + locName: 'missions/ship_event_arcade', difficulty: 'arcade', displayType: 'random_battle', ...NAVAL, + }, + { + gameModeId: 6, name: 'ship_event_in_random_battles_realistic', economicName: 'test_ship_realistic', + locName: 'missions/ship_event_historical', difficulty: 'realistic', displayType: 'random_battle', ...NAVAL, + }, +]; diff --git a/packages/local-service/src/game-modes/catalogue/simulator-battles.ts b/packages/local-service/src/game-modes/catalogue/simulator-battles.ts new file mode 100644 index 0000000..735916e --- /dev/null +++ b/packages/local-service/src/game-modes/catalogue/simulator-battles.ts @@ -0,0 +1,32 @@ +/** + * Simulator battles: listed in the events window under the "simulation_battles" chapter, + * which is what the stock "Simulator Battles" tile opens and what lights it up + * (scripts/gameModes/gameModeManagerState.nut, custom_mode_fullreal). + * + * Air and ground use the stock names that have short display texts in the game + * ("missions/short/air_simulation_timeDelay_battles", "missions/short/tank_random_battles_simulation"); + * the game has no stock name for naval simulator battles, so that one is named after its + * display text "missions/ship_event_simulator". + */ +import type { GameModeDeclaration } from './game-mode-declaration.ts'; +import { AIR_BATTLE_MISSIONS, GROUND_BATTLE_MISSIONS, NAVAL_BATTLE_MISSIONS } from './mission-pools.ts'; + +const SIMULATOR = { difficulty: 'simulator', displayType: 'regular', chapter: 'simulation_battles' } as const; + +export const SIMULATOR_BATTLES: readonly GameModeDeclaration[] = [ + { + gameModeId: 11, name: 'air_simulation_timeDelay_battles', economicName: 'air_simulation_timeDelay_battles', + locName: 'missions/air_simulation_timeDelay_battles', ...SIMULATOR, + requiredClass: 'aircraft', allowedClasses: ['aircraft'], missions: AIR_BATTLE_MISSIONS, + }, + { + gameModeId: 12, name: 'tank_random_battles_simulation', economicName: 'tank_simulation', + locName: 'missions/tank_event_in_random_battles_simulator', ...SIMULATOR, + requiredClass: 'tank', allowedClasses: ['tank', 'aircraft', 'helicopter'], missions: GROUND_BATTLE_MISSIONS, + }, + { + gameModeId: 13, name: 'ship_event_simulator', economicName: 'ship_event_simulator', + locName: 'missions/ship_event_simulator', ...SIMULATOR, + requiredClass: 'ship', allowedClasses: ['ship', 'aircraft'], missions: NAVAL_BATTLE_MISSIONS, + }, +]; diff --git a/packages/local-service/src/game-modes/catalogue/special-events.ts b/packages/local-service/src/game-modes/catalogue/special-events.ts new file mode 100644 index 0000000..b1ed318 --- /dev/null +++ b/packages/local-service/src/game-modes/catalogue/special-events.ts @@ -0,0 +1,17 @@ +/** + * Events shown in the events window. + * + * The Great War: the two First World War missions of the "test" category of + * config/mislist.blk (great_war_Dom, great_war_inv_Dom). Display name: the game's + * "loading_bg/login_layer_the_great_war" text. + */ +import type { GameModeDeclaration } from './game-mode-declaration.ts'; + +export const SPECIAL_EVENTS: readonly GameModeDeclaration[] = [ + { + gameModeId: 31, name: 'great_war_event', economicName: 'great_war_event', locName: 'loading_bg/login_layer_the_great_war', + difficulty: 'arcade', displayType: 'regular', chapter: 'special_events', + requiredClass: 'tank', allowedClasses: ['tank', 'aircraft'], + missions: { categories: ['test'], requireAllowed: ['tank'], include: /^great_war_/i }, + }, +]; diff --git a/packages/local-service/src/game-modes/game-modes.ts b/packages/local-service/src/game-modes/game-modes.ts new file mode 100644 index 0000000..1d28c1d --- /dev/null +++ b/packages/local-service/src/game-modes/game-modes.ts @@ -0,0 +1,42 @@ +/** + * The game modes the local matching server offers: the catalogue's modes, each filled in + * from the game's own files at start-up. A mode none of whose missions are in the player's + * game files is left out (and reported), since it could not be played. + * + * 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 { 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 class GameModes { + readonly #definitions = new Map(); + + constructor(missions: MultiplayerMissions, countries: readonly string[], report: (line: string) => void, + catalogue: readonly GameModeDeclaration[] = GAME_MODE_CATALOGUE) { + 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`); + continue; + } + this.#definitions.set(mode.gameModeId, buildModeDefinition(mode, selected, countries)); + } + report(`game modes: ${this.#definitions.size} of ${catalogue.length} offered`); + } + + ids(): number[] { + return [...this.#definitions.keys()]; + } + + /** 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] : []; + }); + } +} diff --git a/packages/local-service/src/game-modes/mission-pool.ts b/packages/local-service/src/game-modes/mission-pool.ts new file mode 100644 index 0000000..82da8f7 --- /dev/null +++ b/packages/local-service/src/game-modes/mission-pool.ts @@ -0,0 +1,30 @@ +/** Choose a mode's missions from the game's multiplayer missions (docs/implementation notes). */ +import type { MissionHeader, MultiplayerMissions } from '../game-data/datasets/multiplayer-missions.ts'; +import type { MissionSelection, UnitClass } from './catalogue/game-mode-declaration.ts'; + +/** The switch a mission's mission_settings/mission/allowedUnitTypes block uses for each class. */ +const ALLOWED_SWITCH: Readonly> = { + aircraft: 'isAirplanesAllowed', + tank: 'isTanksAllowed', + ship: 'isShipsAllowed', + helicopter: 'isHelicoptersAllowed', +}; + +/** The selected missions in the order the game lists them, without repeats. */ +export function selectMissions(selection: MissionSelection, index: MultiplayerMissions): MissionHeader[] { + const chosen = new Map(); + for (const category of index.categories) { + if (!selection.categories.includes(category.name)) continue; + for (const name of category.missions) { + const mission = index.missions[name]; + if (mission && !chosen.has(name) && matches(selection, mission)) chosen.set(name, mission); + } + } + return [...chosen.values()]; +} + +function matches(selection: MissionSelection, mission: MissionHeader): boolean { + if (selection.include && !selection.include.test(mission.name)) return false; + if (selection.exclude?.test(mission.name)) return false; + return selection.requireAllowed.every((unitClass) => mission.allowedUnitTypes[ALLOWED_SWITCH[unitClass]] === true); +} diff --git a/packages/local-service/src/game-modes/mode-definition.ts b/packages/local-service/src/game-modes/mode-definition.ts new file mode 100644 index 0000000..1fc0574 --- /dev/null +++ b/packages/local-service/src/game-modes/mode-definition.ts @@ -0,0 +1,86 @@ +/** + * A game mode in the form the stock UI reads from the matching server + * (match.fetch_game_modes_info, docs/implementation notes): + * + * - difficulty: the matching name (scripts/difficulty.nut matchingName: arcade, realistic, + * simulation); mission_decl.difficulty: the mission name of the same difficulty + * (arcade, realistic, hardcore; scripts/events/eventsManager.nut diffTable). + * - teamA / teamB: identical, so the UI treats the mode as symmetric + * (scripts/events/eventTeamsInfo.nut initSidesOnce); a missing team B would count as + * playable and mark the mode invalid. Craft rules name a vehicle class; requiredCrafts + * is what greys the mode out for a player without that class (gameModeManagerState.nut + * 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, + * 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. + * - 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 + * take the highest battle rating of the lineup. + * + * Fields the stock scripts read unguarded only in later stages are not set yet: + * suggestToChangeTeamOnQueueDisbalanceSec (queueing for an event, eventsHandler.nut) and + * missionsBanMode (map preferences; absent means none, mapPreferencesParams.nut). + */ +import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts'; +import type { GameModeDeclaration, ModeDifficulty } from './catalogue/game-mode-declaration.ts'; + +const MATCHING_DIFFICULTY: Readonly> = { + arcade: 'arcade', + realistic: 'realistic', + simulator: 'simulation', +}; + +const MISSION_DIFFICULTY: Readonly> = { + arcade: 'arcade', + realistic: 'realistic', + simulator: 'hardcore', +}; + +export type ModeDefinition = Readonly>; + +export function buildModeDefinition(mode: GameModeDeclaration, missions: readonly MissionHeader[], + countries: readonly string[]): ModeDefinition { + const team = { + countries: [...countries], + allowedCrafts: mode.allowedClasses.map((unitClass) => ({ class: unitClass })), + requiredCrafts: [{ class: mode.requiredClass }], + minTeamSize: 1, + maxTeamSize: teamSize(mode, missions), + }; + return { + gameModeId: mode.gameModeId, + name: mode.name, + tag: '', + economicName: mode.economicName, + loc_name: mode.locName, + difficulty: MATCHING_DIFFICULTY[mode.difficulty], + rankCalcMode: 'maximum', + displayType: mode.displayType, + ...(mode.chapter === undefined ? {} : { chapter: mode.chapter }), + visible: true, + disabled: false, + teamA: team, + teamB: structuredClone(team), + mission_decl: { + difficulty: MISSION_DIFFICULTY[mode.difficulty], + missions_list: Object.fromEntries(missions.map((mission) => [mission.name, {}])), + }, + }; +} + +/** + * The fewest player spawn slots per side among the missions, so every mission can hold a + * full team. A side without player slots is the AI side of a PvE mission and is not counted. + */ +function teamSize(mode: GameModeDeclaration, missions: readonly MissionHeader[]): number { + const slots = missions.flatMap(({ playerSlots: { teamA, teamB } }) => { + const sides = [teamA, teamB].filter((count) => count > 0); + return sides.length ? [Math.min(...sides)] : []; + }); + if (!slots.length) throw new Error(`game mode ${mode.name}: none of its missions lists player spawn slots`); + return Math.min(...slots); +} diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index ecd58fa..019685f 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -7,8 +7,13 @@ import { AccountStore } from './accounts/account-store.ts'; import { actionTable } from './char/actions/action-table.ts'; import { CharService } from './char/char-service.ts'; import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; +import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; +import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; +import { shopCountries } from './game-data/datasets/shop-countries.ts'; import { GameFiles } from './game-data/game-files.ts'; +import { GameModes } from './game-modes/game-modes.ts'; import { LoginService } from './login/login-service.ts'; +import { matchingRequests } from './matching/matching-requests.ts'; import { PlayerProfiles } from './profile/player-profiles.ts'; import { SaveStore } from './saves/save-store.ts'; import { createPortListener } from './server/port-listener.ts'; @@ -21,6 +26,8 @@ export interface LocalServiceOptions { /** Accounts, saves and logs. */ readonly dataFolder: string; readonly port: number; + /** Start-up progress lines (static data extraction, game modes). */ + readonly report?: (line: string) => void; } export const LOOPBACK = '127.0.0.1'; @@ -31,7 +38,13 @@ export interface RunningLocalService { } export async function startLocalService(options: LocalServiceOptions): Promise { + const report = options.report ?? (() => {}); const gameFiles = new GameFiles(options.gameFolder); + // Static data first, before the port opens. + const datasets = new DatasetCache(options.dataFolder, gameFiles, report); + const gameModes = new GameModes(datasets.load(multiplayerMissions), datasets.load(shopCountries), report); + gameFiles.releasePacks(); + const profiles = new PlayerProfiles(new SaveStore(options.dataFolder), gameFiles); // One store for both services: accounts registered at sign-in must be visible to char. const accounts = new AccountStore(options.dataFolder); @@ -41,7 +54,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise ({ modes: gameModes.ids() })], + ['match.fetch_game_modes_info', (request, session) => { + const { byId, asString } = request.params; + const ids = Array.isArray(byId) ? byId.filter((id): id is number => typeof id === 'number') : []; + const modes = gameModes.definitions(ids); + session.note(`${modes.length} of ${ids.length} requested modes`); + return asString === false ? { modes } : { modes_str: JSON.stringify(modes) }; + }], + ]; +} diff --git a/packages/local-service/src/matching/matching-requests.ts b/packages/local-service/src/matching/matching-requests.ts index 01b3531..0a19462 100644 --- a/packages/local-service/src/matching/matching-requests.ts +++ b/packages/local-service/src/matching/matching-requests.ts @@ -8,7 +8,9 @@ * Nothing local checks the credentials (single-player machine); the session key is needed * because the client encrypts everything after this request. */ +import type { GameModes } from '../game-modes/game-modes.ts'; import { fetchClustersList } from './cluster-list.ts'; +import { gameModeRequests } from './game-modes-requests.ts'; import type { MatchingRequest } from './matching-message.ts'; import { jwtDecryptsWith, unwrapSessionKey } from './session-crypto/session-key.ts'; @@ -22,10 +24,19 @@ export interface MatchingSessionControl { export type MatchingRequestHandler = (request: MatchingRequest, session: MatchingSessionControl) => Record; -export const MATCHING_REQUESTS: ReadonlyMap = new Map([ - ['mlogin.login', signIn], - ['wtmm_static.fetch_clusters_list', fetchClustersList], -]); +export type MatchingRequestTable = ReadonlyMap; + +export interface MatchingRules { + readonly gameModes: GameModes; +} + +export function matchingRequests({ gameModes }: MatchingRules): MatchingRequestTable { + return new Map([ + ['mlogin.login', signIn], + ['wtmm_static.fetch_clusters_list', fetchClustersList], + ...gameModeRequests(gameModes), + ]); +} function signIn(request: MatchingRequest, session: MatchingSessionControl): Record { const { login, auth_jwt_enc: authJwtEnc } = request.params; diff --git a/packages/local-service/src/matching/matching-service.ts b/packages/local-service/src/matching/matching-service.ts index 99509ef..bac7bd0 100644 --- a/packages/local-service/src/matching/matching-service.ts +++ b/packages/local-service/src/matching/matching-service.ts @@ -15,19 +15,21 @@ import type { Socket } from 'node:net'; import type { TrafficLog } from '../traffic-log/traffic-log.ts'; import { encodePacket, PacketReader } from './matching-frame.ts'; import { answerTo, asPing, asRequest, decodeMessage, encodeMessage, pingAnswer, type MatchingMessage } from './matching-message.ts'; -import { MATCHING_REQUESTS, type MatchingSessionControl } from './matching-requests.ts'; +import type { MatchingRequestTable, MatchingSessionControl } from './matching-requests.ts'; import { messageLogText } from './message-redaction.ts'; import { EnvelopeReader, sealEnvelope } from './session-crypto/encrypted-envelope.ts'; export class MatchingService { + readonly #requests: MatchingRequestTable; readonly #log: TrafficLog; - constructor(log: TrafficLog) { + constructor(requests: MatchingRequestTable, log: TrafficLog) { + this.#requests = requests; this.#log = log; } accept(socket: Socket, connectionId: number): void { - const session = new MatchingSession(socket, connectionId, this.#log); + const session = new MatchingSession(socket, connectionId, this.#requests, this.#log); socket.on('data', (chunk: Buffer) => { try { session.receive(chunk); @@ -43,14 +45,16 @@ export class MatchingService { class MatchingSession { readonly #socket: Socket; readonly #connectionId: number; + readonly #requests: MatchingRequestTable; readonly #log: TrafficLog; readonly #packets = new PacketReader(); #sessionKey: Buffer | undefined; #envelopes: EnvelopeReader | undefined; - constructor(socket: Socket, connectionId: number, log: TrafficLog) { + constructor(socket: Socket, connectionId: number, requests: MatchingRequestTable, log: TrafficLog) { this.#socket = socket; this.#connectionId = connectionId; + this.#requests = requests; this.#log = log; } @@ -89,7 +93,7 @@ class MatchingSession { this.#record('in', message, 'not a request', false); return; } - const handler = MATCHING_REQUESTS.get(request.name); + const handler = this.#requests.get(request.name); const notes: string[] = []; const control: MatchingSessionControl = { useSessionKey: (key) => { diff --git a/packages/local-service/src/server/port-listener.ts b/packages/local-service/src/server/port-listener.ts index 0fac1e2..b097a53 100644 --- a/packages/local-service/src/server/port-listener.ts +++ b/packages/local-service/src/server/port-listener.ts @@ -6,6 +6,7 @@ * to the HTTP server. */ import { createServer, type Server, type Socket } from 'node:net'; +import type { MatchingRequestTable } from '../matching/matching-requests.ts'; import { MatchingService } from '../matching/matching-service.ts'; import { startsMatchingPacket } from '../matching/matching-frame.ts'; import type { TrafficLog } from '../traffic-log/traffic-log.ts'; @@ -18,12 +19,12 @@ export interface PortListener { destroyConnections(): void; } -export function createPortListener(router: Router, log: TrafficLog): PortListener { +export function createPortListener(router: Router, matchingRequests: MatchingRequestTable, log: TrafficLog): PortListener { const numbers = new WeakMap(); const open = new Set(); let lastNumber = 0; const http = createHttpServer(router, log, (socket) => numbers.get(socket) ?? 0); - const matching = new MatchingService(log); + const matching = new MatchingService(matchingRequests, log); const server = createServer((socket) => { lastNumber += 1;