Files
WT-Offline/packages/local-service/src/matching/battle-queue-requests.ts
T
N0VAN0M4LY 7f570c85c3 Price LocalMP battle rewards in the local service
The LocalMP host has no battle server, and the previous bridge filled the
gap by computing money in the client: the native ledger wrote invented
amounts into SessionStatsNet, the spawn patch derived reward rates from
warpoints.blk, and the settlement patch summed and rescaled the result.
Rewards came out as zero or several orders of magnitude too high.

Now the client reports facts and the local service prices them.

Native (wto_ws.dll):
- local_mp_ledger.c is removed together with its SessionStatsNet
  offsets and four signatures (43 -> 39).
- local_mp_awards.c raises the HUD script event wtoLocalMpExpEvent for
  every combat event of the local player (event code, victim expClass
  and name, player or AI victim, friendly, naval damage). The DataBlock
  helpers and the HUD event queue are resolved from call sites inside
  GameSaveData::addScoreMessage, which already has a signature.

GUI patches:
- record-local-battle-awards records events and lives in nestdb and
  raises the stock InBattleReward banner from launch-time parameters.
- report-local-battle-settlement sends only facts and rebuilds the
  debriefing from the settled table; failures show the stock error box.
- use-settled-debriefing-stats makes gatherDebriefingResult read that
  table instead of the empty stat_get_exp().
- pass-spawn-modifications-blk no longer computes economy factors.

Local service:
- battle-economy dataset reads every reward factor from wpcost.blk,
  warpoints.blk and rank.blk; tuning/battle-economy.jsonc holds the
  mission score per event with its source (official values where
  published, otherwise marked).
- battle-economy.ts is the single pricing function, shared by the
  banner parameters and the settlement; battle-rewards.ts adds battle
  time, timed award, win/defeat bonus, activity, premium account,
  talisman, skill bonus and free research points; the debriefing table
  has the stat_get_exp() layout and travels in EULT_SESSION_RESULT.
- Crews earn skill points from the battle's research points.
- A battle left before it ends counts as a defeat.

Verified: npm run typecheck, check-gui (35 patches), check-patches,
check-offsets, native build. Not yet run in game.
2026-11-28 04:42:27 +08:00

185 lines
8.3 KiB
TypeScript

/**
* Matching-server RPC handlers for hangar battle-rating display and battle queueing
*:
* - `wtmm_static.calc_ranks` (scripts/battlerating.nut:179)
* - `match.enqueue` (scripts/matching/servicenotifications/match.nut:75)
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
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 { 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 BattleQueueDependencies {
readonly gameModes: GameModes;
readonly profiles: PlayerProfiles;
readonly matchmaker: BattleMatchmaker;
readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
}
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
return [
['wtmm_static.calc_ranks', (request) => answerCalcRanks(request.params, deps.gameModes)],
['match.enqueue', (request, session) => handleEnqueue(request.params, session, deps)],
['match.leave_queue', (_request, session) => {
const userId = session.authenticatedUserId();
if (userId) deps.sessions.cancelPendingForUser(userId);
return {};
}],
['match.check_reconnect', () => ({})],
];
}
function answerCalcRanks(params: Readonly<Record<string, unknown>>, gameModes: GameModes): Record<string, unknown> {
const mode = typeof params.gameModeId === 'number' ? gameModes.byId(params.gameModeId) : undefined;
const players = Array.isArray(params.players) ? params.players : [];
const answer: Record<string, Array<{ mrank: number }>> = {};
for (const rawPlayer of players) {
if (!isRecord(rawPlayer) || typeof rawPlayer.name !== 'string' || !rawPlayer.name) continue;
const crafts = parsePlayerCrafts(rawPlayer.crafts);
const slot = typeof rawPlayer.slot === 'number' && Number.isInteger(rawPlayer.slot) ? rawPlayer.slot : -1;
const singleSlotCraft = mode?.declaration.multiSlot === false && slot >= 0 && slot < crafts.length
? crafts[slot]
: undefined;
const scopedCrafts = singleSlotCraft && singleSlotCraft.unitClass === mode?.declaration.requiredClass
? [singleSlotCraft]
: crafts;
const mrank = mode
? maxModeMrank(scopedCrafts, mode.declaration.requiredClass, mode.declaration.allowedClasses)
: scopedCrafts.reduce((max, craft) => Math.max(max, craft.mrank), 0);
answer[rawPlayer.name] = [{ mrank }];
}
return answer;
}
function handleEnqueue(
params: Readonly<Record<string, unknown>>,
session: { authenticatedUserId(): string | undefined; note(text: string): void },
deps: BattleQueueDependencies,
): Record<string, unknown> {
const userId = session.authenticatedUserId();
if (!userId) {
session.note('rejected: matching session is not authenticated');
return { error: 'AUTH_REQ_ERROR' };
}
const modes = resolveQueuedModes(params, deps.gameModes);
if (modes.length === 0) {
session.note('rejected: unknown game mode');
return { error: 'UNKNOWN_GAME_MODE' };
}
const playerEntry = extractPlayerEntry(params, userId);
if (!playerEntry) {
session.note('rejected: missing player country in match.enqueue');
return { error: 'BAD_PARAMS' };
}
const profile = deps.profiles.profileOf(userId);
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
const selectedSlotVehicle = playerEntry.selectedSlot !== undefined
? crewSlotVehicleOfCountry(profile, playerEntry.country, playerEntry.selectedSlot)
: undefined;
const outcome = deps.matchmaker.enqueue({
userId,
mode: modes[0]!,
modes,
country: playerEntry.country,
slotVehicles,
...(selectedSlotVehicle !== undefined ? { selectedSlotVehicle } : {}),
bannedMissions: playerEntry.bannedMissions,
dislikedMissions: playerEntry.dislikedMissions,
});
if (!outcome.ok) {
session.note(`rejected: ${outcome.error}`);
return { error: outcome.error };
}
const { launch } = outcome;
session.note(`mode=${launch.modeName}, mission=${launch.missionName}, mrank=${launch.minMrank}..${launch.maxMrank}`);
const playerVehicles = new Set([
...slotVehicles,
...launch.extraBattleSlots.map((slot) => slot.unitName),
...Object.values(launch.randomUnits).flat(),
]);
const awards = deps.economy.bannerParams(playerVehicles, economyDifficulty(modes[0]!.declaration.difficulty));
setImmediate(() => {
if (!deps.sessions.isPending(userId, launch.sessionId)) return;
deps.sessions.clearPending(userId, launch.sessionId);
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards));
});
return {};
}
function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] {
if (!Array.isArray(rawCrafts)) return [];
return rawCrafts.flatMap((craft): CraftRankEntry[] => {
if (!isRecord(craft) || typeof craft.mrank !== 'number' || !Number.isFinite(craft.mrank)) return [];
const fromExp = typeof craft.craftType === 'string' ? unitClassOfExpClass(craft.craftType) : undefined;
const fromCode = typeof craft.unitTypeCode === 'number' ? unitClassOfTypeCode(craft.unitTypeCode) : undefined;
return [{ unitClass: fromExp ?? fromCode, mrank: Math.max(0, Math.trunc(craft.mrank)) }];
});
}
/**
* Resolve every candidate `OfferedGameMode` allowed by `match.enqueue` (`scripts/queue/queue/queueevent.nut:191-207`):
* - `game_mode_id`: explicit single mode ID;
* - `game_modes_list`: filtered IDs after applying `onlyTags` / `excludedTags`;
* - `mode`: sent when `onlyTags` and `excludedTags` are both empty (classic mode plus every
* sub-mode of that `economicName` is enabled; server-side BR/craft guards still apply).
*/
function resolveQueuedModes(params: Readonly<Record<string, unknown>>, gameModes: GameModes): OfferedGameMode[] {
if (typeof params.game_mode_id === 'number') {
const found = gameModes.byId(params.game_mode_id);
return found ? [found] : [];
}
if (Array.isArray(params.game_modes_list)) {
return params.game_modes_list.flatMap((id) => (typeof id === 'number' ? gameModes.byId(id) ?? [] : []));
}
if (typeof params.mode === 'string' && params.mode) {
const primary = gameModes.byName(params.mode);
if (!primary) return [];
const family = gameModes.byEconomicName(primary.declaration.economicName);
return family.length > 0 ? [...family] : [primary];
}
return [];
}
function extractPlayerEntry(
params: Readonly<Record<string, unknown>>,
userId: string,
): {
readonly country: string;
readonly selectedSlot?: number;
readonly bannedMissions: Set<string>;
readonly dislikedMissions: Set<string>;
} | undefined {
const players = isRecord(params.players) ? params.players : undefined;
const entry = players && isRecord(players[userId]) ? players[userId] : undefined;
const rawCountry = typeof entry?.country === 'string' ? entry.country.trim() : '';
if (!rawCountry) return undefined;
const country = rawCountry.startsWith('country_') ? rawCountry : `country_${rawCountry}`;
const slots = isRecord(entry?.slots) ? entry.slots : undefined;
const rawSlot = slots?.[country] ?? slots?.[rawCountry];
const selectedSlot = typeof rawSlot === 'number' && Number.isInteger(rawSlot) && rawSlot >= 0 ? rawSlot : undefined;
return {
country,
...(selectedSlot !== undefined ? { selectedSlot } : {}),
bannedMissions: toStringSet(entry?.bannedMissions),
dislikedMissions: toStringSet(entry?.dislikedMissions),
};
}
function toStringSet(raw: unknown): Set<string> {
if (!Array.isArray(raw)) return new Set();
return new Set(raw.filter((item): item is string => typeof item === 'string' && item.length > 0));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}