Apply boosters and wagers in LocalMP battle settlement
Boosters (rateBooster items) now add to the settled battle as the stock client and the official wiki describe: each booster adds its percent of the base reward; boosters stack per event type and personal / all-allies group with the client's calc_public_boost factors; a battle uses one battle of a booster plus one per spentInSessionTimeMin span, and a booster with R battles left covers the first R spans; kill, ground kill and assist boosters add only to that event and end after their kill count. The debriefing table gets the booster columns, the session log lists affectedBoosters, the research breakdown carries boosterExpTotal, progress is saved and used-up boosters are removed with an EULT_REMOVE_ITEM log. The active wager now moves with each battle that meets its active conditions (lineup rank range, random battle, mission postfix): a stage when its win condition holds (battle won, players killed, or the listed battle awards, hidden ones included), otherwise a failed battle. It ends at maxWins or maxFails and pays a x stake x stages^b + c of the reached stage. Each counted battle logs EULT_CHARD_AWARD in the battle's room and the session log lists affectedWagers, which the stock debriefing shows. Hidden battle awards are now judged (not shown or logged) so wagers can name them; awards of mode missionsWon are supported, and "unlocks" awards honour num. The new GUI patch battle/match-settled-battle-room-logs matches the settled battle's logs by room id in isUserlogVisible, the one filter all "this battle's logs" queries use; it replaces the two per-call edits in use-settled-debriefing-stats. Not yet verified in game.
This commit is contained in:
1 parent
f8735e5ca5
commit
19be0d2443
28 files changed
+734
-79
No files matched your search
@@ -0,0 +1 @@
|
||||
if ((filter?.currentRoomOnly ?? false) && !is_user_log_for_current_room(idx))
|
||||
@@ -0,0 +1 @@
|
||||
function isUserlogVisible(blk, filter, idx) {
|
||||
@@ -0,0 +1,29 @@
|
||||
// Let the debriefing of a settled LocalMP battle find that battle's logs: session result, awards,
|
||||
// research breakdown, boosters and wager.
|
||||
// Why the client: every "this battle's logs" query goes through is_user_log_for_current_room
|
||||
// (aces.exe 2.61.0.37 0x1799d30), which compares with the matching room id or GameSaveData+0x3f370;
|
||||
// a LocalMP host is in no matching room, so nothing matches.
|
||||
// Without it: the debriefing shows no research breakdown, awards, used boosters or wager stage.
|
||||
{
|
||||
"id": "battle/match-settled-battle-room-logs",
|
||||
"title": "Match the logs of a settled LocalMP battle by its room id",
|
||||
"file": "scripts/userlog/userlogutils.nut",
|
||||
"features": [
|
||||
"L-结算页",
|
||||
"G-加成道具",
|
||||
"H-合同 / 赌注"
|
||||
],
|
||||
"verified_on": [
|
||||
"2.61.0.37"
|
||||
],
|
||||
"edits": [
|
||||
{
|
||||
"find": "find.nut",
|
||||
"replace": "replace.nut"
|
||||
},
|
||||
{
|
||||
"find": "find-room-check.nut",
|
||||
"replace": "replace-room-check.nut"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
if ((filter?.currentRoomOnly ?? false) && !isLogOfCurrentRoom(blk, idx))
|
||||
@@ -0,0 +1,9 @@
|
||||
// WTOffline: while the debriefing of a settled LocalMP battle is gathered, nestdb wto.settled names
|
||||
// the battle's room (written by report-local-battle-settlement). The client is in no matching
|
||||
// room, so is_user_log_for_current_room cannot match that room's logs; match them by room id.
|
||||
function isLogOfCurrentRoom(blk, idx) {
|
||||
let settledRoomId = require("nestdb").ndbTryRead(["wto", "settled"])?.roomId
|
||||
return settledRoomId != null ? blk?.roomId == settledRoomId : is_user_log_for_current_room(idx)
|
||||
}
|
||||
|
||||
function isUserlogVisible(blk, filter, idx) {
|
||||
@@ -1 +0,0 @@
|
||||
let resPointsLogs = getUserLogsList({ show = [EULT_SESSION_RESULT], currentRoomOnly = true })?[0].container.researchPoints.unit ?? []
|
||||
@@ -1,5 +0,0 @@
|
||||
roomUserlogs = getUserLogsList({
|
||||
currentRoomOnly = true
|
||||
needStackItems = false
|
||||
disableVisible = true
|
||||
})
|
||||
@@ -1,9 +1,8 @@
|
||||
// Build the debriefing of a settled LocalMP battle from what the local service settled: its
|
||||
// statistics table, its room's logs and their Research Points breakdown.
|
||||
// Build the debriefing of a settled LocalMP battle from the statistics table the local service
|
||||
// settled (its logs are matched by match-settled-battle-room-logs).
|
||||
// Why the client: the debriefing reads stat_get_exp() (aces.exe 0x1053b70, the battle's
|
||||
// SessionStatsNet), which online the battle server fills, and picks the battle's logs with
|
||||
// is_user_log_for_current_room (0x1799d30), which needs a matching room; a LocalMP host has neither.
|
||||
// Without it: the debriefing shows no rewards, awards, activity or research.
|
||||
// SessionStatsNet), which online the battle server fills; a LocalMP host has no battle server.
|
||||
// Without it: the debriefing shows no rewards or activity.
|
||||
{
|
||||
"id": "battle/use-settled-debriefing-stats",
|
||||
"title": "Use the local service's settled battle in the LocalMP debriefing",
|
||||
@@ -19,17 +18,9 @@
|
||||
"find": "find-gather.nut",
|
||||
"replace": "replace-gather.nut"
|
||||
},
|
||||
{
|
||||
"find": "find-room-logs.nut",
|
||||
"replace": "replace-room-logs.nut"
|
||||
},
|
||||
{
|
||||
"find": "find.nut",
|
||||
"replace": "replace.nut"
|
||||
},
|
||||
{
|
||||
"find": "find-research-points.nut",
|
||||
"replace": "replace-research-points.nut"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
function gatherDebriefingResult() {
|
||||
// WTOffline: while a LocalMP battle is being settled, nestdb wto.settled holds what the local
|
||||
// service settled: { exp = the debriefing table, roomId = the battle's room id }
|
||||
// (written by report-local-battle-settlement).
|
||||
// (written by report-local-battle-settlement; the room id is read by match-settled-battle-room-logs).
|
||||
let wtoSettled = require("nestdb").ndbTryRead(["wto", "settled"])
|
||||
let gm = get_game_mode()
|
||||
@@ -1,3 +0,0 @@
|
||||
let resPointsLogs = (wtoSettled != null
|
||||
? debriefingResult.roomUserlogs.findvalue(@(l) l?.type == EULT_SESSION_RESULT)?.container?.researchPoints?.unit
|
||||
: getUserLogsList({ show = [EULT_SESSION_RESULT], currentRoomOnly = true })?[0].container.researchPoints.unit) ?? []
|
||||
@@ -1,9 +0,0 @@
|
||||
// WTOffline: a settled LocalMP battle's logs carry its room id, but the client is not in a
|
||||
// matching room, so is_user_log_for_current_room cannot match them; select them by room id.
|
||||
roomUserlogs = wtoSettled != null
|
||||
? getUserLogsList({ needStackItems = false, disableVisible = true }).filter(@(l) l?.roomId == wtoSettled.roomId)
|
||||
: getUserLogsList({
|
||||
currentRoomOnly = true
|
||||
needStackItems = false
|
||||
disableVisible = true
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* What the player's active boosters (rateBooster items, config/items.blk rateBoosterParams) add
|
||||
* to a battle, and how much of each the battle uses up. Online the server applies them; the
|
||||
* client only shows the result (debriefing column "booster", log affectedBoosters).
|
||||
*
|
||||
* Rules and where they come from:
|
||||
* - A booster adds its percent of the base reward (without premium account or talisman): the
|
||||
* percents of booster, premium account and talisman are added, not multiplied (official wiki
|
||||
* "Boosters" https://wiki.warthunder.com/awards/5028-boosters : "1.42 x (100% + 500% + 50%)").
|
||||
* - Stacking (scripts globals/ranks_common_shared.nut calc_public_boost, used for personal and
|
||||
* "(all allies)" boosters alike; items/boosterEffect.nut getBoostersEffects): boosters are grouped
|
||||
* by event type (none, kill, kill_ground, assist) and by personal / all allies; within a group
|
||||
* the percents, largest first, count x1, x0.6, x0.4, x0.2, then x0.1 (at least 1 point each),
|
||||
* rounded to a whole percent; the groups add up. The wiki's "penalty in order of increasing
|
||||
* bonus" says the same.
|
||||
* - Battles used (stop type sessionsStarted): a battle counts once, and with spentInSessionTimeMin
|
||||
* every such span counts as one more (items/itemsClasses/itemBooster.nut getLeftStopSessions;
|
||||
* wiki: "in a battle that lasted 1 hour and 20 minutes, a booster for 1 battle will only be
|
||||
* effective for the first 30 minutes of the battle ... 3 battles will be deducted"). So a booster
|
||||
* with R battles left covers the first R spans of the battle.
|
||||
* - Event boosters (rateBoosterParams/event kill, kill_ground, assist with targetIsPlayer) add only
|
||||
* to the reward of that event. The event names are the client's expEvent names (ExpEvent.KILL,
|
||||
* KILL_GROUND, ASSIST; inferred). Their stop killedPlayers / killedGround ends them after N kills;
|
||||
* which kills count is inferred: killedPlayers = kills of players, killedGround = kills of ground
|
||||
* vehicles. Event-free boosters add to every reward of the battle, including the mission reward
|
||||
* (lang "for all battle actions and mission reward").
|
||||
* - Not boosted (offline design; nothing official found): battle awards (streaks), the skill bonus.
|
||||
* Other stop types (none in 2.61.0.37) count the battle once.
|
||||
*/
|
||||
import type { BoosterDefinition } from '../game-data/datasets/item-catalogue.ts';
|
||||
import { ExpEvent } from './battle-economy.ts';
|
||||
import type { BattleReport, ReportedCombatEvent } from './battle-report.ts';
|
||||
|
||||
export interface ActiveBooster {
|
||||
readonly uid: string;
|
||||
readonly id: string;
|
||||
readonly booster: BoosterDefinition;
|
||||
/** Stop condition progress before the battle (items/<uid>/progress). */
|
||||
readonly progress: number;
|
||||
}
|
||||
|
||||
export interface BoosterPercent {
|
||||
readonly wp: number;
|
||||
readonly rp: number;
|
||||
}
|
||||
|
||||
export interface BoosterUse {
|
||||
readonly booster: ActiveBooster;
|
||||
/** Stop condition progress after the battle. */
|
||||
readonly progress: number;
|
||||
/** The stop condition is reached: the booster is used up. */
|
||||
readonly finished: boolean;
|
||||
}
|
||||
|
||||
/** Rates the settlement asks for (battle-rewards.ts). */
|
||||
export interface BoosterRates {
|
||||
/** Percents for the reward of one combat event. */
|
||||
forEvent(event: ReportedCombatEvent): BoosterPercent;
|
||||
/** Percents averaged over time spans, for rewards earned over time. */
|
||||
overSpans(spans: readonly { readonly start: number; readonly end: number }[]): BoosterPercent;
|
||||
}
|
||||
|
||||
export const NO_BOOSTER: BoosterPercent = { wp: 0, rp: 0 };
|
||||
|
||||
const STACK_FACTORS = [1.0, 0.6, 0.4, 0.2, 0.1] as const;
|
||||
const EVENT_CODES: Readonly<Record<string, number>> = { kill: ExpEvent.KILL, kill_ground: ExpEvent.KILL_GROUND, assist: ExpEvent.ASSIST };
|
||||
const KILL_CODES: ReadonlySet<number> = new Set([ExpEvent.KILL, ExpEvent.KILL_GROUND, ExpEvent.KILL_HUMAN]);
|
||||
|
||||
/** One booster in one battle: until when it covers, and what it applies to. */
|
||||
interface Coverage {
|
||||
readonly booster: ActiveBooster;
|
||||
/** The event code it is limited to; undefined for every reward. */
|
||||
readonly eventCode?: number;
|
||||
/** An event booster that requires the target to be a player. */
|
||||
readonly playersOnly: boolean;
|
||||
/** Mission time up to which it covers. */
|
||||
readonly end: number;
|
||||
/** The end itself is covered (kill-counted boosters cover the kill that ends them). */
|
||||
readonly endCovered: boolean;
|
||||
readonly used: number;
|
||||
}
|
||||
|
||||
export class BattleBoosters implements BoosterRates {
|
||||
readonly #coverage: readonly Coverage[];
|
||||
|
||||
constructor(boosters: readonly ActiveBooster[], report: Pick<BattleReport, 'sessionStart' | 'sessionEnd' | 'events'>) {
|
||||
this.#coverage = boosters.flatMap((booster) => {
|
||||
const coverage = coverageOf(booster, report);
|
||||
return coverage ? [coverage] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The boosters that took part in the battle (log affectedBoosters). */
|
||||
get applied(): readonly ActiveBooster[] {
|
||||
return this.#coverage.map((coverage) => coverage.booster);
|
||||
}
|
||||
|
||||
/** What the battle used of each booster. */
|
||||
get uses(): readonly BoosterUse[] {
|
||||
return this.#coverage.map(({ booster, used }) => {
|
||||
const progress = booster.progress + used;
|
||||
return { booster, progress, finished: progress >= booster.booster.stop.count };
|
||||
});
|
||||
}
|
||||
|
||||
forEvent(event: ReportedCombatEvent): BoosterPercent {
|
||||
if (event.friendly) return NO_BOOSTER;
|
||||
const active = this.#coverage.filter((coverage) =>
|
||||
covers(coverage, event.time)
|
||||
&& (coverage.eventCode === undefined || (coverage.eventCode === event.code && (!coverage.playersOnly || event.victimIsPlayer))));
|
||||
return percentOf(active);
|
||||
}
|
||||
|
||||
overSpans(spans: readonly { readonly start: number; readonly end: number }[]): BoosterPercent {
|
||||
const general = this.#coverage.filter((coverage) => coverage.eventCode === undefined);
|
||||
let length = 0;
|
||||
let wp = 0;
|
||||
let rp = 0;
|
||||
for (const span of spans) {
|
||||
const cuts = [span.start, ...general.map((c) => c.end).filter((t) => t > span.start && t < span.end), span.end].sort((a, b) => a - b);
|
||||
for (let i = 0; i + 1 < cuts.length; i++) {
|
||||
const from = cuts[i]!;
|
||||
const to = cuts[i + 1]!;
|
||||
if (to <= from) continue;
|
||||
const percent = percentOf(general.filter((c) => covers(c, (from + to) / 2)));
|
||||
length += to - from;
|
||||
wp += percent.wp * (to - from);
|
||||
rp += percent.rp * (to - from);
|
||||
}
|
||||
}
|
||||
return length > 0 ? { wp: wp / length, rp: rp / length } : NO_BOOSTER;
|
||||
}
|
||||
}
|
||||
|
||||
function coverageOf(booster: ActiveBooster, report: Pick<BattleReport, 'sessionStart' | 'sessionEnd' | 'events'>): Coverage | undefined {
|
||||
const def = booster.booster;
|
||||
const left = def.stop.count - booster.progress;
|
||||
if (left <= 0 || (def.wpPercent <= 0 && def.rpPercent <= 0)) return undefined;
|
||||
const eventType = def.event?.type;
|
||||
const eventCode = eventType === undefined ? undefined : EVENT_CODES[eventType];
|
||||
if (eventType !== undefined && eventCode === undefined) return undefined;
|
||||
const playersOnly = def.event?.conditions.some((condition) => condition.type === 'targetIsPlayer') ?? false;
|
||||
const base = { booster, ...(eventCode !== undefined ? { eventCode } : {}), playersOnly };
|
||||
|
||||
if (def.stop.type === 'killedPlayers' || def.stop.type === 'killedGround') {
|
||||
const kills = report.events
|
||||
.filter((e) => !e.friendly && (def.stop.type === 'killedPlayers' ? KILL_CODES.has(e.code) && e.victimIsPlayer : e.code === ExpEvent.KILL_GROUND))
|
||||
.map((e) => e.time)
|
||||
.sort((a, b) => a - b);
|
||||
const last = kills[left - 1];
|
||||
return { ...base, end: last ?? Infinity, endCovered: true, used: Math.min(left, kills.length) };
|
||||
}
|
||||
const duration = Math.max(0, report.sessionEnd - report.sessionStart);
|
||||
if (def.stop.type !== 'sessionsStarted' || def.minutesPerBattle <= 0) {
|
||||
return { ...base, end: Infinity, endCovered: true, used: 1 };
|
||||
}
|
||||
const span = def.minutesPerBattle * 60;
|
||||
return {
|
||||
...base,
|
||||
end: report.sessionStart + left * span,
|
||||
endCovered: false,
|
||||
used: Math.min(left, 1 + Math.floor(duration / span)),
|
||||
};
|
||||
}
|
||||
|
||||
function covers(coverage: Coverage, time: number): boolean {
|
||||
return time < coverage.end || (coverage.endCovered && time === coverage.end);
|
||||
}
|
||||
|
||||
function percentOf(active: readonly Coverage[]): BoosterPercent {
|
||||
const groups = new Map<string, { wp: number[]; rp: number[] }>();
|
||||
for (const { booster, eventCode } of active) {
|
||||
const key = `${eventCode ?? ''}/${booster.booster.personal}`;
|
||||
let group = groups.get(key);
|
||||
if (!group) groups.set(key, group = { wp: [], rp: [] });
|
||||
if (booster.booster.wpPercent > 0) group.wp.push(booster.booster.wpPercent);
|
||||
if (booster.booster.rpPercent > 0) group.rp.push(booster.booster.rpPercent);
|
||||
}
|
||||
let wp = 0;
|
||||
let rp = 0;
|
||||
for (const group of groups.values()) {
|
||||
wp += stacked(group.wp);
|
||||
rp += stacked(group.rp);
|
||||
}
|
||||
return { wp, rp };
|
||||
}
|
||||
|
||||
/** calc_public_boost (= calc_personal_boost) of scripts globals/ranks_common_shared.nut. */
|
||||
export function stacked(percents: readonly number[]): number {
|
||||
const last = STACK_FACTORS[STACK_FACTORS.length - 1]!;
|
||||
let total = 0;
|
||||
[...percents].sort((a, b) => b - a).forEach((percent, i) => {
|
||||
if (i < STACK_FACTORS.length) total += STACK_FACTORS[i]! * percent;
|
||||
else total += last * percent > 1 ? last * percent : 1;
|
||||
});
|
||||
return Math.round(total);
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
* 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 }
|
||||
* num<Row>:i wp<Row>:i exp<Row>:i tbl<Row>{ noBonusWp noBonusExp premAccWp premAccExp premModExp boosterWp boosterExp }
|
||||
* 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
|
||||
@@ -15,7 +15,7 @@
|
||||
* (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';
|
||||
import { emptyRowRewards, type BattleRewards, type RewardRow, type RowRewards } from './battle-rewards.ts';
|
||||
import type { BattleRpResult } from './battle-rp-investment.ts';
|
||||
|
||||
/** STATS_RESULT_* script constants, registered by aces.exe 0x17db810 (SUCCESS 1, FAIL 2). */
|
||||
@@ -34,7 +34,7 @@ export function debriefingTable(name: string, rewards: BattleRewards, research:
|
||||
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 };
|
||||
const sum = rootRows.get(row) ?? emptyRowRewards();
|
||||
for (const key of Object.keys(sum) as (keyof RowRewards)[]) sum[key] += amounts[key];
|
||||
rootRows.set(row, sum);
|
||||
}
|
||||
@@ -44,7 +44,7 @@ export function debriefingTable(name: string, rewards: BattleRewards, research:
|
||||
setParam(root, 'sessionTime', { type: 'real', value: rewards.sessionTime });
|
||||
setParam(root, 'battleTime', { type: 'real', value: rewards.battleTime });
|
||||
if (unlocks.count > 0) {
|
||||
rootRows.set('Unlocks', { count: unlocks.count, noBonusWp: unlocks.wp, noBonusExp: unlocks.exp, premAccWp: 0, premAccExp: 0, premModExp: 0 });
|
||||
rootRows.set('Unlocks', { ...emptyRowRewards(), count: unlocks.count, noBonusWp: unlocks.wp, noBonusExp: unlocks.exp });
|
||||
}
|
||||
writeRows(root, rootRows, rewards.wpTotal + unlocks.wp, rewards.expTotal + unlocks.exp);
|
||||
setParam(root, 'expFree', { type: 'int', value: rewards.expFree });
|
||||
@@ -78,11 +78,11 @@ export function debriefingTable(name: string, rewards: BattleRewards, research:
|
||||
}
|
||||
|
||||
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 };
|
||||
const total: RowRewards = emptyRowRewards();
|
||||
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 });
|
||||
setParam(block, `wp${row}`, { type: 'int', value: amounts.noBonusWp + amounts.premAccWp + amounts.boosterWp });
|
||||
setParam(block, `exp${row}`, { type: 'int', value: amounts.noBonusExp + amounts.premAccExp + amounts.premModExp + amounts.boosterExp });
|
||||
block.blocks.push(rowTable(`tbl${row}`, amounts));
|
||||
for (const key of Object.keys(total) as (keyof RowRewards)[]) total[key] += amounts[key];
|
||||
}
|
||||
@@ -98,5 +98,7 @@ function rowTable(name: string, amounts: RowRewards): BlkBlock {
|
||||
setParam(table, 'premAccWp', { type: 'int', value: amounts.premAccWp });
|
||||
setParam(table, 'premAccExp', { type: 'int', value: amounts.premAccExp });
|
||||
setParam(table, 'premModExp', { type: 'int', value: amounts.premModExp });
|
||||
setParam(table, 'boosterWp', { type: 'int', value: amounts.boosterWp });
|
||||
setParam(table, 'boosterExp', { type: 'int', value: amounts.boosterExp });
|
||||
return table;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* The player's boosters and wager in a battle's settlement, on the profile side: which are active
|
||||
* (profile/profile-items.ts), what the battle used of them and the user logs the client shows.
|
||||
*
|
||||
* Boosters: items/<uid>/progress:i is the stop condition's progress (client reader aces.exe
|
||||
* 2.61.0.37 0x946360; the scripts read invBlk.progress, itemBooster.nut). A used-up booster is
|
||||
* removed with an EULT_REMOVE_ITEM log (reason "consumed", which the client words "Item ... has
|
||||
* been consumed"; inferred that the server uses it for boosters).
|
||||
* Wager: items/<uid>/numWins:i numBattles:i wager:i lastWinRoomId:i64 (reader 0x969c40). Every
|
||||
* counted battle logs EULT_CHARD_AWARD { rewardType id uid numWins numFails [wpEarned goldEarned] }
|
||||
* in the battle's room (debriefingFull.nut getDebriefingActiveWager reads it; userlogData.nut
|
||||
* shows it as a popup); "name" = "<rewardType>Desc", the lang keys userlog/WagerWinDesc ... (inferred).
|
||||
* An ended wager is removed with an EULT_REMOVE_ITEM log { itemType="wager" wpEarned goldEarned }
|
||||
* (userlogviewdata.nut shows its "Award").
|
||||
*/
|
||||
import { setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
||||
import type { WagerDefinition } from '../game-data/datasets/item-catalogue.ts';
|
||||
import type { ItemCatalogue } from '../items/item-catalogue.ts';
|
||||
import { addGoldenEagles, addSilverLions } from '../profile/profile-currency.ts';
|
||||
import { activeUids, itemRecord, ownedItem, removeItem } from '../profile/profile-items.ts';
|
||||
import { addFreeResearchPoints } from '../profile/profile-research-points.ts';
|
||||
import { appendUserLog, EULT_CHARD_AWARD, EULT_REMOVE_ITEM } from '../profile/profile-trophies-log.ts';
|
||||
import { intField } from '../profile/blk-fields.ts';
|
||||
import type { ActiveBooster, BoosterUse } from './battle-boosters.ts';
|
||||
import type { WagerBattleOutcome, WagerState } from './battle-wager.ts';
|
||||
|
||||
export interface LogTarget {
|
||||
readonly timeSec: number;
|
||||
readonly roomId: bigint;
|
||||
}
|
||||
|
||||
export function activeBattleBoosters(profile: BlkBlock, catalogue: ItemCatalogue): ActiveBooster[] {
|
||||
return activeUids(profile, 'itemActiveBoosters').flatMap((uid): ActiveBooster[] => {
|
||||
const owned = ownedItem(profile, uid);
|
||||
const booster = owned && catalogue.item(owned.id)?.booster;
|
||||
const record = itemRecord(profile, uid);
|
||||
if (!owned || !booster || !record) return [];
|
||||
return [{ uid, id: owned.id, booster, progress: intField(record, 'progress') }];
|
||||
});
|
||||
}
|
||||
|
||||
export function recordBoosterUses(profile: BlkBlock, uses: readonly BoosterUse[], log: LogTarget): void {
|
||||
for (const { booster, progress, finished } of uses) {
|
||||
if (finished) {
|
||||
removeItem(profile, booster.uid);
|
||||
appendUserLog(profile, { type: EULT_REMOVE_ITEM, timeSec: log.timeSec, roomId: log.roomId, bodyParams: [
|
||||
str('id', booster.id), str('uid', booster.uid), str('itemType', 'rateBooster'), str('reason', 'consumed'),
|
||||
] });
|
||||
} else {
|
||||
const record = itemRecord(profile, booster.uid);
|
||||
if (record) setParam(record, 'progress', { type: 'int', value: progress });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface ActiveWager {
|
||||
readonly uid: string;
|
||||
readonly id: string;
|
||||
readonly wager: WagerDefinition;
|
||||
readonly state: WagerState;
|
||||
}
|
||||
|
||||
export function activeWager(profile: BlkBlock, catalogue: ItemCatalogue): ActiveWager | undefined {
|
||||
const uid = activeUids(profile, 'itemActiveWagers')[0];
|
||||
const owned = uid === undefined ? undefined : ownedItem(profile, uid);
|
||||
const wager = owned && catalogue.item(owned.id)?.wager;
|
||||
const record = uid === undefined ? undefined : itemRecord(profile, uid);
|
||||
if (!uid || !owned || !wager || !record) return undefined;
|
||||
return {
|
||||
uid,
|
||||
id: owned.id,
|
||||
wager,
|
||||
state: { stake: intField(record, 'wager'), numWins: intField(record, 'numWins'), numBattles: intField(record, 'numBattles') },
|
||||
};
|
||||
}
|
||||
|
||||
/** Writes the battle's wager outcome, pays an ended wager's reward and logs it. */
|
||||
export function recordWagerBattle(profile: BlkBlock, wager: ActiveWager, outcome: WagerBattleOutcome, log: LogTarget): void {
|
||||
const { reward } = outcome;
|
||||
const earned: BlkParam[] = [
|
||||
...(reward.wp ? [int('wpEarned', reward.wp)] : []),
|
||||
...(reward.gold ? [int('goldEarned', reward.gold)] : []),
|
||||
];
|
||||
appendUserLog(profile, { type: EULT_CHARD_AWARD, timeSec: log.timeSec, roomId: log.roomId, bodyParams: [
|
||||
str('rewardType', outcome.result), str('name', `${outcome.result}Desc`), str('id', wager.id), str('uid', wager.uid),
|
||||
int('numWins', outcome.numWins), int('numFails', outcome.numFails), ...earned,
|
||||
] });
|
||||
if (!outcome.ended) {
|
||||
const record = itemRecord(profile, wager.uid);
|
||||
if (!record) return;
|
||||
setParam(record, 'numWins', { type: 'int', value: outcome.numWins });
|
||||
setParam(record, 'numBattles', { type: 'int', value: outcome.numBattles });
|
||||
if (outcome.numWins > wager.state.numWins) setParam(record, 'lastWinRoomId', { type: 'int64', value: log.roomId });
|
||||
return;
|
||||
}
|
||||
if (reward.wp) addSilverLions(profile, reward.wp);
|
||||
if (reward.gold) addGoldenEagles(profile, reward.gold);
|
||||
if (reward.freeRp) addFreeResearchPoints(profile, reward.freeRp);
|
||||
// rpRewardParams: no 2.61.0.37 wager has it, and where such points would go is not known.
|
||||
removeItem(profile, wager.uid);
|
||||
appendUserLog(profile, { type: EULT_REMOVE_ITEM, timeSec: log.timeSec, roomId: log.roomId, bodyParams: [
|
||||
str('id', wager.id), str('uid', wager.uid), str('itemType', 'wager'), str('reason', 'consumed'), ...earned,
|
||||
] });
|
||||
}
|
||||
|
||||
function str(name: string, value: string): BlkParam {
|
||||
return { name, value: { type: 'string', value } };
|
||||
}
|
||||
|
||||
function int(name: string, value: number): BlkParam {
|
||||
return { name, value: { type: 'int', value } };
|
||||
}
|
||||
@@ -185,6 +185,7 @@ export class BattleMatchmaker {
|
||||
economicName: declaration.economicName,
|
||||
difficulty: declaration.difficulty,
|
||||
requiredClass: declaration.requiredClass,
|
||||
randomBattle: declaration.displayType === 'random_battle',
|
||||
missionName: mission.name,
|
||||
missionPath: mission.path,
|
||||
...(missionLocName !== undefined ? { missionLocName } : {}),
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
* 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.
|
||||
* The boosters and wager of the battle: body affectedBoosters{ activeBooster{ itemId:t } ... } and
|
||||
* container.affectedWagers{ itemId:t } (debriefingFull.nut getDebriefingActiveBoosters /
|
||||
* getDebriefingActiveWager, userlogviewdata.nut "used items"); itemId is the items.blk name.
|
||||
*/
|
||||
import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
||||
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
|
||||
@@ -27,10 +30,12 @@ export interface BattleResultSummary {
|
||||
readonly usedSpares: Readonly<Record<string, number>>;
|
||||
readonly rpItems: readonly EarnedRpItem[];
|
||||
readonly researchUnits: readonly ResearchPointsUnit[];
|
||||
readonly affectedBoosters: readonly string[];
|
||||
readonly affectedWagers: readonly string[];
|
||||
readonly debriefing: BlkBlock;
|
||||
}
|
||||
|
||||
const NO_BONUSES: Bonuses = { premAccWp: 0, premAccExp: 0, premModExp: 0 };
|
||||
const NO_BONUSES: Bonuses = { premAccWp: 0, premAccExp: 0, premModExp: 0, boosterWp: 0, boosterExp: 0 };
|
||||
|
||||
/** Container list of each debriefing row's events (getuserlogbattlerewardstable.nut ids). */
|
||||
const CONTAINER_OF_ROW: Readonly<Record<DebriefingRow, string | undefined>> = {
|
||||
@@ -88,6 +93,9 @@ export function appendBattleResultLog(profile: BlkBlock, session: BattleSession,
|
||||
{ name: 'wtoSessionId', value: { type: 'string', value: session.sessionId } },
|
||||
];
|
||||
const bodyBlocks: BlkBlock[] = [buildContainerBlock(summary), summary.debriefing];
|
||||
if (summary.affectedBoosters.length > 0) {
|
||||
bodyBlocks.push({ name: 'affectedBoosters', params: [], blocks: summary.affectedBoosters.map((itemId) => itemIdBlock('activeBooster', itemId)) });
|
||||
}
|
||||
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);
|
||||
@@ -153,7 +161,7 @@ function buildContainerBlock(summary: BattleResultSummary): BlkBlock {
|
||||
push('eventTimedAward', block);
|
||||
}
|
||||
const mission = vehicle.rows.get('Mission');
|
||||
if (mission) missionWp += mission.noBonusWp + mission.premAccWp;
|
||||
if (mission) missionWp += mission.noBonusWp + mission.premAccWp + mission.boosterWp;
|
||||
}
|
||||
for (const [id, events] of lists) container.blocks.push({ name: id, params: [], blocks: events });
|
||||
if (missionWp > 0) setParam(container, 'wpMissionEndAward', { type: 'int', value: missionWp });
|
||||
@@ -169,9 +177,20 @@ function buildContainerBlock(summary: BattleResultSummary): BlkBlock {
|
||||
if (summary.researchUnits.length > 0) {
|
||||
container.blocks.push({ name: 'researchPoints', params: [], blocks: summary.researchUnits.map(researchPointsUnitBlock) });
|
||||
}
|
||||
if (summary.affectedWagers.length > 0) {
|
||||
const wagers = emptyBlock('affectedWagers');
|
||||
for (const itemId of summary.affectedWagers) wagers.params.push({ name: 'itemId', value: { type: 'string', value: itemId } });
|
||||
container.blocks.push(wagers);
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
function itemIdBlock(name: string, itemId: string): BlkBlock {
|
||||
const block = emptyBlock(name);
|
||||
setParam(block, 'itemId', { type: 'string', value: itemId });
|
||||
return block;
|
||||
}
|
||||
|
||||
/**
|
||||
* One `container.researchPoints.unit` entry, the RP breakdown the stock debriefing tooltips show
|
||||
* (debriefingFull.nut ModsTotal / NewNationBonus / UnitTotal; the client sums the parts itself).
|
||||
@@ -183,6 +202,7 @@ function researchPointsUnitBlock(unit: ResearchPointsUnit): BlkBlock {
|
||||
int('noBonusExpTotal', unit.noBonusExpTotal);
|
||||
int('premAccExpTotal', unit.premAccExpTotal);
|
||||
int('premModExpTotal', unit.premModExpTotal);
|
||||
int('boosterExpTotal', unit.boosterExpTotal);
|
||||
int('expSkillBonus', unit.expSkillBonus);
|
||||
if (unit.invModuleName) setParam(block, 'invModuleName', { type: 'string', value: unit.invModuleName });
|
||||
int('invModuleExp', unit.invModuleExp);
|
||||
@@ -209,6 +229,8 @@ function writeAmounts(block: BlkBlock, wp: number, exp: number, bonuses: Bonuses
|
||||
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 });
|
||||
if (bonuses.boosterWp) setParam(block, 'wpBooster', { type: 'int', value: bonuses.boosterWp });
|
||||
if (bonuses.boosterExp) setParam(block, 'expBooster', { type: 'int', value: bonuses.boosterExp });
|
||||
}
|
||||
|
||||
function buildSpareBlock(usedSpares: Readonly<Record<string, number>>): BlkBlock | undefined {
|
||||
|
||||
@@ -15,12 +15,16 @@
|
||||
* - 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).
|
||||
* - Boosters: + the stacked booster percent of each row's base reward (battle-boosters.ts): per
|
||||
* event for combat events, averaged over the vehicle's lives for time rows, and for the mission
|
||||
* reward the share its other rows were boosted with.
|
||||
* - 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 { NO_BOOSTER, type BoosterPercent, type BoosterRates } from './battle-boosters.ts';
|
||||
import { BattleEconomy, ExpEvent, type DebriefingRow, type PricedEvent } from './battle-economy.ts';
|
||||
import type { BattleReport, ReportedCombatEvent } from './battle-report.ts';
|
||||
|
||||
@@ -33,6 +37,12 @@ export interface RowRewards {
|
||||
premAccWp: number;
|
||||
premAccExp: number;
|
||||
premModExp: number;
|
||||
boosterWp: number;
|
||||
boosterExp: number;
|
||||
}
|
||||
|
||||
export function emptyRowRewards(): RowRewards {
|
||||
return { count: 0, noBonusWp: 0, noBonusExp: 0, premAccWp: 0, premAccExp: 0, premModExp: 0, boosterWp: 0, boosterExp: 0 };
|
||||
}
|
||||
|
||||
export interface VehicleRewards {
|
||||
@@ -49,6 +59,8 @@ export interface Bonuses {
|
||||
readonly premAccWp: number;
|
||||
readonly premAccExp: number;
|
||||
readonly premModExp: number;
|
||||
readonly boosterWp: number;
|
||||
readonly boosterExp: number;
|
||||
}
|
||||
|
||||
export interface SettledEvent {
|
||||
@@ -77,6 +89,8 @@ export interface RewardContext {
|
||||
readonly premiumAccount: boolean;
|
||||
/** Premium vehicle (costGold or premPackAir) or talisman installed. */
|
||||
readonly hasTalisman: (vehicle: string) => boolean;
|
||||
/** The player's active boosters in this battle. */
|
||||
readonly boosters: BoosterRates;
|
||||
}
|
||||
|
||||
export function computeBattleRewards(report: BattleReport, economy: BattleEconomy, ctx: RewardContext): BattleRewards {
|
||||
@@ -91,24 +105,28 @@ export function computeBattleRewards(report: BattleReport, economy: BattleEconom
|
||||
const activity = sessionTime > 0 ? Math.min(1, battleTime / sessionTime) : 0;
|
||||
|
||||
const { data, multipliers } = economy;
|
||||
const bonusesOf = (vehicle: string, wp: number, exp: number): Bonuses => ({
|
||||
const bonusesOf = (vehicle: string, wp: number, exp: number, booster: BoosterPercent): 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,
|
||||
boosterWp: Math.max(0, Math.round(wp * booster.wp / 100)),
|
||||
boosterExp: Math.max(0, Math.round(exp * booster.rp / 100)),
|
||||
});
|
||||
const rowsByVehicle = new Map<string, Map<RewardRow, RowRewards>>();
|
||||
const add = (vehicle: string, row: RewardRow, count: number, wp: number, exp: number): Bonuses => {
|
||||
const add = (vehicle: string, row: RewardRow, count: number, wp: number, exp: number, booster: BoosterPercent): 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);
|
||||
if (!amounts) rows.set(row, amounts = emptyRowRewards());
|
||||
const bonuses = bonusesOf(vehicle, wp, exp, booster);
|
||||
amounts.count += count;
|
||||
amounts.noBonusWp += wp;
|
||||
amounts.noBonusExp += exp;
|
||||
amounts.premAccWp += bonuses.premAccWp;
|
||||
amounts.premAccExp += bonuses.premAccExp;
|
||||
amounts.premModExp += bonuses.premModExp;
|
||||
amounts.boosterWp += bonuses.boosterWp;
|
||||
amounts.boosterExp += bonuses.boosterExp;
|
||||
return bonuses;
|
||||
};
|
||||
for (const vehicle of timeByVehicle.keys()) rowsByVehicle.set(vehicle, new Map());
|
||||
@@ -117,23 +135,26 @@ export function computeBattleRewards(report: BattleReport, economy: BattleEconom
|
||||
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) });
|
||||
events.push({ event, priced, bonuses: add(event.unit, priced.row, priced.count, priced.wp, priced.exp, ctx.boosters.forEvent(event)) });
|
||||
}
|
||||
|
||||
for (const [vehicle, seconds] of timeByVehicle) {
|
||||
const veh = economy.vehicle(vehicle)!;
|
||||
const minutes = seconds / 60;
|
||||
const booster = ctx.boosters.overSpans(report.lives.filter((life) => life.unit === vehicle));
|
||||
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);
|
||||
if (timeWp > 0 || timeRp > 0) add(vehicle, 'BattleTime', Math.round(seconds), timeWp, timeRp, booster);
|
||||
const timedWp = Math.round(veh.timedAward[ctx.difficulty] * minutes * multipliers.silverLions);
|
||||
if (timedWp > 0) add(vehicle, 'TimedAward', 1, timedWp, 0);
|
||||
if (timedWp > 0) add(vehicle, 'TimedAward', 1, timedWp, 0, booster);
|
||||
}
|
||||
for (const [vehicle, rows] of rowsByVehicle) {
|
||||
const earned = [...rows.values()].reduce((sum, amounts) => sum + Math.max(0, amounts.noBonusWp), 0);
|
||||
const boosted = [...rows.values()].reduce((sum, amounts) => sum + amounts.boosterWp, 0);
|
||||
const missionWp = Math.round(earned * (win ? data.winK : data.defeatK));
|
||||
if (missionWp > 0) add(vehicle, 'Mission', 1, missionWp, 0);
|
||||
const missionBooster = earned > 0 ? { wp: boosted / earned * 100, rp: 0 } : NO_BOOSTER;
|
||||
if (missionWp > 0) add(vehicle, 'Mission', 1, missionWp, 0, missionBooster);
|
||||
}
|
||||
|
||||
const { level: skillBonusLevel, percent: skillBonusPercent } = skillBonus(report.events, economy, ctx.economicName);
|
||||
@@ -143,9 +164,9 @@ export function computeBattleRewards(report: BattleReport, economy: BattleEconom
|
||||
let baseExp = 0;
|
||||
let expTotal = 0;
|
||||
for (const amounts of rows.values()) {
|
||||
wpTotal += amounts.noBonusWp + amounts.premAccWp;
|
||||
wpTotal += amounts.noBonusWp + amounts.premAccWp + amounts.boosterWp;
|
||||
baseExp += amounts.noBonusExp;
|
||||
expTotal += amounts.noBonusExp + amounts.premAccExp + amounts.premModExp;
|
||||
expTotal += amounts.noBonusExp + amounts.premAccExp + amounts.premModExp + amounts.boosterExp;
|
||||
}
|
||||
const skillBonusExp = Math.round(baseExp * skillBonusPercent / 100);
|
||||
expTotal += skillBonusExp;
|
||||
|
||||
@@ -69,8 +69,9 @@ export interface VehicleRp {
|
||||
readonly noBonusExp: number;
|
||||
readonly premAccExp: number;
|
||||
readonly premModExp: number;
|
||||
readonly boosterExp: number;
|
||||
readonly skillBonusExp: number;
|
||||
/** The sum of the four. */
|
||||
/** The sum of the five. */
|
||||
readonly total: number;
|
||||
}
|
||||
|
||||
@@ -87,6 +88,7 @@ export interface ResearchPointsUnit {
|
||||
readonly noBonusExpTotal: number;
|
||||
readonly premAccExpTotal: number;
|
||||
readonly premModExpTotal: number;
|
||||
readonly boosterExpTotal: number;
|
||||
readonly expSkillBonus: number;
|
||||
readonly invModuleName?: string;
|
||||
/** RP that reached the modification. */
|
||||
@@ -188,6 +190,7 @@ function vehicleResearchShare(
|
||||
noBonusExpTotal: rp.noBonusExp,
|
||||
premAccExpTotal: rp.premAccExp,
|
||||
premModExpTotal: rp.premModExp,
|
||||
boosterExpTotal: rp.boosterExp,
|
||||
expSkillBonus: rp.skillBonusExp,
|
||||
invUnitExp: 0,
|
||||
};
|
||||
|
||||
@@ -17,6 +17,8 @@ export interface BattleSession {
|
||||
readonly economicName: string;
|
||||
readonly difficulty: ModeDifficulty;
|
||||
readonly requiredClass: UnitClass;
|
||||
/** A random battle (the mode's displayType random_battle), as opposed to an event. */
|
||||
readonly randomBattle: boolean;
|
||||
readonly missionName: string;
|
||||
readonly missionPath: string;
|
||||
readonly missionLocName?: string;
|
||||
@@ -32,6 +34,7 @@ export interface NewBattleSession {
|
||||
readonly economicName: string;
|
||||
readonly difficulty: ModeDifficulty;
|
||||
readonly requiredClass: UnitClass;
|
||||
readonly randomBattle: boolean;
|
||||
readonly missionName: string;
|
||||
readonly missionPath: string;
|
||||
readonly missionLocName?: string;
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
/**
|
||||
* 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.
|
||||
* Post-battle settlement (`cln_wto_finish_battle`): prices the reported battle with the player's
|
||||
* active boosters (battle-rewards.ts, battle-boosters.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, uses up boosters, moves the wager (battle-wager.ts, battle-items.ts),
|
||||
* 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 type { ItemCatalogue } from '../items/item-catalogue.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 { crewForVehicleInCountry, crewVehiclesOfCountry } 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';
|
||||
@@ -19,15 +21,18 @@ import { addFreeResearchPoints } from '../profile/profile-research-points.ts';
|
||||
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
||||
import type { ResearchEfficiency } from '../research/research-efficiency.ts';
|
||||
import type { ResearchRules } from '../research/research-rules.ts';
|
||||
import { BattleBoosters } from './battle-boosters.ts';
|
||||
import { debriefingTable } from './battle-debriefing.ts';
|
||||
import { economyDifficulty, type BattleEconomy } from './battle-economy.ts';
|
||||
import type { BattleReport } from './battle-report.ts';
|
||||
import { activeBattleBoosters, activeWager, recordBoosterUses, recordWagerBattle } from './battle-items.ts';
|
||||
import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts';
|
||||
import { computeBattleRewards, type VehicleRewards } from './battle-rewards.ts';
|
||||
import { investBattleRp, type VehicleRp } from './battle-rp-investment.ts';
|
||||
import { appendStreakLogs } from './battle-streak-log.ts';
|
||||
import type { BattleStreaks } from './battle-streaks.ts';
|
||||
import type { BattleSession } from './battle-session-store.ts';
|
||||
import { wagerBattle } from './battle-wager.ts';
|
||||
|
||||
/** Talisman modification name (scripts/airinfo.nut shopIsModificationEnabled(unit, "premExpMul")). */
|
||||
const TALISMAN = 'premExpMul';
|
||||
@@ -39,19 +44,24 @@ export interface BattleSettlementDeps {
|
||||
readonly crew: CrewSkillCatalogue;
|
||||
readonly economy: BattleEconomy;
|
||||
readonly streaks: BattleStreaks;
|
||||
readonly items: ItemCatalogue;
|
||||
}
|
||||
|
||||
export function settleBattle(profile: BlkBlock, report: BattleReport, session: BattleSession, deps: BattleSettlementDeps): void {
|
||||
const difficulty = economyDifficulty(session.difficulty);
|
||||
const now = serverTimeNow();
|
||||
const log = { timeSec: serverTimeToUnixSeconds(now), roomId: session.roomId };
|
||||
const boosters = new BattleBoosters(activeBattleBoosters(profile, deps.items), report);
|
||||
const rewards = computeBattleRewards(report, deps.economy, {
|
||||
difficulty,
|
||||
economicName: session.economicName,
|
||||
premiumAccount: remainingPremiumDays(profile, now) > 0,
|
||||
hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN),
|
||||
boosters,
|
||||
});
|
||||
|
||||
const streaks = deps.streaks.evaluate(report, session);
|
||||
const allStreaks = deps.streaks.evaluate(report, session);
|
||||
const streaks = allStreaks.filter((streak) => !streak.hidden);
|
||||
const unlocks = {
|
||||
count: streaks.length,
|
||||
wp: streaks.reduce((sum, streak) => sum + streak.wp, 0),
|
||||
@@ -69,8 +79,23 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
|
||||
country: session.country,
|
||||
requiredClass: session.requiredClass,
|
||||
difficulty,
|
||||
nowUnixSec: serverTimeToUnixSeconds(now),
|
||||
nowUnixSec: log.timeSec,
|
||||
}, deps);
|
||||
recordBoosterUses(profile, boosters.uses, log);
|
||||
const wager = activeWager(profile, deps.items);
|
||||
const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, {
|
||||
won: rewards.win,
|
||||
events: report.events,
|
||||
awards: countById(allStreaks),
|
||||
difficulty,
|
||||
missionName: session.missionName,
|
||||
randomBattle: session.randomBattle,
|
||||
lineupRanks: crewVehiclesOfCountry(profile, session.country).flatMap((vehicle) => {
|
||||
const rank = deps.research.techTree.vehicle(vehicle)?.rank;
|
||||
return rank === undefined ? [] : [rank];
|
||||
}),
|
||||
});
|
||||
if (wager && wagerOutcome) recordWagerBattle(profile, wager, wagerOutcome, log);
|
||||
const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks);
|
||||
appendStreakLogs(profile, session, streaks);
|
||||
appendBattleResultLog(profile, session, {
|
||||
@@ -81,20 +106,30 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
|
||||
usedSpares: report.usedSpares,
|
||||
rpItems: mergeEarnedRpItems(research.rpItems),
|
||||
researchUnits: research.units,
|
||||
affectedBoosters: boosters.applied.map((booster) => booster.id),
|
||||
affectedWagers: wager && wagerOutcome ? [wager.id] : [],
|
||||
debriefing,
|
||||
});
|
||||
}
|
||||
|
||||
function countById(streaks: readonly { readonly id: string }[]): Map<string, number> {
|
||||
const counts = new Map<string, number>();
|
||||
for (const streak of streaks) counts.set(streak.id, (counts.get(streak.id) ?? 0) + 1);
|
||||
return counts;
|
||||
}
|
||||
|
||||
function vehicleRpOf(vehicle: VehicleRewards): VehicleRp {
|
||||
let noBonusExp = 0;
|
||||
let premAccExp = 0;
|
||||
let premModExp = 0;
|
||||
let boosterExp = 0;
|
||||
for (const amounts of vehicle.rows.values()) {
|
||||
noBonusExp += amounts.noBonusExp;
|
||||
premAccExp += amounts.premAccExp;
|
||||
premModExp += amounts.premModExp;
|
||||
boosterExp += amounts.boosterExp;
|
||||
}
|
||||
return { vehicle: vehicle.vehicle, noBonusExp, premAccExp, premModExp, skillBonusExp: vehicle.skillBonusExp, total: vehicle.expTotal };
|
||||
return { vehicle: vehicle.vehicle, noBonusExp, premAccExp, premModExp, boosterExp, skillBonusExp: vehicle.skillBonusExp, total: vehicle.expTotal };
|
||||
}
|
||||
|
||||
function applyNetSilverLions(profile: BlkBlock, netDelta: number): void {
|
||||
|
||||
@@ -15,12 +15,14 @@
|
||||
* 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 all listed awards earned in the battle
|
||||
* unlocks `num` of the listed awards earned in the battle (all when
|
||||
* num is missing, as scripts unlocksConditions.nut counts)
|
||||
* Not supported (the facts are not reported): finalBlow, lastManStanding, killWithoutHit,
|
||||
* hitWithoutDeath, killWithoutMiss, landings, scout / repair / extinguish help, squad awards,
|
||||
* kill-streak support vehicles, shell interception, specified naval damage, event missions; and
|
||||
@@ -37,7 +39,7 @@ import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.t
|
||||
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, FeedKill, ReportedCombatEvent, ScoreboardPlayer } from './battle-report.ts';
|
||||
import type { BattleLife, BattleOutcomeKind, FeedKill, ReportedCombatEvent, ScoreboardPlayer } from './battle-report.ts';
|
||||
import type { BattleSession } from './battle-session-store.ts';
|
||||
|
||||
export interface StreakFacts {
|
||||
@@ -48,6 +50,8 @@ export interface StreakFacts {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -64,6 +68,8 @@ export interface StreakContext {
|
||||
|
||||
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. */
|
||||
@@ -122,7 +128,7 @@ export function evaluateStreaks(definitions: readonly StreakDefinition[], facts:
|
||||
const n = occurrences.get(def.id) ?? 0;
|
||||
occurrences.set(def.id, n + 1);
|
||||
const reward = rewardOf(def, stage, diff);
|
||||
awarded.push({ id: def.id, ...(stage !== undefined ? { stage } : {}), stageParam, time, ...reward, key: `${def.id}#${n}` });
|
||||
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);
|
||||
@@ -158,6 +164,9 @@ export function evaluateStreaks(definitions: readonly StreakDefinition[], facts:
|
||||
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 'firstKill': {
|
||||
const first = facts.feed.find((k) => k.killerTeam !== k.victimTeam);
|
||||
if (first && first.killer === facts.localPlayerId) award(def, first.time, 1);
|
||||
@@ -181,8 +190,9 @@ export function evaluateStreaks(definitions: readonly StreakDefinition[], facts:
|
||||
}
|
||||
}
|
||||
for (const def of deferred) {
|
||||
const needed = (def.mode?.params.unlock ?? []).map(String);
|
||||
if (needed.length > 0 && needed.every((id) => occurrences.has(id))) award(def, facts.sessionEnd, 1);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* How one battle moves the player's wager (wager items, config/items.blk wagerParams; started by
|
||||
* cln_set_current_wager, items/item-activation.ts). Pure: the settlement writes the result
|
||||
* (battle-items.ts). Online the server does this; the client shows the stage (EULT_CHARD_AWARD
|
||||
* WagerStageWin / WagerStageFail / WagerWin / WagerFail) and the stake table.
|
||||
*
|
||||
* - A battle counts when wagerParams/active holds. Its mode maxUnitsRankOnStartMission means, as the
|
||||
* client describes it (scripts unlocks/unlocksConditions.nut), that at least one crew-slot vehicle
|
||||
* has rank >= minRank and none has rank > maxRank. Conditions: "online" holds (a LocalMP battle
|
||||
* stands in for an online one, offline design); eventMode is_event:b=no holds in random battles;
|
||||
* missionPostfix as for battle awards; "inSquad" never holds (no squads offline); unknown ones do not.
|
||||
* - A counted battle completes a stage when wagerParams/win holds in it ("The above conditions must
|
||||
* be fulfilled within a single battle"): missionsWon = the battle is won; killedPlayersScore =
|
||||
* kills of players x mulArcade / mulRealistic / mulHardcore >= num; unlocks = at least num
|
||||
* (all when num is missing, as the client counts it) of the listed battle awards, hidden ones
|
||||
* included. Otherwise it is a failed battle ("Battles in which a new stage was not achieved").
|
||||
* - The wager ends at maxWins stages (WagerWin) or maxFails failed battles (WagerFail). Either way
|
||||
* it pays the reward of the stages reached (community descriptions; the official text is not
|
||||
* found): the winParams reward with the highest param <= stages, each kind a x stake x stages^b + c
|
||||
* (itemWager.nut getRewardValueByNumWins). The stake is not returned.
|
||||
*/
|
||||
import type { WagerDefinition, WagerRewardKind } from '../game-data/datasets/item-catalogue.ts';
|
||||
import type { StreakCondition } from '../game-data/datasets/battle-streaks.ts';
|
||||
import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts';
|
||||
import { ExpEvent } from './battle-economy.ts';
|
||||
import type { ReportedCombatEvent } from './battle-report.ts';
|
||||
|
||||
export type WagerStageResult = 'WagerStageWin' | 'WagerStageFail' | 'WagerWin' | 'WagerFail';
|
||||
|
||||
export interface WagerBattleFacts {
|
||||
readonly won: boolean;
|
||||
readonly events: readonly ReportedCombatEvent[];
|
||||
/** Ids of the battle awards earned, hidden ones included. */
|
||||
readonly awards: ReadonlyMap<string, number>;
|
||||
readonly difficulty: EconomyDifficulty;
|
||||
readonly missionName: string;
|
||||
readonly randomBattle: boolean;
|
||||
/** Ranks of the vehicles in the battle country's crew slots. */
|
||||
readonly lineupRanks: readonly number[];
|
||||
}
|
||||
|
||||
export interface WagerState {
|
||||
readonly stake: number;
|
||||
readonly numWins: number;
|
||||
readonly numBattles: number;
|
||||
}
|
||||
|
||||
export interface WagerBattleOutcome {
|
||||
readonly result: WagerStageResult;
|
||||
readonly numWins: number;
|
||||
readonly numBattles: number;
|
||||
readonly numFails: number;
|
||||
readonly ended: boolean;
|
||||
/** Paid when the wager ended. */
|
||||
readonly reward: Readonly<Partial<Record<WagerRewardKind, number>>>;
|
||||
}
|
||||
|
||||
const KILL_CODES: ReadonlySet<number> = new Set([ExpEvent.KILL, ExpEvent.KILL_GROUND, ExpEvent.KILL_HUMAN]);
|
||||
const MUL_NAMES: Readonly<Record<EconomyDifficulty, string>> = { arcade: 'mulArcade', historical: 'mulRealistic', simulation: 'mulHardcore' };
|
||||
|
||||
/** Undefined when the battle does not count for the wager. */
|
||||
export function wagerBattle(def: WagerDefinition, state: WagerState, facts: WagerBattleFacts): WagerBattleOutcome | undefined {
|
||||
if (!isCounted(def, facts)) return undefined;
|
||||
const stageWon = isStageWon(def, facts);
|
||||
const numWins = state.numWins + (stageWon ? 1 : 0);
|
||||
const numBattles = state.numBattles + 1;
|
||||
const numFails = numBattles - numWins;
|
||||
const won = def.maxWins > 0 && numWins >= def.maxWins;
|
||||
const failed = !won && def.maxFails > 0 && numFails >= def.maxFails;
|
||||
const ended = won || failed;
|
||||
return {
|
||||
result: won ? 'WagerWin' : failed ? 'WagerFail' : stageWon ? 'WagerStageWin' : 'WagerStageFail',
|
||||
numWins,
|
||||
numBattles,
|
||||
numFails,
|
||||
ended,
|
||||
reward: ended ? wagerReward(def, numWins, state.stake) : {},
|
||||
};
|
||||
}
|
||||
|
||||
export function wagerReward(def: WagerDefinition, stages: number, stake: number): Partial<Record<WagerRewardKind, number>> {
|
||||
const entry = [...def.rewards].reverse().find((reward) => reward.stage <= stages);
|
||||
if (!entry || stages < 1) return {};
|
||||
const out: Partial<Record<WagerRewardKind, number>> = {};
|
||||
for (const [kind, terms] of Object.entries(entry.terms) as [WagerRewardKind, readonly [number, number, number]][]) {
|
||||
const [a, b, c] = terms;
|
||||
const value = Math.round(a * stake * stages ** b + c);
|
||||
if (value > 0) out[kind] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isCounted(def: WagerDefinition, facts: WagerBattleFacts): boolean {
|
||||
const active = def.active;
|
||||
if (!active) return true;
|
||||
if (active.type === 'maxUnitsRankOnStartMission') {
|
||||
const minRank = numberParam(active.params, 'minRank') ?? 0;
|
||||
const maxRank = numberParam(active.params, 'maxRank');
|
||||
if (facts.lineupRanks.length === 0) return false;
|
||||
if (maxRank !== undefined && Math.max(...facts.lineupRanks) > maxRank) return false;
|
||||
if (!facts.lineupRanks.some((rank) => rank >= minRank)) return false;
|
||||
} else if (active.type !== '') {
|
||||
return false;
|
||||
}
|
||||
return active.conditions.every((condition) => conditionHolds(condition, facts));
|
||||
}
|
||||
|
||||
function conditionHolds(condition: StreakCondition, facts: WagerBattleFacts): boolean {
|
||||
const p = condition.params;
|
||||
switch (condition.type) {
|
||||
case 'online':
|
||||
return true;
|
||||
case 'eventMode':
|
||||
if ((p.event_name ?? []).length > 0 || p.for_clans_only?.[0] === true) return false;
|
||||
return p.is_event?.[0] === false ? facts.randomBattle : !facts.randomBattle;
|
||||
case 'missionPostfix': {
|
||||
const listed = (p.postfix ?? []).some((postfix) => facts.missionName.endsWith(String(postfix)));
|
||||
return p.allowed?.[0] === false ? !listed : listed;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isStageWon(def: WagerDefinition, facts: WagerBattleFacts): boolean {
|
||||
const win = def.win;
|
||||
if (!win) return false;
|
||||
const p = win.params;
|
||||
switch (win.type) {
|
||||
case 'missionsWon':
|
||||
return facts.won;
|
||||
case 'killedPlayersScore': {
|
||||
const kills = facts.events.filter((e) => KILL_CODES.has(e.code) && e.victimIsPlayer && !e.friendly).length;
|
||||
return kills * (numberParam(p, MUL_NAMES[facts.difficulty]) ?? 1) >= (numberParam(p, 'num') ?? 1);
|
||||
}
|
||||
case 'unlocks': {
|
||||
const listed = (p.unlock ?? []).map(String);
|
||||
const earned = listed.filter((id) => (facts.awards.get(id) ?? 0) > 0).length;
|
||||
return listed.length > 0 && earned >= (numberParam(p, 'num') ?? listed.length);
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function numberParam(p: Readonly<Record<string, readonly unknown[]>>, name: string): number | undefined {
|
||||
const value = p[name]?.[0];
|
||||
return typeof value === 'number' ? value : undefined;
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-set
|
||||
import type { BattleEconomy } from '../../battle/battle-economy.ts';
|
||||
import type { BattleStreaks } from '../../battle/battle-streaks.ts';
|
||||
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
|
||||
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
|
||||
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
|
||||
import { clientProfile } from '../../profile/client-profile.ts';
|
||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||
@@ -31,6 +32,7 @@ export interface FinishBattleContext {
|
||||
readonly research: ResearchRules;
|
||||
readonly equipment: EquipmentCatalogue;
|
||||
readonly crew: CrewSkillCatalogue;
|
||||
readonly items: ItemCatalogue;
|
||||
}
|
||||
|
||||
export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler {
|
||||
@@ -41,6 +43,7 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
|
||||
crew: ctx.crew,
|
||||
economy: battle.economy,
|
||||
streaks: battle.streaks,
|
||||
items: ctx.items,
|
||||
};
|
||||
return (context) => withAccount(context, ctx.accounts, (account) => {
|
||||
const report = context.payload && parseBattleReport(context.payload);
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
* }
|
||||
*
|
||||
* Three-value parameters (p3 / ip3) are per difficulty: arcade, realistic, simulator. Hidden
|
||||
* awards are left out: the stock client does not show them (scripts/unlocks isUnlockVisible).
|
||||
* awards are kept and flagged: the stock client does not show them (scripts/unlocks
|
||||
* isUnlockVisible), but wagers name some of them as win conditions (hidden_win_streak ...).
|
||||
* Online the battle server evaluates these definitions; battle/battle-streaks.ts does it offline.
|
||||
*/
|
||||
import type { BlkBlock, BlkValue } from '@wto/blk';
|
||||
@@ -35,6 +36,7 @@ export type PerDifficulty = readonly [number, number, number];
|
||||
|
||||
export interface StreakDefinition {
|
||||
readonly id: string;
|
||||
readonly hidden: boolean;
|
||||
readonly afterFlight: boolean;
|
||||
readonly multiStage: boolean;
|
||||
readonly wp: PerDifficulty;
|
||||
@@ -49,19 +51,20 @@ export interface StreakDefinition {
|
||||
|
||||
export const battleStreaks: Dataset<readonly StreakDefinition[]> = {
|
||||
id: 'battle-streaks',
|
||||
version: 1,
|
||||
version: 2,
|
||||
extract: (source) => source.readBlk('char.vromfs.bin', 'config/unlocks.blk').blocks
|
||||
.filter((block) => block.name === 'unlockable')
|
||||
.flatMap((block): StreakDefinition[] => {
|
||||
const params = paramsOf(block);
|
||||
const id = params.id?.[0];
|
||||
if (params.type?.[0] !== 'streak' || typeof id !== 'string' || params.hidden?.[0] === true) return [];
|
||||
if (params.type?.[0] !== 'streak' || typeof id !== 'string') return [];
|
||||
const stage = block.blocks.find((child) => child.name === 'stage');
|
||||
const stageParams = stage && paramsOf(stage);
|
||||
const stageParam = stageParams?.param?.[0];
|
||||
const mode = block.blocks.find((child) => child.name === 'mode');
|
||||
return [{
|
||||
id,
|
||||
hidden: params.hidden?.[0] === true,
|
||||
afterFlight: params.isAfterFlight?.[0] === true,
|
||||
multiStage: params.isMultiStage?.[0] === true,
|
||||
wp: perDifficulty(params.amount_warpoints),
|
||||
@@ -73,12 +76,13 @@ export const battleStreaks: Dataset<readonly StreakDefinition[]> = {
|
||||
wpB: perDifficulty(params.wpB),
|
||||
expA: perDifficulty(params.expA),
|
||||
expB: perDifficulty(params.expB),
|
||||
...(mode ? { mode: modeOf(mode) } : {}),
|
||||
...(mode ? { mode: unlockModeOf(mode) } : {}),
|
||||
}];
|
||||
}),
|
||||
};
|
||||
|
||||
function modeOf(block: BlkBlock): StreakMode {
|
||||
/** An unlock mode block: its type, parameters and condition{} children (also used by wagers). */
|
||||
export function unlockModeOf(block: BlkBlock): StreakMode {
|
||||
const params = paramsOf(block);
|
||||
return {
|
||||
type: String(params.type?.[0] ?? ''),
|
||||
|
||||
@@ -12,11 +12,23 @@
|
||||
* expiredAt:t absolute end, "YYYY-MM-DD hh:mm:ss" UTC
|
||||
* canPacked:b the pieces stack under one uid
|
||||
* universalSpareParams{ numSpares:i country:t... unitType:t... minRank:i maxRank:i }
|
||||
* wagerParams{ minWager:i maxWager:i wagerStep:i goldWager:b ... }
|
||||
* rateBoosterParams{ wpRate:i xpRate:i percent added to the battle's Silver Lions / Research Points
|
||||
* personal:b no: "(all allies)" booster; missing = personal
|
||||
* spentInSessionTimeMin:i each such span of one battle counts as one more battle
|
||||
* event{ type:t condition{...} } only rewards of this event (kill, kill_ground, assist)
|
||||
* stop{ type:t num:i } ends after num sessionsStarted / killedPlayers / killedGround
|
||||
* }
|
||||
* wagerParams{ minWager:i maxWager:i wagerStep:i goldWager:b maxWins:i maxFails:i
|
||||
* win{ <unlock mode> } what one battle must achieve to complete a stage
|
||||
* active{ <unlock mode> condition{...} } which battles count at all
|
||||
* winParams{ reward{ param:i <type>RewardParams:p3 } ... } wpRewardParams, goldRewardParams,
|
||||
* rpRewardParams, freeRpRewardParams: (a, b, c)
|
||||
* }
|
||||
* personalDiscountsParams{ purchasesMaxCount:i discountsDesc{ <category>{ <key>:i aircrafts{ <vehicle>:i } } } }
|
||||
* }
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import { findParam, type BlkBlock } from '@wto/blk';
|
||||
import { unlockModeOf, type StreakMode } from './battle-streaks.ts';
|
||||
import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts';
|
||||
import type { Dataset } from './dataset.ts';
|
||||
|
||||
@@ -32,11 +44,38 @@ export interface SpareConditions {
|
||||
readonly maxRank?: number;
|
||||
}
|
||||
|
||||
export interface WagerLimits {
|
||||
export interface BoosterDefinition {
|
||||
readonly wpPercent: number;
|
||||
readonly rpPercent: number;
|
||||
/** False for the "(all allies)" boosters. */
|
||||
readonly personal: boolean;
|
||||
/** spentInSessionTimeMin; 0 when a battle counts once however long it lasts. */
|
||||
readonly minutesPerBattle: number;
|
||||
/** rateBoosterParams/event: the booster only adds to the rewards of this event. */
|
||||
readonly event?: StreakMode;
|
||||
readonly stop: { readonly type: string; readonly count: number };
|
||||
}
|
||||
|
||||
export type WagerRewardKind = 'rp' | 'freeRp' | 'wp' | 'gold';
|
||||
export type WagerRewardTerms = readonly [a: number, b: number, c: number];
|
||||
|
||||
export interface WagerReward {
|
||||
/** The stage (number of won battles) from which this reward applies. */
|
||||
readonly stage: number;
|
||||
readonly terms: Readonly<Partial<Record<WagerRewardKind, WagerRewardTerms>>>;
|
||||
}
|
||||
|
||||
export interface WagerDefinition {
|
||||
readonly minStake: number;
|
||||
readonly maxStake: number;
|
||||
readonly stakeStep: number;
|
||||
readonly goldenEagles: boolean;
|
||||
readonly maxWins: number;
|
||||
readonly maxFails: number;
|
||||
readonly win?: StreakMode;
|
||||
readonly active?: StreakMode;
|
||||
/** Sorted by stage. */
|
||||
readonly rewards: readonly WagerReward[];
|
||||
}
|
||||
|
||||
/** One category of a discount description: percentages by key, and by vehicle under "aircrafts". */
|
||||
@@ -64,7 +103,8 @@ export interface ItemDefinition {
|
||||
readonly expiresAt?: number;
|
||||
readonly stacks: boolean;
|
||||
readonly spare?: SpareConditions;
|
||||
readonly wager?: WagerLimits;
|
||||
readonly booster?: BoosterDefinition;
|
||||
readonly wager?: WagerDefinition;
|
||||
readonly discount?: DiscountDefinition;
|
||||
/** External inventory craft-part itemdef id granted on recycling (299000..299004; implementation notes). */
|
||||
readonly recycleItemResult?: number;
|
||||
@@ -72,7 +112,7 @@ export interface ItemDefinition {
|
||||
|
||||
export const itemCatalogue: Dataset<readonly ItemDefinition[]> = {
|
||||
id: 'item-catalogue',
|
||||
version: 2,
|
||||
version: 3,
|
||||
extract: (source) => source.readBlk('char.vromfs.bin', ITEMS).blocks.flatMap(itemOf),
|
||||
};
|
||||
|
||||
@@ -85,6 +125,7 @@ function itemOf(entry: BlkBlock): ItemDefinition[] {
|
||||
const purchaseFeature = stringField(entry, 'purchase_feature');
|
||||
const recycleItemResult = positive(numberField(entry, 'recycleItemResult'));
|
||||
const spare = spareOf(blockAt(entry, 'universalSpareParams'));
|
||||
const booster = boosterOf(blockAt(entry, 'rateBoosterParams'));
|
||||
const wager = wagerOf(blockAt(entry, 'wagerParams'));
|
||||
const discount = discountOf(blockAt(entry, 'personalDiscountsParams'));
|
||||
return [{
|
||||
@@ -100,6 +141,7 @@ function itemOf(entry: BlkBlock): ItemDefinition[] {
|
||||
...(expiresAt !== undefined ? { expiresAt } : {}),
|
||||
...(recycleItemResult !== undefined ? { recycleItemResult } : {}),
|
||||
...(spare ? { spare } : {}),
|
||||
...(booster ? { booster } : {}),
|
||||
...(wager ? { wager } : {}),
|
||||
...(discount ? { discount } : {}),
|
||||
}];
|
||||
@@ -118,13 +160,47 @@ function spareOf(params: BlkBlock | undefined): SpareConditions | undefined {
|
||||
};
|
||||
}
|
||||
|
||||
function wagerOf(params: BlkBlock | undefined): WagerLimits | undefined {
|
||||
function boosterOf(params: BlkBlock | undefined): BoosterDefinition | undefined {
|
||||
if (!params) return undefined;
|
||||
const event = blockAt(params, 'event');
|
||||
const stop = blockAt(params, 'stop');
|
||||
return {
|
||||
wpPercent: Math.max(0, numberField(params, 'wpRate') ?? 0),
|
||||
rpPercent: Math.max(0, numberField(params, 'xpRate') ?? 0),
|
||||
personal: boolField(params, 'personal') ?? true,
|
||||
minutesPerBattle: Math.max(0, numberField(params, 'spentInSessionTimeMin') ?? 0),
|
||||
...(event ? { event: unlockModeOf(event) } : {}),
|
||||
stop: { type: stringField(stop, 'type') ?? 'sessionsStarted', count: Math.max(1, numberField(stop, 'num') ?? 1) },
|
||||
};
|
||||
}
|
||||
|
||||
const REWARD_KINDS: Readonly<Record<string, WagerRewardKind>> = {
|
||||
rpRewardParams: 'rp', freeRpRewardParams: 'freeRp', wpRewardParams: 'wp', goldRewardParams: 'gold',
|
||||
};
|
||||
|
||||
function wagerOf(params: BlkBlock | undefined): WagerDefinition | undefined {
|
||||
if (!params) return undefined;
|
||||
const win = blockAt(params, 'win');
|
||||
const active = blockAt(params, 'active');
|
||||
const rewards = (blockAt(params, 'winParams')?.blocks ?? []).filter((block) => block.name === 'reward').flatMap((reward): WagerReward[] => {
|
||||
const stage = numberField(reward, 'param') ?? 0;
|
||||
const terms: Partial<Record<WagerRewardKind, WagerRewardTerms>> = {};
|
||||
for (const [name, kind] of Object.entries(REWARD_KINDS)) {
|
||||
const value = findParam(reward, name)?.value;
|
||||
if (value?.type === 'point3' && value.value.some((part) => part !== 0)) terms[kind] = [value.value[0], value.value[1], value.value[2]];
|
||||
}
|
||||
return stage > 0 && Object.keys(terms).length > 0 ? [{ stage, terms }] : [];
|
||||
}).sort((a, b) => a.stage - b.stage);
|
||||
return {
|
||||
minStake: Math.max(0, numberField(params, 'minWager') ?? 0),
|
||||
maxStake: Math.max(0, numberField(params, 'maxWager') ?? 0),
|
||||
stakeStep: Math.max(1, numberField(params, 'wagerStep') ?? 1),
|
||||
goldenEagles: boolField(params, 'goldWager') ?? false,
|
||||
maxWins: Math.max(0, numberField(params, 'maxWins') ?? 0),
|
||||
maxFails: Math.max(0, numberField(params, 'maxFails') ?? 0),
|
||||
...(win ? { win: unlockModeOf(win) } : {}),
|
||||
...(active ? { active: unlockModeOf(active) } : {}),
|
||||
rewards,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* cln_set_current_booster name:t (scripts items/itemsClasses/itemBooster.nut)
|
||||
* Any number of boosters can be active (the scripts only warn that stacking lowers their
|
||||
* effect). What they do in battle belongs to the battle phase.
|
||||
* effect). What they do in battle: battle/battle-boosters.ts.
|
||||
* cln_set_current_personal_discount name:t (itemDiscount.nut)
|
||||
* The item's lifetime after activation (expiredTimeHAfterActivation) starts now. The
|
||||
* discount itself applies to purchases (items/personal-discounts.ts).
|
||||
@@ -12,7 +12,7 @@
|
||||
* otherwise; it must be minWager, or (when maxWager is set) a minWager + k x wagerStep
|
||||
* up to maxWager, as the scripts' stake slider offers. Only one contract runs: starting
|
||||
* another replaces it, and the replaced one is gone (the scripts ask the player first,
|
||||
* msgbox/conflictingWager). Counting wins and paying out belongs to the battle phase.
|
||||
* msgbox/conflictingWager). Counting stages and paying out: battle/battle-wager.ts.
|
||||
*/
|
||||
import { setParam, type BlkBlock } from '@wto/blk';
|
||||
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
|
||||
|
||||
@@ -38,7 +38,7 @@ export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string,
|
||||
localTeam: int(p.localTeam, 0),
|
||||
sessionEnd: Math.max(0, ...log.lives.map((life) => life.end), ...log.events.map((e) => e.time)),
|
||||
}, session);
|
||||
const fresh = awarded.filter((streak) => !log.announced.has(streak.key));
|
||||
const fresh = awarded.filter((streak) => !streak.hidden && !log.announced.has(streak.key));
|
||||
for (const streak of fresh) log.announced.add(streak.key);
|
||||
return {
|
||||
streaks: fresh.map((streak) => ({
|
||||
|
||||
@@ -17,6 +17,9 @@ export const EULT_SESSION_RESULT = 2;
|
||||
const EULT_BUYENTITLEMENT = 13;
|
||||
export const EULT_OPEN_TROPHY = 30;
|
||||
export const EULT_BUY_TROPHY = 20;
|
||||
// Registered by the client at 0x1a558ba / 0x1a55ad6 (2.61.0.37).
|
||||
export const EULT_CHARD_AWARD = 25;
|
||||
export const EULT_REMOVE_ITEM = 37;
|
||||
|
||||
export function trophyOpenCount(profile: BlkBlock, trophyId: string): number {
|
||||
const trophies = findBlock(profile, TROPHIES);
|
||||
|
||||
Reference in new issue
Block a user