From b1392c05124bd03b79638dedf861b9dbcd66862b Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:39:53 +0800 Subject: [PATCH] Build the local battle mission settings in the local service The launch script patch used to assemble the whole MissionSettings block on the client: reading the mission file for localization keys and ticket rules, filling the AI vehicle pool, rank window and extra slot costs. All of that is pre-battle data the local service already owns. - multiplayer-missions dataset v3 keeps the scalar parameters of mission_settings.mission and of each per-difficulty sub-block, with their BLK types. - battle-mission-settings.ts builds the complete MissionSettings block from the launch plan (same parameters as before). - battle-launch-notify.ts sends it as a typed tree, so ints and reals keep the types the engine reads, plus the lobby settings and the per-battle record the in-battle patches read from nestdb. - The launch patch shrinks from 208 to about 70 lines: rebuild the DataBlock, set _gameMode from the client's own native constant, enter the session lobby and start the LocalMP battle. Behaviour is unchanged; coalitions, extra slots and economy are reworked in later commits. Verified: npm run typecheck, check-gui (33 patches). --- .../patch.jsonc | 12 +- .../replace.nut | 197 +++--------------- .../src/battle/battle-matchmaker.ts | 3 + .../src/battle/battle-mission-settings.ts | 128 ++++++++++++ .../datasets/multiplayer-missions.ts | 26 ++- .../src/matching/battle-launch-notify.ts | 79 +++++++ .../src/matching/battle-queue-requests.ts | 12 +- 7 files changed, 276 insertions(+), 181 deletions(-) create mode 100644 packages/local-service/src/battle/battle-mission-settings.ts create mode 100644 packages/local-service/src/matching/battle-launch-notify.ts diff --git a/gui-patches/battle/launch-local-battle-from-queue/patch.jsonc b/gui-patches/battle/launch-local-battle-from-queue/patch.jsonc index 8fc2b90..b27e9dd 100644 --- a/gui-patches/battle/launch-local-battle-from-queue/patch.jsonc +++ b/gui-patches/battle/launch-local-battle-from-queue/patch.jsonc @@ -1,12 +1,16 @@ -// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +// Start a local battle pushed by the local service: rebuild the mission settings it sends and host +// the battle as an in-process LocalMP session (select_training_mission + guiStartFlight). +// Why the client: the stock queue only ever joins a remote room (connect_to_host_list, peer mode); +// nothing in it enters LocalMP, so no answer from the service can start a hosted battle. +// Without it: "To Battle!" queues forever. { "id": "battle/launch-local-battle-from-queue", "title": "Launch local authoritative multiplayer battle on queue notification", "file": "scripts/matching/servicenotifications/match.nut", "features": [ - "battle-matchmaking", - "mission-launch", - "ai-bots" + "J-陆战 街机 / 历史", + "J-空战 街机 / 历史", + "J-海战 街机 / 历史" ], "verified_on": [ "2.61.0.37" diff --git a/gui-patches/battle/launch-local-battle-from-queue/replace.nut b/gui-patches/battle/launch-local-battle-from-queue/replace.nut index ba00b67..197e921 100644 --- a/gui-patches/battle/launch-local-battle-from-queue/replace.nut +++ b/gui-patches/battle/launch-local-battle-from-queue/replace.nut @@ -1,196 +1,61 @@ matchingApiFunc("match.enqueue", cb, params) } -function fillWtoBotEntries(parentBlk, blockName, entries) { - if (entries == null) - return - foreach (entry in entries) { - let b = parentBlk.addNewBlock(blockName) - b.name = entry.name - b.weight = (entry?.weight ?? 1.0).tofloat() - b.country = entry.country +// WTOffline: rebuild a DataBlock sent by the local service as { p = [[name, type, value]], b = [[name, node]] }. +// The type ("t", "i", "r", "b") travels with each value because the engine reads ints and reals with typed getters. +function wtoBlkFromWire(blk, node) { + foreach (param in (node?.p ?? [])) { + let [name, kind, value] = param + blk[name] <- kind == "i" ? value.tointeger() + : kind == "r" ? value.tofloat() + : kind == "b" ? value == true + : value.tostring() } + foreach (child in (node?.b ?? [])) + wtoBlkFromWire(blk.addNewBlock(child[0]), child[1]) + return blk } -function copyWtoMissionMetadata(misBlk, missionFile, difficulty) { - if (missionFile == null || missionFile == "") - return - let { blkOptFromPath } = require("%sqstd/datablock.nut") - let rawMis = blkOptFromPath(missionFile)?.mission_settings?.mission - if (rawMis == null) - return - let ruleKeys = [ - "scoreLimit", "timeLimit", "killLimit", "deathPenaltyMul", - "ctaCaptureZoneEqualPenaltyMul", "ctaCaptureZonePenaltyMul", - "captureZonePenaltyMul", "scorePerSec", - "ctaInstantDecreaseTicketsWhenNoRespawn", - "randomSpawnTeams", "remapAiTankModels", "useAlternativeMapCoord" - ] - foreach (key in [ - "locName", "locDesc", "locNameTeamA", "locNameTeamB", - "locDescTeamA", "locDescTeamB", "loc_name", "postfix", "restoreType" - ].extend(ruleKeys)) { - let val = rawMis?[key] - if (val != null) - misBlk[key] = val - } - let targetDiff = (difficulty == "simulator" || difficulty == "fullreal") ? "hardcore" - : (difficulty == "historical" ? "realistic" : difficulty) - foreach (sub in (rawMis % "mission")) { - let subDiff = sub?.difficulty - if (subDiff != difficulty && subDiff != targetDiff) - continue - foreach (dKey in ruleKeys) { - let dVal = sub?[dKey] - if (dVal != null) - misBlk[dKey] = dVal - } - } -} - -function toWtoPrefixedCountries(list, fallback) { - let src = (list != null && list.len() > 0) ? list : [fallback] - return src.map(@(c) c.indexof("country_") == 0 ? c : $"country_{c}") -} - -function buildWtoMissionBlk(ev, gmConsts, guiMis) { - let DataBlock = require("DataBlock") - let misBlk = DataBlock() - let baseBlk = guiMis.get_meta_mission_info_by_gm_and_name(gmConsts.GM_SKIRMISH, ev.missionName) - ?? guiMis.get_meta_mission_info_by_name(ev.missionName) - copyWtoMissionMetadata(misBlk, ev?.missionFile, ev.difficulty) - let levelVal = ev?.level ?? baseBlk?.level ?? misBlk?.level - let envVal = ev?.environment ?? baseBlk?.environment ?? misBlk?.environment - let weatherVal = ev?.weather ?? baseBlk?.weather ?? misBlk?.weather - if (levelVal != null) - misBlk.level = levelVal - if (envVal != null) - misBlk.environment = envVal - if (weatherVal != null) - misBlk.weather = weatherVal - - misBlk.localMP = true - misBlk._gameMode = gmConsts.GM_DOMINATION - misBlk.name = ev.missionName - misBlk.economicName = ev.economicName - misBlk.mis_file = ev.missionFile - misBlk.chapter = "skirmish" - misBlk.type = ev.missionType - misBlk.difficulty = ev.difficulty - misBlk.country_allies = ev.countryAllies - misBlk.country_axis = ev.countryAxis - misBlk.arcadeCountry = true - misBlk.symmetricTeams = ev?.symmetricTeams ?? false - misBlk.gt_versus = true - misBlk.gt_mp_tickets = true - misBlk.gt_mp_capture = true - misBlk.gt_mp_solo = false - misBlk.gt_use_wp = true - misBlk.gt_use_xp = true - misBlk.gt_use_stats = true - misBlk.gt_use_unlocks = true - misBlk.useSpawnScore = ev?.useSpawnScore ?? false - misBlk.allowSpare = true - misBlk.isLimitedAmmo = true - misBlk.allowUseArtillerySupport = true - misBlk.isBotsAllowed = true - misBlk.useTankBots = ev?.useTankBots ?? false - misBlk.useShipBots = ev?.useShipBots ?? false - misBlk.autoBalance = true - misBlk.maxPlayers = ev.maxPlayers - misBlk.maxBots = ev.maxBots - - let extraSlots = ev?.extraBattleSlots ?? [] - local persistentBlk = null - foreach (slot in extraSlots) { - let cost = slot?.persistentCost ?? 0 - let uName = slot?.unitName ?? "" - if (cost > 0 && uName != "") { - if (persistentBlk == null) - persistentBlk = misBlk.addNewBlock("customSpawnScore").addNewBlock("persistent_costs") - persistentBlk[uName] = cost.tointeger() - } - } - - foreach (tag in ["ranks", "forcedRanks"]) { - let rBlk = misBlk.addNewBlock(tag) - rBlk.min = ev.minMrank - rBlk.max = ev.maxMrank - } - let alliesBare = ev?.countriesAllies ?? [ev.countryAllies] - let axisBare = ev?.countriesAxis ?? [ev.countryAxis] - let botsBlk = misBlk.addNewBlock("customBots") - botsBlk.wtoPlayerTeam = $"{ev?.playerTeam ?? 1}" - botsBlk.wtoTeamACountries = ";".join(alliesBare) - botsBlk.wtoTeamBCountries = ";".join(axisBare) - botsBlk.numBotRespawnsInMultiSlot = ev.airBotRespawns - botsBlk.numTankBotRespawnsInMultiSlot = ev.tankBotRespawns - botsBlk.numBotRespawnsInVersus = ev.airBotRespawns - botsBlk.numTankBotRespawnsInVersus = ev.tankBotRespawns - fillWtoBotEntries(botsBlk.addNewBlock("allowedTanks"), "tank", ev?.customBots?.tanks) - fillWtoBotEntries(botsBlk.addNewBlock("allowedAircrafts"), "aircraft", ev?.customBots?.aircrafts) - fillWtoBotEntries(botsBlk.addNewBlock("allowedShips"), "ship", ev?.customBots?.ships) - return misBlk -} - -function enterWtoSessionRoom(ev, gmConsts) { - let lobbyStates = require("%scripts/matchingRooms/lobbyStates.nut") - let { setSessionLobbySettings, switchSessionLobbyStatus } = require("%scripts/matchingRooms/sessionLobbyManager.nut") - let alliesCountries = toWtoPrefixedCountries(ev?.countriesAllies, ev.countryAllies) - let axisCountries = toWtoPrefixedCountries(ev?.countriesAxis, ev.countryAxis) - setSessionLobbySettings({ - game_mode_id = ev.modeId - game_mode_name = ev.modeName - economicName = ev.economicName - symmetricTeams = ev?.symmetricTeams ?? false - country_allies = alliesCountries - country_axis = axisCountries - mission = { - name = ev.missionName - _gameMode = gmConsts.GM_DOMINATION - difficulty = ev.difficulty - } - }, true, false) - switchSessionLobbyStatus(lobbyStates.IN_SESSION) -} - +// WTOffline: start a local battle pushed by the local service (mrpc.generic_notify, from = "wto_battle"). +// The service sends the complete mission settings; the client hosts the battle as a LocalMP session. function onWtoBattleNotify(ev) { if (ev?.func != "launch" || isInFlight()) return + let DataBlock = require("DataBlock") let { ndbWrite } = require("nestdb") let guiMis = require("guiMission") - let missionMod = require("mission") - let gmConsts = require("%globalScripts/gameModeNativeConsts.nut") + let { set_game_mode } = require("mission") + let { GM_DOMINATION } = require("%globalScripts/gameModeNativeConsts.nut") let { reset_cur_mission_mode } = require("%appGlobals/ranks_common_shared.nut") let { notifyQueueLeave } = require("%scripts/queue/queueManager.nut") let destroySessionScripted = require("%scripts/matchingRooms/destroySessionScripted.nut") let { invalidateCrewsList } = require("%scripts/slotbar/crewsList.nut") let { guiStartFlight } = require("%scripts/missions/startMissionsList.nut") let { currentCampaignMission } = require("%scripts/missions/missionsStates.nut") + let lobbyStates = require("%scripts/matchingRooms/lobbyStates.nut") + let { setSessionLobbySettings, switchSessionLobbyStatus } = require("%scripts/matchingRooms/sessionLobbyManager.nut") notifyQueueLeave({}) destroySessionScripted("on start wto local battle") - ndbWrite(["wto", "activeBattle"], { - sessionId = ev.sessionId - modeName = ev.modeName - economicName = ev.economicName - country = ev.country - missionName = ev.missionName - extraBattleSlots = ev?.extraBattleSlots ?? [] - randomUnits = ev?.randomUnits ?? {} - randomUnitsEventName = ev?.randomUnitsEventName ?? "" - }) + ndbWrite(["wto", "activeBattle"], ev.battle) invalidateCrewsList(true) - let misBlk = buildWtoMissionBlk(ev, gmConsts, guiMis) - currentCampaignMission.set(ev.missionName) - missionMod.set_game_mode(gmConsts.GM_DOMINATION) - enterWtoSessionRoom(ev, gmConsts) + + let misBlk = wtoBlkFromWire(DataBlock(), ev.mission) + misBlk._gameMode = GM_DOMINATION + let lobby = ev.lobby + lobby.mission._gameMode <- GM_DOMINATION + + currentCampaignMission.set(misBlk.name) + set_game_mode(GM_DOMINATION) + setSessionLobbySettings(lobby, true, false) + switchSessionLobbyStatus(lobbyStates.IN_SESSION) reset_cur_mission_mode() guiMis.select_training_mission(misBlk) reset_cur_mission_mode() guiStartFlight() } +// WTOffline: forget the battle record when the session ends outside a battle (left before loading). require("%sqStdLibs/helpers/subscriptions.nut").addListenersWithoutEnv({ SessionDestroyed = function(_p) { if (!isInFlight()) { diff --git a/packages/local-service/src/battle/battle-matchmaker.ts b/packages/local-service/src/battle/battle-matchmaker.ts index 445fbdf..0beb51b 100644 --- a/packages/local-service/src/battle/battle-matchmaker.ts +++ b/packages/local-service/src/battle/battle-matchmaker.ts @@ -41,6 +41,8 @@ export interface BattleLaunchPlan { 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; @@ -205,6 +207,7 @@ export class BattleMatchmaker { modeName: declaration.name, economicName: declaration.economicName, missionName: mission.name, + mission, missionFile: mission.path, missionType: mission.type ?? 'domination', ...(mission.level !== undefined ? { level: mission.level } : {}), diff --git a/packages/local-service/src/battle/battle-mission-settings.ts b/packages/local-service/src/battle/battle-mission-settings.ts new file mode 100644 index 0000000..bc876d0 --- /dev/null +++ b/packages/local-service/src/battle/battle-mission-settings.ts @@ -0,0 +1,128 @@ +/** + * Mission settings for a local battle: the block the client hands to the native + * `select_training_mission` (guiMission) to host the battle as an in-process LocalMP session. + * + * The client loads the mission file itself, but does not copy the localization keys or the + * ticket and capture rules of `mission_settings.mission` into its MissionSettings; they are + * copied here from the mission file, base values first and then the sub-block for the battle's + * difficulty. `_gameMode` is left to the client, which takes it from its own native constants. + */ +import { emptyBlock, ensureBlock, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk'; +import type { ExtraBattleSlot } from './battle-extra-slots.ts'; +import type { BattleLaunchPlan } from './battle-matchmaker.ts'; +import type { CustomBotsPool } from './battle-ranks.ts'; + +/** Mission localization keys the client reads from MissionSettings (missionsText.nut). */ +const LOCALIZATION_KEYS: readonly string[] = [ + 'locName', 'locDesc', 'locNameTeamA', 'locNameTeamB', 'locDescTeamA', 'locDescTeamB', 'loc_name', 'postfix', 'restoreType', +]; + +/** Ticket, capture and time rules of the mission. */ +const RULE_KEYS: readonly string[] = [ + 'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul', + 'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec', + 'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord', +]; + +/** Game type switches of a versus battle with tickets, capture zones and session rewards. */ +const VERSUS_SWITCHES: readonly string[] = [ + 'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks', + 'allowSpare', 'isLimitedAmmo', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance', +]; + +export function battleMissionSettings(plan: BattleLaunchPlan): BlkBlock { + const settings = emptyBlock(); + copyMissionParams(settings, plan); + if (plan.level !== undefined) setParam(settings, 'level', text(plan.level)); + if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment)); + if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather)); + + setParam(settings, 'localMP', flag(true)); + setParam(settings, 'name', text(plan.missionName)); + setParam(settings, 'economicName', text(plan.economicName)); + setParam(settings, 'mis_file', text(plan.missionFile)); + setParam(settings, 'chapter', text('skirmish')); + setParam(settings, 'type', text(plan.missionType)); + setParam(settings, 'difficulty', text(plan.difficulty)); + setParam(settings, 'country_allies', text(plan.countryAllies)); + setParam(settings, 'country_axis', text(plan.countryAxis)); + setParam(settings, 'arcadeCountry', flag(true)); + setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams)); + setParam(settings, 'gt_mp_solo', flag(false)); + for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true)); + setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore)); + setParam(settings, 'useTankBots', flag(plan.useTankBots)); + setParam(settings, 'useShipBots', flag(plan.useShipBots)); + setParam(settings, 'maxPlayers', integer(plan.maxPlayers)); + setParam(settings, 'maxBots', integer(plan.maxBots)); + + addPersistentSpawnCosts(settings, plan.extraBattleSlots); + for (const name of ['ranks', 'forcedRanks']) { + const ranks = ensureBlock(settings, name); + setParam(ranks, 'min', integer(plan.minMrank)); + setParam(ranks, 'max', integer(plan.maxMrank)); + } + settings.blocks.push(customBotsBlock(plan)); + return settings; +} + +function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void { + const wanted = new Set([...LOCALIZATION_KEYS, ...RULE_KEYS]); + const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet): void => { + for (const param of params ?? []) { + if (keys.has(param.name)) setParam(settings, param.name, param.value); + } + }; + copy(plan.mission.missionParams, wanted); + copy(plan.mission.difficultyParams[plan.difficulty], new Set(RULE_KEYS)); +} + +/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */ +function addPersistentSpawnCosts(settings: BlkBlock, slots: readonly ExtraBattleSlot[]): void { + const costed = slots.filter((slot) => slot.persistentCost > 0 && slot.unitName !== ''); + if (costed.length === 0) return; + const costs = ensureBlock(ensureBlock(settings, 'customSpawnScore'), 'persistent_costs'); + for (const slot of costed) setParam(costs, slot.unitName, integer(slot.persistentCost)); +} + +/** AI vehicle pool in the layout of config/bots.blk; repeated entries are separate blocks. */ +function customBotsBlock(plan: BattleLaunchPlan): BlkBlock { + const bots = emptyBlock('customBots'); + setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam))); + setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';'))); + setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';'))); + setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns)); + setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns)); + setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns)); + setParam(bots, 'numTankBotRespawnsInVersus', integer(plan.tankBotRespawns)); + bots.blocks.push( + poolBlock('allowedTanks', 'tank', plan.customBots.tanks), + poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts), + poolBlock('allowedShips', 'ship', plan.customBots.ships), + ); + return bots; +} + +function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tanks']): BlkBlock { + const pool = emptyBlock(name); + for (const entry of entries) { + const block = emptyBlock(entryName); + appendParam(block, 'name', text(entry.name)); + appendParam(block, 'weight', { type: 'real', value: entry.weight }); + appendParam(block, 'country', text(entry.country)); + pool.blocks.push(block); + } + return pool; +} + +function text(value: string): BlkValue { + return { type: 'string', value }; +} + +function integer(value: number): BlkValue { + return { type: 'int', value: Math.trunc(value) }; +} + +function flag(value: boolean): BlkValue { + return { type: 'bool', value }; +} diff --git a/packages/local-service/src/game-data/datasets/multiplayer-missions.ts b/packages/local-service/src/game-data/datasets/multiplayer-missions.ts index aad63f4..e10fc5a 100644 --- a/packages/local-service/src/game-data/datasets/multiplayer-missions.ts +++ b/packages/local-service/src/game-data/datasets/multiplayer-missions.ts @@ -7,11 +7,13 @@ * - 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). + * ("wing" entries of player / player_teamB). Its scalar parameters (and those of each + * per-difficulty "mission" sub-block) are also kept as written, with their BLK types, for + * the mission settings the local service sends when a battle starts. * * 2.61.0.37: 1315 missions, each name matching exactly one mission file (docs/implementation notes). */ -import type { BlkBlock } from '@wto/blk'; +import type { BlkBlock, BlkParam } from '@wto/blk'; import type { Dataset, DatasetSource } from './dataset.ts'; import { blockAt, boolFields, numberField, stringField, stringList } from './blk-fields.ts'; @@ -43,6 +45,10 @@ export interface MissionHeader { readonly difficultyOverrides: readonly string[]; /** Spawn slots per side. */ readonly playerSlots: { readonly teamA: number; readonly teamB: number }; + /** String, int, real and bool parameters of mission_settings.mission, in file order. */ + readonly missionParams: readonly BlkParam[]; + /** The same for each per-difficulty "mission" sub-block, keyed by its `difficulty`. */ + readonly difficultyParams: Readonly>; } export interface MultiplayerMissions { @@ -52,7 +58,7 @@ export interface MultiplayerMissions { export const multiplayerMissions: Dataset = { id: 'multiplayer-missions', - version: 2, + version: 3, extract(source: DatasetSource): MultiplayerMissions { const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION); if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`); @@ -113,5 +119,19 @@ function readHeader(name: string, path: string, document: BlkBlock): MissionHead teamA: stringList(blockAt(settings, 'player'), 'wing').length, teamB: stringList(blockAt(settings, 'player_teamB'), 'wing').length, }, + missionParams: scalarParams(mission), + difficultyParams: Object.fromEntries((mission?.blocks ?? []) + .filter((block) => block.name === 'mission') + .flatMap((block) => { + const difficulty = stringField(block, 'difficulty'); + return difficulty ? [[difficulty, scalarParams(block)]] : []; + })), }; } + +const SCALAR_TYPES = new Set(['string', 'int', 'real', 'bool']); + +/** The parameters whose values survive the dataset cache's JSON unchanged. */ +function scalarParams(block: BlkBlock | undefined): BlkParam[] { + return (block?.params ?? []).filter((param) => SCALAR_TYPES.has(param.value.type)); +} diff --git a/packages/local-service/src/matching/battle-launch-notify.ts b/packages/local-service/src/matching/battle-launch-notify.ts new file mode 100644 index 0000000..67d6e15 --- /dev/null +++ b/packages/local-service/src/matching/battle-launch-notify.ts @@ -0,0 +1,79 @@ +/** + * The `mrpc.generic_notify` message that starts a local battle (`from: "wto_battle"`, + * `func: "launch"`), received by the client's launch script patch + * (gui-patches/battle/launch-local-battle-from-queue). + * + * - `mission`: the complete mission settings for `select_training_mission`, as a typed tree + * `{ p: [[name, type, value], ...], b: [[name, node], ...] }` with type "t", "i", "r" or "b". + * Matching notifications are JSON, which cannot tell 1 from 1.0; the engine reads ints and reals + * with typed getters, so the type travels with every value. Repeated blocks stay separate. + * - `lobby`: the session lobby settings the client's own room scripts read during the battle + * (game mode and both sides' countries). + * - `battle`: what the client keeps for this battle (session id for the settlement, extra slots). + */ +import type { BlkBlock, BlkValue } from '@wto/blk'; +import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts'; +import { battleMissionSettings } from '../battle/battle-mission-settings.ts'; + +type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean]; + +interface WireBlock { + readonly p: readonly WireParam[]; + readonly b: ReadonlyArray; +} + +export interface BattleLaunchNotify extends Record { + readonly from: 'wto_battle'; + readonly func: 'launch'; + readonly mission: WireBlock; + readonly lobby: Readonly>; + readonly battle: Readonly>; +} + +export function battleLaunchNotify(plan: BattleLaunchPlan): BattleLaunchNotify { + return { + from: 'wto_battle', + func: 'launch', + mission: toWire(battleMissionSettings(plan)), + lobby: { + game_mode_id: plan.modeId, + game_mode_name: plan.modeName, + economicName: plan.economicName, + symmetricTeams: plan.symmetricTeams, + country_allies: plan.countriesAllies.map(withCountryPrefix), + country_axis: plan.countriesAxis.map(withCountryPrefix), + mission: { name: plan.missionName, difficulty: plan.difficulty }, + }, + battle: { + sessionId: plan.sessionId, + modeName: plan.modeName, + economicName: plan.economicName, + country: plan.country, + missionName: plan.missionName, + extraBattleSlots: plan.extraBattleSlots, + randomUnits: plan.randomUnits, + randomUnitsEventName: plan.randomUnitsEventName ?? '', + }, + }; +} + +function toWire(block: BlkBlock): WireBlock { + return { + p: block.params.map((param) => [param.name, ...wireValue(param.name, param.value)] as const), + b: block.blocks.map((child) => [child.name, toWire(child)] as const), + }; +} + +function wireValue(name: string, value: BlkValue): readonly ['t' | 'i' | 'r' | 'b', string | number | boolean] { + switch (value.type) { + case 'string': return ['t', value.value]; + case 'int': return ['i', value.value]; + case 'real': return ['r', value.value]; + case 'bool': return ['b', value.value]; + default: throw new Error(`mission settings parameter ${name} has type ${value.type}, which the launch message cannot carry`); + } +} + +function withCountryPrefix(country: string): string { + return country.startsWith('country_') ? country : `country_${country}`; +} diff --git a/packages/local-service/src/matching/battle-queue-requests.ts b/packages/local-service/src/matching/battle-queue-requests.ts index 1872c2f..de38df8 100644 --- a/packages/local-service/src/matching/battle-queue-requests.ts +++ b/packages/local-service/src/matching/battle-queue-requests.ts @@ -6,25 +6,21 @@ * - `match.leave_queue` (scripts/queue/queuestate.nut:28) * - `match.check_reconnect` */ -import type { BattleLaunchPlan, BattleMatchmaker } from '../battle/battle-matchmaker.ts'; +import type { 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 { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts'; import type { MatchingRequestHandler } from './matching-requests.ts'; -export interface BattleLaunchNotifyPayload extends BattleLaunchPlan, Record { - 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; + readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void; } export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> { @@ -106,7 +102,7 @@ function handleEnqueue( setImmediate(() => { if (!deps.sessions.isPending(userId, launch.sessionId)) return; deps.sessions.clearPending(userId, launch.sessionId); - deps.notifyLaunch(userId, { from: 'wto_battle', func: 'launch', ...launch }); + deps.notifyLaunch(userId, battleLaunchNotify(launch)); }); return {}; }