Files
WT-Offline/apps/server/src/battle/battle-streaks.ts
T
N0VAN0M4LY 194417a388 fix(battle): ignore non-player kills for firstKill and clamp assist loop
Ignore HUD kill feed entries with killer == -1 (mission air defense SAM/AAA and NPC units, common in Nuclear Escalation) when awarding firstKill, matching avengeAwards.

Also re-read the offenders vector count after orig_iground_award_assists in local_mp_events.c so the post-call scan never reads past a shrunk array.

Verified with root typecheck, MSVC x64 wto_ws.dll rebuild (0 warnings in project C code), and a runnable streak check.
2026-12-04 03:43:05 +08:00

473 lines
21 KiB
TypeScript

/**
* Battle awards ("streaks", char.vromfs.bin config/unlocks.blk, dataset battle-streaks): which of
* them the local player earned, from the facts of the battle (pure; online the battle server does
* this and the client only shows the result).
*
* The meaning of each mode comes from the game's own award texts (lang.vromfs.bin, "streaks/<id>/desc"),
* e.g. multi_kill_air "Destroyed %d player vehicles in a row" with mode killedPlayersTimed and
* delay 10/30/30 s, heroic_fighter "Destroyed the most aircraft" with minVal 12 and mul 1/2/3,
* trophy_near_fighter "... If several players have equal number ..., the award is given to the
* one with a bigger score". Where the texts leave a point open the choice is marked "inferred".
*
* Supported modes:
* killedPlayersTimed, killedGroundTimed kills in a chain, each within `delay` of the previous;
* ground: AI ground units (ships when isShip)
* killedPlayers kills of players, `mul` per kill, `inRow` = no death between
* assistUnits, assistAir, assistPlayers assists, `inRow` as above
* captures zone captures
* missionsWon after the battle: the battle is won
* firstKill the battle's first kill of an enemy (HUD kill log)
* killLastOffender, killLastTeamOffender killing the enemy who last killed you / a teammate
* killedAirBest, killedGroundBest,
* killedPlayersBest, assistAirBest after the battle: the most of it on the scoreboard
* (not those limited by battle rating, e.g. heroic_punisher)
* unlocks `num` of the listed awards earned in the battle (all when
* num is missing, as scripts unlocksConditions.nut counts)
* killStreakNuclearSuccess each explosion of the local player's nuclear bomb
* (killStreak_bomber_nuclear_success)
* Not supported (the facts are not reported): finalBlow, lastManStanding, killWithoutHit,
* hitWithoutDeath, killWithoutMiss, landings, scout / repair / extinguish help, squad awards,
* other kill-streak support vehicles, shell interception, specified naval damage, event missions; and
* any award with a condition on weapon, distance, head shot, scouting, death reason, offender
* flags, unit tags or the awards' platform-free "customOnline" / "mission". Their awards are
* never given.
*
* In a LocalMP battle the other side's crews are AI-driven MPlayers standing in for players; they
* count as players (offline design), mission AI units do not.
*/
import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts';
import type { StreakCondition, StreakDefinition, StreakParams } from '../game-data/datasets/battle-streaks.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
import { economyDifficulty, ExpEvent, type BattleEconomy } from './battle-economy.ts';
import { vehicleMrank } from './battle-ranks.ts';
import type { BattleLife, BattleOutcomeKind, FeedKill, ReportedCombatEvent, ScoreboardPlayer } from './battle-report.ts';
import type { BattleSession } from './battle-session-store.ts';
export interface StreakFacts {
readonly events: readonly ReportedCombatEvent[];
readonly lives: readonly BattleLife[];
readonly feed: readonly FeedKill[];
/** Mission times at which the local player's nuclear bombs exploded. */
readonly nuclearStrikes: readonly number[];
readonly localPlayerId: number;
readonly localTeam: number;
/** The final scoreboard; absent while the battle runs (after-battle awards are then skipped). */
readonly players?: readonly ScoreboardPlayer[];
/** How the battle ended; absent while it runs. */
readonly outcome?: BattleOutcomeKind;
readonly sessionEnd: number;
}
export interface StreakContext {
readonly difficulty: EconomyDifficulty;
/** The mission's ediff (unit type x 3 + difficulty), which conditions "missionType" list. */
readonly ediff: number;
readonly missionName: string;
/** wpcost.blk unitClass of a vehicle. */
readonly classOf: (vehicle: string) => string | undefined;
/** Battle rating of a vehicle in this battle's mode. */
readonly battleRatingOf: (vehicle: string) => number | undefined;
}
export interface AwardedStreak {
readonly id: string;
/** A hidden award: not shown or logged, only judged for wagers that name it. */
readonly hidden: boolean;
/** Stage of a multi-stage award (0 = the first), undefined for a single-stage one. */
readonly stage?: number;
/** The number the award text shows (%d): the stage's count. */
readonly stageParam: number;
readonly time: number;
readonly wp: number;
readonly exp: number;
/** Unique within the battle: id and occurrence. */
readonly key: string;
}
const DIFFICULTY_INDEX: Readonly<Record<EconomyDifficulty, 0 | 1 | 2>> = { arcade: 0, historical: 1, simulation: 2 };
const MUL_NAMES = ['mulArcade', 'mulRealistic', 'mulHardcore'] as const;
const KILL_CODES: ReadonlySet<number> = new Set([ExpEvent.KILL, ExpEvent.KILL_GROUND, ExpEvent.KILL_HUMAN]);
const SATISFIED_CONDITIONS = new Set(['online', 'playerPlatform', '', 'offenderIsPlayerControlled']);
/** Tolerance of the BR thresholds written as 2.0000999 etc. in unlocks.blk. */
const BR_EPSILON = 0.001;
type Group = 'air' | 'ground' | 'naval' | 'human';
const CLASS_GROUP: Readonly<Record<string, Group>> = {
exp_fighter: 'air', exp_bomber: 'air', exp_assault: 'air', exp_helicopter: 'air',
exp_tank: 'ground', exp_heavy_tank: 'ground', exp_tank_destroyer: 'ground', exp_SPAA: 'ground',
exp_ship: 'naval', exp_destroyer: 'naval', exp_cruiser: 'naval', exp_torpedo_boat: 'naval', exp_gun_boat: 'naval',
exp_torpedo_gun_boat: 'naval', exp_submarine_chaser: 'naval', exp_naval_ferry_barge: 'naval',
exp_human: 'human',
};
/** The unitType names conditions use, by the wpcost.blk classes they cover. */
const UNIT_TYPE_CLASSES: Readonly<Record<string, readonly string[]>> = {
aircraft: ['exp_fighter', 'exp_bomber', 'exp_assault'],
typeFighter: ['exp_fighter'],
typeBomber: ['exp_bomber'],
typeStormovik: ['exp_assault'],
typeHelicopter: ['exp_helicopter'],
tank: ['exp_tank', 'exp_heavy_tank', 'exp_tank_destroyer', 'exp_SPAA'],
ship: ['exp_ship', 'exp_destroyer', 'exp_cruiser'],
boat: ['exp_torpedo_boat', 'exp_gun_boat', 'exp_torpedo_gun_boat', 'exp_submarine_chaser', 'exp_naval_ferry_barge'],
human: ['exp_human'],
};
/** A kill or assist of the local player, with what conditions look at. */
interface Action {
readonly time: number;
readonly unit: string;
readonly victim: string;
readonly victimClass: string;
readonly victimIsPlayer: boolean;
}
export function evaluateStreaks(definitions: readonly StreakDefinition[], facts: StreakFacts, ctx: StreakContext): AwardedStreak[] {
const diff = DIFFICULTY_INDEX[ctx.difficulty];
const awarded: AwardedStreak[] = [];
const occurrences = new Map<string, number>();
const award = (def: StreakDefinition, time: number, stageParam: number, stage?: number): void => {
const n = occurrences.get(def.id) ?? 0;
occurrences.set(def.id, n + 1);
const reward = rewardOf(def, stage, diff);
awarded.push({ id: def.id, hidden: def.hidden, ...(stage !== undefined ? { stage } : {}), stageParam, time, ...reward, key: `${def.id}#${n}` });
};
const deaths = facts.lives.filter((life) => life.died).map((life) => life.end);
const kills = actions(facts.events, (e) => KILL_CODES.has(e.code) && !e.friendly);
const assists = actions(facts.events, (e) => e.code === ExpEvent.ASSIST && !e.friendly);
const captures = facts.events.filter((e) => e.code === ExpEvent.CAPTURE_ZONE).map((e) => e.time);
const deferred: StreakDefinition[] = [];
for (const def of definitions) {
const mode = def.mode;
if (!mode || !mode.conditions.every((c) => isSupportedCondition(c))) continue;
if (def.afterFlight && !facts.players) continue;
if (!mode.conditions.every((c) => battleConditionHolds(c, ctx))) continue;
const p = mode.params;
const actionHolds = (a: Action): boolean => mode.conditions.every((c) => actionConditionHolds(c, a, ctx));
switch (mode.type) {
case 'killedPlayersTimed':
chainAwards(def, kills.filter((a) => a.victimIsPlayer && actionHolds(a)), delayOf(p, diff), award);
break;
case 'killedGroundTimed':
chainAwards(def, kills.filter((a) => !a.victimIsPlayer && isGroundTarget(a, p) && actionHolds(a)), delayOf(p, diff), award);
break;
case 'killedPlayers':
countAwards(def, kills.filter((a) => a.victimIsPlayer && actionHolds(a)).map((a) => a.time), mulOf(p, diff), flag(p, 'inRow'), deaths, award);
break;
case 'assistUnits':
case 'assistPlayers':
countAwards(def, assists.filter((a) => a.victimIsPlayer && actionHolds(a)).map((a) => a.time), 1, flag(p, 'inRow'), deaths, award);
break;
case 'assistAir':
countAwards(def, assists.filter((a) => groupOf(a.victimClass) === 'air' && actionHolds(a)).map((a) => a.time), mulOf(p, diff), flag(p, 'inRow'), deaths, award);
break;
case 'captures':
countAwards(def, captures, 1, flag(p, 'inRow'), deaths, award);
break;
case 'missionsWon':
if (facts.outcome === 'win') award(def, facts.sessionEnd, 1);
break;
case 'killStreakNuclearSuccess':
for (const time of facts.nuclearStrikes) award(def, time, 1);
break;
case 'firstKill': {
// Ignore non-player mission units (air defense SAM/AAA, NPCs) whose HUD feed killer id is -1.
const first = facts.feed.find((k) => k.killer >= 0 && k.killerTeam !== k.victimTeam);
if (first && first.killer === facts.localPlayerId) award(def, first.time, 1);
break;
}
case 'killLastOffender':
case 'killLastTeamOffender':
avengeAwards(def, facts, mode.type === 'killLastOffender', award);
break;
case 'killedAirBest':
case 'killedGroundBest':
case 'killedPlayersBest':
case 'assistAirBest':
if (facts.players && mode.conditions.every((c) => bestConditionHolds(c, ctx))) bestAward(def, facts, diff, award);
break;
case 'unlocks':
deferred.push(def);
break;
default:
break;
}
}
for (const def of deferred) {
const listed = (def.mode?.params.unlock ?? []).map(String);
const earned = listed.filter((id) => occurrences.has(id)).length;
if (listed.length > 0 && earned >= (numberParam(def.mode?.params ?? {}, 'num') ?? listed.length)) award(def, facts.sessionEnd, 1);
}
return awarded.sort((a, b) => a.time - b.time);
}
function actions(events: readonly ReportedCombatEvent[], keep: (e: ReportedCombatEvent) => boolean): Action[] {
return events.filter(keep).map((e) => ({
time: e.time, unit: e.unit, victim: e.victim, victimClass: e.expClass, victimIsPlayer: e.victimIsPlayer,
})).sort((a, b) => a.time - b.time);
}
/** Chains of actions each within `delay` seconds of the previous; one award per stage reached. */
function chainAwards(def: StreakDefinition, list: readonly Action[], delay: number, award: AwardFn): void {
let length = 0;
let last = -Infinity;
for (const action of list) {
length = action.time - last <= delay ? length + 1 : 1;
last = action.time;
stageAward(def, length, action.time, award);
}
}
/** A running count (reset by a death when `inRow`); one award per stage or per `num` reached. */
function countAwards(
def: StreakDefinition,
times: readonly number[],
mul: number,
inRow: boolean,
deaths: readonly number[],
award: AwardFn,
): void {
let count = 0;
let deathIndex = 0;
for (const time of times) {
if (inRow) {
while (deathIndex < deaths.length && deaths[deathIndex]! <= time) {
deathIndex++;
count = 0;
}
}
const before = count;
count += mul;
if (def.multiStage) {
for (let reached = Math.floor(before) + 1; reached <= Math.floor(count); reached++) stageAward(def, reached, time, award);
} else {
const num = numOf(def);
if (num > 0 && Math.floor(count / num) > Math.floor(before / num)) award(def, time, num);
}
}
}
/** Multi-stage: stage n at count = stage.param + n. Single-stage: once per `num` reached. */
function stageAward(def: StreakDefinition, count: number, time: number, award: AwardFn): void {
if (def.multiStage) {
const first = def.stage?.param ?? 1;
if (count >= first) award(def, time, count, count - first);
return;
}
const num = numOf(def);
if (num > 0 && count === num) award(def, time, num);
}
function avengeAwards(def: StreakDefinition, facts: StreakFacts, self: boolean, award: AwardFn): void {
let offender: number | undefined;
for (const kill of facts.feed) {
if (kill.killer === facts.localPlayerId && kill.victimTeam !== facts.localTeam && offender !== undefined && kill.victim === offender) {
stageAward(def, 1, kill.time, award);
offender = undefined;
continue;
}
const victimIsOurs = self
? kill.victim === facts.localPlayerId
: kill.victimTeam === facts.localTeam && kill.victim !== facts.localPlayerId;
if (victimIsOurs && kill.killerTeam !== facts.localTeam && kill.killer >= 0) offender = kill.killer;
}
}
/** Scoreboard counter each "Best" mode ranks players by. */
function bestValueOf(def: StreakDefinition, player: ScoreboardPlayer): number {
const mode = def.mode!;
const aiOnly = mode.conditions.some((c) => c.type === 'targetIsPlayer' && c.params.includePlayers?.[0] === false);
const humans = flag(mode.params, 'includeHumans');
switch (mode.type) {
case 'killedAirBest':
return aiOnly ? player.aiKills : player.kills;
case 'killedGroundBest':
if (humans) return player.humanKills;
if (flag(mode.params, 'isShip')) return aiOnly ? player.aiNavalKills : player.navalKills;
return aiOnly ? player.aiGroundKills : player.groundKills;
case 'killedPlayersBest':
return humans ? player.humanKills : player.kills + player.groundKills + player.navalKills + player.humanKills;
default:
return player.assists;
}
}
/** The player with the most of the counter (ties: the higher score) is the local player, within minVal / maxVal. */
function bestAward(def: StreakDefinition, facts: StreakFacts, diff: 0 | 1 | 2, award: AwardFn): void {
const p = def.mode!.params;
const mul = mulOf(p, diff);
const noDeaths = flag(p, 'noDeaths');
const candidates = facts.players!.filter((player) => !noDeaths || player.deaths === 0);
let best: ScoreboardPlayer | undefined;
for (const player of candidates) {
const value = bestValueOf(def, player);
const bestValue = best ? bestValueOf(def, best) : -1;
if (value > bestValue || (value === bestValue && best && player.score > best.score)) best = player;
}
if (!best || best.id !== facts.localPlayerId) return;
const value = bestValueOf(def, best) * mul;
if (value <= 0) return;
const minVal = numberParam(p, 'minVal');
const maxVal = numberParam(p, 'maxVal');
if (minVal !== undefined && value < minVal) return;
if (maxVal !== undefined && value > maxVal) return;
award(def, facts.sessionEnd, 1);
}
type AwardFn = (def: StreakDefinition, time: number, stageParam: number, stage?: number) => void;
/**
* Reward of an award. Single-stage: amount_warpoints / amount_exp. Multi-stage (inferred: the
* formula is server-side): the first stage pays stage.amount_*, each later stage n pays
* wpA + wpB x n (expA + expB x n).
*/
function rewardOf(def: StreakDefinition, stage: number | undefined, diff: 0 | 1 | 2): { wp: number; exp: number } {
if (stage === undefined) return { wp: def.wp[diff], exp: def.exp[diff] };
if (stage === 0 && def.stage) return { wp: def.stage.wp[diff], exp: def.stage.exp[diff] };
return { wp: Math.round(def.wpA[diff] + def.wpB[diff] * stage), exp: Math.round(def.expA[diff] + def.expB[diff] * stage) };
}
function isSupportedCondition(condition: StreakCondition): boolean {
return SATISFIED_CONDITIONS.has(condition.type) || [
'targetIsPlayer', 'missionType', 'missionPostfix', 'targetType', 'offenderType', 'higherBR', 'sameUnitType',
].includes(condition.type);
}
/** Conditions on the battle itself. */
function battleConditionHolds(condition: StreakCondition, ctx: StreakContext): boolean {
const p = condition.params;
switch (condition.type) {
case 'missionType':
return (p.missionType ?? []).includes(ctx.ediff);
case 'missionPostfix': {
const listed = (p.postfix ?? []).some((postfix) => ctx.missionName.endsWith(String(postfix)));
return p.allowed?.[0] === false ? !listed : listed;
}
default:
return true;
}
}
/** Conditions on one kill or assist. */
function actionConditionHolds(condition: StreakCondition, action: Action, ctx: StreakContext): boolean {
const p = condition.params;
switch (condition.type) {
case 'targetIsPlayer':
return action.victimIsPlayer ? p.includePlayers?.[0] !== false : p.includeAI?.[0] === true;
case 'targetType':
return matchesUnitType(action.victimClass, p.unitType ?? []);
case 'offenderType':
return matchesUnitType(ctx.classOf(action.unit) ?? '', p.unitType ?? []);
case 'sameUnitType':
return groupOf(action.victimClass) !== undefined && groupOf(action.victimClass) === groupOf(ctx.classOf(action.unit) ?? '');
case 'higherBR': {
const own = ctx.battleRatingOf(action.unit);
const victim = ctx.battleRatingOf(action.victim);
if (own === undefined || victim === undefined) return false;
const diff = victim - own;
const min = numberParam(p, 'diffBR') ?? 0;
const max = numberParam(p, 'diffBRMax');
return diff >= min - BR_EPSILON && (max === undefined || diff <= max + BR_EPSILON);
}
default:
return true;
}
}
/**
* A "Best" award ranks players by a scoreboard counter, so only conditions the counters reflect
* can hold: the target kind (players / AI, humans) picks the counter (bestValueOf), and the
* offender's type holds when it is the mission's unit type. Per-kill conditions (battle rating
* difference, target or vehicle type of each kill) cannot be checked for other players.
*/
function bestConditionHolds(condition: StreakCondition, ctx: StreakContext): boolean {
switch (condition.type) {
case 'targetIsPlayer':
return true;
case 'targetType':
return (condition.params.unitType ?? []).every((type) => type === 'human');
case 'offenderType':
return (condition.params.unitType ?? []).some((type) => MISSION_UNIT_TYPES[Math.floor(ctx.ediff / 3)]?.includes(String(type)));
case 'higherBR':
case 'sameUnitType':
return false;
default:
return true;
}
}
/** The unitType names of each ediff group (0 air, 1 ground, 2 naval, 3 helicopter). */
const MISSION_UNIT_TYPES: readonly (readonly string[])[] = [['aircraft'], ['tank'], ['ship', 'boat'], ['typeHelicopter']];
function isGroundTarget(action: Action, p: StreakParams): boolean {
const group = groupOf(action.victimClass);
if (flag(p, 'isShip')) return group === 'naval';
return group === 'ground' || (group === 'human' && flag(p, 'includeHumans'));
}
function matchesUnitType(expClass: string, unitTypes: readonly unknown[]): boolean {
return unitTypes.some((type) => UNIT_TYPE_CLASSES[String(type)]?.includes(expClass));
}
function groupOf(expClass: string): Group | undefined {
return CLASS_GROUP[expClass];
}
function delayOf(p: StreakParams, diff: 0 | 1 | 2): number {
const values = (p.delay ?? []).filter((v): v is number => typeof v === 'number');
return values[diff] ?? values[0] ?? 0;
}
/** mulArcade / mulRealistic / mulHardcore of the difficulty; 1 when absent. */
function mulOf(p: StreakParams, diff: 0 | 1 | 2): number {
return numberParam(p, MUL_NAMES[diff]) ?? 1;
}
function numOf(def: StreakDefinition): number {
return numberParam(def.mode?.params ?? {}, 'num') ?? 1;
}
function numberParam(p: StreakParams, name: string): number | undefined {
const value = p[name]?.[0];
return typeof value === 'number' ? value : undefined;
}
function flag(p: StreakParams, name: string): boolean {
return p[name]?.[0] === true;
}
/** ediff of the mission's unit type (unit type x 3 + difficulty, as unlocks.blk "missionType" lists it). */
const EDIFF_BASE: Readonly<Record<UnitClass, number>> = { aircraft: 0, tank: 3, ship: 6, helicopter: 9 };
/** The battle awards of the game data, bound to the vehicles they are judged on. */
export class BattleStreaks {
readonly #definitions: readonly StreakDefinition[];
readonly #vehicles: ReadonlyMap<string, CatalogueVehicle>;
readonly #economy: BattleEconomy;
constructor(definitions: readonly StreakDefinition[], vehicles: readonly CatalogueVehicle[], economy: BattleEconomy) {
this.#definitions = definitions;
this.#vehicles = new Map(vehicles.map((vehicle) => [vehicle.name, vehicle]));
this.#economy = economy;
}
evaluate(facts: StreakFacts, session: Pick<BattleSession, 'difficulty' | 'requiredClass' | 'missionName'>): AwardedStreak[] {
const difficulty = economyDifficulty(session.difficulty);
return evaluateStreaks(this.#definitions, facts, {
difficulty,
ediff: EDIFF_BASE[session.requiredClass] + DIFFICULTY_INDEX[difficulty],
missionName: session.missionName,
classOf: (vehicle) => this.#economy.vehicle(vehicle)?.unitClass,
battleRatingOf: (vehicle) => {
const known = this.#vehicles.get(vehicle);
return known ? vehicleMrank(known, session.difficulty, session.requiredClass) / 3 + 1 : undefined;
},
});
}
}