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.
This commit is contained in:
1 parent
b1392c0512
commit
7f570c85c3
39 files changed
+1488
-1128
No files matched your search
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* The debriefing table of a settled battle, in the shape of `stat_get_exp()` (aces.exe 0x1053b70,
|
||||
* which serializes the battle's SessionStatsNet; online the battle server fills it). The client's
|
||||
* settlement patch puts it in `debriefingResult.exp` in place of the empty local statistics.
|
||||
*
|
||||
* Root and every `aircrafts.<vehicle>`:
|
||||
* num<Row>:i wp<Row>:i exp<Row>:i tbl<Row>{ noBonusWp noBonusExp premAccWp premAccExp premModExp }
|
||||
* tblTotal{ ... } wpTotal:i expTotal:i sessionTime:r battleTime:r
|
||||
* Root only: result:i activity:r expFree:i expSkillBonusTotal:i expSkillBonusLevel:i
|
||||
* investUnitName<Type>:t expInvestUnit<Type>:i expInvestUnitTotal<Type>:i
|
||||
* Vehicle only: expSkillBonus:i investModuleName:t expInvestModule:i expInvestModuleTotal:i
|
||||
* expInvestUnit:i expInvestUnitTotal:i
|
||||
* (key names from the strings of 0x1053b70, 0xf86c10 and 0xf89f90).
|
||||
*/
|
||||
import { emptyBlock, setParam, type BlkBlock } from '@wto/blk';
|
||||
import type { BattleRewards, RewardRow, RowRewards } from './battle-rewards.ts';
|
||||
|
||||
/** STATS_RESULT_* script constants, registered by aces.exe 0x17db810 (SUCCESS 1, FAIL 2). */
|
||||
const STATS_RESULT_SUCCESS = 1;
|
||||
const STATS_RESULT_FAIL = 2;
|
||||
|
||||
export interface ModuleInvestment {
|
||||
readonly vehicle: string;
|
||||
readonly module: string;
|
||||
readonly rp: number;
|
||||
}
|
||||
|
||||
export interface BranchInvestment {
|
||||
/** Unit type suffix of the research branch: Aircraft, Tank, Ship, Boat or Helicopter. */
|
||||
readonly type: string;
|
||||
readonly unit: string;
|
||||
readonly rp: number;
|
||||
}
|
||||
|
||||
export interface DebriefingInvestments {
|
||||
readonly modules: readonly ModuleInvestment[];
|
||||
readonly branches: readonly BranchInvestment[];
|
||||
}
|
||||
|
||||
export function debriefingTable(name: string, rewards: BattleRewards, investments: DebriefingInvestments): BlkBlock {
|
||||
const root = emptyBlock(name);
|
||||
const rootRows = new Map<RewardRow, RowRewards>();
|
||||
for (const vehicle of rewards.vehicles) {
|
||||
for (const [row, amounts] of vehicle.rows) {
|
||||
const sum = rootRows.get(row) ?? { count: 0, noBonusWp: 0, noBonusExp: 0, premAccWp: 0, premAccExp: 0, premModExp: 0 };
|
||||
for (const key of Object.keys(sum) as (keyof RowRewards)[]) sum[key] += amounts[key];
|
||||
rootRows.set(row, sum);
|
||||
}
|
||||
}
|
||||
setParam(root, 'result', { type: 'int', value: rewards.win ? STATS_RESULT_SUCCESS : STATS_RESULT_FAIL });
|
||||
setParam(root, 'activity', { type: 'real', value: rewards.activity });
|
||||
setParam(root, 'sessionTime', { type: 'real', value: rewards.sessionTime });
|
||||
setParam(root, 'battleTime', { type: 'real', value: rewards.battleTime });
|
||||
writeRows(root, rootRows, rewards.wpTotal, rewards.expTotal);
|
||||
setParam(root, 'expFree', { type: 'int', value: rewards.expFree });
|
||||
setParam(root, 'expSkillBonusTotal', { type: 'int', value: rewards.vehicles.reduce((sum, v) => sum + v.skillBonusExp, 0) });
|
||||
setParam(root, 'expSkillBonusLevel', { type: 'int', value: rewards.skillBonusLevel });
|
||||
for (const branch of investments.branches) {
|
||||
setParam(root, `investUnitName${branch.type}`, { type: 'string', value: branch.unit });
|
||||
setParam(root, `expInvestUnit${branch.type}`, { type: 'int', value: branch.rp });
|
||||
setParam(root, `expInvestUnitTotal${branch.type}`, { type: 'int', value: branch.rp });
|
||||
}
|
||||
|
||||
const aircrafts = emptyBlock('aircrafts');
|
||||
for (const vehicle of rewards.vehicles) {
|
||||
const block = emptyBlock(vehicle.vehicle);
|
||||
setParam(block, 'sessionTime', { type: 'real', value: vehicle.sessionTime });
|
||||
setParam(block, 'battleTime', { type: 'real', value: vehicle.sessionTime });
|
||||
writeRows(block, vehicle.rows, vehicle.wpTotal, vehicle.expTotal);
|
||||
setParam(block, 'expSkillBonus', { type: 'int', value: vehicle.skillBonusExp });
|
||||
setParam(block, 'expSkillBonusTotal', { type: 'int', value: vehicle.skillBonusExp });
|
||||
const module = investments.modules.find((m) => m.vehicle === vehicle.vehicle);
|
||||
if (module) setParam(block, 'investModuleName', { type: 'string', value: module.module });
|
||||
setParam(block, 'expInvestModule', { type: 'int', value: module?.rp ?? 0 });
|
||||
setParam(block, 'expInvestModuleTotal', { type: 'int', value: module?.rp ?? 0 });
|
||||
setParam(block, 'expInvestUnit', { type: 'int', value: vehicle.expTotal });
|
||||
setParam(block, 'expInvestUnitTotal', { type: 'int', value: vehicle.expTotal });
|
||||
aircrafts.blocks.push(block);
|
||||
}
|
||||
root.blocks.push(aircrafts);
|
||||
return root;
|
||||
}
|
||||
|
||||
function writeRows(block: BlkBlock, rows: ReadonlyMap<RewardRow, RowRewards>, wpTotal: number, expTotal: number): void {
|
||||
const total: RowRewards = { count: 0, noBonusWp: 0, noBonusExp: 0, premAccWp: 0, premAccExp: 0, premModExp: 0 };
|
||||
for (const [row, amounts] of rows) {
|
||||
setParam(block, `num${row}`, { type: 'int', value: amounts.count });
|
||||
setParam(block, `wp${row}`, { type: 'int', value: amounts.noBonusWp + amounts.premAccWp });
|
||||
setParam(block, `exp${row}`, { type: 'int', value: amounts.noBonusExp + amounts.premAccExp + amounts.premModExp });
|
||||
block.blocks.push(rowTable(`tbl${row}`, amounts));
|
||||
for (const key of Object.keys(total) as (keyof RowRewards)[]) total[key] += amounts[key];
|
||||
}
|
||||
setParam(block, 'wpTotal', { type: 'int', value: wpTotal });
|
||||
setParam(block, 'expTotal', { type: 'int', value: expTotal });
|
||||
block.blocks.push(rowTable('tblTotal', total));
|
||||
}
|
||||
|
||||
function rowTable(name: string, amounts: RowRewards): BlkBlock {
|
||||
const table = emptyBlock(name);
|
||||
setParam(table, 'noBonusWp', { type: 'int', value: amounts.noBonusWp });
|
||||
setParam(table, 'noBonusExp', { type: 'int', value: amounts.noBonusExp });
|
||||
setParam(table, 'premAccWp', { type: 'int', value: amounts.premAccWp });
|
||||
setParam(table, 'premAccExp', { type: 'int', value: amounts.premAccExp });
|
||||
setParam(table, 'premModExp', { type: 'int', value: amounts.premModExp });
|
||||
return table;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Typed reader for `tuning/battle-economy.jsonc`: the mission score of each combat event and the
|
||||
* offline choices the game files do not carry (see the file for the source of every value).
|
||||
*/
|
||||
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
|
||||
|
||||
export const VICTIM_GROUPS = ['ground', 'air', 'naval', 'human'] as const;
|
||||
export type VictimGroup = (typeof VICTIM_GROUPS)[number];
|
||||
|
||||
export const SCORED_EVENTS = ['kill', 'assist', 'severeDamage', 'criticalHit', 'hit'] as const;
|
||||
export type ScoredEvent = (typeof SCORED_EVENTS)[number];
|
||||
|
||||
export interface BattleEconomyTuning {
|
||||
/** Destroyed-unit expClass -> victim group; classes not listed are "ground". */
|
||||
readonly victimGroups: ReadonlyMap<string, VictimGroup>;
|
||||
readonly eventScores: Readonly<Record<VictimGroup, Readonly<Record<ScoredEvent, number>>>>;
|
||||
readonly captureZoneScore: Readonly<Record<VictimGroup, number>>;
|
||||
readonly navalDamageScorePerPoint: number;
|
||||
readonly referenceScore: Readonly<Record<VictimGroup, number>>;
|
||||
readonly friendlyKillPenaltyMul: number;
|
||||
}
|
||||
|
||||
export function readBattleEconomyTuning(reader: TuningReader): BattleEconomyTuning {
|
||||
const groups = reader.object('victimGroups');
|
||||
const victimGroups = new Map<string, VictimGroup>();
|
||||
for (const group of groups.keys()) {
|
||||
if (!isVictimGroup(group) || group === 'ground') {
|
||||
throw new TuningError(`tuning file battle-economy.jsonc: victimGroups.${group} is not one of air, naval, human`);
|
||||
}
|
||||
for (const expClass of groups.stringList(group)) victimGroups.set(expClass, group);
|
||||
}
|
||||
const scores = reader.object('eventScores');
|
||||
const perGroup = (key: string, min: number): Record<VictimGroup, number> => {
|
||||
const table = reader.object(key);
|
||||
return Object.fromEntries(VICTIM_GROUPS.map((group) => [group, table.number(group, { min, max: 100000 })])) as Record<VictimGroup, number>;
|
||||
};
|
||||
return {
|
||||
victimGroups,
|
||||
eventScores: Object.fromEntries(VICTIM_GROUPS.map((group) => {
|
||||
const table = scores.object(group);
|
||||
return [group, Object.fromEntries(SCORED_EVENTS.map((event) => [event, table.number(event, { min: 0, max: 100000 })]))];
|
||||
})) as Record<VictimGroup, Record<ScoredEvent, number>>,
|
||||
captureZoneScore: perGroup('captureZoneScore', 0),
|
||||
navalDamageScorePerPoint: reader.number('navalDamageScorePerPoint', { min: 0, max: 100 }),
|
||||
referenceScore: perGroup('referenceScore', 1),
|
||||
friendlyKillPenaltyMul: reader.number('friendlyKillPenaltyMul', { min: 0, max: 100 }),
|
||||
};
|
||||
}
|
||||
|
||||
function isVictimGroup(value: string): value is VictimGroup {
|
||||
return (VICTIM_GROUPS as readonly string[]).includes(value);
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Prices the local player's combat events: the one place battle rewards are computed.
|
||||
*
|
||||
* The in-battle banner and the settlement use the same two steps, so what the banner shows is
|
||||
* what the settlement pays:
|
||||
* 1. baseReward(vehicle, event, victim group): Silver Lions and Research Points of the event
|
||||
* before the destroyed unit's class factor (sent to the client at launch, `bannerParams`);
|
||||
* 2. x class factor of the victim's expClass (warpoints.blk / rank.blk units{}), x aiKillK when
|
||||
* the victim is not a player, x damage points for naval damage.
|
||||
* The formula and the source of every factor are in tuning/battle-economy.jsonc.
|
||||
*/
|
||||
import type { BattleEconomyData, EconomyDifficulty, VehicleEconomy } from '../game-data/datasets/battle-economy.ts';
|
||||
import type { ModeDifficulty } from '../game-modes/catalogue/game-mode-declaration.ts';
|
||||
import type { BattleEconomyTuning, ScoredEvent, VictimGroup } from './battle-economy-tuning.ts';
|
||||
|
||||
/** EXP_EVENT_* codes the LocalMP host reports (gui.vromfs.bin globalScripts/expEventConsts.nut). */
|
||||
export const ExpEvent = {
|
||||
CAPTURE_ZONE: 2,
|
||||
KILL: 5,
|
||||
KILL_GROUND: 6,
|
||||
ASSIST: 9,
|
||||
CRITICAL_HIT: 10,
|
||||
HIT: 13,
|
||||
UNIT_DAMAGE: 24,
|
||||
SEVERE_DAMAGE: 35,
|
||||
KILL_HUMAN: 39,
|
||||
} as const;
|
||||
|
||||
/** Debriefing rows (`stat_get_exp()` `num<Row>`/`wp<Row>`/`exp<Row>`, aces.exe 0x1053b70) an event lands in. */
|
||||
export type DebriefingRow =
|
||||
| 'AirKills' | 'GroundKills' | 'NavalKills' | 'HumanKills' | 'FriendlyKills'
|
||||
| 'Assist' | 'AirSevereDamage' | 'ShipSevereDamage' | 'Critical' | 'Hit'
|
||||
| 'Captures' | 'AwardDamage';
|
||||
|
||||
/** What the client reports for one combat event (gui-patches/battle/record-local-battle-awards). */
|
||||
export interface CombatEventFact {
|
||||
readonly code: number;
|
||||
readonly expClass: string;
|
||||
readonly victimIsPlayer: boolean;
|
||||
readonly friendly: boolean;
|
||||
readonly damage: number;
|
||||
}
|
||||
|
||||
export interface PricedEvent {
|
||||
readonly row: DebriefingRow;
|
||||
/** How much the row's counter grows: 1, or the damage points for AwardDamage. */
|
||||
readonly count: number;
|
||||
readonly wp: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
export interface RewardPair {
|
||||
readonly wp: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch-time parameters of the in-battle banner (`battle.awards` of the launch message):
|
||||
* vehicles.<name>["<code>:<group>"] = [wp, exp] before the class factor; capture uses the group
|
||||
* "own". The client multiplies by slClass/rpClass of the victim's expClass, by aiKillK for a
|
||||
* victim that is not a player, by the damage points for naval damage, and shows a friendly kill as
|
||||
* -wp x friendlyKillPenaltyMul.
|
||||
*/
|
||||
export interface BannerParams {
|
||||
readonly vehicles: Readonly<Record<string, Readonly<Record<string, readonly [number, number]>>>>;
|
||||
readonly groups: Readonly<Record<string, VictimGroup>>;
|
||||
readonly slClass: Readonly<Record<string, number>>;
|
||||
readonly rpClass: Readonly<Record<string, number>>;
|
||||
readonly aiKillK: number;
|
||||
readonly friendlyKillPenaltyMul: number;
|
||||
}
|
||||
|
||||
export interface RewardMultipliers {
|
||||
readonly silverLions: number;
|
||||
readonly researchPoints: number;
|
||||
}
|
||||
|
||||
export function economyDifficulty(difficulty: ModeDifficulty): EconomyDifficulty {
|
||||
return difficulty === 'arcade' ? 'arcade' : difficulty === 'realistic' ? 'historical' : 'simulation';
|
||||
}
|
||||
|
||||
export class BattleEconomy {
|
||||
readonly data: BattleEconomyData;
|
||||
readonly #tuning: BattleEconomyTuning;
|
||||
readonly #multipliers: RewardMultipliers;
|
||||
readonly #premiumVehicles: ReadonlySet<string>;
|
||||
|
||||
/** `premiumVehicles`: vehicles the client counts as special (isUnitSpecial: costGold > 0 or premPackAir). */
|
||||
constructor(
|
||||
data: BattleEconomyData,
|
||||
tuning: BattleEconomyTuning,
|
||||
multipliers: RewardMultipliers,
|
||||
premiumVehicles: ReadonlySet<string>,
|
||||
) {
|
||||
this.data = data;
|
||||
this.#tuning = tuning;
|
||||
this.#multipliers = multipliers;
|
||||
this.#premiumVehicles = premiumVehicles;
|
||||
}
|
||||
|
||||
/** Premium vehicles earn the talisman research bonus without a talisman (scripts/airinfo.nut hasTalisman). */
|
||||
isPremiumVehicle(name: string): boolean {
|
||||
return this.#premiumVehicles.has(name);
|
||||
}
|
||||
|
||||
get multipliers(): RewardMultipliers {
|
||||
return this.#multipliers;
|
||||
}
|
||||
|
||||
vehicle(name: string): VehicleEconomy | undefined {
|
||||
return this.data.vehicles[name];
|
||||
}
|
||||
|
||||
victimGroup(expClass: string): VictimGroup {
|
||||
return this.#tuning.victimGroups.get(expClass) ?? 'ground';
|
||||
}
|
||||
|
||||
/** Reward of one event before the victim's class factor; undefined for an event that pays nothing. */
|
||||
baseReward(vehicle: string, difficulty: EconomyDifficulty, code: number, group: VictimGroup): RewardPair | undefined {
|
||||
const economy = this.vehicle(vehicle);
|
||||
if (!economy) return undefined;
|
||||
const score = this.#score(code, group);
|
||||
if (score === undefined) return undefined;
|
||||
const reference = this.#tuning.referenceScore[code === ExpEvent.UNIT_DAMAGE ? 'naval' : group];
|
||||
return {
|
||||
wp: this.data.killSilverLions * economy.rewardMul[difficulty] * (score / reference) * this.#multipliers.silverLions,
|
||||
exp: score * economy.expMul * this.#multipliers.researchPoints,
|
||||
};
|
||||
}
|
||||
|
||||
price(vehicle: string, difficulty: EconomyDifficulty, fact: CombatEventFact): PricedEvent | undefined {
|
||||
const economy = this.vehicle(vehicle);
|
||||
if (!economy) return undefined;
|
||||
const isCapture = fact.code === ExpEvent.CAPTURE_ZONE;
|
||||
const group = isCapture ? this.victimGroup(economy.unitClass) : this.victimGroup(fact.expClass);
|
||||
const row = debriefingRow(fact, group);
|
||||
const base = this.baseReward(vehicle, difficulty, fact.code, group);
|
||||
if (!row || !base) return undefined;
|
||||
const count = fact.code === ExpEvent.UNIT_DAMAGE ? Math.max(0, Math.trunc(fact.damage)) : 1;
|
||||
const ai = isCapture || fact.victimIsPlayer ? 1 : this.data.aiKillK;
|
||||
const slClass = isCapture ? 1 : this.data.silverLionsClassFactors[fact.expClass] ?? 1;
|
||||
const rpClass = isCapture ? 1 : this.data.researchClassFactors[fact.expClass] ?? 1;
|
||||
if (fact.friendly) {
|
||||
return { row: 'FriendlyKills', count: 1, wp: -Math.round(base.wp * slClass * ai * this.#tuning.friendlyKillPenaltyMul), exp: 0 };
|
||||
}
|
||||
return {
|
||||
row,
|
||||
count,
|
||||
wp: Math.round(base.wp * slClass * ai * count),
|
||||
exp: Math.round(base.exp * rpClass * ai * count),
|
||||
};
|
||||
}
|
||||
|
||||
bannerParams(vehicles: Iterable<string>, difficulty: EconomyDifficulty): BannerParams {
|
||||
const table: Record<string, Record<string, [number, number]>> = {};
|
||||
for (const name of vehicles) {
|
||||
const economy = this.vehicle(name);
|
||||
if (!economy || table[name]) continue;
|
||||
const entries: Record<string, [number, number]> = {};
|
||||
for (const code of Object.values(ExpEvent)) {
|
||||
const groups: readonly (VictimGroup | 'own')[] = code === ExpEvent.CAPTURE_ZONE ? ['own'] : ['ground', 'air', 'naval', 'human'];
|
||||
for (const group of groups) {
|
||||
const priceGroup = group === 'own' ? this.victimGroup(economy.unitClass) : group;
|
||||
const base = this.baseReward(name, difficulty, code, priceGroup);
|
||||
if (base) entries[`${code}:${group}`] = [base.wp, base.exp];
|
||||
}
|
||||
}
|
||||
table[name] = entries;
|
||||
}
|
||||
return {
|
||||
vehicles: table,
|
||||
groups: Object.fromEntries(this.#tuning.victimGroups),
|
||||
slClass: this.data.silverLionsClassFactors,
|
||||
rpClass: this.data.researchClassFactors,
|
||||
aiKillK: this.data.aiKillK,
|
||||
friendlyKillPenaltyMul: this.#tuning.friendlyKillPenaltyMul,
|
||||
};
|
||||
}
|
||||
|
||||
#score(code: number, group: VictimGroup): number | undefined {
|
||||
const scored = (event: ScoredEvent): number => this.#tuning.eventScores[group][event];
|
||||
switch (code) {
|
||||
case ExpEvent.KILL:
|
||||
case ExpEvent.KILL_GROUND:
|
||||
case ExpEvent.KILL_HUMAN: return scored('kill');
|
||||
case ExpEvent.ASSIST: return scored('assist');
|
||||
case ExpEvent.CRITICAL_HIT: return scored('criticalHit');
|
||||
case ExpEvent.HIT: return scored('hit');
|
||||
case ExpEvent.SEVERE_DAMAGE: return scored('severeDamage');
|
||||
case ExpEvent.CAPTURE_ZONE: return this.#tuning.captureZoneScore[group];
|
||||
case ExpEvent.UNIT_DAMAGE: return this.#tuning.navalDamageScorePerPoint;
|
||||
default: return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function debriefingRow(fact: CombatEventFact, group: VictimGroup): DebriefingRow | undefined {
|
||||
switch (fact.code) {
|
||||
case ExpEvent.KILL:
|
||||
case ExpEvent.KILL_GROUND:
|
||||
case ExpEvent.KILL_HUMAN:
|
||||
if (fact.friendly) return 'FriendlyKills';
|
||||
return group === 'air' ? 'AirKills' : group === 'naval' ? 'NavalKills' : group === 'human' ? 'HumanKills' : 'GroundKills';
|
||||
case ExpEvent.ASSIST: return 'Assist';
|
||||
case ExpEvent.CRITICAL_HIT: return 'Critical';
|
||||
case ExpEvent.HIT: return 'Hit';
|
||||
case ExpEvent.SEVERE_DAMAGE: return group === 'naval' ? 'ShipSevereDamage' : 'AirSevereDamage';
|
||||
case ExpEvent.CAPTURE_ZONE: return 'Captures';
|
||||
case ExpEvent.UNIT_DAMAGE: return 'AwardDamage';
|
||||
default: return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,167 +1,101 @@
|
||||
/**
|
||||
* Battle debriefing report schema and DataBlock parser for `cln_wto_finish_battle`,
|
||||
* including per-unit and top-level reward categories mapped to `EULT_SESSION_RESULT`
|
||||
* `body/container` event blocks (`scripts/userlog/getuserlogbattlerewardstable.nut`).
|
||||
* The battle report of `cln_wto_finish_battle` (gui-patches/battle/report-local-battle-settlement):
|
||||
* what happened in the battle, as facts only. The client sends no money; the local service
|
||||
* prices every event (battle-economy.ts).
|
||||
*
|
||||
* sessionId:t outcome:t ("win" | "lose" | "running") localTeam:i
|
||||
* teamAScore:i teamBScore:i sessionStart:r sessionEnd:r (mission time, seconds)
|
||||
* lives{ life{ unit:t start:r end:r } ... } one per spawn of the local player
|
||||
* events{ e{ time:r unit:t code:i expClass:t victim:t victimIsPlayer:b friendly:b
|
||||
* modifier:t damage:i } ... } the local player's combat events
|
||||
* spares{ <unit>:i ... } backup vehicles used
|
||||
*/
|
||||
import { findBlock, type BlkBlock } from '@wto/blk';
|
||||
import type { CombatEventFact } from './battle-economy.ts';
|
||||
|
||||
export type BattleOutcomeKind = 'win' | 'lose' | 'running';
|
||||
|
||||
export interface RewardCategoryStat {
|
||||
readonly count: number;
|
||||
readonly wp: number;
|
||||
readonly exp: number;
|
||||
export interface BattleLife {
|
||||
readonly unit: string;
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
}
|
||||
|
||||
export interface RewardCategorySpec {
|
||||
readonly category: string;
|
||||
readonly containerId: string;
|
||||
readonly victimUnitFileName?: string;
|
||||
readonly singleSummaryEvent?: boolean;
|
||||
}
|
||||
|
||||
export const REWARD_CATEGORY_SPECS: readonly RewardCategorySpec[] = [
|
||||
{ category: 'AirKills', containerId: 'eventKill' },
|
||||
{ category: 'GroundKills', containerId: 'eventKillGround' },
|
||||
{ category: 'NavalKills', containerId: 'eventKillGround', victimUnitFileName: 'ships/' },
|
||||
{ category: 'HumanKills', containerId: 'eventKillHuman' },
|
||||
{ category: 'Assist', containerId: 'eventAssist' },
|
||||
{ category: 'AirSevereDamage', containerId: 'eventSevereDamage' },
|
||||
{ category: 'ShipSevereDamage', containerId: 'eventSevereDamage' },
|
||||
{ category: 'Critical', containerId: 'eventCriticalHit' },
|
||||
{ category: 'Hit', containerId: 'eventHit' },
|
||||
{ category: 'Takeoffs', containerId: 'eventTakeoff' },
|
||||
{ category: 'Landings', containerId: 'eventLanding' },
|
||||
{ category: 'MissileEvade', containerId: 'eventMissileEvade' },
|
||||
{ category: 'ShellInterception', containerId: 'eventShellInterception' },
|
||||
{ category: 'Captures', containerId: 'eventCaptureZone' },
|
||||
{ category: 'SectorCapture', containerId: 'eventSectorCapture' },
|
||||
{ category: 'SuppliesDelivery', containerId: 'eventSuppliesDelivery' },
|
||||
{ category: 'SuppliesReturn', containerId: 'eventSuppliesReturn' },
|
||||
{ category: 'SuppliesDestroy', containerId: 'eventSuppliesDestroy' },
|
||||
{ category: 'SuppliesEscort', containerId: 'eventSuppliesEscort' },
|
||||
{ category: 'Destruction', containerId: 'eventDestroyZone' },
|
||||
{ category: 'Damage', containerId: 'eventDamageZone' },
|
||||
{ category: 'Scout', containerId: 'eventScout' },
|
||||
{ category: 'ScoutCriticalHit', containerId: 'eventScoutCriticalHit' },
|
||||
{ category: 'ScoutKill', containerId: 'eventScoutKill' },
|
||||
{ category: 'ScoutKillUnknown', containerId: 'eventScoutKill' },
|
||||
{ category: 'TimedAward', containerId: 'eventTimedAward' },
|
||||
{ category: 'Unlocks', containerId: 'eventStreak' },
|
||||
{ category: 'BattleTime', containerId: 'eventBattletime', singleSummaryEvent: true },
|
||||
];
|
||||
|
||||
export interface VehicleBattleStats {
|
||||
readonly vehicle: string;
|
||||
readonly wpTotal: number;
|
||||
readonly expTotal: number;
|
||||
readonly expModsTotal: number;
|
||||
readonly expUnitTotal: number;
|
||||
readonly wpMission: number;
|
||||
readonly expSkillBonusTotal: number;
|
||||
readonly expSkillBonusLevel: number;
|
||||
readonly sessionTime: number;
|
||||
readonly battleTime: number;
|
||||
readonly rewards: Readonly<Record<string, RewardCategoryStat>>;
|
||||
export interface ReportedCombatEvent extends CombatEventFact {
|
||||
readonly time: number;
|
||||
readonly unit: string;
|
||||
readonly victim: string;
|
||||
readonly modifier: string;
|
||||
}
|
||||
|
||||
export interface BattleReport {
|
||||
readonly sessionId: string;
|
||||
readonly country: string;
|
||||
readonly outcome: BattleOutcomeKind;
|
||||
readonly localTeam: number;
|
||||
readonly teamAScore: number;
|
||||
readonly teamBScore: number;
|
||||
readonly teamAKills: number;
|
||||
readonly teamBKills: number;
|
||||
readonly wpTotal: number;
|
||||
readonly expTotal: number;
|
||||
readonly expFree: number;
|
||||
readonly wpMission: number;
|
||||
readonly wpTeamKills: number;
|
||||
readonly expSkillBonusTotal: number;
|
||||
readonly expSkillBonusLevel: number;
|
||||
readonly activity: number;
|
||||
readonly sessionTime: number;
|
||||
readonly battleTime: number;
|
||||
readonly rewards: Readonly<Record<string, RewardCategoryStat>>;
|
||||
readonly sessionStart: number;
|
||||
readonly sessionEnd: number;
|
||||
readonly lives: readonly BattleLife[];
|
||||
readonly events: readonly ReportedCombatEvent[];
|
||||
readonly usedSpares: Readonly<Record<string, number>>;
|
||||
readonly vehicles: readonly VehicleBattleStats[];
|
||||
}
|
||||
|
||||
/** Undefined when the report is malformed; lives and events that make no sense are dropped. */
|
||||
export function parseBattleReport(payload: BlkBlock): BattleReport | undefined {
|
||||
const sessionId = strOf(payload, 'sessionId');
|
||||
if (!sessionId || !/^[0-9a-f]{16}$/i.test(sessionId)) return undefined;
|
||||
const rawOutcome = strOf(payload, 'outcome');
|
||||
const outcome: BattleOutcomeKind = rawOutcome === 'win' || rawOutcome === 'lose' ? rawOutcome : 'running';
|
||||
const vehiclesBlock = findBlock(payload, 'vehicles');
|
||||
const vehicles: VehicleBattleStats[] = (vehiclesBlock?.blocks ?? [])
|
||||
.filter((block) => block.name.length > 0)
|
||||
.map((block) => ({
|
||||
vehicle: block.name,
|
||||
wpTotal: intOf(block, 'wpTotal'),
|
||||
expTotal: intOf(block, 'expTotal'),
|
||||
expModsTotal: intOf(block, 'expModsTotal'),
|
||||
expUnitTotal: intOf(block, 'expUnitTotal'),
|
||||
wpMission: intOf(block, 'wpMission'),
|
||||
expSkillBonusTotal: intOf(block, 'expSkillBonusTotal'),
|
||||
expSkillBonusLevel: intOf(block, 'expSkillBonusLevel'),
|
||||
sessionTime: realOf(block, 'sessionTime'),
|
||||
battleTime: realOf(block, 'battleTime'),
|
||||
rewards: parseRewardMap(findBlock(block, 'rewards')),
|
||||
}));
|
||||
const sessionStart = Math.max(0, realOf(payload, 'sessionStart'));
|
||||
const sessionEnd = Math.max(sessionStart, realOf(payload, 'sessionEnd'));
|
||||
const lives = (findBlock(payload, 'lives')?.blocks ?? []).flatMap((block): BattleLife[] => {
|
||||
const unit = strOf(block, 'unit');
|
||||
const start = Math.max(sessionStart, realOf(block, 'start'));
|
||||
const end = Math.min(sessionEnd, Math.max(start, realOf(block, 'end')));
|
||||
return unit ? [{ unit, start, end }] : [];
|
||||
});
|
||||
const livedUnits = new Set(lives.map((life) => life.unit));
|
||||
const events = (findBlock(payload, 'events')?.blocks ?? []).flatMap((block): ReportedCombatEvent[] => {
|
||||
const unit = strOf(block, 'unit');
|
||||
if (!unit || !livedUnits.has(unit)) return [];
|
||||
return [{
|
||||
time: realOf(block, 'time'),
|
||||
unit,
|
||||
code: intOf(block, 'code'),
|
||||
expClass: strOf(block, 'expClass') ?? '',
|
||||
victim: strOf(block, 'victim') ?? '',
|
||||
victimIsPlayer: boolOf(block, 'victimIsPlayer'),
|
||||
friendly: boolOf(block, 'friendly'),
|
||||
modifier: strOf(block, 'modifier') ?? '',
|
||||
damage: Math.max(0, intOf(block, 'damage')),
|
||||
}];
|
||||
});
|
||||
return {
|
||||
sessionId: sessionId.toLowerCase(),
|
||||
country: strOf(payload, 'country') ?? '',
|
||||
outcome,
|
||||
outcome: rawOutcome === 'win' || rawOutcome === 'lose' ? rawOutcome : 'running',
|
||||
localTeam: intOf(payload, 'localTeam', 1),
|
||||
teamAScore: intOf(payload, 'teamAScore'),
|
||||
teamBScore: intOf(payload, 'teamBScore'),
|
||||
teamAKills: intOf(payload, 'teamAKills'),
|
||||
teamBKills: intOf(payload, 'teamBKills'),
|
||||
wpTotal: intOf(payload, 'wpTotal'),
|
||||
expTotal: intOf(payload, 'expTotal'),
|
||||
expFree: intOf(payload, 'expFree'),
|
||||
wpMission: intOf(payload, 'wpMission'),
|
||||
wpTeamKills: intOf(payload, 'wpTeamKills'),
|
||||
expSkillBonusTotal: intOf(payload, 'expSkillBonusTotal'),
|
||||
expSkillBonusLevel: intOf(payload, 'expSkillBonusLevel'),
|
||||
activity: realOf(payload, 'activity'),
|
||||
sessionTime: realOf(payload, 'sessionTime'),
|
||||
battleTime: realOf(payload, 'battleTime'),
|
||||
rewards: parseRewardMap(findBlock(payload, 'rewards')),
|
||||
sessionStart,
|
||||
sessionEnd,
|
||||
lives,
|
||||
events,
|
||||
usedSpares: parseSpareMap(findBlock(payload, 'spares')),
|
||||
vehicles,
|
||||
};
|
||||
}
|
||||
|
||||
function parseRewardMap(rewardsBlk: BlkBlock | undefined): Record<string, RewardCategoryStat> {
|
||||
const out: Record<string, RewardCategoryStat> = {};
|
||||
if (!rewardsBlk) return out;
|
||||
for (const catBlk of rewardsBlk.blocks) {
|
||||
if (!catBlk.name) continue;
|
||||
const count = Math.max(0, intOf(catBlk, 'count'));
|
||||
const wp = Math.max(0, intOf(catBlk, 'wp'));
|
||||
const exp = Math.max(0, intOf(catBlk, 'exp'));
|
||||
if (count > 0 || wp > 0 || exp > 0) out[catBlk.name] = { count, wp, exp };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseSpareMap(sparesBlk: BlkBlock | undefined): Record<string, number> {
|
||||
const out: Record<string, number> = {};
|
||||
if (!sparesBlk) return out;
|
||||
for (const param of sparesBlk.params) {
|
||||
if (!param.name) continue;
|
||||
const count = param.value.type === 'int' ? param.value.value : param.value.type === 'int64' ? Number(param.value.value) : 0;
|
||||
if (count > 0) out[param.name] = count;
|
||||
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 : undefined;
|
||||
return value?.type === 'string' && value.value !== '' ? value.value : undefined;
|
||||
}
|
||||
|
||||
function intOf(block: BlkBlock, name: string, fallback = 0): number {
|
||||
@@ -173,7 +107,11 @@ function intOf(block: BlkBlock, name: string, fallback = 0): number {
|
||||
|
||||
function realOf(block: BlkBlock, name: string): number {
|
||||
const value = block.params.find((p) => p.name === name)?.value;
|
||||
if (value?.type === 'real') return value.value;
|
||||
if (value?.type === 'int') return value.value;
|
||||
if (value?.type === 'real' || value?.type === 'int') return Number.isFinite(value.value) ? value.value : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function boolOf(block: BlkBlock, name: string): boolean {
|
||||
const value = block.params.find((p) => p.name === name)?.value;
|
||||
return value?.type === 'bool' ? value.value : value?.type === 'int' ? value.value !== 0 : false;
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
/**
|
||||
* Assemble and append full `EULT_SESSION_RESULT` (`type = 2`) battle mail entries into
|
||||
* `profile.userlogs` matching `scripts/userlog/userlogviewdata.nut` and
|
||||
* `scripts/userlog/getuserlogbattlerewardstable.nut`.
|
||||
* The `EULT_SESSION_RESULT` (type 2) user log of a settled battle, in the shape the client's battle
|
||||
* log reads (gui.vromfs.bin scripts/userlog/userlogviewdata.nut, getuserlogbattlerewardstable.nut),
|
||||
* plus the debriefing table (`wtoDebriefing`, battle-debriefing.ts) the settlement patch shows.
|
||||
*/
|
||||
import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
||||
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
|
||||
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
||||
import { REWARD_CATEGORY_SPECS, type BattleReport, type RewardCategorySpec } from './battle-report.ts';
|
||||
import type { DebriefingRow } from './battle-economy.ts';
|
||||
import type { BattleRewards, Bonuses } from './battle-rewards.ts';
|
||||
import type { BattleSession } from './battle-session-store.ts';
|
||||
|
||||
export interface EarnedRpItem {
|
||||
@@ -17,19 +18,33 @@ export interface EarnedRpItem {
|
||||
}
|
||||
|
||||
export interface BattleResultSummary {
|
||||
readonly win: boolean;
|
||||
readonly country: string;
|
||||
readonly wpEarned: number;
|
||||
readonly xpEarned: number;
|
||||
readonly activity: number;
|
||||
readonly slMul: number;
|
||||
readonly rpMul: number;
|
||||
readonly rewards: BattleRewards;
|
||||
readonly weaponRefillSl: number;
|
||||
readonly friendlyFirePenalty: number;
|
||||
readonly report: BattleReport;
|
||||
readonly usedSpares: Readonly<Record<string, number>>;
|
||||
readonly rpItems: readonly EarnedRpItem[];
|
||||
readonly debriefing: BlkBlock;
|
||||
}
|
||||
|
||||
const NO_BONUSES: Bonuses = { premAccWp: 0, premAccExp: 0, premModExp: 0 };
|
||||
|
||||
/** Container list of each debriefing row's events (getuserlogbattlerewardstable.nut ids). */
|
||||
const CONTAINER_OF_ROW: Readonly<Record<DebriefingRow, string | undefined>> = {
|
||||
AirKills: 'eventKill',
|
||||
GroundKills: 'eventKillGround',
|
||||
NavalKills: 'eventKillGround',
|
||||
HumanKills: 'eventKillHuman',
|
||||
FriendlyKills: undefined,
|
||||
Assist: 'eventAssist',
|
||||
AirSevereDamage: 'eventSevereDamage',
|
||||
ShipSevereDamage: 'eventSevereDamage',
|
||||
Critical: 'eventCriticalHit',
|
||||
Hit: 'eventHit',
|
||||
Captures: 'eventCaptureZone',
|
||||
// No user log list carries naval damage awards; they show in the debriefing table only.
|
||||
AwardDamage: undefined,
|
||||
};
|
||||
|
||||
export function mergeEarnedRpItems(items: readonly EarnedRpItem[]): EarnedRpItem[] {
|
||||
const byKey = new Map<string, EarnedRpItem>();
|
||||
for (const item of items) {
|
||||
@@ -51,32 +66,28 @@ export function mergeEarnedRpItems(items: readonly EarnedRpItem[]): EarnedRpItem
|
||||
return [...byKey.values()];
|
||||
}
|
||||
|
||||
export function appendBattleResultLog(
|
||||
profile: BlkBlock,
|
||||
session: BattleSession,
|
||||
summary: BattleResultSummary,
|
||||
): void {
|
||||
export function appendBattleResultLog(profile: BlkBlock, session: BattleSession, summary: BattleResultSummary): void {
|
||||
const { rewards } = summary;
|
||||
const friendlyFirePenalty = rewards.events
|
||||
.filter((settled) => settled.priced.row === 'FriendlyKills')
|
||||
.reduce((sum, settled) => sum + settled.priced.wp, 0);
|
||||
const bodyParams: BlkParam[] = [
|
||||
{ name: 'win', value: { type: 'bool', value: summary.win } },
|
||||
{ name: 'win', value: { type: 'bool', value: rewards.win } },
|
||||
{ name: 'mission', value: { type: 'string', value: session.missionName } },
|
||||
...(session.missionLocName ? [{ name: 'locName', value: { type: 'string' as const, value: session.missionLocName } }] : []),
|
||||
{ name: 'country', value: { type: 'string', value: summary.country } },
|
||||
{ name: 'eventId', value: { type: 'string', value: session.modeName } },
|
||||
{ name: 'wpEarned', value: { type: 'int', value: summary.wpEarned } },
|
||||
{ name: 'xpEarned', value: { type: 'int', value: summary.xpEarned } },
|
||||
{ name: 'activity', value: { type: 'real', value: summary.activity } },
|
||||
...(summary.friendlyFirePenalty !== 0
|
||||
? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: summary.friendlyFirePenalty } }]
|
||||
: []),
|
||||
{ name: 'wpEarned', value: { type: 'int', value: rewards.wpTotal } },
|
||||
{ name: 'xpEarned', value: { type: 'int', value: rewards.expTotal } },
|
||||
{ name: 'activity', value: { type: 'real', value: rewards.activity } },
|
||||
...(friendlyFirePenalty !== 0 ? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: friendlyFirePenalty } }] : []),
|
||||
{ name: 'wtoSessionId', value: { type: 'string', value: session.sessionId } },
|
||||
{ name: 'wtoSlMul', value: { type: 'real', value: summary.slMul } },
|
||||
{ name: 'wtoRpMul', value: { type: 'real', value: summary.rpMul } },
|
||||
];
|
||||
|
||||
const bodyBlocks: BlkBlock[] = [buildContainerBlock(summary)];
|
||||
const aircrafts = buildAircraftsBlock(summary.report);
|
||||
if (aircrafts) bodyBlocks.push(aircrafts);
|
||||
const spare = buildSpareBlock(summary.report);
|
||||
const bodyBlocks: BlkBlock[] = [buildContainerBlock(summary), summary.debriefing];
|
||||
const aircrafts = emptyBlock('aircrafts');
|
||||
for (const vehicle of rewards.vehicles) setParam(aircrafts, vehicle.vehicle, { type: 'real', value: 1.0 });
|
||||
if (aircrafts.params.length > 0) bodyBlocks.push(aircrafts);
|
||||
const spare = buildSpareBlock(summary.usedSpares);
|
||||
if (spare) bodyBlocks.push(spare);
|
||||
const rpEarned = buildRpEarnedBlock(summary.rpItems);
|
||||
if (rpEarned) bodyBlocks.push(rpEarned);
|
||||
@@ -92,171 +103,81 @@ export function appendBattleResultLog(
|
||||
|
||||
function buildContainerBlock(summary: BattleResultSummary): BlkBlock {
|
||||
const container = emptyBlock('container');
|
||||
const { report, slMul, rpMul } = summary;
|
||||
if (summary.weaponRefillSl > 0) {
|
||||
setParam(container, 'wpCostWeaponRefill', { type: 'int', value: summary.weaponRefillSl });
|
||||
}
|
||||
const wpMission = scalePositive(
|
||||
Math.max(report.wpMission, report.vehicles.reduce((s, v) => s + Math.max(0, v.wpMission), 0)),
|
||||
slMul,
|
||||
);
|
||||
if (wpMission > 0) {
|
||||
setParam(container, 'wpMissionEndAward', { type: 'int', value: wpMission });
|
||||
}
|
||||
const { rewards } = summary;
|
||||
if (summary.weaponRefillSl > 0) setParam(container, 'wpCostWeaponRefill', { type: 'int', value: summary.weaponRefillSl });
|
||||
|
||||
const eventLists = new Map<string, BlkBlock[]>();
|
||||
for (const spec of REWARD_CATEGORY_SPECS) {
|
||||
appendCategoryEvents(eventLists, spec, report, slMul, rpMul);
|
||||
}
|
||||
for (const [containerId, events] of eventLists) {
|
||||
if (events.length > 0) {
|
||||
container.blocks.push({ name: containerId, params: [], blocks: events });
|
||||
const lists = new Map<string, BlkBlock[]>();
|
||||
const push = (id: string, event: BlkBlock): void => {
|
||||
const list = lists.get(id);
|
||||
if (list) list.push(event);
|
||||
else lists.set(id, [event]);
|
||||
};
|
||||
for (const { event, priced, bonuses } of rewards.events) {
|
||||
const id = CONTAINER_OF_ROW[priced.row];
|
||||
if (!id) continue;
|
||||
const block = emptyBlock('event');
|
||||
setParam(block, 'offenderUnit', { type: 'string', value: event.unit });
|
||||
if (event.victim) setParam(block, 'victimUnit', { type: 'string', value: event.victim });
|
||||
if (priced.row === 'NavalKills' || priced.row === 'ShipSevereDamage') {
|
||||
setParam(block, 'victimUnitFileName', { type: 'string', value: 'ships/' });
|
||||
}
|
||||
writeAmounts(block, priced.wp, priced.exp, bonuses);
|
||||
push(id, block);
|
||||
}
|
||||
|
||||
const sessionAward = buildUnitSessionAwardBlock(report);
|
||||
if (sessionAward) container.blocks.push(sessionAward);
|
||||
const skillBonus = buildSkillBonusBlock(report, rpMul);
|
||||
if (skillBonus) container.blocks.push(skillBonus);
|
||||
let missionWp = 0;
|
||||
for (const vehicle of rewards.vehicles) {
|
||||
if (vehicle.sessionTime > 0) {
|
||||
const block = emptyBlock('event');
|
||||
setParam(block, 'unit', { type: 'string', value: vehicle.vehicle });
|
||||
setParam(block, 'lifetime', { type: 'int', value: Math.round(vehicle.sessionTime) });
|
||||
writeAmounts(block, 0, 0, NO_BONUSES);
|
||||
push('unitSessionAward', block);
|
||||
}
|
||||
const time = vehicle.rows.get('BattleTime');
|
||||
if (time) {
|
||||
const block = emptyBlock('event');
|
||||
setParam(block, 'offenderUnit', { type: 'string', value: vehicle.vehicle });
|
||||
writeAmounts(block, time.noBonusWp, time.noBonusExp, time);
|
||||
push('eventBattletime', block);
|
||||
}
|
||||
const timed = vehicle.rows.get('TimedAward');
|
||||
if (timed) {
|
||||
const block = emptyBlock('event');
|
||||
setParam(block, 'offenderUnit', { type: 'string', value: vehicle.vehicle });
|
||||
writeAmounts(block, timed.noBonusWp, 0, timed);
|
||||
push('eventTimedAward', block);
|
||||
}
|
||||
const mission = vehicle.rows.get('Mission');
|
||||
if (mission) missionWp += mission.noBonusWp + mission.premAccWp;
|
||||
}
|
||||
for (const [id, events] of lists) container.blocks.push({ name: id, params: [], blocks: events });
|
||||
if (missionWp > 0) setParam(container, 'wpMissionEndAward', { type: 'int', value: missionWp });
|
||||
|
||||
const skillUnits = rewards.vehicles.filter((vehicle) => vehicle.skillBonusExp > 0).map((vehicle) => {
|
||||
const unit = emptyBlock('unit');
|
||||
setParam(unit, 'unit', { type: 'string', value: vehicle.vehicle });
|
||||
setParam(unit, 'bonusLevel', { type: 'int', value: rewards.skillBonusLevel });
|
||||
setParam(unit, 'exp', { type: 'int', value: vehicle.skillBonusExp });
|
||||
return unit;
|
||||
});
|
||||
if (skillUnits.length > 0) container.blocks.push({ name: 'expSkillBonus', params: [], blocks: skillUnits });
|
||||
return container;
|
||||
}
|
||||
|
||||
function appendCategoryEvents(
|
||||
eventLists: Map<string, BlkBlock[]>,
|
||||
spec: RewardCategorySpec,
|
||||
report: BattleReport,
|
||||
slMul: number,
|
||||
rpMul: number,
|
||||
): void {
|
||||
let unitWpSum = 0;
|
||||
let unitExpSum = 0;
|
||||
let hasUnitEntries = false;
|
||||
for (const vehicle of report.vehicles) {
|
||||
const stat = vehicle.rewards[spec.category];
|
||||
if (!stat) continue;
|
||||
hasUnitEntries = true;
|
||||
const wp = scalePositive(stat.wp, slMul);
|
||||
const exp = scalePositive(stat.exp, rpMul);
|
||||
unitWpSum += stat.wp;
|
||||
unitExpSum += stat.exp;
|
||||
pushSplitEvents(eventLists, spec, vehicle.vehicle, stat.count, wp, exp);
|
||||
}
|
||||
const rootStat = report.rewards[spec.category];
|
||||
if (!rootStat) return;
|
||||
if (!hasUnitEntries) {
|
||||
const fallbackUnit = report.vehicles[0]?.vehicle ?? '';
|
||||
pushSplitEvents(
|
||||
eventLists,
|
||||
spec,
|
||||
fallbackUnit,
|
||||
rootStat.count,
|
||||
scalePositive(rootStat.wp, slMul),
|
||||
scalePositive(rootStat.exp, rpMul),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const extraWp = scalePositive(rootStat.wp - unitWpSum, slMul);
|
||||
const extraExp = scalePositive(rootStat.exp - unitExpSum, rpMul);
|
||||
if (extraWp > 0 || extraExp > 0) {
|
||||
pushSplitEvents(eventLists, spec, report.vehicles[0]?.vehicle ?? '', 1, extraWp, extraExp);
|
||||
}
|
||||
function writeAmounts(block: BlkBlock, wp: number, exp: number, bonuses: Bonuses): void {
|
||||
setParam(block, 'wpNoBonus', { type: 'int', value: wp });
|
||||
setParam(block, 'expNoBonus', { type: 'int', value: exp });
|
||||
if (bonuses.premAccWp) setParam(block, 'wpPremAcc', { type: 'int', value: bonuses.premAccWp });
|
||||
if (bonuses.premAccExp) setParam(block, 'expPremAcc', { type: 'int', value: bonuses.premAccExp });
|
||||
if (bonuses.premModExp) setParam(block, 'expPremMod', { type: 'int', value: bonuses.premModExp });
|
||||
}
|
||||
|
||||
function pushSplitEvents(
|
||||
eventLists: Map<string, BlkBlock[]>,
|
||||
spec: RewardCategorySpec,
|
||||
offenderUnit: string,
|
||||
rawCount: number,
|
||||
totalWp: number,
|
||||
totalExp: number,
|
||||
): void {
|
||||
if (rawCount <= 0 && totalWp <= 0 && totalExp <= 0) return;
|
||||
const count = spec.singleSummaryEvent ? 1 : Math.min(64, Math.max(1, rawCount));
|
||||
let list = eventLists.get(spec.containerId);
|
||||
if (!list) {
|
||||
list = [];
|
||||
eventLists.set(spec.containerId, list);
|
||||
}
|
||||
let prevWp = 0;
|
||||
let prevExp = 0;
|
||||
for (let i = 0; i < count; i++) {
|
||||
const nextWp = Math.round((totalWp * (i + 1)) / count);
|
||||
const nextExp = Math.round((totalExp * (i + 1)) / count);
|
||||
const ev = emptyBlock('event');
|
||||
if (offenderUnit) setParam(ev, 'offenderUnit', { type: 'string', value: offenderUnit });
|
||||
if (spec.victimUnitFileName) setParam(ev, 'victimUnitFileName', { type: 'string', value: spec.victimUnitFileName });
|
||||
setParam(ev, 'wpNoBonus', { type: 'int', value: nextWp - prevWp });
|
||||
setParam(ev, 'expNoBonus', { type: 'int', value: nextExp - prevExp });
|
||||
list.push(ev);
|
||||
prevWp = nextWp;
|
||||
prevExp = nextExp;
|
||||
}
|
||||
}
|
||||
|
||||
function buildUnitSessionAwardBlock(report: BattleReport): BlkBlock | undefined {
|
||||
const events: BlkBlock[] = [];
|
||||
for (const v of report.vehicles) {
|
||||
const sec = Math.round(v.sessionTime > 0 ? v.sessionTime : v.battleTime);
|
||||
if (sec <= 0) continue;
|
||||
const ev = emptyBlock('event');
|
||||
setParam(ev, 'unit', { type: 'string', value: v.vehicle });
|
||||
setParam(ev, 'lifetime', { type: 'int', value: sec });
|
||||
setParam(ev, 'wpNoBonus', { type: 'int', value: 0 });
|
||||
setParam(ev, 'expNoBonus', { type: 'int', value: 0 });
|
||||
events.push(ev);
|
||||
}
|
||||
if (events.length === 0) {
|
||||
const rootSec = Math.round(report.sessionTime > 0 ? report.sessionTime : report.battleTime);
|
||||
if (rootSec <= 0) return undefined;
|
||||
const ev = emptyBlock('event');
|
||||
setParam(ev, 'lifetime', { type: 'int', value: rootSec });
|
||||
setParam(ev, 'wpNoBonus', { type: 'int', value: 0 });
|
||||
setParam(ev, 'expNoBonus', { type: 'int', value: 0 });
|
||||
events.push(ev);
|
||||
}
|
||||
return { name: 'unitSessionAward', params: [], blocks: events };
|
||||
}
|
||||
|
||||
function buildSkillBonusBlock(report: BattleReport, rpMul: number): BlkBlock | undefined {
|
||||
const units: BlkBlock[] = [];
|
||||
for (const v of report.vehicles) {
|
||||
const exp = scalePositive(v.expSkillBonusTotal, rpMul);
|
||||
if (exp <= 0) continue;
|
||||
const uBlk = emptyBlock('unit');
|
||||
setParam(uBlk, 'unit', { type: 'string', value: v.vehicle });
|
||||
setParam(uBlk, 'bonusLevel', { type: 'int', value: Math.max(1, v.expSkillBonusLevel || report.expSkillBonusLevel) });
|
||||
setParam(uBlk, 'exp', { type: 'int', value: exp });
|
||||
units.push(uBlk);
|
||||
}
|
||||
if (units.length === 0 && report.expSkillBonusTotal > 0) {
|
||||
const exp = scalePositive(report.expSkillBonusTotal, rpMul);
|
||||
if (exp > 0) {
|
||||
const uBlk = emptyBlock('unit');
|
||||
setParam(uBlk, 'unit', { type: 'string', value: report.vehicles[0]?.vehicle ?? '' });
|
||||
setParam(uBlk, 'bonusLevel', { type: 'int', value: Math.max(1, report.expSkillBonusLevel) });
|
||||
setParam(uBlk, 'exp', { type: 'int', value: exp });
|
||||
units.push(uBlk);
|
||||
}
|
||||
}
|
||||
return units.length > 0 ? { name: 'expSkillBonus', params: [], blocks: units } : undefined;
|
||||
}
|
||||
|
||||
function buildAircraftsBlock(report: BattleReport): BlkBlock | undefined {
|
||||
if (report.vehicles.length === 0) return undefined;
|
||||
const blk = emptyBlock('aircrafts');
|
||||
for (const v of report.vehicles) {
|
||||
setParam(blk, v.vehicle, { type: 'real', value: 1.0 });
|
||||
}
|
||||
return blk;
|
||||
}
|
||||
|
||||
function buildSpareBlock(report: BattleReport): BlkBlock | undefined {
|
||||
const entries = Object.entries(report.usedSpares).filter(([unit, cnt]) => unit.length > 0 && cnt > 0);
|
||||
function buildSpareBlock(usedSpares: Readonly<Record<string, number>>): BlkBlock | undefined {
|
||||
const entries = Object.entries(usedSpares).filter(([unit, count]) => unit.length > 0 && count > 0);
|
||||
if (entries.length === 0) return undefined;
|
||||
const blk = emptyBlock('spare');
|
||||
for (const [unit, count] of entries) {
|
||||
setParam(blk, unit, { type: 'int', value: Math.trunc(count) });
|
||||
}
|
||||
for (const [unit, count] of entries) setParam(blk, unit, { type: 'int', value: Math.trunc(count) });
|
||||
return blk;
|
||||
}
|
||||
|
||||
@@ -267,14 +188,7 @@ function buildRpEarnedBlock(items: readonly EarnedRpItem[]): BlkBlock | undefine
|
||||
setParam(rpEarned, `aname${index}`, { type: 'string', value: item.unit });
|
||||
if (item.modification) setParam(rpEarned, `mname${index}`, { type: 'string', value: item.modification });
|
||||
setParam(rpEarned, `mrp${index}`, { type: 'int', value: item.rp });
|
||||
if (item.excessRp && item.excessRp > 0) {
|
||||
setParam(rpEarned, `merp${index}`, { type: 'int', value: item.excessRp });
|
||||
}
|
||||
if (item.excessRp && item.excessRp > 0) setParam(rpEarned, `merp${index}`, { type: 'int', value: item.excessRp });
|
||||
});
|
||||
return rpEarned;
|
||||
}
|
||||
|
||||
function scalePositive(base: number, mul: number): number {
|
||||
if (!Number.isFinite(base) || base <= 0) return 0;
|
||||
return Math.min(0x7fffffff, Math.max(0, Math.round(base * mul)));
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Settles a battle report into rewards, row by row as the debriefing shows them (pure: reads no
|
||||
* profile, writes nothing).
|
||||
*
|
||||
* - Combat events: priced by battle-economy.ts against the vehicle the player was in.
|
||||
* - BattleTime: Silver Lions = battleTimeAward x active minutes x activity (offline: the game
|
||||
* files do not say what battleTimeAward measures; the client labels the sibling timedAward
|
||||
* "per minute"); Research Points = active seconds x expForVictoryVersusPerSec (win) or
|
||||
* expForPlayingVersusPerSec x expMul x activity (rank.blk; the per-second rates match the
|
||||
* official numbers).
|
||||
* - TimedAward: timedAward (Silver Lions per minute, client label "max_timed_reward") x active minutes.
|
||||
* - Mission: winK or defeatK (warpoints.blk) x the vehicle's other Silver Lions; a battle the player
|
||||
* left before it ended counts as a defeat.
|
||||
* - Activity: time spent in a vehicle / time in the battle (offline: the online formula is not published).
|
||||
* - Premium account: + (wpMultiplier - 1) Silver Lions and + (xpMultiplier - 1) Research Points on
|
||||
* every row; premium vehicle or talisman: + (goldPlaneExpMul - 1) Research Points (the same terms
|
||||
* as the client's vehicle card, scripts/airinfo.nut).
|
||||
* - Skill bonus: rank.blk ExpSkillBonus of the mode's economic name, by kills of players (or naval
|
||||
* damage), as a percentage of the Research Points without bonuses.
|
||||
* - Free Research Points: total Research Points / denominateFreeExp (rank.blk; how the server uses
|
||||
* it is inferred from the name, not verified).
|
||||
*/
|
||||
import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts';
|
||||
import { BattleEconomy, ExpEvent, type DebriefingRow, type PricedEvent } from './battle-economy.ts';
|
||||
import type { BattleReport, ReportedCombatEvent } from './battle-report.ts';
|
||||
|
||||
export type RewardRow = DebriefingRow | 'BattleTime' | 'TimedAward' | 'Mission';
|
||||
|
||||
export interface RowRewards {
|
||||
count: number;
|
||||
noBonusWp: number;
|
||||
noBonusExp: number;
|
||||
premAccWp: number;
|
||||
premAccExp: number;
|
||||
premModExp: number;
|
||||
}
|
||||
|
||||
export interface VehicleRewards {
|
||||
readonly vehicle: string;
|
||||
/** Seconds the player spent in this vehicle. */
|
||||
readonly sessionTime: number;
|
||||
readonly rows: ReadonlyMap<RewardRow, RowRewards>;
|
||||
readonly skillBonusExp: number;
|
||||
readonly wpTotal: number;
|
||||
readonly expTotal: number;
|
||||
}
|
||||
|
||||
export interface Bonuses {
|
||||
readonly premAccWp: number;
|
||||
readonly premAccExp: number;
|
||||
readonly premModExp: number;
|
||||
}
|
||||
|
||||
export interface SettledEvent {
|
||||
readonly event: ReportedCombatEvent;
|
||||
readonly priced: PricedEvent;
|
||||
readonly bonuses: Bonuses;
|
||||
}
|
||||
|
||||
export interface BattleRewards {
|
||||
readonly win: boolean;
|
||||
readonly activity: number;
|
||||
readonly sessionTime: number;
|
||||
readonly battleTime: number;
|
||||
readonly vehicles: readonly VehicleRewards[];
|
||||
readonly events: readonly SettledEvent[];
|
||||
readonly skillBonusLevel: number;
|
||||
readonly wpTotal: number;
|
||||
readonly expTotal: number;
|
||||
readonly expFree: number;
|
||||
}
|
||||
|
||||
export interface RewardContext {
|
||||
readonly difficulty: EconomyDifficulty;
|
||||
/** The mode's economic name, which selects rank.blk ExpSkillBonus. */
|
||||
readonly economicName: string;
|
||||
readonly premiumAccount: boolean;
|
||||
/** Premium vehicle (costGold or premPackAir) or talisman installed. */
|
||||
readonly hasTalisman: (vehicle: string) => boolean;
|
||||
}
|
||||
|
||||
export function computeBattleRewards(report: BattleReport, economy: BattleEconomy, ctx: RewardContext): BattleRewards {
|
||||
const win = report.outcome === 'win';
|
||||
const sessionTime = Math.max(0, report.sessionEnd - report.sessionStart);
|
||||
const timeByVehicle = new Map<string, number>();
|
||||
for (const life of report.lives) {
|
||||
if (!economy.vehicle(life.unit)) continue;
|
||||
timeByVehicle.set(life.unit, (timeByVehicle.get(life.unit) ?? 0) + (life.end - life.start));
|
||||
}
|
||||
const battleTime = [...timeByVehicle.values()].reduce((sum, seconds) => sum + seconds, 0);
|
||||
const activity = sessionTime > 0 ? Math.min(1, battleTime / sessionTime) : 0;
|
||||
|
||||
const { data, multipliers } = economy;
|
||||
const bonusesOf = (vehicle: string, wp: number, exp: number): Bonuses => ({
|
||||
premAccWp: ctx.premiumAccount ? Math.max(0, Math.round(wp * (data.premiumSilverLionsMul - 1))) : 0,
|
||||
premAccExp: ctx.premiumAccount ? Math.round(exp * (data.premiumResearchMul - 1)) : 0,
|
||||
premModExp: ctx.hasTalisman(vehicle) ? Math.round(exp * (data.talismanResearchMul - 1)) : 0,
|
||||
});
|
||||
const rowsByVehicle = new Map<string, Map<RewardRow, RowRewards>>();
|
||||
const add = (vehicle: string, row: RewardRow, count: number, wp: number, exp: number): Bonuses => {
|
||||
let rows = rowsByVehicle.get(vehicle);
|
||||
if (!rows) rowsByVehicle.set(vehicle, rows = new Map());
|
||||
let amounts = rows.get(row);
|
||||
if (!amounts) rows.set(row, amounts = { count: 0, noBonusWp: 0, noBonusExp: 0, premAccWp: 0, premAccExp: 0, premModExp: 0 });
|
||||
const bonuses = bonusesOf(vehicle, wp, exp);
|
||||
amounts.count += count;
|
||||
amounts.noBonusWp += wp;
|
||||
amounts.noBonusExp += exp;
|
||||
amounts.premAccWp += bonuses.premAccWp;
|
||||
amounts.premAccExp += bonuses.premAccExp;
|
||||
amounts.premModExp += bonuses.premModExp;
|
||||
return bonuses;
|
||||
};
|
||||
for (const vehicle of timeByVehicle.keys()) rowsByVehicle.set(vehicle, new Map());
|
||||
|
||||
const events: SettledEvent[] = [];
|
||||
for (const event of report.events) {
|
||||
const priced = economy.price(event.unit, ctx.difficulty, event);
|
||||
if (!priced) continue;
|
||||
events.push({ event, priced, bonuses: add(event.unit, priced.row, priced.count, priced.wp, priced.exp) });
|
||||
}
|
||||
|
||||
for (const [vehicle, seconds] of timeByVehicle) {
|
||||
const veh = economy.vehicle(vehicle)!;
|
||||
const minutes = seconds / 60;
|
||||
const timeWp = Math.round(veh.battleTimeAward[ctx.difficulty] * minutes * activity * multipliers.silverLions);
|
||||
const timeRp = Math.round(seconds * (win ? data.researchPerSecondWin : data.researchPerSecondPlaying)
|
||||
* veh.expMul * activity * multipliers.researchPoints);
|
||||
if (timeWp > 0 || timeRp > 0) add(vehicle, 'BattleTime', Math.round(seconds), timeWp, timeRp);
|
||||
const timedWp = Math.round(veh.timedAward[ctx.difficulty] * minutes * multipliers.silverLions);
|
||||
if (timedWp > 0) add(vehicle, 'TimedAward', 1, timedWp, 0);
|
||||
}
|
||||
for (const [vehicle, rows] of rowsByVehicle) {
|
||||
const earned = [...rows.values()].reduce((sum, amounts) => sum + Math.max(0, amounts.noBonusWp), 0);
|
||||
const missionWp = Math.round(earned * (win ? data.winK : data.defeatK));
|
||||
if (missionWp > 0) add(vehicle, 'Mission', 1, missionWp, 0);
|
||||
}
|
||||
|
||||
const { level: skillBonusLevel, percent: skillBonusPercent } = skillBonus(report.events, economy, ctx.economicName);
|
||||
const vehicles: VehicleRewards[] = [];
|
||||
for (const [vehicle, rows] of rowsByVehicle) {
|
||||
let wpTotal = 0;
|
||||
let baseExp = 0;
|
||||
let expTotal = 0;
|
||||
for (const amounts of rows.values()) {
|
||||
wpTotal += amounts.noBonusWp + amounts.premAccWp;
|
||||
baseExp += amounts.noBonusExp;
|
||||
expTotal += amounts.noBonusExp + amounts.premAccExp + amounts.premModExp;
|
||||
}
|
||||
const skillBonusExp = Math.round(baseExp * skillBonusPercent / 100);
|
||||
expTotal += skillBonusExp;
|
||||
vehicles.push({ vehicle, sessionTime: timeByVehicle.get(vehicle) ?? 0, rows, skillBonusExp, wpTotal, expTotal });
|
||||
}
|
||||
|
||||
const wpTotal = vehicles.reduce((sum, v) => sum + v.wpTotal, 0);
|
||||
const expTotal = vehicles.reduce((sum, v) => sum + v.expTotal, 0);
|
||||
return {
|
||||
win,
|
||||
activity,
|
||||
sessionTime,
|
||||
battleTime,
|
||||
vehicles,
|
||||
events,
|
||||
skillBonusLevel,
|
||||
wpTotal,
|
||||
expTotal,
|
||||
expFree: data.freeResearchDivisor > 0 ? Math.round(expTotal / data.freeResearchDivisor) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
function skillBonus(
|
||||
events: readonly ReportedCombatEvent[],
|
||||
economy: BattleEconomy,
|
||||
economicName: string,
|
||||
): { level: number; percent: number } {
|
||||
const levels = economy.data.skillBonus[economicName] ?? [];
|
||||
let level = 0;
|
||||
let percent = 0;
|
||||
for (const rule of levels) {
|
||||
const value = rule.metric === 'damage'
|
||||
? events.reduce((sum, e) => sum + (e.code === ExpEvent.UNIT_DAMAGE && !e.friendly ? e.damage : 0), 0)
|
||||
: events.filter((e) => isKill(e.code) && e.victimIsPlayer && !e.friendly).length;
|
||||
if (value >= rule.threshold) {
|
||||
level = rule.level;
|
||||
percent = rule.bonusPercent;
|
||||
}
|
||||
}
|
||||
return { level, percent };
|
||||
}
|
||||
|
||||
function isKill(code: number): boolean {
|
||||
return code === ExpEvent.KILL || code === ExpEvent.KILL_GROUND || code === ExpEvent.KILL_HUMAN;
|
||||
}
|
||||
@@ -39,7 +39,6 @@ import { addResearchPoints } from '../research/research-progress.ts';
|
||||
import type { ResearchRules } from '../research/research-rules.ts';
|
||||
import { currentStatus, refreshResearchState } from '../research/research-state.ts';
|
||||
import { VehicleStatus } from '../research/vehicle-status.ts';
|
||||
import type { BattleReport } from './battle-report.ts';
|
||||
import type { EarnedRpItem } from './battle-result-log.ts';
|
||||
import type { BattleSession } from './battle-session-store.ts';
|
||||
|
||||
@@ -49,34 +48,31 @@ export interface BattleRpDeps {
|
||||
readonly crew: CrewSkillCatalogue;
|
||||
}
|
||||
|
||||
export interface VehicleRp {
|
||||
readonly vehicle: string;
|
||||
readonly rp: number;
|
||||
}
|
||||
|
||||
/** Each vehicle's Research Points go both to its own modification research and to its branch's vehicle research. */
|
||||
export function collectEarnedBattleRp(
|
||||
profile: BlkBlock,
|
||||
report: BattleReport,
|
||||
earned: readonly VehicleRp[],
|
||||
session: BattleSession,
|
||||
deps: BattleRpDeps,
|
||||
rpMul: number,
|
||||
earnedTotalRp: number,
|
||||
): EarnedRpItem[] {
|
||||
const rpItems: EarnedRpItem[] = [];
|
||||
const owned = ownedVehicles(profile);
|
||||
const branchTotals = new Map<string, { readonly country: string; readonly branchType: string; amount: number }>();
|
||||
|
||||
refreshResearchState(profile, deps.research);
|
||||
for (const stat of report.vehicles) {
|
||||
const modRp = scaleRp(stat.expModsTotal > 0 ? stat.expModsTotal : stat.expTotal, rpMul);
|
||||
const unitRp = scaleRp(stat.expUnitTotal > 0 ? stat.expUnitTotal : stat.expTotal, rpMul);
|
||||
if (modRp > 0 && owned.has(stat.vehicle)) {
|
||||
const modItem = investModificationRp(profile, deps.equipment, stat.vehicle, modRp);
|
||||
for (const { vehicle, rp } of earned) {
|
||||
if (rp <= 0) continue;
|
||||
if (owned.has(vehicle)) {
|
||||
const modItem = investModificationRp(profile, deps.equipment, vehicle, rp);
|
||||
if (modItem) rpItems.push(modItem);
|
||||
investAceCrewRp(profile, deps.crew, session.country, vehicle, rp);
|
||||
}
|
||||
if (unitRp > 0) {
|
||||
if (owned.has(stat.vehicle)) investAceCrewRp(profile, deps.crew, session.country, stat.vehicle, unitRp);
|
||||
accumulateBranchRp(branchTotals, profile, deps.research, stat.vehicle, session, unitRp);
|
||||
}
|
||||
}
|
||||
if (report.vehicles.length === 0 && earnedTotalRp > 0) {
|
||||
const fallbackBranch = resolveFallbackBranch(profile, session.country, session.requiredClass);
|
||||
if (fallbackBranch) addToBranchMap(branchTotals, session.country, fallbackBranch, earnedTotalRp);
|
||||
accumulateBranchRp(branchTotals, profile, deps.research, vehicle, session, rp);
|
||||
}
|
||||
for (const entry of branchTotals.values()) {
|
||||
const item = investIntoBranch(profile, deps.research, entry.country, entry.branchType, entry.amount);
|
||||
@@ -259,8 +255,3 @@ function investAceCrewRp(
|
||||
addExpertToAceRp(crew, vehicleName, amount, targetRp);
|
||||
}
|
||||
}
|
||||
|
||||
function scaleRp(base: number, multiplier: number): number {
|
||||
if (!Number.isFinite(base) || base <= 0) return 0;
|
||||
return Math.min(0x7fffffff, Math.max(0, Math.round(base * multiplier)));
|
||||
}
|
||||
@@ -1,75 +1,88 @@
|
||||
/**
|
||||
* Post-battle settlement rules (`cln_wto_finish_battle`):
|
||||
* - Resolves battle win/loss (direct outcome when finished, weighted ticket + kill ratio on
|
||||
* early leave).
|
||||
* - Applies offline multipliers (`tuning/battle.jsonc`) to Silver Lions, Free RP, Modification
|
||||
* RP, and Vehicle RP, runs `autoRefillWeapons` equipment top-ups, and appends the full
|
||||
* `EULT_SESSION_RESULT` battle mail log.
|
||||
* Post-battle settlement (`cln_wto_finish_battle`): prices the reported battle (battle-rewards.ts),
|
||||
* pays Silver Lions and free Research Points, invests the vehicles' Research Points, credits crew
|
||||
* skill points, refills equipment when the player has it enabled, and appends the
|
||||
* `EULT_SESSION_RESULT` log that carries the debriefing table back to the client.
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts';
|
||||
import { stockAndRefillEquipment } from '../modifications/ammo-refill.ts';
|
||||
import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts';
|
||||
import { isAutoRefillWeaponsEnabled } from '../profile/profile-client-settings.ts';
|
||||
import { addEarnedSkillPoints } from '../profile/profile-crew-skills.ts';
|
||||
import { crewForVehicleInCountry } from '../profile/profile-crews.ts';
|
||||
import { addSilverLions, balanceOf, pay } from '../profile/profile-currency.ts';
|
||||
import { remainingPremiumDays } from '../profile/profile-entitlements.ts';
|
||||
import { ownedVehicles } from '../profile/profile-hangar.ts';
|
||||
import { ownsModification } from '../profile/profile-modifications.ts';
|
||||
import { addFreeResearchPoints } from '../profile/profile-research-points.ts';
|
||||
import { serverTimeNow } from '../profile/server-time.ts';
|
||||
import type { ResearchRules } from '../research/research-rules.ts';
|
||||
import { debriefingTable, type BranchInvestment, type ModuleInvestment } from './battle-debriefing.ts';
|
||||
import { economyDifficulty, type BattleEconomy } from './battle-economy.ts';
|
||||
import type { BattleReport } from './battle-report.ts';
|
||||
import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts';
|
||||
import { appendBattleResultLog, mergeEarnedRpItems, type EarnedRpItem } from './battle-result-log.ts';
|
||||
import { computeBattleRewards } from './battle-rewards.ts';
|
||||
import { collectEarnedBattleRp } from './battle-rp-investment.ts';
|
||||
import type { BattleSession } from './battle-session-store.ts';
|
||||
import type { BattleTuning } from './battle-tuning.ts';
|
||||
|
||||
export type { BattleOutcomeKind, BattleReport, VehicleBattleStats } from './battle-report.ts';
|
||||
/** Talisman modification name (scripts/airinfo.nut shopIsModificationEnabled(unit, "premExpMul")). */
|
||||
const TALISMAN = 'premExpMul';
|
||||
|
||||
export interface BattleSettlementDeps {
|
||||
readonly research: ResearchRules;
|
||||
readonly equipment: EquipmentCatalogue;
|
||||
readonly crew: CrewSkillCatalogue;
|
||||
readonly tuning: BattleTuning;
|
||||
readonly economy: BattleEconomy;
|
||||
}
|
||||
|
||||
export function settleBattle(
|
||||
profile: BlkBlock,
|
||||
report: BattleReport,
|
||||
session: BattleSession,
|
||||
deps: BattleSettlementDeps,
|
||||
): void {
|
||||
const win = resolveWin(report, deps.tuning);
|
||||
const slMul = deps.tuning.rewardMultiplierSilverLions;
|
||||
const rpMul = deps.tuning.rewardMultiplierResearchPoints;
|
||||
|
||||
const earnedSilverLions = scaleNonNegative(report.wpTotal, slMul);
|
||||
const friendlyFirePenalty = report.wpTeamKills !== 0
|
||||
? -scaleNonNegative(Math.abs(report.wpTeamKills), slMul)
|
||||
: 0;
|
||||
const baseTotalRp = Math.max(
|
||||
report.expTotal,
|
||||
report.vehicles.reduce((sum, vehicle) => sum + Math.max(0, vehicle.expTotal), 0),
|
||||
);
|
||||
const earnedTotalRp = scaleNonNegative(baseTotalRp, rpMul);
|
||||
const earnedFreeRp = scaleNonNegative(report.expFree > 0 ? report.expFree : baseTotalRp, rpMul);
|
||||
|
||||
applyNetSilverLions(profile, earnedSilverLions + friendlyFirePenalty);
|
||||
if (earnedFreeRp > 0) addFreeResearchPoints(profile, earnedFreeRp);
|
||||
|
||||
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
|
||||
const rpItems = collectEarnedBattleRp(profile, report, session, deps, rpMul, earnedTotalRp);
|
||||
const country = report.country.startsWith('country_') ? report.country : session.country;
|
||||
appendBattleResultLog(profile, session, {
|
||||
win,
|
||||
country,
|
||||
wpEarned: earnedSilverLions,
|
||||
xpEarned: earnedTotalRp,
|
||||
activity: clampActivity(report.activity),
|
||||
slMul,
|
||||
rpMul,
|
||||
weaponRefillSl,
|
||||
friendlyFirePenalty,
|
||||
report,
|
||||
rpItems: mergeEarnedRpItems(rpItems),
|
||||
export function settleBattle(profile: BlkBlock, report: BattleReport, session: BattleSession, deps: BattleSettlementDeps): void {
|
||||
const difficulty = economyDifficulty(session.difficulty);
|
||||
const rewards = computeBattleRewards(report, deps.economy, {
|
||||
difficulty,
|
||||
economicName: session.economicName,
|
||||
premiumAccount: remainingPremiumDays(profile, serverTimeNow()) > 0,
|
||||
hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN),
|
||||
});
|
||||
|
||||
applyNetSilverLions(profile, rewards.wpTotal);
|
||||
if (rewards.expFree > 0) addFreeResearchPoints(profile, rewards.expFree);
|
||||
const crewExpMul = deps.economy.data.crewExpMul[difficulty];
|
||||
for (const vehicle of rewards.vehicles) {
|
||||
const crew = crewForVehicleInCountry(profile, session.country, vehicle.vehicle);
|
||||
if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul);
|
||||
}
|
||||
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
|
||||
const rpItems = collectEarnedBattleRp(
|
||||
profile,
|
||||
rewards.vehicles.map((vehicle) => ({ vehicle: vehicle.vehicle, rp: vehicle.expTotal })),
|
||||
session,
|
||||
deps,
|
||||
);
|
||||
const debriefing = debriefingTable('wtoDebriefing', rewards, investmentsOf(rpItems, deps.research));
|
||||
appendBattleResultLog(profile, session, {
|
||||
country: session.country.startsWith('country_') ? session.country : `country_${session.country}`,
|
||||
rewards,
|
||||
weaponRefillSl,
|
||||
usedSpares: report.usedSpares,
|
||||
rpItems: mergeEarnedRpItems(rpItems),
|
||||
debriefing,
|
||||
});
|
||||
}
|
||||
|
||||
function investmentsOf(items: readonly EarnedRpItem[], research: ResearchRules): { modules: ModuleInvestment[]; branches: BranchInvestment[] } {
|
||||
const modules: ModuleInvestment[] = [];
|
||||
const branches: BranchInvestment[] = [];
|
||||
for (const item of items) {
|
||||
if (item.rp <= 0) continue;
|
||||
if (item.modification) {
|
||||
modules.push({ vehicle: item.unit, module: item.modification, rp: item.rp });
|
||||
continue;
|
||||
}
|
||||
const type = research.techTree.vehicle(item.unit)?.type;
|
||||
if (type) branches.push({ type, unit: item.unit, rp: item.rp });
|
||||
}
|
||||
return { modules, branches };
|
||||
}
|
||||
|
||||
function applyNetSilverLions(profile: BlkBlock, netDelta: number): void {
|
||||
@@ -91,27 +104,3 @@ function refillOwnedEquipment(profile: BlkBlock, catalogue: EquipmentCatalogue):
|
||||
}
|
||||
return totalSpent;
|
||||
}
|
||||
|
||||
function resolveWin(report: BattleReport, tuning: BattleTuning): boolean {
|
||||
if (report.outcome === 'win') return true;
|
||||
if (report.outcome === 'lose') return false;
|
||||
const isTeamB = report.localTeam === 2;
|
||||
const myTickets = Math.max(0, isTeamB ? report.teamBScore : report.teamAScore);
|
||||
const enemyTickets = Math.max(0, isTeamB ? report.teamAScore : report.teamBScore);
|
||||
const myKills = Math.max(0, isTeamB ? report.teamBKills : report.teamAKills);
|
||||
const enemyKills = Math.max(0, isTeamB ? report.teamAKills : report.teamBKills);
|
||||
const ticketShare = myTickets + enemyTickets > 0 ? myTickets / (myTickets + enemyTickets) : 0.5;
|
||||
const killShare = myKills + enemyKills > 0 ? myKills / (myKills + enemyKills) : 0.5;
|
||||
const totalWeight = tuning.earlyLeaveTicketWeight + tuning.earlyLeaveKillWeight;
|
||||
return (ticketShare * tuning.earlyLeaveTicketWeight + killShare * tuning.earlyLeaveKillWeight) / totalWeight >= 0.5;
|
||||
}
|
||||
|
||||
function scaleNonNegative(base: number, multiplier: number): number {
|
||||
if (!Number.isFinite(base) || base <= 0) return 0;
|
||||
return Math.min(0x7fffffff, Math.max(0, Math.round(base * multiplier)));
|
||||
}
|
||||
|
||||
function clampActivity(activity: number): number {
|
||||
if (!Number.isFinite(activity)) return 0;
|
||||
return Math.min(1, Math.max(0, activity));
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
/**
|
||||
* Typed reader for `tuning/battle.jsonc`: offline Silver Lions and Research Points
|
||||
* multipliers, LocalMP slot and bot counts, matchmaking BR window, coalition pairing
|
||||
* rules, and early-leave win-inference weights.
|
||||
* multipliers, LocalMP slot and bot counts, matchmaking BR window and coalition pairing rules.
|
||||
*/
|
||||
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
|
||||
|
||||
@@ -22,8 +21,6 @@ export interface BattleTuning {
|
||||
readonly simColdWarMinMrank: number;
|
||||
readonly tankBotRespawns: number;
|
||||
readonly airBotRespawns: number;
|
||||
readonly earlyLeaveTicketWeight: number;
|
||||
readonly earlyLeaveKillWeight: number;
|
||||
}
|
||||
|
||||
export function readBattleTuning(reader: TuningReader): BattleTuning {
|
||||
@@ -45,11 +42,6 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
|
||||
`tuning file battle.jsonc: rbCoalitionMaxCountries (${rbCoalitionMaxCountries}) must be at least rbCoalitionMinCountries (${rbCoalitionMinCountries})`,
|
||||
);
|
||||
}
|
||||
const earlyLeaveTicketWeight = reader.number('earlyLeaveTicketWeight', { min: 0, max: 1 });
|
||||
const earlyLeaveKillWeight = reader.number('earlyLeaveKillWeight', { min: 0, max: 1 });
|
||||
if (earlyLeaveTicketWeight + earlyLeaveKillWeight <= 0) {
|
||||
throw new TuningError('tuning file battle.jsonc: earlyLeaveTicketWeight + earlyLeaveKillWeight must be positive');
|
||||
}
|
||||
return {
|
||||
rewardMultiplierSilverLions: reader.number('rewardMultiplierSilverLions', { min: 0, max: 100 }),
|
||||
rewardMultiplierResearchPoints: reader.number('rewardMultiplierResearchPoints', { min: 0, max: 100 }),
|
||||
@@ -67,7 +59,5 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
|
||||
simColdWarMinMrank: reader.int('simColdWarMinMrank', { min: 0, max: 40 }),
|
||||
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
|
||||
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
|
||||
earlyLeaveTicketWeight,
|
||||
earlyLeaveKillWeight,
|
||||
};
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
/**
|
||||
* Char action `cln_wto_finish_battle`: receives the client's local-battle debriefing stats
|
||||
* (`stat_get_exp()`), settles Silver Lions, Research Points, equipment refills, and
|
||||
* `EULT_SESSION_RESULT` into the player's save, and answers the updated profile.
|
||||
* Char action `cln_wto_finish_battle`: receives the facts of a local battle (battle-report.ts),
|
||||
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
|
||||
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
|
||||
*/
|
||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||
import { parseBattleReport } from '../../battle/battle-report.ts';
|
||||
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
|
||||
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
|
||||
import type { BattleTuning } from '../../battle/battle-tuning.ts';
|
||||
import type { BattleEconomy } from '../../battle/battle-economy.ts';
|
||||
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
|
||||
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
|
||||
import { clientProfile } from '../../profile/client-profile.ts';
|
||||
@@ -18,7 +18,7 @@ import { withAccount } from './account-context.ts';
|
||||
|
||||
export interface BattleActionDependencies {
|
||||
readonly sessions: BattleSessionStore;
|
||||
readonly tuning: BattleTuning;
|
||||
readonly economy: BattleEconomy;
|
||||
}
|
||||
|
||||
export interface FinishBattleContext {
|
||||
@@ -34,7 +34,7 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
|
||||
research: ctx.research,
|
||||
equipment: ctx.equipment,
|
||||
crew: ctx.crew,
|
||||
tuning: battle.tuning,
|
||||
economy: battle.economy,
|
||||
};
|
||||
return (context) => withAccount(context, ctx.accounts, (account) => {
|
||||
const report = context.payload && parseBattleReport(context.payload);
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Dataset: the battle reward factors the game files carry (implementation notes "3d").
|
||||
*
|
||||
* char.vromfs.bin config/wpcost.blk, per vehicle:
|
||||
* unitClass, expMul, rewardMul<Arcade|Historical|Simulation>, battleTimeAward<...>, timedAward<...>
|
||||
* char.vromfs.bin config/warpoints.blk:
|
||||
* aKill (Silver Lions of a reference kill), aiKillK, winK, defeatK, wpMultiplier (premium account),
|
||||
* units{} (Silver Lions factor by the destroyed unit's expClass)
|
||||
* char.vromfs.bin config/rank.blk:
|
||||
* xpMultiplier (premium account), goldPlaneExpMul (premium vehicle / talisman),
|
||||
* expForVictoryVersusPerSec, expForPlayingVersusPerSec, crew_exp_mul_<difficulty>, denominateFreeExp,
|
||||
* units{} (Research Points factor by the destroyed unit's expClass),
|
||||
* ExpSkillBonus{<economic name>{BonusLevel<N>{bonusPercent, kills|damage}}}
|
||||
*
|
||||
* The stock client shows the same factors on the vehicle card (gui.vromfs.bin scripts/airinfo.nut,
|
||||
* reward formula: expMul x (1 + premium + talisman), rewardMul x (1 + premium)).
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import { blockAt, numberField, stringField } from './blk-fields.ts';
|
||||
import type { Dataset } from './dataset.ts';
|
||||
|
||||
export type EconomyDifficulty = 'arcade' | 'historical' | 'simulation';
|
||||
|
||||
const DIFFICULTY_SUFFIX: Readonly<Record<EconomyDifficulty, string>> = {
|
||||
arcade: 'Arcade',
|
||||
historical: 'Historical',
|
||||
simulation: 'Simulation',
|
||||
};
|
||||
|
||||
export interface VehicleEconomy {
|
||||
readonly unitClass: string;
|
||||
readonly expMul: number;
|
||||
readonly rewardMul: Readonly<Record<EconomyDifficulty, number>>;
|
||||
readonly battleTimeAward: Readonly<Record<EconomyDifficulty, number>>;
|
||||
readonly timedAward: Readonly<Record<EconomyDifficulty, number>>;
|
||||
}
|
||||
|
||||
export interface SkillBonusLevel {
|
||||
readonly level: number;
|
||||
readonly bonusPercent: number;
|
||||
/** Kills needed, or naval damage needed when `metric` is "damage". */
|
||||
readonly threshold: number;
|
||||
readonly metric: 'kills' | 'damage';
|
||||
}
|
||||
|
||||
export interface BattleEconomyData {
|
||||
readonly vehicles: Readonly<Record<string, VehicleEconomy>>;
|
||||
readonly killSilverLions: number;
|
||||
readonly aiKillK: number;
|
||||
readonly winK: number;
|
||||
readonly defeatK: number;
|
||||
readonly premiumSilverLionsMul: number;
|
||||
readonly premiumResearchMul: number;
|
||||
readonly talismanResearchMul: number;
|
||||
readonly silverLionsClassFactors: Readonly<Record<string, number>>;
|
||||
readonly researchClassFactors: Readonly<Record<string, number>>;
|
||||
readonly researchPerSecondWin: number;
|
||||
readonly researchPerSecondPlaying: number;
|
||||
readonly crewExpMul: Readonly<Record<EconomyDifficulty, number>>;
|
||||
readonly freeResearchDivisor: number;
|
||||
readonly skillBonus: Readonly<Record<string, readonly SkillBonusLevel[]>>;
|
||||
}
|
||||
|
||||
export const battleEconomy: Dataset<BattleEconomyData> = {
|
||||
id: 'battle-economy',
|
||||
version: 1,
|
||||
extract: (source) => {
|
||||
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
|
||||
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
|
||||
const rank = source.readBlk('char.vromfs.bin', 'config/rank.blk');
|
||||
const required = (block: BlkBlock, file: string, name: string): number => {
|
||||
const value = numberField(block, name);
|
||||
if (value === undefined) throw new Error(`${file}: ${name} is missing`);
|
||||
return value;
|
||||
};
|
||||
return {
|
||||
vehicles: Object.fromEntries(wpcost.blocks.map((vehicle) => [vehicle.name, vehicleEconomy(vehicle)])),
|
||||
killSilverLions: required(warpoints, 'warpoints.blk', 'aKill'),
|
||||
aiKillK: required(warpoints, 'warpoints.blk', 'aiKillK'),
|
||||
winK: required(warpoints, 'warpoints.blk', 'winK'),
|
||||
defeatK: required(warpoints, 'warpoints.blk', 'defeatK'),
|
||||
premiumSilverLionsMul: required(warpoints, 'warpoints.blk', 'wpMultiplier'),
|
||||
premiumResearchMul: required(rank, 'rank.blk', 'xpMultiplier'),
|
||||
talismanResearchMul: required(rank, 'rank.blk', 'goldPlaneExpMul'),
|
||||
silverLionsClassFactors: numberMap(blockAt(warpoints, 'units')),
|
||||
researchClassFactors: numberMap(blockAt(rank, 'units')),
|
||||
researchPerSecondWin: required(rank, 'rank.blk', 'expForVictoryVersusPerSec'),
|
||||
researchPerSecondPlaying: required(rank, 'rank.blk', 'expForPlayingVersusPerSec'),
|
||||
crewExpMul: {
|
||||
arcade: required(rank, 'rank.blk', 'crew_exp_mul_arcade'),
|
||||
historical: required(rank, 'rank.blk', 'crew_exp_mul_historical'),
|
||||
simulation: required(rank, 'rank.blk', 'crew_exp_mul_simulation'),
|
||||
},
|
||||
freeResearchDivisor: required(rank, 'rank.blk', 'denominateFreeExp'),
|
||||
skillBonus: skillBonusTable(blockAt(rank, 'ExpSkillBonus')),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
function vehicleEconomy(vehicle: BlkBlock): VehicleEconomy {
|
||||
const perDifficulty = (prefix: string, fallback: number): Record<EconomyDifficulty, number> => ({
|
||||
arcade: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.arcade}`) ?? fallback,
|
||||
historical: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.historical}`) ?? fallback,
|
||||
simulation: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.simulation}`) ?? fallback,
|
||||
});
|
||||
return {
|
||||
unitClass: stringField(vehicle, 'unitClass') ?? '',
|
||||
expMul: numberField(vehicle, 'expMul') ?? 1,
|
||||
// The client reads a missing rewardMul as 1.0 (scripts/unit/unit.nut getWpRewardMulList).
|
||||
rewardMul: perDifficulty('rewardMul', 1),
|
||||
battleTimeAward: perDifficulty('battleTimeAward', 0),
|
||||
timedAward: perDifficulty('timedAward', 0),
|
||||
};
|
||||
}
|
||||
|
||||
function numberMap(block: BlkBlock | undefined): Record<string, number> {
|
||||
return Object.fromEntries((block?.params ?? []).flatMap((param) =>
|
||||
param.value.type === 'real' || param.value.type === 'int' ? [[param.name, param.value.value]] : []));
|
||||
}
|
||||
|
||||
function skillBonusTable(block: BlkBlock | undefined): Record<string, SkillBonusLevel[]> {
|
||||
return Object.fromEntries((block?.blocks ?? []).map((event) => [
|
||||
event.name,
|
||||
event.blocks.flatMap((level): SkillBonusLevel[] => {
|
||||
const index = /^BonusLevel(\d+)$/.exec(level.name)?.[1];
|
||||
const bonusPercent = numberField(level, 'bonusPercent');
|
||||
const kills = numberField(level, 'kills');
|
||||
const damage = numberField(level, 'damage');
|
||||
if (index === undefined || bonusPercent === undefined || (kills === undefined && damage === undefined)) return [];
|
||||
return [{
|
||||
level: Number(index),
|
||||
bonusPercent,
|
||||
threshold: kills ?? damage ?? 0,
|
||||
metric: kills !== undefined ? 'kills' : 'damage',
|
||||
}];
|
||||
}).sort((a, b) => a.level - b.level),
|
||||
]));
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
import type { Server } from 'node:net';
|
||||
import { AccountStore } from './accounts/account-store.ts';
|
||||
import { BattleEconomy } from './battle/battle-economy.ts';
|
||||
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
|
||||
import { BattleSessionStore } from './battle/battle-session-store.ts';
|
||||
import { actionTable } from './char/actions/action-table.ts';
|
||||
@@ -13,6 +14,7 @@ import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
|
||||
import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts';
|
||||
import { DecorShop } from './decor/decor-purchase.ts';
|
||||
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
|
||||
import { battleEconomy } from './game-data/datasets/battle-economy.ts';
|
||||
import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts';
|
||||
import { clanEconomy } from './game-data/datasets/clan-economy.ts';
|
||||
import { crewSkillData } from './game-data/datasets/crew-skills.ts';
|
||||
@@ -80,6 +82,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
const cloudSettings = new CloudSettingsStore(options.dataFolder);
|
||||
const vehicles = datasets.load(vehicleCatalogue);
|
||||
const spawnRules = datasets.load(battleSpawnRules);
|
||||
const economyData = datasets.load(battleEconomy);
|
||||
const decals = datasets.load(decalTextures);
|
||||
const labels = datasets.load(uiLabels);
|
||||
const { profiles, research, equipment } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
|
||||
@@ -97,6 +100,12 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
|
||||
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
|
||||
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules);
|
||||
const economy = new BattleEconomy(
|
||||
economyData,
|
||||
tuning.battleEconomy,
|
||||
{ silverLions: tuning.battle.rewardMultiplierSilverLions, researchPoints: tuning.battle.rewardMultiplierResearchPoints },
|
||||
new Set(vehicles.filter((vehicle) => vehicle.goldenEagles > 0 || vehicle.premiumPack).map((vehicle) => vehicle.name)),
|
||||
);
|
||||
|
||||
const router = new Router([
|
||||
webUi,
|
||||
@@ -112,7 +121,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
...catalogues,
|
||||
clans: { store: clans, economy: squadronEconomy },
|
||||
cloudSettings,
|
||||
battle: { sessions: battleSessions, tuning: tuning.battle },
|
||||
battle: { sessions: battleSessions, economy },
|
||||
notifyInventoryChanged,
|
||||
})),
|
||||
new DownloadableContentService(decals, options.gameFolder),
|
||||
@@ -128,6 +137,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
profiles,
|
||||
matchmaker: battleMatchmaker,
|
||||
sessions: battleSessions,
|
||||
economy,
|
||||
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
* 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).
|
||||
* - `battle`: what the client keeps for this battle (session id for the settlement, extra slots,
|
||||
* and `awards`, the parameters of the in-battle reward banner, battle-economy.ts BannerParams).
|
||||
*/
|
||||
import type { BlkBlock, BlkValue } from '@wto/blk';
|
||||
import type { BannerParams } from '../battle/battle-economy.ts';
|
||||
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
|
||||
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
|
||||
|
||||
@@ -30,7 +32,7 @@ export interface BattleLaunchNotify extends Record<string, unknown> {
|
||||
readonly battle: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export function battleLaunchNotify(plan: BattleLaunchPlan): BattleLaunchNotify {
|
||||
export function battleLaunchNotify(plan: BattleLaunchPlan, awards: BannerParams): BattleLaunchNotify {
|
||||
return {
|
||||
from: 'wto_battle',
|
||||
func: 'launch',
|
||||
@@ -53,6 +55,7 @@ export function battleLaunchNotify(plan: BattleLaunchPlan): BattleLaunchNotify {
|
||||
extraBattleSlots: plan.extraBattleSlots,
|
||||
randomUnits: plan.randomUnits,
|
||||
randomUnitsEventName: plan.randomUnitsEventName ?? '',
|
||||
awards,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
* - `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';
|
||||
@@ -20,6 +21,7 @@ export interface BattleQueueDependencies {
|
||||
readonly profiles: PlayerProfiles;
|
||||
readonly matchmaker: BattleMatchmaker;
|
||||
readonly sessions: BattleSessionStore;
|
||||
readonly economy: BattleEconomy;
|
||||
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
|
||||
}
|
||||
|
||||
@@ -99,10 +101,16 @@ function handleEnqueue(
|
||||
}
|
||||
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));
|
||||
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards));
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -49,6 +49,11 @@ export function addSkillPoints(crew: BlkBlock, points: number): void {
|
||||
setParam(crew, BOOKED_POINTS, { type: 'int64', value: BigInt(intOf(crew, BOOKED_POINTS) + points * POINTS_SCALE) });
|
||||
}
|
||||
|
||||
/** Skill points the crew earned in battle (kept apart from bought or spent points, as the client does). */
|
||||
export function addEarnedSkillPoints(crew: BlkBlock, points: number): void {
|
||||
setParam(crew, EARNED_POINTS, { type: 'int64', value: BigInt(intOf(crew, EARNED_POINTS) + Math.round(points * POINTS_SCALE)) });
|
||||
}
|
||||
|
||||
export function isTrainedFor(crew: BlkBlock, vehicle: string): boolean {
|
||||
return (findBlock(crew, VEHICLES)?.params ?? []).some((param) => param.name === TRAINED && param.value.type === 'string' && param.value.value === vehicle);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* limits, preset content). Values the game data already has are read from the game files
|
||||
* instead, and protocol constants stay in the code next to their source.
|
||||
*/
|
||||
import { readBattleEconomyTuning, type BattleEconomyTuning } from '../battle/battle-economy-tuning.ts';
|
||||
import { readBattleTuning, type BattleTuning } from '../battle/battle-tuning.ts';
|
||||
import { readClanTuning, type ClanTuning } from '../clans/clan-tuning.ts';
|
||||
import { readMarketplaceTuning, type MarketplaceTuning } from '../inventory/marketplace-tuning.ts';
|
||||
@@ -28,6 +29,7 @@ export interface Tuning {
|
||||
readonly trophies: TrophyTuning;
|
||||
readonly clans: ClanTuning;
|
||||
readonly battle: BattleTuning;
|
||||
readonly battleEconomy: BattleEconomyTuning;
|
||||
readonly limits: LimitsTuning;
|
||||
}
|
||||
|
||||
@@ -44,6 +46,7 @@ export function loadTuning(dataFolder: string, report: (line: string) => void):
|
||||
trophies: readTrophyTuning(files.read('trophies')),
|
||||
clans: readClanTuning(files.read('clans')),
|
||||
battle: readBattleTuning(files.read('battle')),
|
||||
battleEconomy: readBattleEconomyTuning(files.read('battle-economy')),
|
||||
limits: readLimitsTuning(files.read('limits')),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Battle rewards the game files do not carry. The reward factors themselves (aKill, rewardMul,
|
||||
// expMul, class factors, win/defeat bonus, premium multipliers, time RP rates, skill bonus) are
|
||||
// read from wpcost.blk, warpoints.blk and rank.blk. What the battle server keeps private is the
|
||||
// mission score of each combat event; the values below are the official published ones where
|
||||
// they exist, and the offline version's own choice where they do not (marked "offline").
|
||||
//
|
||||
// How a combat event is priced (battle/battle-economy.ts):
|
||||
// Silver Lions = aKill x SL class factor(victim) x rewardMul(own vehicle, difficulty)
|
||||
// x eventScore / referenceScore(victim group)
|
||||
// Research Points = eventScore x expMul(own vehicle) x RP class factor(victim)
|
||||
// both x aiKillK when the victim is not a player.
|
||||
{
|
||||
// Destroyed-unit classes (warpoints.blk / rank.blk units{} keys) by victim group; any class not
|
||||
// listed counts as "ground".
|
||||
"victimGroups": {
|
||||
"air": ["exp_bomber", "exp_fighter", "exp_assault", "exp_helicopter", "exp_ufo"],
|
||||
"naval": [
|
||||
"exp_torpedo_boat", "exp_gun_boat", "exp_torpedo_gun_boat", "exp_submarine_chaser",
|
||||
"exp_destroyer", "exp_cruiser", "exp_naval_ferry_barge",
|
||||
"exp_ship", "exp_ca_ship", "exp_bb_ship", "exp_cv_ship"
|
||||
],
|
||||
"human": ["exp_human", "exp_infantry"]
|
||||
},
|
||||
|
||||
// Mission score per combat event, by victim group.
|
||||
// ground kill 180: official ("Basic mission score for destruction of an enemy ground vehicle
|
||||
// ... 150 -> 180", server update 2021-11-10, devtrackers.gg/war-thunder/p/2edb7e23).
|
||||
// air kill 450, air assist 300, air critical 150: official, same update (air simulator values).
|
||||
// naval kill 30, naval assist 10: official, same update; naval damage is scored separately below.
|
||||
// ground assist 120, air severe damage 360, naval severe damage 15: original author's values.
|
||||
// ground critical 30, hits 10, ground severe damage 0: offline (no published value).
|
||||
"eventScores": {
|
||||
"ground": { "kill": 180, "assist": 120, "severeDamage": 0, "criticalHit": 30, "hit": 10 },
|
||||
"air": { "kill": 450, "assist": 300, "severeDamage": 360, "criticalHit": 150, "hit": 10 },
|
||||
"naval": { "kill": 30, "assist": 10, "severeDamage": 15, "criticalHit": 0, "hit": 0 },
|
||||
"human": { "kill": 180, "assist": 120, "severeDamage": 0, "criticalHit": 30, "hit": 10 }
|
||||
},
|
||||
|
||||
// Score of a capture by a single player, by the capturing vehicle's group. ground 300: official
|
||||
// (300 for the first capturer, +200 for each additional one, shared; same 2021 update).
|
||||
// naval 200: official ("175 -> 200", same update). air and human: offline, as ground. The
|
||||
// LocalMP host reports captures without the number of capturers, so a capture always scores
|
||||
// the single-capturer value.
|
||||
"captureZoneScore": { "ground": 300, "air": 300, "naval": 200, "human": 300 },
|
||||
|
||||
// Naval mission score per point of damage dealt: official ("0.15 -> 0.18", same update).
|
||||
"navalDamageScorePerPoint": 0.18,
|
||||
|
||||
// The score at which an event pays exactly one reference kill (warpoints.blk aKill), by victim
|
||||
// group. ground 180 and air 450 are the official base kill scores; naval 216 is the official
|
||||
// example of a boat destruction ("now awarded with 216 points instead of 180").
|
||||
"referenceScore": { "ground": 180, "air": 450, "naval": 216, "human": 180 },
|
||||
|
||||
// Destroying a teammate costs the Silver Lions that destroying an enemy of that class would pay,
|
||||
// times this factor (offline: the penalty rules are not published).
|
||||
"friendlyKillPenaltyMul": 1.0
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// Offline battle session capacity, AI bot pool rules, nation coalitions, and post-battle multipliers.
|
||||
{
|
||||
// Global post-battle Silver Lions and Research Points multipliers (1.0 matches stock rates).
|
||||
// Offline multipliers on every battle reward, Silver Lions and Research Points (1.0 = the rates of
|
||||
// tuning/battle-economy.jsonc and the game files).
|
||||
"rewardMultiplierSilverLions": 1.0,
|
||||
"rewardMultiplierResearchPoints": 1.0,
|
||||
|
||||
@@ -33,9 +34,5 @@
|
||||
|
||||
// AI bot respawn limits per battle in multi-slot versus modes.
|
||||
"tankBotRespawns": 3,
|
||||
"airBotRespawns": 2,
|
||||
|
||||
// Team win-inference weights when the player leaves while the battle is still running.
|
||||
"earlyLeaveTicketWeight": 0.7,
|
||||
"earlyLeaveKillWeight": 0.3
|
||||
"airBotRespawns": 2
|
||||
}
|
||||
Reference in new issue
Block a user