fix(battle): show and debit confirmed backup vehicles

Use the signed i64 profile encoding identified in PR #13. Make attached backups selectable in LocalMP after the daily quota, and debit backups only after the engine confirms the selected slot entered play.

Record the stock daily allowance once per room and slot. Settle owned backups using the confirmed spawn facts and keep repeat settlement from charging the same battle again.

Verified server and launcher types, MSVC compilation, three client builds for patch and Quirrel checks, and a temporary 2.61.0.58 build. In-game acceptance is pending.

Co-authored-by: duduyagame <[email protected]>
This commit is contained in:
N0VAN0M4LYandduduyagame committed 2026-12-04 06:24:34 +08:00
1 parent 6d0abf9caf
commit 3282320fb7
34 files changed
+402 -46

No files matched your search

+3 -1
View File
@@ -10,7 +10,7 @@ import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-ru
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { MISSION_DIFFICULTY, SINGLE_SPAWN, modeMaxRespawns } from '../game-modes/mode-definition.ts';
import { MISSION_DIFFICULTY, SINGLE_SPAWN, UNLIMITED_RESPAWNS, modeMaxRespawns } from '../game-modes/mode-definition.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
@@ -73,6 +73,7 @@ export interface BattleLaunchPlan {
readonly maxPlayers: number;
readonly maxBots: number;
readonly maxRespawns?: number;
readonly allowSpares: boolean;
readonly tankBotRespawns: number;
readonly airBotRespawns: number;
readonly useTankBots: boolean;
@@ -281,6 +282,7 @@ export class BattleMatchmaker {
maxMrank,
maxPlayers,
maxBots,
allowSpares: declaration.multiSlot !== false && maxRespawns !== SINGLE_SPAWN && maxRespawns !== UNLIMITED_RESPAWNS,
...(maxRespawns === undefined ? {} : { maxRespawns }),
tankBotRespawns: this.#tuning.tankBotRespawns,
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
@@ -72,7 +72,7 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
// MissionSettings defaults isLimitedFuel to false, which disables fuel consumption and HUD timers.
setParam(settings, 'isLimitedFuel', flag(true));
setParam(settings, 'allowSpare', flag(!plan.selectedSlot && plan.maxRespawns !== UNLIMITED_RESPAWNS));
setParam(settings, 'allowSpare', flag(plan.allowSpares));
if (plan.maxRespawns !== undefined) setParam(settings, 'maxRespawns', integer(plan.maxRespawns));
if (plan.selectedSlot) {
setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true));
+9 -12
View File
@@ -17,10 +17,11 @@
* the final scoreboard
* strikes{ s{ time:r } ... } explosions of the local player's
* nuclear bombs (native local_mp_nuke.c)
* spares{ <unit>:i ... } backup vehicles used
* spares{ spawn{ slot:i unit:t backup:t } ... } confirmed backup spawns
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import type { CombatEventFact } from './battle-economy.ts';
import type { BackupSpawn } from './battle-spares.ts';
export type BattleOutcomeKind = 'win' | 'lose' | 'running';
@@ -83,7 +84,7 @@ export interface BattleReport {
readonly players: readonly ScoreboardPlayer[];
/** Mission times at which the local player's nuclear bombs exploded. */
readonly nuclearStrikes: readonly number[];
readonly usedSpares: Readonly<Record<string, number>>;
readonly spareSpawns: readonly BackupSpawn[];
}
/** Undefined when the report is malformed; lives and events that make no sense are dropped. */
@@ -139,19 +140,15 @@ export function parseBattleReport(payload: BlkBlock): BattleReport | undefined {
...Object.fromEntries(SCOREBOARD_FIELDS.map((field) => [field, Math.max(0, intOf(block, field))])) as Record<(typeof SCOREBOARD_FIELDS)[number], number>,
})),
nuclearStrikes: (findBlock(payload, 'strikes')?.blocks ?? []).map((block) => realOf(block, 'time')).sort((a, b) => a - b),
usedSpares: parseSpareMap(findBlock(payload, 'spares')),
spareSpawns: (findBlock(payload, 'spares')?.blocks ?? []).flatMap((block): BackupSpawn[] => {
const slot = intOf(block, 'slot', -1);
const unit = strOf(block, 'unit');
const backup = strOf(block, 'backup');
return slot >= 0 && unit && backup ? [{ slot, unit, backup }] : [];
}),
};
}
function parseSpareMap(sparesBlk: BlkBlock | undefined): Record<string, number> {
const out: Record<string, number> = {};
for (const param of sparesBlk?.params ?? []) {
const count = param.value.type === 'int' ? param.value.value : 0;
if (param.name && count > 0) out[param.name] = count;
}
return out;
}
function strOf(block: BlkBlock, name: string): string | undefined {
const value = block.params.find((p) => p.name === name)?.value;
return value?.type === 'string' && value.value !== '' ? value.value : undefined;
+7 -1
View File
@@ -9,7 +9,8 @@
* container.aircraftsRepaired{ aname<i>:t cost<i>:i } and container.wpExpensesCompensation:i
* (userlogviewdata.nut "damaged vehicles", "automatic repair", "expenses compensation").
*/
import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { emptyBlock, findBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { intField, int64Field } from '../profile/blk-fields.ts';
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import type { DebriefingRow } from './battle-economy.ts';
@@ -18,6 +19,11 @@ import type { ResearchPointsUnit } from './battle-rp-investment.ts';
import type { AutoRepair, VehicleDamage } from './battle-repair.ts';
import type { BattleSession } from './battle-session-store.ts';
export function hasBattleResultLog(profile: BlkBlock, roomId: bigint): boolean {
return findBlock(profile, 'userlogs')?.blocks.some((log) =>
intField(log, 'type') === EULT_SESSION_RESULT && int64Field(log, 'roomId') === roomId) ?? false;
}
export interface EarnedRpItem {
readonly unit: string;
readonly modification?: string;
@@ -24,6 +24,8 @@ export interface BattleSession {
readonly missionLocName?: string;
readonly country: string;
readonly startedAtSec: number;
/** Owned lineup slots that may use a backup in this session. Filled when launch is sent. */
spareSlots?: ReadonlyMap<number, string>;
settled: boolean;
}
+3 -1
View File
@@ -35,6 +35,7 @@ import { autoRepairVehicles, damageBattleVehicles, expensesCompensation } from '
import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts';
import { computeBattleRewards, type VehicleRewards } from './battle-rewards.ts';
import { investBattleRp, type VehicleRp } from './battle-rp-investment.ts';
import { consumeBattleSpares } from './battle-spares.ts';
import { appendStreakLogs } from './battle-streak-log.ts';
import type { BattleStreaks } from './battle-streaks.ts';
import type { BattleSession } from './battle-session-store.ts';
@@ -121,13 +122,14 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
if (compensation > 0) addSilverLions(profile, compensation);
const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks, compensation);
const usedSpares = consumeBattleSpares(profile, session, report.spareSpawns, deps.items, deps.research.techTree);
appendStreakLogs(profile, session, streaks);
appendBattleResultLog(profile, session, {
country: session.country.startsWith('country_') ? session.country : `country_${session.country}`,
rewards,
unlocksWp: unlocks.wp,
weaponRefillSl,
usedSpares: report.usedSpares,
usedSpares,
rpItems: mergeEarnedRpItems(research.rpItems),
researchUnits: research.units,
affectedBoosters: boosters.applied.map((booster) => booster.id),
+51
View File
@@ -0,0 +1,51 @@
import type { BlkBlock } from '@wto/blk';
import type { ItemCatalogue } from '../items/item-catalogue.ts';
import { applyUniversalSpares } from '../items/universal-spares.ts';
import { dailySparesLeft, recordDailySpare, usedDailySpare } from '../profile/profile-daily-spares.ts';
import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts';
import type { TechTree } from '../research/tech-tree.ts';
import type { BattleSession } from './battle-session-store.ts';
/** LocalMP uses a source token for an attached backup and the stock UID for an inventory item. */
const VEHICLE_BACKUP = 'vehicle';
export const DAILY_BACKUP = 'daily_free_spare';
export interface BackupSpawn {
readonly slot: number;
readonly unit: string;
readonly backup: string;
}
function receiptKey(session: BattleSession, slot: number): string {
return `${session.sessionId}_${slot}`;
}
export function recordDailyBackupSpawn(profile: BlkBlock, session: BattleSession, spawn: BackupSpawn): boolean {
return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === spawn.unit
&& recordDailySpare(profile, session.startedAtSec, receiptKey(session, spawn.slot));
}
/** Debit confirmed backup spawns from the lineup that the server sent at launch. */
export function consumeBattleSpares(
profile: BlkBlock, session: BattleSession, spawns: readonly BackupSpawn[], items: ItemCatalogue, techTree: TechTree,
): Readonly<Record<string, number>> {
const seenSlots = new Set<number>();
const consumed = new Map<string, number>();
for (const spawn of spawns) {
const { slot, unit, backup } = spawn;
if (session.spareSlots?.get(slot) !== unit || seenSlots.has(slot)) continue;
seenSlots.add(slot);
if (backup === DAILY_BACKUP) {
recordDailyBackupSpawn(profile, session, spawn);
continue;
}
if (dailySparesLeft(profile, session.startedAtSec) > 0
|| usedDailySpare(profile, session.startedAtSec, receiptKey(session, slot))) continue;
if (backup !== VEHICLE_BACKUP && !applyUniversalSpares(profile, items, techTree, backup, unit, 1).ok) continue;
const owned = spareCount(profile, unit);
if (owned < 1) continue;
setSpareCount(profile, unit, owned - 1);
consumed.set(unit, (consumed.get(unit) ?? 0) + 1);
}
return Object.fromEntries(consumed);
}
@@ -6,6 +6,7 @@
import type { BattleSettlementContext } from '@wto/mods';
import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts';
import { hasBattleResultLog } from '../../battle/battle-result-log.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
import type { BattleEconomy } from '../../battle/battle-economy.ts';
@@ -62,15 +63,19 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
if (session.settled) {
return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) };
}
const updated = ctx.profiles.update(account.userId, (profile) => {
const updated = ctx.profiles.updateWhen(account.userId, (profile) => {
// The result log and expenses are written together. A retry can arrive after the profile
// was saved but before the session was marked settled.
if (hasBattleResultLog(profile, session.roomId)) return false;
settleBattle(profile, report, session, settlementDeps);
battle.onAfterSettle?.({
userId: account.userId,
roomId: session.sessionId,
summary: { profile, report, session },
});
return true;
});
battle.sessions.markSettled(session.sessionId);
return { kind: 'data', blk: clientProfile(updated, account) };
return { kind: 'data', blk: clientProfile(updated ?? ctx.profiles.profileOf(account.userId), account) };
});
}
@@ -32,10 +32,16 @@ export interface BattleLaunchNotify extends Record<string, unknown> {
readonly battle: Readonly<Record<string, unknown>>;
}
export interface BattleBackupAllowance {
readonly daily: number;
readonly vehicles: Readonly<Record<string, number>>;
}
export function battleLaunchNotify(
plan: BattleLaunchPlan,
awards: BannerParams,
scores: Readonly<Record<string, number>>,
backups?: BattleBackupAllowance,
): BattleLaunchNotify {
return {
from: 'wto_battle',
@@ -64,6 +70,7 @@ export function battleLaunchNotify(
...(plan.selectedSlot ? { selectedSlot: plan.selectedSlot } : {}),
extraBattleSlots: plan.extraBattleSlots,
...(plan.spawnScore ? { spawnScore: plan.spawnScore } : {}),
...(backups ? { backups } : {}),
awards,
},
};
@@ -5,17 +5,21 @@
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
import type { BlkBlock } from '@wto/blk';
import type { BattleMatchmakeContext } from '@wto/mods';
import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts';
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.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 { BattleSession, BattleSessionStore } from '../battle/battle-session-store.ts';
import { DAILY_BACKUP, recordDailyBackupSpawn } from '../battle/battle-spares.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
import { dailySparesLeft } from '../profile/profile-daily-spares.ts';
import { vehicleMrankDelta } from '../profile/profile-hangar.ts';
import { spareCount } from '../profile/profile-vehicle-state.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
import { battleLaunchNotify, type BattleBackupAllowance, type BattleLaunchNotify } from './battle-launch-notify.ts';
import type { MatchingRequestHandler } from './matching-requests.ts';
export interface BattleQueueDependencies {
@@ -38,6 +42,18 @@ export function battleQueueRequests(deps: BattleQueueDependencies): Array<[strin
return {};
}],
['match.check_reconnect', () => ({})],
['wto_battle.daily_spare', ({ params }, connection) => {
const userId = connection.authenticatedUserId();
if (!userId) return { error: 'AUTH_REQ_ERROR' };
const { sessionId, slot, unit } = params;
if (typeof sessionId !== 'string' || typeof slot !== 'number' || typeof unit !== 'string') {
return { error: 'BAD_PARAMS' };
}
const battle = deps.sessions.findForUser(sessionId, userId);
if (!battle || battle.settled || battle.spareSlots?.get(slot) !== unit) return { error: 'BAD_PARAMS' };
deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit, backup: DAILY_BACKUP }));
return {};
}],
];
}
@@ -119,11 +135,25 @@ function handleEnqueue(
const battle = deps.sessions.findForUser(launch.sessionId, userId);
if (!battle) return;
const awards = deps.economy.bannerParams(playerVehicles, economyDifficulty(battle.difficulty), battle.modeName);
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards, deps.economy.missionScores(battle.modeName)));
const backups = launch.allowSpares ? configureBattleBackups(battle, profile) : undefined;
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards, deps.economy.missionScores(battle.modeName), backups));
});
return {};
}
function configureBattleBackups(battle: BattleSession, profile: BlkBlock): BattleBackupAllowance {
const slots = new Map<number, string>();
for (let slot = 0; slot < MAX_BATTLE_CREW_SLOTS; slot++) {
const unit = crewSlotVehicleOfCountry(profile, battle.country, slot);
if (unit) slots.set(slot, unit);
}
battle.spareSlots = slots;
return {
daily: dailySparesLeft(profile, battle.startedAtSec),
vehicles: Object.fromEntries([...slots.values()].map((unit) => [unit, spareCount(profile, unit)])),
};
}
function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] {
if (!Array.isArray(rawCrafts)) return [];
return rawCrafts.flatMap((craft): CraftRankEntry[] => {
+5 -2
View File
@@ -11,15 +11,18 @@
import { setParam, type BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts';
import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts';
import { clearStoreCart } from './profile-store-cart.ts';
import { clientHangarSpares } from './profile-vehicle-state.ts';
import { serverTimeNow } from './server-time.ts';
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
// Shallow-copy only the top-level lists; child blocks are never mutated here.
// Clone the hangar entries whose spare count has a different wire representation.
const profile: BlkBlock = {
name: saved.name,
params: [...saved.params],
blocks: [...saved.blocks],
blocks: saved.blocks.filter((block) => block.name !== DAILY_SPARES_BLOCK)
.map((block) => block.name === 'hangar' ? clientHangarSpares(block) : block),
};
clearStoreCart(profile);
const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON;
@@ -0,0 +1,33 @@
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
export const DAILY_SPARES_BLOCK = 'wtoDailySpares';
// Stock quota from the Spearhead release notes and aces.exe 2.61.0.58 at 0x967a8d.
const FREE_SPARES_PER_DAY = 5;
const DAY_SECONDS = 24 * 60 * 60;
function utcDay(seconds: number): string {
return String(Math.floor(seconds / DAY_SECONDS));
}
function dayOf(profile: BlkBlock, startedAtSec: number): BlkBlock | undefined {
const ledger = findBlock(profile, DAILY_SPARES_BLOCK);
return ledger && findBlock(ledger, utcDay(startedAtSec));
}
export function dailySparesLeft(profile: BlkBlock, startedAtSec: number): number {
return Math.max(0, FREE_SPARES_PER_DAY - (dayOf(profile, startedAtSec)?.params.length ?? 0));
}
export function usedDailySpare(profile: BlkBlock, startedAtSec: number, key: string): boolean {
const day = dayOf(profile, startedAtSec);
return day !== undefined && findParam(day, key) !== undefined;
}
/** One receipt per room and crew slot, shared by the live and settlement writes. */
export function recordDailySpare(profile: BlkBlock, startedAtSec: number, key: string): boolean {
if (usedDailySpare(profile, startedAtSec, key) || dailySparesLeft(profile, startedAtSec) === 0) return false;
const day = ensureBlock(ensureBlock(profile, DAILY_SPARES_BLOCK), utcDay(startedAtSec));
setParam(day, key, { type: 'bool', value: true });
return true;
}
@@ -5,7 +5,7 @@
* investMode:t the modification being researched, empty = none (AircraftInfo+0x100)
* investModePrev:t the modification whose research just finished (+0x108)
* tierNumber:i the highest open modification tier (script is_tier_available)
* spareAircraftsCount:i spares the player has for this vehicle
* spareAircraftsCount:i owned spares in the saved profile, encoded as a negative i64 on the wire
* excessExp:i64 banked modification research points (+0x70)
* freeRepairs:i64 free repairs used (0x941cef; shop_get_free_repairs_used at 0x17a4b80)
*/
@@ -55,6 +55,19 @@ export function setSpareCount(profile: BlkBlock, vehicle: string, count: number)
if (entry) setParam(entry, SPARES, { type: 'int', value: count });
}
/** SpareAircraftStat reads i64 and clears positive values. The getter negates the stat
* (aces.exe 2.61.0.58 0x9447bb, 0x94f7ab, 0x17abe70). */
export function clientHangarSpares(hangar: BlkBlock): BlkBlock {
const blocks = hangar.blocks.map((vehicle) => {
const count = findParam(vehicle, SPARES)?.value;
if (count?.type !== 'int') return vehicle;
const clientVehicle = { ...vehicle, params: [...vehicle.params] };
setParam(clientVehicle, SPARES, { type: 'int64', value: -BigInt(count.value) });
return clientVehicle;
});
return { ...hangar, blocks };
}
/** Uses one free repair on an owned vehicle if it still has an allowance. */
export function consumeFreeRepair(profile: BlkBlock, vehicle: string, allowance: number): boolean {
const entry = vehicleEntry(profile, vehicle);