Files
WT-Offline/apps/server/src/battle/battle-settlement.ts
T
N0VAN0M4LY 429c5eec12 fix(clans): fix squadron timestamps, 20k RP cap, and configurable initial RP
Fix two 1970 squadron timestamps by sending nextRewardDayId as a 64-bit Unix timestamp in seconds and emitting dynamic bi-monthly season fields (clanDuelNextReward, clanSeasonStart, clanSeasonOrdinal, clanSeasonInYear) in clientProfile. Backfill preset normal squadrons to 58-60 deterministic NPC members so the client activity reward cap reaches 20,000, default startingPeriods and startingActivity to 0 in tuning/clans.jsonc, remove the hardcoded 20,000 empty-history fallback, and wire battle RP into squadron activity accumulation and period settlement.
2026-12-04 19:55:04 +08:00

189 lines
9.3 KiB
TypeScript

/**
* 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),
* damages and repairs the battle's vehicles and pays the premium expense compensation
* (battle-repair.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, isAutoRepairEnabled } from '../profile/profile-client-settings.ts';
import { addEarnedSkillPoints } from '../profile/profile-crew-skills.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';
import { ownsModification } from '../profile/profile-modifications.ts';
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 type { RepairMode } from '../game-data/datasets/vehicle-repair.ts';
import type { ModeDifficulty } from '../game-modes/catalogue/game-mode-declaration.ts';
import type { RepairRules } from '../repair/repair-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 { autoRepairVehicles, damageBattleVehicles, expensesCompensation } from './battle-repair.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 { consumeBattleSpares } from './battle-spares.ts';
import { appendStreakLogs } from './battle-streak-log.ts';
import type { BattleStreaks } from './battle-streaks.ts';
import type { BattleSession } from './battle-session-store.ts';
import { wagerBattle } from './battle-wager.ts';
/** Talisman modification name (scripts/airinfo.nut shopIsModificationEnabled(unit, "premExpMul")). */
const TALISMAN = 'premExpMul';
export interface BattleSettlementDeps {
readonly research: ResearchRules;
readonly efficiency: ResearchEfficiency;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
readonly economy: BattleEconomy;
readonly streaks: BattleStreaks;
readonly items: ItemCatalogue;
readonly repair: RepairRules;
/** Optional hook receiving total base (unboosted) vehicle RP earned in the battle. */
readonly onBattleRpEarned?: ((baseVehicleRp: number, nowSec: number) => void) | undefined;
}
const REPAIR_MODE: Readonly<Record<ModeDifficulty, RepairMode>> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' };
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 premiumAccount = remainingPremiumDays(profile, now) > 0;
const rewards = computeBattleRewards(report, deps.economy, {
difficulty,
modeName: session.modeName,
economicName: session.economicName,
premiumAccount,
hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN),
boosters,
});
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),
exp: streaks.reduce((sum, streak) => sum + streak.exp, 0),
};
applyNetSilverLions(profile, rewards.wpTotal + unlocks.wp);
if (rewards.expFree > 0) addFreeResearchPoints(profile, rewards.expFree);
const crewExpMul = deps.economy.data.crewExpMul[difficulty];
for (const vehicle of rewards.vehicles) {
const crew = crewForVehicleInCountry(profile, session.country, vehicle.vehicle);
if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul);
}
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
const vehicleRps = rewards.vehicles.map(vehicleRpOf);
const research = investBattleRp(profile, vehicleRps, {
country: session.country,
requiredClass: session.requiredClass,
difficulty,
nowUnixSec: log.timeSec,
}, deps);
const baseVehicleRp = vehicleRps.reduce((sum, vehicle) => sum + Math.max(0, vehicle.noBonusExp), 0);
if (baseVehicleRp > 0) deps.onBattleRpEarned?.(baseVehicleRp, log.timeSec);
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 damages = damageBattleVehicles(profile, report, REPAIR_MODE[session.difficulty], deps.repair, now);
const autoRepair = isAutoRepairEnabled(profile);
const repairs = autoRepair ? autoRepairVehicles(profile, damages, deps.repair) : [];
const friendlyFirePenalty = rewards.events.reduce((sum, settled) => sum + (settled.priced.row === 'FriendlyKills' ? -settled.priced.wp : 0), 0);
const compensation = premiumAccount && autoRepair && isAutoRefillWeaponsEnabled(profile)
? expensesCompensation(
rewards.wpTotal + unlocks.wp + friendlyFirePenalty,
repairs.reduce((sum, repair) => sum + Math.max(0, repair.cost), 0) + weaponRefillSl,
)
: 0;
if (compensation > 0) addSilverLions(profile, compensation);
const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks, compensation);
const usedSpares = consumeBattleSpares(profile, session, report.spareSpawns, deps.items, deps.research.techTree);
appendStreakLogs(profile, session, streaks);
appendBattleResultLog(profile, session, {
country: session.country.startsWith('country_') ? session.country : `country_${session.country}`,
rewards,
unlocksWp: unlocks.wp,
weaponRefillSl,
usedSpares,
rpItems: mergeEarnedRpItems(research.rpItems),
researchUnits: research.units,
affectedBoosters: boosters.applied.map((booster) => booster.id),
affectedWagers: wager && wagerOutcome ? [wager.id] : [],
damages,
autoRepair,
repairs,
compensation,
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, boosterExp, skillBonusExp: vehicle.skillBonusExp, total: vehicle.expTotal };
}
function applyNetSilverLions(profile: BlkBlock, netDelta: number): void {
if (netDelta > 0) {
addSilverLions(profile, netDelta);
} else if (netDelta < 0) {
const deduction = Math.min(balanceOf(profile).silverLions, -netDelta);
if (deduction > 0) pay(profile, { silverLions: deduction, goldenEagles: 0 });
}
}
function refillOwnedEquipment(profile: BlkBlock, catalogue: EquipmentCatalogue): number {
if (!isAutoRefillWeaponsEnabled(profile)) return 0;
const owned = [...ownedVehicles(profile)].sort((a, b) => a.localeCompare(b));
let totalSpent = 0;
for (const vehicle of owned) {
const eq = catalogue.vehicle(vehicle);
if (eq) totalSpent += stockAndRefillEquipment(profile, eq, true).silverLionsSpent;
}
return totalSpent;
}