From 901f504dc67d388c7679418846ba706c79178b60 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:48:17 +0800 Subject: [PATCH] Choose LocalMP extra lineup vehicles from the game data Rebuild the extra vehicles a battle adds to the player's lineup on the game files and the official rules: - Random vehicles (dice slots): one per gameplay.blk RandomSpawnUnits group of the event economic name and country, offered from the group's minPlayerMRank on, with no condition on the lineup. The option window follows the official changelog examples (never the session's top BR, lower BR when nothing fits); its formula is inferred from the group parameters. Only the listed addModification items are enabled. - Nuclear carrier: missionSupportPlane preset of the session rank, cost spawnScoreToUse. - Strike UCAV: offered by an offline tuning rule, priced by the stock spawn score formula, no forced preset. The spawn request enables exactly the slot's modifications, and every forced weapon travels in the slot, so the event-name fallback is gone. --- .../append-extra-battle-slots/patch.jsonc | 11 +- .../force-extra-slot-weapons/patch.jsonc | 11 +- .../force-extra-slot-weapons/replace.nut | 11 +- .../pass-spawn-modifications-blk/replace.nut | 9 +- .../patch.jsonc | 11 +- .../src/battle/battle-extra-slots.ts | 312 ++++++------------ .../src/battle/battle-matchmaker.ts | 13 +- .../src/battle/battle-mission-settings.ts | 7 +- .../local-service/src/battle/battle-tuning.ts | 7 +- .../game-data/datasets/battle-spawn-rules.ts | 227 ++++++------- .../src/matching/battle-launch-notify.ts | 1 - packages/local-service/tuning/battle.jsonc | 8 + 12 files changed, 259 insertions(+), 369 deletions(-) diff --git a/gui-patches/battle/append-extra-battle-slots/patch.jsonc b/gui-patches/battle/append-extra-battle-slots/patch.jsonc index 6c49f12..bfc1f95 100644 --- a/gui-patches/battle/append-extra-battle-slots/patch.jsonc +++ b/gui-patches/battle/append-extra-battle-slots/patch.jsonc @@ -1,11 +1,14 @@ -// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +// Add the extra vehicles the local service chose for a LocalMP battle (nuclear carrier, strike UCAV, +// random tank / SPAA / naval aircraft) to the in-battle crew list. +// Why the client: online the battle server adds them to the player's crews; a LocalMP host has no +// battle server, and the in-battle crew list comes from the native get_crew_info. +// Without it: the lineup holds only the player's own vehicles. { "id": "battle/append-extra-battle-slots", - "title": "Append session killstreak aircraft and random-spawn vehicles to in-battle crew list", + "title": "Add the LocalMP battle's extra vehicles to the in-battle crew list", "file": "scripts/slotbar/crewslist.nut", "features": [ - "J-本地对局", - "K-战局任务加载" + "K-补充载具" ], "verified_on": [ "2.61.0.37" diff --git a/gui-patches/battle/force-extra-slot-weapons/patch.jsonc b/gui-patches/battle/force-extra-slot-weapons/patch.jsonc index cd32050..61254c7 100644 --- a/gui-patches/battle/force-extra-slot-weapons/patch.jsonc +++ b/gui-patches/battle/force-extra-slot-weapons/patch.jsonc @@ -1,11 +1,14 @@ -// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +// Lock the weapon preset the local service set for an extra LocalMP vehicle (the nuclear carrier's +// bomb, the RandomSpawnUnits forceWeapon). +// Why the client: online getForcedUnitWeapon finds the random vehicle's weapon through the room +// event, which a LocalMP host does not have, and the nuclear carrier comes from the server. +// Without it: the extra vehicles spawn with whatever preset the respawn screen picks. { "id": "battle/force-extra-slot-weapons", - "title": "Lock nuclear, strike-UCAV, and RandomSpawnUnits forced weapon presets in LocalMP", + "title": "Lock the weapon presets of LocalMP extra vehicles", "file": "scripts/miscustomrules/rulebase.nut", "features": [ - "D-改装件与挂载", - "J-本地对局" + "K-补充载具" ], "verified_on": [ "2.61.0.37" diff --git a/gui-patches/battle/force-extra-slot-weapons/replace.nut b/gui-patches/battle/force-extra-slot-weapons/replace.nut index 2a17a62..36eaa67 100644 --- a/gui-patches/battle/force-extra-slot-weapons/replace.nut +++ b/gui-patches/battle/force-extra-slot-weapons/replace.nut @@ -1,15 +1,12 @@ function getForcedUnitWeapon(unit) { - let { ndbTryRead } = require("nestdb") - let wtoBattle = ndbTryRead(["wto", "activeBattle"]) - foreach (wtoSlot in (wtoBattle?.extraBattleSlots ?? [])) { + // WTOffline: the extra slots the local service added to a LocalMP lineup carry their forced + // weapon (nuclear carrier, RandomSpawnUnits forceWeapon); online the room event resolves it. + foreach (wtoSlot in (require("nestdb").ndbTryRead(["wto", "activeBattle"])?.extraBattleSlots ?? [])) if (wtoSlot?.unitName == unit.name && (wtoSlot?.forceWeapon ?? "") != "") return wtoSlot.forceWeapon - } let groupName = this.getRandomUnitsGroupName(unit.name) if (groupName == null) return this.missionParams?.editSlotbar[unit.shopCountry][unit.name]["forceWeapon"] - let wtoRoomEcon = getEventEconomicName(getRoomEvent()) - let wtoEconName = wtoRoomEcon != "" ? wtoRoomEcon : (wtoBattle?.randomUnitsEventName ?? "") - return getRandomUnitsForceWeapon(wtoEconName, unit.name) + return getRandomUnitsForceWeapon(getEventEconomicName(getRoomEvent()), unit.name) } diff --git a/gui-patches/battle/pass-spawn-modifications-blk/replace.nut b/gui-patches/battle/pass-spawn-modifications-blk/replace.nut index 79a655f..16d21d9 100644 --- a/gui-patches/battle/pass-spawn-modifications-blk/replace.nut +++ b/gui-patches/battle/pass-spawn-modifications-blk/replace.nut @@ -16,7 +16,7 @@ } if ((wtoExtraSlot?.forceWeapon ?? "") != "") requestData.weapon = wtoExtraSlot.forceWeapon - let wtoIsSpaded = wtoExtraSlot?.spaded == true + let wtoSlotMods = wtoExtraSlot?.modifications ?? [] let wtoUnit = getAircraftByName(wtoUnitName) ?? this.getCurSlotUnit() let wtoEnabledMods = [] let wtoDisabledMods = [] @@ -24,9 +24,12 @@ let wtoModName = wtoMod?.name ?? "" if (wtoModName == "") continue - if (wtoIsSpaded || wtoChardRes.shopIsModificationEnabled(wtoUnitName, wtoModName)) + let wtoIsEnabled = wtoExtraSlot == null + ? wtoChardRes.shopIsModificationEnabled(wtoUnitName, wtoModName) + : (wtoExtraSlot?.allModifications == true || wtoSlotMods.contains(wtoModName)) + if (wtoIsEnabled) wtoEnabledMods.append(wtoModName) - else if (wtoChardRes.shopIsModificationPurchased(wtoUnitName, wtoModName)) + else if (wtoExtraSlot == null && wtoChardRes.shopIsModificationPurchased(wtoUnitName, wtoModName)) wtoDisabledMods.append(wtoModName) } let wtoBlk = DataBlock() diff --git a/gui-patches/battle/populate-random-spawn-units-state/patch.jsonc b/gui-patches/battle/populate-random-spawn-units-state/patch.jsonc index a6261e6..2369ae9 100644 --- a/gui-patches/battle/populate-random-spawn-units-state/patch.jsonc +++ b/gui-patches/battle/populate-random-spawn-units-state/patch.jsonc @@ -1,11 +1,14 @@ -// Battle patch pending review in the LocalMP rework; its comment is rewritten when the review concludes. +// Fill the local player's random_units state with the options of each random vehicle group the +// local service drew for a LocalMP battle. +// Why the client: online the battle server writes it into the player's custom state; the stock +// slotbar reads it for the dice icon, the group name, the BR range and the list of options. +// Without it: the random vehicles look like plain lineup vehicles. { "id": "battle/populate-random-spawn-units-state", - "title": "Populate local player's random_units state block in LocalMP sessions", + "title": "Fill the random_units state of the local player in LocalMP", "file": "scripts/miscustomrules/rulebase.nut", "features": [ - "J-本地对局", - "K-战局任务加载" + "K-补充载具" ], "verified_on": [ "2.61.0.37" diff --git a/packages/local-service/src/battle/battle-extra-slots.ts b/packages/local-service/src/battle/battle-extra-slots.ts index 7502eb2..3b45177 100644 --- a/packages/local-service/src/battle/battle-extra-slots.ts +++ b/packages/local-service/src/battle/battle-extra-slots.ts @@ -1,32 +1,46 @@ /** - * Session-level extra crew slot selection for Ground RB killstreak aircraft - * (nuclear bombers from `gameplay.blk/missionSupportPlane`, strike UCAVs from `wpcost.blk`) - * and `gameplay.blk/RandomSpawnUnits` auto-supplemented lineup slots. + * The extra vehicles a battle adds to the player's lineup (online the battle server adds them): + * + * - Support plane (the nuclear carrier): gameplay.blk missionSupportPlane, keyed by the game mode + * name; the preset whose rankRange holds the session's top rank, the unit of the player's + * country, with its fixed weapon and its spawnScoreToUse as a fixed spawn cost. + * - Strike UCAV: wpcost.blk ucav_*_killstreak of the player's country. The game files have no rule + * for when it is offered; that is offline design in tuning/battle.jsonc. Its spawn cost comes + * from the stock spawn score formula. + * - Random vehicles (dice slots): gameplay.blk RandomSpawnUnits, keyed by the event economic name, + * one slot per group of the player's country. Rules from the official changelog ("Line of + * Contact", 2025-12-16): offered to lineups of BR 9.3 and higher (the groups' minPlayerMRank), + * with no condition on what the lineup holds; the options depend on the player's BR and the + * session's BR and never include the session's top BR; when no vehicle fits, lower BR vehicles + * are used. Worked examples there: in a 9.7-10.7 session a player at 10.7 gets 9.7-10.3 and a + * player at 9.7 gets 9.3-10.0. The window formula is not published; `randomWindow` is fitted to + * those examples with the group's own parameters (inferred, see there). */ import { randomInt } from 'node:crypto'; import type { BattleSpawnRulesData, - NuclearAircraftEntry, - NuclearPresetBracket, - RandomSpawnCandidate, - RandomSpawnGroupRule, + RandomSpawnGroup, + RandomSpawnUnit, + SupportPlanePreset, } from '../game-data/datasets/battle-spawn-rules.ts'; import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; import type { GameModeDeclaration } from '../game-modes/catalogue/game-mode-declaration.ts'; -import { unitClassOfExpClass, vehicleMrank } from './battle-ranks.ts'; +import type { BattleTuning } from './battle-tuning.ts'; +import { vehicleMrank } from './battle-ranks.ts'; -/** Ground RB persistent spawn-point cost for strike UCAVs (`ucav_*_killstreak`). */ -const STRIKE_UCAV_SPAWN_SCORE = 750; -/** Standard maximum rank spread below `economicRankHistorical` where strike UCAVs appear. */ -const STRIKE_UCAV_MAX_RANK_DIFF = 2; -/** Engine bitmask limit on crew slots (`LMP_MP_OFF_BROKEN_SLOTS_MASK` is `uint32_t`). */ +/** The LocalMP host tracks crew slots in a 32-bit mask (native LMP_MP_OFF_BROKEN_SLOTS_MASK). */ const MAX_BATTLE_CREW_SLOTS = 32; export interface ExtraBattleSlot { readonly unitName: string; - readonly persistentCost: number; - readonly spaded: boolean; + /** Fixed spawn cost (mission customSpawnScore.persistent_costs); absent = the stock formula. */ + readonly persistentCost?: number; + /** Every modification of the unit is enabled. */ + readonly allModifications: boolean; + /** The modifications enabled when not `allModifications`; the unit is otherwise stock. */ + readonly modifications: readonly string[]; readonly forceWeapon?: string; + /** The RandomSpawnUnits group the slot was drawn from (a dice slot). */ readonly groupName?: string; } @@ -34,224 +48,108 @@ export interface ExtraBattleSlotsInput { readonly country: string; readonly slotVehicles: readonly string[]; readonly declaration: GameModeDeclaration; + /** The lineup's mrank the session was matched on. */ + readonly playerMrank: number; readonly sessionMaxMrank: number; readonly vehiclesByName: ReadonlyMap; - readonly rules?: BattleSpawnRulesData; + readonly rules: BattleSpawnRulesData; + readonly tuning: Pick; } export interface ExtraBattleSlotsPlan { readonly extraBattleSlots: readonly ExtraBattleSlot[]; + /** The `random_units` state of the player: every option of each drawn group, by group name. */ readonly randomUnits: Readonly>; - readonly randomUnitsEventName?: string; } export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): ExtraBattleSlotsPlan { - const { rules, declaration, slotVehicles } = input; - const maxExtra = Math.max(0, MAX_BATTLE_CREW_SLOTS - slotVehicles.length); - if (!rules || declaration.multiSlot === false || maxExtra === 0) { - return { extraBattleSlots: [], randomUnits: {} }; - } + const room = MAX_BATTLE_CREW_SLOTS - input.slotVehicles.length; + if (input.declaration.multiSlot === false || room <= 0) return { extraBattleSlots: [], randomUnits: {} }; const slots: ExtraBattleSlot[] = []; - if (declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic') { - const nuclear = pickNuclearSlot(input.country, input.sessionMaxMrank, rules.nuclearBrackets); - if (nuclear) slots.push(nuclear); - const ucav = pickStrikeUcavSlot(input.country, input.sessionMaxMrank, rules); - if (ucav) slots.push(ucav); - } + const supportPlane = supportPlaneSlot(input); + if (supportPlane) slots.push(supportPlane); + const ucav = strikeUcavSlot(input); + if (ucav) slots.push(ucav); - const randomPlan = pickRandomSpawnSlots(input, rules); - slots.push(...randomPlan.slots); - - return { - extraBattleSlots: slots.slice(0, maxExtra), - randomUnits: randomPlan.randomUnits, - ...(randomPlan.eventName ? { randomUnitsEventName: randomPlan.eventName } : {}), - }; -} - -function pickNuclearSlot( - country: string, - sessionMaxMrank: number, - brackets: readonly NuclearPresetBracket[], -): ExtraBattleSlot | undefined { - if (brackets.length === 0) return undefined; - const minNuclearRank = brackets[0]!.minMrank; - if (sessionMaxMrank < minNuclearRank) return undefined; - - const matchingBracket = brackets.find((b) => sessionMaxMrank >= b.minMrank && sessionMaxMrank <= b.maxMrank) - ?? (sessionMaxMrank > brackets[brackets.length - 1]!.maxMrank ? brackets[brackets.length - 1] : undefined); - if (!matchingBracket) return undefined; - - const countryEntries = matchingBracket.entries.filter((entry) => entry.country === country); - if (countryEntries.length === 0) return undefined; - - const chosen = chooseBestNuclearEntry(countryEntries, sessionMaxMrank); - return { - unitName: chosen.unitName, - persistentCost: matchingBracket.spawnScore, - spaded: true, - forceWeapon: chosen.weapon, - }; -} - -function chooseBestNuclearEntry( - entries: readonly NuclearAircraftEntry[], - sessionMaxMrank: number, -): NuclearAircraftEntry { - const withinRank = entries.filter((entry) => entry.tankRealisticMrank <= sessionMaxMrank); - if (withinRank.length > 0) { - const highestRank = withinRank.reduce((max, entry) => Math.max(max, entry.tankRealisticMrank), 0); - const tied = withinRank.filter((entry) => entry.tankRealisticMrank === highestRank); - return tied[randomInt(tied.length)]!; - } - const lowestRank = entries.reduce((min, entry) => Math.min(min, entry.tankRealisticMrank), Infinity); - const fallback = entries.filter((entry) => entry.tankRealisticMrank === lowestRank); - return fallback[randomInt(fallback.length)]!; -} - -function pickStrikeUcavSlot( - country: string, - sessionMaxMrank: number, - rules: BattleSpawnRulesData, -): ExtraBattleSlot | undefined { - const ucav = rules.strikeUcavs.find((entry) => entry.country === country); - if (!ucav) return undefined; - const minSessionRank = Math.max(0, ucav.historicalMrank - STRIKE_UCAV_MAX_RANK_DIFF); - if (sessionMaxMrank < minSessionRank) return undefined; - return { - unitName: ucav.unitName, - persistentCost: STRIKE_UCAV_SPAWN_SCORE, - spaded: true, - ...(ucav.weapon ? { forceWeapon: ucav.weapon } : {}), - }; -} - -function pickRandomSpawnSlots( - input: ExtraBattleSlotsInput, - rules: BattleSpawnRulesData, -): { - readonly eventName?: string; - readonly slots: readonly ExtraBattleSlot[]; - readonly randomUnits: Readonly>; -} { - const eventName = resolveRandomSpawnEventName(input.declaration); - if (!eventName) return { slots: [], randomUnits: {} }; - const eventRule = rules.randomSpawnEvents.find((entry) => entry.eventName === eventName); - const groups = eventRule?.countries[input.country]; - if (!groups || groups.length === 0) return { slots: [], randomUnits: {} }; - - const playerTopMrank = topAllowedLineupMrank(input.slotVehicles, input.declaration, input.vehiclesByName); - const equipped = new Set(input.slotVehicles); - const slots: ExtraBattleSlot[] = []; const randomUnits: Record = {}; - - for (const group of groups) { - if (playerTopMrank < group.minPlayerMRank) continue; - if (input.sessionMaxMrank - playerTopMrank > group.maxDiffBetweenTopUnitAndSessionRank) continue; - const minWindowRank = Math.max(0, playerTopMrank - group.mRanksCount); - if (!lineupNeedsRandomGroup(group.groupName, input.slotVehicles, minWindowRank, input.declaration, input.vehiclesByName)) { - continue; - } - const candidates = filterGroupCandidates(group, minWindowRank, playerTopMrank, equipped, input.declaration, input.vehiclesByName); - if (candidates.length === 0) continue; - - const chosen = candidates[randomInt(candidates.length)]!; - randomUnits[group.groupName] = candidates.map((candidate) => candidate.unitName); + for (const group of input.rules.randomSpawnUnits[input.declaration.economicName]?.[input.country] ?? []) { + const options = randomGroupOptions(group, input); + if (options.length === 0) continue; + const chosen = options[randomInt(options.length)]!; + randomUnits[group.name] = options.map((unit) => unit.unitName); slots.push({ unitName: chosen.unitName, - persistentCost: 0, - spaded: true, - groupName: group.groupName, + allModifications: false, + modifications: chosen.addModifications, ...(chosen.forceWeapon ? { forceWeapon: chosen.forceWeapon } : {}), + groupName: group.name, }); } - if (slots.length === 0) return { slots: [], randomUnits: {} }; - return { eventName, slots, randomUnits }; + const kept = slots.slice(0, room); + const keptGroups = new Set(kept.flatMap((slot) => slot.groupName ?? [])); + return { + extraBattleSlots: kept, + randomUnits: Object.fromEntries(Object.entries(randomUnits).filter(([name]) => keptGroups.has(name))), + }; } -function resolveRandomSpawnEventName(declaration: GameModeDeclaration): string | undefined { - if (declaration.requiredClass === 'tank') { - if (declaration.difficulty === 'realistic') return 'tank_random_battles_historical_base'; - if (declaration.difficulty === 'arcade') return 'tank_event_in_random_battles_arcade'; - } - if (declaration.requiredClass === 'ship') { - if (declaration.difficulty === 'realistic') return 'ship_event_in_random_battles_realistic'; - if (declaration.difficulty === 'arcade') return 'ship_event_in_random_battles_arcade'; - } - return undefined; +function supportPlaneSlot(input: ExtraBattleSlotsInput): ExtraBattleSlot | undefined { + const presets: readonly SupportPlanePreset[] = input.rules.supportPlanes[input.declaration.name] ?? []; + const preset = presets.find((p) => input.sessionMaxMrank >= p.minMrank && input.sessionMaxMrank <= p.maxMrank); + const unit = preset?.units[input.country]; + if (!preset || !unit) return undefined; + return { + unitName: unit.unitName, + persistentCost: preset.spawnScoreToUse, + allModifications: true, + modifications: [], + forceWeapon: unit.weapon, + }; } -function topAllowedLineupMrank( - slotVehicles: readonly string[], - declaration: GameModeDeclaration, - byName: ReadonlyMap, -): number { - const allowed = new Set(declaration.allowedClasses); - let top = 0; - for (const name of slotVehicles) { - const vehicle = byName.get(name); - const cls = vehicle && unitClassOfExpClass(vehicle.unitClass); - if (!vehicle || !cls || !allowed.has(cls)) continue; - top = Math.max(top, vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass)); - } - return top; +function strikeUcavSlot(input: ExtraBattleSlotsInput): ExtraBattleSlot | undefined { + if (!input.tuning.strikeUcavModes.includes(input.declaration.name)) return undefined; + const ucav = input.rules.strikeUcavs.find((entry) => entry.country === input.country); + const vehicle = ucav && input.vehiclesByName.get(ucav.unitName); + if (!ucav || !vehicle) return undefined; + const ucavMrank = vehicleMrank(vehicle, input.declaration.difficulty, input.declaration.requiredClass); + if (input.sessionMaxMrank < ucavMrank - input.tuning.strikeUcavSessionMrankAllowance) return undefined; + // Offline design: the UCAV comes fully upgraded and keeps its weapon choice (the game files force no preset). + return { unitName: ucav.unitName, allModifications: true, modifications: [] }; } -function lineupNeedsRandomGroup( - groupName: string, - slotVehicles: readonly string[], - minWindowRank: number, - declaration: GameModeDeclaration, - byName: ReadonlyMap, -): boolean { - let matching = 0; - for (const name of slotVehicles) { - const vehicle = byName.get(name); - if (!vehicle) continue; - const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass); - if (groupName === 'spaa') { - if (vehicle.unitClass === 'exp_SPAA' && rank >= minWindowRank) matching++; - } else if (groupName === 'tank') { - if (unitClassOfExpClass(vehicle.unitClass) === 'tank' && vehicle.unitClass !== 'exp_SPAA' && rank >= minWindowRank) { - matching++; - } - } else if (groupName === 'bomber') { - if (vehicle.unitClass === 'exp_bomber' || vehicle.unitClass === 'exp_assault') matching++; - } else if (groupName === 'fighter') { - if (vehicle.unitClass === 'exp_fighter') matching++; - } - } - return groupName === 'tank' ? matching < 2 : matching < 1; -} - -function filterGroupCandidates( - group: RandomSpawnGroupRule, - minWindowRank: number, - maxWindowRank: number, - equipped: ReadonlySet, - declaration: GameModeDeclaration, - byName: ReadonlyMap, -): RandomSpawnCandidate[] { - const inWindow = group.units.filter((candidate) => { - if (equipped.has(candidate.unitName)) return false; - const vehicle = byName.get(candidate.unitName); - if (!vehicle) return false; - const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass); - return rank >= minWindowRank && rank <= maxWindowRank; +/** + * The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits, + * those of the highest rank below it. Vehicles already in the lineup are left out (the stock + * slotbar hides a lineup vehicle that a random group lists as disabled, rulebase.nut + * isUnitEnabledByRandomGroups, so listing them would be ambiguous). + */ +function randomGroupOptions(group: RandomSpawnGroup, input: ExtraBattleSlotsInput): RandomSpawnUnit[] { + if (input.playerMrank < group.minPlayerMrank) return []; + const { low, high } = randomWindow(group, input.playerMrank, input.sessionMaxMrank); + const lineup = new Set(input.slotVehicles); + const ranked = group.units.flatMap((unit) => { + const vehicle = input.vehiclesByName.get(unit.unitName); + if (!vehicle || lineup.has(unit.unitName)) return []; + const mrank = vehicleMrank(vehicle, input.declaration.difficulty, input.declaration.requiredClass); + return mrank <= high ? [{ unit, mrank }] : []; }); - if (inWindow.length > 0) return inWindow; + const inWindow = ranked.filter((entry) => entry.mrank >= low); + if (inWindow.length > 0) return inWindow.map((entry) => entry.unit); + const best = Math.max(...ranked.map((entry) => entry.mrank)); + return ranked.filter((entry) => entry.mrank === best).map((entry) => entry.unit); +} - const lowerCandidates = group.units - .flatMap((candidate) => { - if (equipped.has(candidate.unitName)) return []; - const vehicle = byName.get(candidate.unitName); - if (!vehicle) return []; - const rank = vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass); - return rank <= maxWindowRank ? [{ candidate, rank }] : []; - }); - if (lowerCandidates.length === 0) return []; - const bestRank = lowerCandidates.reduce((max, item) => Math.max(max, item.rank), 0); - return lowerCandidates.filter((item) => item.rank === bestRank).map((item) => item.candidate); +/** + * Inferred window (the formula is not published): the top option is the player's rank, raised to + * at least `maxDiffBetweenTopUnitAndSessionRank` below the session's top rank and capped one rank + * below it; the window spans `mRanksCount` ranks under the top option. With the stock values + * (2 and 2) this gives both official examples: session 10.7 (mrank 29), player 10.7 (29) -> + * mranks 26-28 = BR 9.7-10.3; player 9.7 (26) -> mranks 25-27 = BR 9.3-10.0. + */ +function randomWindow(group: RandomSpawnGroup, playerMrank: number, sessionMaxMrank: number) { + const high = Math.min(Math.max(playerMrank, sessionMaxMrank - group.maxDiffBetweenTopUnitAndSessionRank), sessionMaxMrank - 1); + return { low: Math.max(0, high - group.mranksCount), high }; } diff --git a/packages/local-service/src/battle/battle-matchmaker.ts b/packages/local-service/src/battle/battle-matchmaker.ts index 0beb51b..22e6b38 100644 --- a/packages/local-service/src/battle/battle-matchmaker.ts +++ b/packages/local-service/src/battle/battle-matchmaker.ts @@ -68,7 +68,6 @@ export interface BattleLaunchPlan { readonly customBots: CustomBotsPool; readonly extraBattleSlots: readonly ExtraBattleSlot[]; readonly randomUnits: Readonly>; - readonly randomUnitsEventName?: string; } export type MatchmakeOutcome = @@ -81,14 +80,14 @@ export class BattleMatchmaker { readonly #vehiclesByName: ReadonlyMap; readonly #sessions: BattleSessionStore; readonly #tuning: BattleTuning; - readonly #spawnRules: BattleSpawnRulesData | undefined; + readonly #spawnRules: BattleSpawnRulesData; constructor( gameModes: GameModes, vehicles: readonly CatalogueVehicle[], sessions: BattleSessionStore, tuning: BattleTuning, - spawnRules?: BattleSpawnRulesData, + spawnRules: BattleSpawnRulesData, ) { this.#gameModes = gameModes; this.#vehicles = vehicles; @@ -137,7 +136,7 @@ export class BattleMatchmaker { }); return { ok: true, - launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, minMrank, maxMrank, customBots), + launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots), }; } @@ -169,6 +168,7 @@ export class BattleMatchmaker { chosenMode: OfferedGameMode, mission: MissionHeader, coalitions: CoalitionPairing, + playerMrank: number, minMrank: number, maxMrank: number, customBots: CustomBotsPool, @@ -197,9 +197,11 @@ export class BattleMatchmaker { country: input.country, slotVehicles: input.slotVehicles, declaration, + playerMrank, sessionMaxMrank: maxMrank, vehiclesByName: this.#vehiclesByName, - ...(this.#spawnRules ? { rules: this.#spawnRules } : {}), + rules: this.#spawnRules, + tuning: this.#tuning, }); return { sessionId: session.sessionId, @@ -233,7 +235,6 @@ export class BattleMatchmaker { customBots, extraBattleSlots: extraPlan.extraBattleSlots, randomUnits: extraPlan.randomUnits, - ...(extraPlan.randomUnitsEventName ? { randomUnitsEventName: extraPlan.randomUnitsEventName } : {}), }; } } diff --git a/packages/local-service/src/battle/battle-mission-settings.ts b/packages/local-service/src/battle/battle-mission-settings.ts index bc876d0..4f3e5f3 100644 --- a/packages/local-service/src/battle/battle-mission-settings.ts +++ b/packages/local-service/src/battle/battle-mission-settings.ts @@ -79,10 +79,13 @@ function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void { /** 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 !== ''); + const costed = slots.flatMap((slot) => + slot.persistentCost !== undefined && slot.persistentCost > 0 && slot.unitName !== '' + ? [{ unitName: slot.unitName, cost: slot.persistentCost }] + : []); 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)); + for (const slot of costed) setParam(costs, slot.unitName, integer(slot.cost)); } /** AI vehicle pool in the layout of config/bots.blk; repeated entries are separate blocks. */ diff --git a/packages/local-service/src/battle/battle-tuning.ts b/packages/local-service/src/battle/battle-tuning.ts index 7fd9d7c..f243128 100644 --- a/packages/local-service/src/battle/battle-tuning.ts +++ b/packages/local-service/src/battle/battle-tuning.ts @@ -1,6 +1,7 @@ /** * Typed reader for `tuning/battle.jsonc`: offline Silver Lions and Research Points - * multipliers, LocalMP slot and bot counts, matchmaking BR window and coalition pairing rules. + * multipliers, LocalMP slot and bot counts, matchmaking BR window, coalition pairing rules and + * the strike UCAV extra slot. */ import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts'; @@ -19,6 +20,8 @@ export interface BattleTuning { readonly rbAirMixedChance: number; readonly rbNavalMixedChance: number; readonly simColdWarMinMrank: number; + readonly strikeUcavModes: readonly string[]; + readonly strikeUcavSessionMrankAllowance: number; readonly tankBotRespawns: number; readonly airBotRespawns: number; } @@ -57,6 +60,8 @@ export function readBattleTuning(reader: TuningReader): BattleTuning { rbAirMixedChance: reader.number('rbAirMixedChance', { min: 0, max: 1 }), rbNavalMixedChance: reader.number('rbNavalMixedChance', { min: 0, max: 1 }), simColdWarMinMrank: reader.int('simColdWarMinMrank', { min: 0, max: 40 }), + strikeUcavModes: reader.stringList('strikeUcavModes'), + strikeUcavSessionMrankAllowance: reader.int('strikeUcavSessionMrankAllowance', { min: 0, max: 12 }), tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }), airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }), }; diff --git a/packages/local-service/src/game-data/datasets/battle-spawn-rules.ts b/packages/local-service/src/game-data/datasets/battle-spawn-rules.ts index b426281..8048c68 100644 --- a/packages/local-service/src/game-data/datasets/battle-spawn-rules.ts +++ b/packages/local-service/src/game-data/datasets/battle-spawn-rules.ts @@ -1,184 +1,151 @@ /** - * Dataset: Ground RB special spawn aircraft (`missionSupportPlane` nuclear bombers and - * `ucav_*_killstreak` strike UCAVs) and `RandomSpawnUnits` auto-supplemented vehicle pools. + * Dataset: the extra vehicles a battle adds to a player's lineup, as the game files list them. * * aces.vromfs.bin config/gameplay.blk - * missionSupportPlane{ tank_event_in_random_battles_historical{ UnitPreset{ ... } } } - * RandomSpawnUnits{ { { { minPlayerMRank:i ... { ... } } } } } + * missionSupportPlane{ { UnitPreset{ killStreakTagName:t rankRange:ip2 spawnScoreToShow:i + * spawnScoreToUse:i { unitName:t weapon:t } } } } + * Killstreak aircraft (the nuclear carrier) per session rank bracket, one per country. + * RandomSpawnUnits{ { { { minPlayerMRank:i + * maxDiffBetweenTopUnitAndSessionRank:i mRanksCount:i { addModification:t addWeapon:t + * forceWeapon:t } } } } } + * The random vehicle groups (dice slots: random tank and SPAA in ground battles, random fighter + * and bomber in naval battles). The stock client reads the same block for forced weapons + * (scripts/unit/randomunitsforceweapon.nut). * char.vromfs.bin config/wpcost.blk - * _killstreak{ country:t economicRankHistorical:i economicRankTankHistorical:i weapons{ ... } } + * ucav_*_killstreak{ country:t ... } + * The strike UCAVs, one per country. */ -import { findBlock, findParam, type BlkBlock } from '@wto/blk'; -import { numberField, stringField } from './blk-fields.ts'; +import type { BlkBlock } from '@wto/blk'; +import { findParam } from '@wto/blk'; +import { blockAt, numberField, stringField, stringList } from './blk-fields.ts'; import type { Dataset } from './dataset.ts'; -export interface NuclearAircraftEntry { - readonly country: string; +export interface SupportPlaneUnit { readonly unitName: string; readonly weapon: string; - readonly tankRealisticMrank: number; } -export interface NuclearPresetBracket { +export interface SupportPlanePreset { + readonly killStreakTag: string; + /** Session rank bracket (`rankRange`, inclusive). */ readonly minMrank: number; readonly maxMrank: number; - readonly spawnScore: number; - readonly entries: readonly NuclearAircraftEntry[]; + readonly spawnScoreToShow: number; + readonly spawnScoreToUse: number; + /** By country. */ + readonly units: Readonly>; } -export interface StrikeUcavEntry { +export interface StrikeUcav { readonly country: string; readonly unitName: string; - readonly weapon: string; - readonly historicalMrank: number; } -export interface RandomSpawnCandidate { +export interface RandomSpawnUnit { readonly unitName: string; + readonly addModifications: readonly string[]; readonly forceWeapon?: string; } -export interface RandomSpawnGroupRule { - readonly groupName: string; - readonly minPlayerMRank: number; +export interface RandomSpawnGroup { + /** `tank`, `spaa`, `fighter`, `bomber`: the key of `random_units` and of gui.blk `randomSpawnUnitPresets`. */ + readonly name: string; + readonly minPlayerMrank: number; readonly maxDiffBetweenTopUnitAndSessionRank: number; - readonly mRanksCount: number; - readonly units: readonly RandomSpawnCandidate[]; -} - -export interface RandomSpawnEventRule { - readonly eventName: string; - readonly countries: Readonly>; + readonly mranksCount: number; + readonly units: readonly RandomSpawnUnit[]; } export interface BattleSpawnRulesData { - readonly nuclearBrackets: readonly NuclearPresetBracket[]; - readonly strikeUcavs: readonly StrikeUcavEntry[]; - readonly randomSpawnEvents: readonly RandomSpawnEventRule[]; + /** By event name (`missionSupportPlane` keys are game mode names). */ + readonly supportPlanes: Readonly>; + readonly strikeUcavs: readonly StrikeUcav[]; + /** By event economic name, then country. */ + readonly randomSpawnUnits: Readonly>>>; } const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/; export const battleSpawnRules: Dataset = { id: 'battle-spawn-rules', - version: 1, + version: 2, extract: (source) => { const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk'); const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk'); - const wpcostByUnit = new Map(wpcost.blocks.map((block) => [block.name, block])); return { - nuclearBrackets: extractNuclearBrackets(gameplay, wpcostByUnit), + supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')), strikeUcavs: extractStrikeUcavs(wpcost.blocks), - randomSpawnEvents: extractRandomSpawnEvents(gameplay), + randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')), }; }, }; -function extractNuclearBrackets( - gameplay: BlkBlock, - wpcostByUnit: ReadonlyMap, -): NuclearPresetBracket[] { - const msp = findBlock(gameplay, 'missionSupportPlane'); - const tankRb = msp && findBlock(msp, 'tank_event_in_random_battles_historical'); - if (!tankRb) return []; - - const brackets: NuclearPresetBracket[] = []; - for (const preset of tankRb.blocks) { - if (preset.name !== 'UnitPreset') continue; - if (stringField(preset, 'killStreakTagName') !== 'bomber_nuclear') continue; - const range = ipoint2Field(preset, 'rankRange'); - const spawnScore = numberField(preset, 'spawnScoreToUse'); - if (!range || spawnScore === undefined || spawnScore <= 0) continue; - - const entries: NuclearAircraftEntry[] = []; - for (const countryBlk of preset.blocks) { - if (!countryBlk.name.startsWith('country_')) continue; - const unitName = stringField(countryBlk, 'unitName') ?? ''; - const weapon = stringField(countryBlk, 'weapon') ?? ''; - if (!unitName || !weapon) continue; - const costBlk = wpcostByUnit.get(unitName); - const tankRealisticMrank = (costBlk && ( - numberField(costBlk, 'economicRankTankHistorical') - ?? numberField(costBlk, 'economicRankHistorical') - ?? numberField(costBlk, 'economicRank') - )) ?? range[0]; - entries.push({ country: countryBlk.name, unitName, weapon, tankRealisticMrank }); - } - if (entries.length > 0) { - brackets.push({ minMrank: range[0], maxMrank: range[1], spawnScore, entries }); +function extractSupportPlanes(root: BlkBlock | undefined): Record { + const byEvent: Record = {}; + for (const eventBlk of root?.blocks ?? []) { + const presets: SupportPlanePreset[] = []; + for (const preset of eventBlk.blocks) { + if (preset.name !== 'UnitPreset') continue; + const range = findParam(preset, 'rankRange')?.value; + const spawnScoreToUse = numberField(preset, 'spawnScoreToUse'); + if (range?.type !== 'ipoint2' || spawnScoreToUse === undefined) continue; + const units: Record = {}; + for (const countryBlk of preset.blocks) { + const unitName = stringField(countryBlk, 'unitName'); + const weapon = stringField(countryBlk, 'weapon'); + if (countryBlk.name.startsWith('country_') && unitName && weapon) units[countryBlk.name] = { unitName, weapon }; + } + presets.push({ + killStreakTag: stringField(preset, 'killStreakTagName') ?? '', + minMrank: range.value[0], + maxMrank: range.value[1], + spawnScoreToShow: numberField(preset, 'spawnScoreToShow') ?? spawnScoreToUse, + spawnScoreToUse, + units, + }); } + if (presets.length > 0) byEvent[eventBlk.name] = presets; } - return brackets.sort((a, b) => a.minMrank - b.minMrank); + return byEvent; } -function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcavEntry[] { - const entries: StrikeUcavEntry[] = []; - for (const unitBlk of wpcostBlocks) { - if (!STRIKE_UCAV_PATTERN.test(unitBlk.name)) continue; +function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcav[] { + return wpcostBlocks.flatMap((unitBlk) => { const country = stringField(unitBlk, 'country') ?? ''; - if (!country.startsWith('country_')) continue; - const historicalMrank = numberField(unitBlk, 'economicRankTankHistorical') - ?? numberField(unitBlk, 'economicRankHistorical') - ?? numberField(unitBlk, 'economicRank') - ?? 0; - const weapon = pickArmedUcavWeapon(unitBlk); - entries.push({ country, unitName: unitBlk.name, weapon, historicalMrank }); - } - return entries; + return STRIKE_UCAV_PATTERN.test(unitBlk.name) && country.startsWith('country_') + ? [{ country, unitName: unitBlk.name }] + : []; + }); } -function pickArmedUcavWeapon(unitBlk: BlkBlock): string { - const weaponsBlk = findBlock(unitBlk, 'weapons'); - const presets = (weaponsBlk?.blocks ?? []).filter((b) => - b.name !== 'custom_presets' - && !b.name.startsWith('bombguns_') - && !b.name.startsWith('containers_') - && !b.name.startsWith('rocketguns_')); - const armed = presets.find((preset) => - (numberField(preset, 'atgmMaxDistance') ?? 0) > 0 - || (numberField(preset, 'totalBombRocketMass') ?? 0) > 0 - || (numberField(preset, 'totalGuidedBombMass') ?? 0) > 0); - return armed?.name ?? presets[0]?.name ?? ''; -} - -function extractRandomSpawnEvents(gameplay: BlkBlock): RandomSpawnEventRule[] { - const root = findBlock(gameplay, 'RandomSpawnUnits'); - if (!root) return []; - const events: RandomSpawnEventRule[] = []; - for (const eventBlk of root.blocks) { - const countries: Record = {}; +function extractRandomSpawnUnits( + root: BlkBlock | undefined, +): Record> { + const byEvent: Record> = {}; + for (const eventBlk of root?.blocks ?? []) { + const byCountry: Record = {}; for (const countryBlk of eventBlk.blocks) { if (!countryBlk.name.startsWith('country_')) continue; - const groups: RandomSpawnGroupRule[] = []; - for (const groupBlk of countryBlk.blocks) { - const minPlayerMRank = numberField(groupBlk, 'minPlayerMRank') ?? 0; - const maxDiff = numberField(groupBlk, 'maxDiffBetweenTopUnitAndSessionRank') ?? 0; - const mRanksCount = numberField(groupBlk, 'mRanksCount') ?? 0; - const units: RandomSpawnCandidate[] = groupBlk.blocks - .filter((u) => u.name.length > 0) - .map((u) => { - const forceWeapon = stringField(u, 'forceWeapon'); - return forceWeapon ? { unitName: u.name, forceWeapon } : { unitName: u.name }; - }); - if (units.length > 0) { - groups.push({ - groupName: groupBlk.name, - minPlayerMRank, - maxDiffBetweenTopUnitAndSessionRank: maxDiff, - mRanksCount, - units, - }); - } - } - if (groups.length > 0) countries[countryBlk.name] = groups; + const groups = countryBlk.blocks.flatMap((groupBlk): RandomSpawnGroup[] => { + const units = groupBlk.blocks.map((unitBlk): RandomSpawnUnit => { + const forceWeapon = stringField(unitBlk, 'forceWeapon'); + return { + unitName: unitBlk.name, + addModifications: stringList(unitBlk, 'addModification'), + ...(forceWeapon ? { forceWeapon } : {}), + }; + }); + return units.length === 0 ? [] : [{ + name: groupBlk.name, + minPlayerMrank: numberField(groupBlk, 'minPlayerMRank') ?? 0, + maxDiffBetweenTopUnitAndSessionRank: numberField(groupBlk, 'maxDiffBetweenTopUnitAndSessionRank') ?? 0, + mranksCount: numberField(groupBlk, 'mRanksCount') ?? 0, + units, + }]; + }); + if (groups.length > 0) byCountry[countryBlk.name] = groups; } - events.push({ eventName: eventBlk.name, countries }); + byEvent[eventBlk.name] = byCountry; } - return events; -} - -function ipoint2Field(block: BlkBlock, name: string): readonly [number, number] | undefined { - const value = findParam(block, name)?.value; - if (value?.type === 'ipoint2') return value.value; - return undefined; + return byEvent; } diff --git a/packages/local-service/src/matching/battle-launch-notify.ts b/packages/local-service/src/matching/battle-launch-notify.ts index 835e67c..7eb0d0e 100644 --- a/packages/local-service/src/matching/battle-launch-notify.ts +++ b/packages/local-service/src/matching/battle-launch-notify.ts @@ -54,7 +54,6 @@ export function battleLaunchNotify(plan: BattleLaunchPlan, awards: BannerParams) missionName: plan.missionName, extraBattleSlots: plan.extraBattleSlots, randomUnits: plan.randomUnits, - randomUnitsEventName: plan.randomUnitsEventName ?? '', awards, }, }; diff --git a/packages/local-service/tuning/battle.jsonc b/packages/local-service/tuning/battle.jsonc index beefff7..97509da 100644 --- a/packages/local-service/tuning/battle.jsonc +++ b/packages/local-service/tuning/battle.jsonc @@ -32,6 +32,14 @@ // Simulator Battles Cold War / modern bloc cutoff mrank (18 = BR 7.0). "simColdWarMinMrank": 18, + // Strike UCAV extra slot (char.vromfs.bin config/wpcost.blk ucav_*_killstreak, one per country). + // The game files have no rule for when it is offered (online the battle server decides), so this + // is offline design: offered in these game modes when the session's top rank is at least the + // UCAV's own rank minus the allowance (0 = the UCAV's BR fits the session). Its spawn cost comes + // from the stock spawn score formula (warpoints.blk respawn_points). + "strikeUcavModes": ["tank_event_in_random_battles_historical"], + "strikeUcavSessionMrankAllowance": 0, + // AI bot respawn limits per battle in multi-slot versus modes. "tankBotRespawns": 3, "airBotRespawns": 2