diff --git a/packages/local-service/src/battle/battle-debriefing.ts b/packages/local-service/src/battle/battle-debriefing.ts index d0bfdc6..41e2792 100644 --- a/packages/local-service/src/battle/battle-debriefing.ts +++ b/packages/local-service/src/battle/battle-debriefing.ts @@ -29,7 +29,11 @@ export interface UnlockRewards { readonly exp: number; } -export function debriefingTable(name: string, rewards: BattleRewards, research: BattleRpResult, unlocks: UnlockRewards): BlkBlock { +/** + * `compensation`: the premium account's expense compensation, the root-only row + * "ExpensesCompensation" (debriefingFull.nut). + */ +export function debriefingTable(name: string, rewards: BattleRewards, research: BattleRpResult, unlocks: UnlockRewards, compensation: number): BlkBlock { const root = emptyBlock(name); const rootRows = new Map(); for (const vehicle of rewards.vehicles) { @@ -46,7 +50,8 @@ export function debriefingTable(name: string, rewards: BattleRewards, research: if (unlocks.count > 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); + if (compensation > 0) rootRows.set('ExpensesCompensation', { ...emptyRowRewards(), count: 1, noBonusWp: compensation }); + writeRows(root, rootRows, rewards.wpTotal + unlocks.wp + compensation, rewards.expTotal + unlocks.exp); setParam(root, 'expFree', { type: 'int', value: rewards.expFree }); setParam(root, 'expSkillBonusTotal', { type: 'int', value: rewards.vehicles.reduce((sum, v) => sum + v.skillBonusExp, 0) }); setParam(root, 'expSkillBonusLevel', { type: 'int', value: rewards.skillBonusLevel }); diff --git a/packages/local-service/src/battle/battle-repair.ts b/packages/local-service/src/battle/battle-repair.ts new file mode 100644 index 0000000..cae3be8 --- /dev/null +++ b/packages/local-service/src/battle/battle-repair.ts @@ -0,0 +1,115 @@ +/** + * Vehicle damage, automatic repair and premium expense compensation of a settled battle. Online + * the server does this; the client shows the result in the battle log (userlogviewdata.nut: + * aircrafts{:r=hp} below 1 lists it as damaged, container.aircraftsRepaired{aname + * cost} the automatic repair (a negative cost: not enough Silver Lions), autoRepairWasOn, + * container.wpExpensesCompensation) and in the hangar (repair cost and time from hp). + * + * Rules (official "Following the Roadmap: Sons of Attila", 2023-09-19, Changes to Silver Lion + * mechanics; "Compensation of Battle Expenses, Free Backups and More", 2023-07-25): + * - A destroyed vehicle costs a per-minute share of its lifetime (repairCostPerMin), at most + * the full repair cost of the stat card. Whole minutes started (inferred: "calculated per + * minute"). + * - Leaving a vehicle by yourself costs the full repair cost, however long it lived. A life that + * ended without the vehicle being destroyed before the battle ended, or in a battle the player + * left, counts as that (inferred). A vehicle still alive at the end costs nothing (inferred). + * - Destroyed by an ally (the HUD kill log names a teammate as the killer): no repair cost. + * - Several lives of one vehicle add up, at most the full cost (offline design). + * - The cost becomes damage: hp = 1 - cost / full cost, so that the client's own repair cost + * (1 - hp) x full cost (repair/repair-rules.ts) is that cost. + * - "Automatically repair all vehicles after the battle" (autoRepairAircrafts, on by default, + * aces.exe 0x90b6a0) repairs the vehicles damaged in the battle when the Silver Lions suffice. + * - Premium account insurance: with automatic repair and automatic ammunition purchase on, when + * the repair and ammunition expenses exceed what the battle earned (friendly fire penalties + * not counted), the difference is paid back. + */ +import type { BlkBlock } from '@wto/blk'; +import type { RepairMode } from '../game-data/datasets/vehicle-repair.ts'; +import { canAfford, pay } from '../profile/profile-currency.ts'; +import { clearVehicleDamage, setVehicleDamage, vehicleCondition } from '../profile/profile-vehicle-condition.ts'; +import type { ServerTime } from '../profile/server-time.ts'; +import { gameModeIndexOf, type RepairRules } from '../repair/repair-rules.ts'; +import type { BattleReport } from './battle-report.ts'; + +/** Seconds between a death and its kill log entry that still match (both come from the same frame in practice). */ +const KILL_LOG_TOLERANCE_SEC = 2; +/** A life ending this close to the battle's end ended with the battle. */ +const BATTLE_END_TOLERANCE_SEC = 1; + +export interface VehicleDamage { + readonly vehicle: string; + /** Condition after the battle, before any repair. */ + readonly hp: number; +} + +export interface AutoRepair { + readonly vehicle: string; + /** Paid; negative when the player could not pay it and the vehicle stays damaged. */ + readonly cost: number; +} + +/** Damages the vehicles of the battle; returns each vehicle's condition after it. */ +export function damageBattleVehicles( + profile: BlkBlock, + report: BattleReport, + mode: RepairMode, + rules: RepairRules, + now: ServerTime, +): VehicleDamage[] { + const costs = new Map(); + for (const life of report.lives) { + costs.set(life.unit, (costs.get(life.unit) ?? 0) + lifeCost(profile, report, life, mode, rules)); + } + const damages: VehicleDamage[] = []; + for (const [vehicle, cost] of costs) { + const full = rules.fullCost(profile, vehicle, mode); + const before = vehicleCondition(profile, vehicle)?.hp ?? 1; + const hp = full > 0 ? Math.max(0, before - Math.min(full, cost) / full) : before; + if (hp < before) setVehicleDamage(profile, vehicle, hp, gameModeIndexOf(mode), now); + damages.push({ vehicle, hp }); + } + return damages; +} + +function lifeCost(profile: BlkBlock, report: BattleReport, life: BattleReport['lives'][number], mode: RepairMode, rules: RepairRules): number { + const full = rules.fullCost(profile, life.unit, mode); + if (full <= 0) return 0; + if (!life.died) { + const endedWithBattle = report.outcome !== 'running' && life.end >= report.sessionEnd - BATTLE_END_TOLERANCE_SEC; + return endedWithBattle ? 0 : full; + } + if (killedByAlly(report, life.end)) return 0; + const minutes = Math.max(1, Math.ceil((life.end - life.start) / 60)); + return Math.min(full, Math.round(rules.costPerMinute(profile, life.unit, mode) * minutes)); +} + +function killedByAlly(report: BattleReport, time: number): boolean { + return report.feed.some((kill) => + kill.victim === report.localPlayerId + && kill.killer >= 0 && kill.killer !== report.localPlayerId + && kill.killerTeam === report.localTeam + && Math.abs(kill.time - time) <= KILL_LOG_TOLERANCE_SEC); +} + +/** Pays the repair of each damaged vehicle of the battle the player can afford, in name order. */ +export function autoRepairVehicles(profile: BlkBlock, damages: readonly VehicleDamage[], rules: RepairRules): AutoRepair[] { + const repairs: AutoRepair[] = []; + for (const { vehicle } of [...damages].sort((a, b) => a.vehicle.localeCompare(b.vehicle))) { + const cost = rules.currentCost(profile, vehicle); + if (cost <= 0) continue; + const price = { silverLions: cost, goldenEagles: 0 }; + if (canAfford(profile, price)) { + pay(profile, price); + clearVehicleDamage(profile, vehicle); + repairs.push({ vehicle, cost }); + } else { + repairs.push({ vehicle, cost: -cost }); + } + } + return repairs; +} + +/** The premium account's compensation of the battle's expenses. */ +export function expensesCompensation(earnedWithoutPenalties: number, expenses: number): number { + return Math.max(0, Math.round(expenses - Math.max(0, earnedWithoutPenalties))); +} diff --git a/packages/local-service/src/battle/battle-result-log.ts b/packages/local-service/src/battle/battle-result-log.ts index 07d90bd..0a44101 100644 --- a/packages/local-service/src/battle/battle-result-log.ts +++ b/packages/local-service/src/battle/battle-result-log.ts @@ -5,6 +5,9 @@ * 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. + * Repair (battle-repair.ts): aircrafts{ :r= }, autoRepairWasOn:b, + * container.aircraftsRepaired{ aname:t cost:i } and container.wpExpensesCompensation:i + * (userlogviewdata.nut "damaged vehicles", "automatic repair", "expenses compensation"). */ import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts'; @@ -12,6 +15,7 @@ import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.t import type { DebriefingRow } from './battle-economy.ts'; import type { BattleRewards, Bonuses } from './battle-rewards.ts'; import type { ResearchPointsUnit } from './battle-rp-investment.ts'; +import type { AutoRepair, VehicleDamage } from './battle-repair.ts'; import type { BattleSession } from './battle-session-store.ts'; export interface EarnedRpItem { @@ -32,6 +36,10 @@ export interface BattleResultSummary { readonly researchUnits: readonly ResearchPointsUnit[]; readonly affectedBoosters: readonly string[]; readonly affectedWagers: readonly string[]; + readonly damages: readonly VehicleDamage[]; + readonly autoRepair: boolean; + readonly repairs: readonly AutoRepair[]; + readonly compensation: number; readonly debriefing: BlkBlock; } @@ -89,6 +97,7 @@ export function appendBattleResultLog(profile: BlkBlock, session: BattleSession, { name: 'wpEarned', value: { type: 'int', value: rewards.wpTotal + summary.unlocksWp } }, { name: 'xpEarned', value: { type: 'int', value: rewards.expTotal } }, { name: 'activity', value: { type: 'real', value: rewards.activity } }, + { name: 'autoRepairWasOn', value: { type: 'bool', value: summary.autoRepair } }, ...(friendlyFirePenalty !== 0 ? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: friendlyFirePenalty } }] : []), { name: 'wtoSessionId', value: { type: 'string', value: session.sessionId } }, ]; @@ -97,7 +106,8 @@ export function appendBattleResultLog(profile: BlkBlock, session: BattleSession, 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 }); + const hpAfter = new Map(summary.damages.map((damage) => [damage.vehicle, damage.hp])); + for (const vehicle of rewards.vehicles) setParam(aircrafts, vehicle.vehicle, { type: 'real', value: hpAfter.get(vehicle.vehicle) ?? 1.0 }); if (aircrafts.params.length > 0) bodyBlocks.push(aircrafts); const spare = buildSpareBlock(summary.usedSpares); if (spare) bodyBlocks.push(spare); @@ -177,6 +187,15 @@ function buildContainerBlock(summary: BattleResultSummary): BlkBlock { if (summary.researchUnits.length > 0) { container.blocks.push({ name: 'researchPoints', params: [], blocks: summary.researchUnits.map(researchPointsUnitBlock) }); } + if (summary.repairs.length > 0) { + const repaired = emptyBlock('aircraftsRepaired'); + summary.repairs.forEach((repair, index) => { + setParam(repaired, `aname${index}`, { type: 'string', value: repair.vehicle }); + setParam(repaired, `cost${index}`, { type: 'int', value: repair.cost }); + }); + container.blocks.push(repaired); + } + if (summary.compensation > 0) setParam(container, 'wpExpensesCompensation', { type: 'int', value: summary.compensation }); 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 } }); diff --git a/packages/local-service/src/battle/battle-rewards.ts b/packages/local-service/src/battle/battle-rewards.ts index 6af3cb8..52469d4 100644 --- a/packages/local-service/src/battle/battle-rewards.ts +++ b/packages/local-service/src/battle/battle-rewards.ts @@ -28,7 +28,7 @@ import { NO_BOOSTER, type BoosterPercent, type BoosterRates } from './battle-boo import { BattleEconomy, ExpEvent, type DebriefingRow, type PricedEvent } from './battle-economy.ts'; import type { BattleReport, ReportedCombatEvent } from './battle-report.ts'; -export type RewardRow = DebriefingRow | 'BattleTime' | 'TimedAward' | 'Mission' | 'Unlocks'; +export type RewardRow = DebriefingRow | 'BattleTime' | 'TimedAward' | 'Mission' | 'Unlocks' | 'ExpensesCompensation'; export interface RowRewards { count: number; diff --git a/packages/local-service/src/battle/battle-settlement.ts b/packages/local-service/src/battle/battle-settlement.ts index 86a3830..4c93951 100644 --- a/packages/local-service/src/battle/battle-settlement.ts +++ b/packages/local-service/src/battle/battle-settlement.ts @@ -3,14 +3,16 @@ * 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. + * 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 } from '../profile/profile-client-settings.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'; @@ -21,11 +23,15 @@ 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'; @@ -45,17 +51,21 @@ export interface BattleSettlementDeps { readonly economy: BattleEconomy; readonly streaks: BattleStreaks; readonly items: ItemCatalogue; + readonly repair: RepairRules; } +const REPAIR_MODE: Readonly> = { 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, economicName: session.economicName, - premiumAccount: remainingPremiumDays(profile, now) > 0, + premiumAccount, hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN), boosters, }); @@ -96,7 +106,20 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B }), }); if (wager && wagerOutcome) recordWagerBattle(profile, wager, wagerOutcome, log); - const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks); + + 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); appendStreakLogs(profile, session, streaks); appendBattleResultLog(profile, session, { country: session.country.startsWith('country_') ? session.country : `country_${session.country}`, @@ -108,6 +131,10 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B researchUnits: research.units, affectedBoosters: boosters.applied.map((booster) => booster.id), affectedWagers: wager && wagerOutcome ? [wager.id] : [], + damages, + autoRepair, + repairs, + compensation, debriefing, }); } diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index 150193d..08779a5 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -71,6 +71,7 @@ import { buyNotResearchedClanUnitAction, flushClanExpToUnitAction, setResearchCl import { setStartingInfo } from './starting-info-actions.ts'; import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts'; import { buyUnlockAction } from './unlock-actions.ts'; +import type { RepairRules } from '../../repair/repair-rules.ts'; import { finishBattleAction, type BattleActionDependencies } from './battle-actions.ts'; import { hangarMiscActionEntries } from './hangar-misc-actions.ts'; @@ -88,6 +89,7 @@ export interface ActionDependencies { readonly decor: DecorShop; readonly unlocks: UnlockShop; readonly items: ItemCatalogue; + readonly repair: RepairRules; readonly store: StoreCatalogue; readonly inventory: InventoryCatalogue; readonly trophies: TrophyCatalogue; @@ -127,7 +129,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH ['cln_move_exp_to_module', moveExpToModuleAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_buy_aircraft', buyAircraft(deps.profiles, deps.accounts, deps.research)], ['cln_buy_slot', buySlot(deps.profiles, deps.accounts, deps.research)], - ['cln_get_price_ex', priceEx({ techTree, equipment: deps.equipment, decor: deps.decor, crew: deps.crew, unlocks: deps.unlocks, items: deps.items, trophies: deps.trophies })], + ['cln_get_price_ex', priceEx({ techTree, equipment: deps.equipment, decor: deps.decor, crew: deps.crew, unlocks: deps.unlocks, items: deps.items, trophies: deps.trophies, repair: deps.repair })], ['cln_buy_modification', buyModificationAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_buy_all_modification', buyAllModificationsAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_buy_spare_aircrafts', buySparesAction(deps.profiles, deps.accounts, deps.equipment)], diff --git a/packages/local-service/src/char/actions/battle-actions.ts b/packages/local-service/src/char/actions/battle-actions.ts index 0de289d..1f25550 100644 --- a/packages/local-service/src/char/actions/battle-actions.ts +++ b/packages/local-service/src/char/actions/battle-actions.ts @@ -15,6 +15,7 @@ import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { ResearchEfficiency } from '../../research/research-efficiency.ts'; +import type { RepairRules } from '../../repair/repair-rules.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; import type { CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; @@ -33,6 +34,7 @@ export interface FinishBattleContext { readonly equipment: EquipmentCatalogue; readonly crew: CrewSkillCatalogue; readonly items: ItemCatalogue; + readonly repair: RepairRules; } export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler { @@ -44,6 +46,7 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio economy: battle.economy, streaks: battle.streaks, items: ctx.items, + repair: ctx.repair, }; return (context) => withAccount(context, ctx.accounts, (account) => { const report = context.payload && parseBattleReport(context.payload); diff --git a/packages/local-service/src/char/actions/hangar-misc-actions.ts b/packages/local-service/src/char/actions/hangar-misc-actions.ts index 73f2ed8..a60e577 100644 --- a/packages/local-service/src/char/actions/hangar-misc-actions.ts +++ b/packages/local-service/src/char/actions/hangar-misc-actions.ts @@ -11,6 +11,8 @@ * - cln_prepare_aircraft (scripts/unit/unitActions.nut:147 job 13; 0x29a610 job 7) * - cln_repair_all (shop_repair_all 0x29a370, job type 7) * - cln_repair_all_in_slots (shop_repair_all 0x29a370, job type 7) + * The repair requests carry no price (0x29a370 sends country, 0x29a610 name and weapon): the + * repair costs what the client shows for it (repair/repair-rules.ts currentCost). * - cln_add_to_wish_list (scripts/wishlist/wishlistManager.nut:39, job type 13) * - cln_remove_from_wish_list (scripts/wishlist/wishlistManager.nut:48, job type 13) */ @@ -30,6 +32,8 @@ import { type WishlistLimits, } from '../../profile/profile-wishlist.ts'; import { serverTimeNow, serverTimeToUnixSeconds } from '../../profile/server-time.ts'; +import { clearVehicleDamage, isDamaged } from '../../profile/profile-vehicle-condition.ts'; +import type { RepairRules } from '../../repair/repair-rules.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../../research/rule-outcome.ts'; import type { TechTree } from '../../research/tech-tree.ts'; @@ -39,7 +43,6 @@ import { headerOrPayloadBool, headerOrPayloadInt, headerOrPayloadString, - realParam, } from './payload-params.ts'; export type ActionEntry = [string, CharActionHandler]; @@ -48,24 +51,24 @@ export interface HangarMiscActionDependencies { readonly profiles: PlayerProfiles; readonly accounts: AccountStore; readonly research: ResearchRules; + readonly repair: RepairRules; readonly wishlistLimits?: WishlistLimits; } const HANGAR_BLOCK = 'hangar'; const ALL_COUNTRIES = 'all'; const WISHLIST_UNIT_TYPE = 'unit'; -const FULL_VEHICLE_HP = 1.0; export function hangarMiscActionEntries(deps: HangarMiscActionDependencies): ActionEntry[] { - const { profiles, accounts, research } = deps; + const { profiles, accounts, research, repair } = deps; const { techTree } = research; const limits = deps.wishlistLimits ?? DEFAULT_WISHLIST_LIMITS; return [ ['cln_set_dest_rp_unit_type', setDestRpUnitTypeAction(profiles, accounts, techTree)], ['cln_unlock_crew', unlockCrewAction(profiles, accounts)], - ['cln_prepare_aircraft', prepareAircraftAction(profiles, accounts)], - ['cln_repair_all', repairVehiclesAction(profiles, accounts, techTree, false)], - ['cln_repair_all_in_slots', repairVehiclesAction(profiles, accounts, techTree, true)], + ['cln_prepare_aircraft', prepareAircraftAction(profiles, accounts, repair)], + ['cln_repair_all', repairVehiclesAction(profiles, accounts, techTree, repair, false)], + ['cln_repair_all_in_slots', repairVehiclesAction(profiles, accounts, techTree, repair, true)], ['cln_add_to_wish_list', addToWishlistAction(profiles, accounts, techTree, limits)], ['cln_remove_from_wish_list', removeFromWishlistAction(profiles, accounts)], ]; @@ -125,23 +128,18 @@ function unlockCrewAction(profiles: PlayerProfiles, accounts: AccountStore): Cha }; } -function prepareAircraftAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { +function prepareAircraftAction(profiles: PlayerProfiles, accounts: AccountStore, repair: RepairRules): CharActionHandler { return (context) => { const unit = headerOrPayloadString(context, 'name') ?? headerOrPayloadString(context, 'aircraft'); - const cost = headerOrPayloadInt(context, 'cost') ?? 0; - const costGold = headerOrPayloadInt(context, 'costGold') ?? 0; - if (!unit || cost < 0 || costGold < 0) return { kind: 'error', code: 'BAD_PARAMS' }; + if (!unit) return { kind: 'error', code: 'BAD_PARAMS' }; return runProfileRule(context, profiles, accounts, (saved) => { if (!ownsVehicle(saved, unit)) return refused('NOT_AVAILABLE'); - const hangar = findBlock(saved, HANGAR_BLOCK); - const unitBlock = hangar && findBlock(hangar, unit); - if (unitBlock && isDamagedVehicleBlock(unitBlock) && (cost > 0 || costGold > 0)) { - const price = { silverLions: cost, goldenEagles: costGold }; - if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY'); - pay(saved, price); - } - if (unitBlock) clearVehicleDamage(unitBlock); + if (!isDamaged(saved, unit)) return ACCEPTED; + const price = { silverLions: repair.currentCost(saved, unit), goldenEagles: 0 }; + if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY'); + pay(saved, price); + clearVehicleDamage(saved, unit); return ACCEPTED; }); }; @@ -151,6 +149,7 @@ function repairVehiclesAction( profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree, + repair: RepairRules, inSlotsOnly: boolean, ): CharActionHandler { return (context) => { @@ -161,10 +160,11 @@ function repairVehiclesAction( return runProfileRule(context, profiles, accounts, (saved) => { const hangar = findBlock(saved, HANGAR_BLOCK); if (!hangar) return ACCEPTED; - const targets = collectRepairTargetUnits(saved, hangar, techTree, country, inSlotsOnly); - for (const unitBlock of hangar.blocks) { - if (targets.has(unitBlock.name)) clearVehicleDamage(unitBlock); - } + const targets = [...collectRepairTargetUnits(saved, hangar, techTree, country, inSlotsOnly)].filter((unit) => isDamaged(saved, unit)); + const price = { silverLions: targets.reduce((sum, unit) => sum + repair.currentCost(saved, unit), 0), goldenEagles: 0 }; + if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY'); + pay(saved, price); + for (const unit of targets) clearVehicleDamage(saved, unit); return ACCEPTED; }); }; @@ -194,17 +194,6 @@ function collectRepairTargetUnits( ); } -/** AircraftInfo::serialize (aces.exe 0x94061f..0x940abc): hp:r (default 1.0f) and time:i64. */ -function isDamagedVehicleBlock(unitBlock: BlkBlock): boolean { - const hp = realParam(unitBlock, 'hp'); - return hp !== undefined && hp < FULL_VEHICLE_HP; -} - -function clearVehicleDamage(unitBlock: BlkBlock): void { - removeParam(unitBlock, 'hp'); - removeParam(unitBlock, 'time'); -} - function addToWishlistAction( profiles: PlayerProfiles, accounts: AccountStore, diff --git a/packages/local-service/src/char/actions/price-table.ts b/packages/local-service/src/char/actions/price-table.ts index 84ffb7a..9fe0e42 100644 --- a/packages/local-service/src/char/actions/price-table.ts +++ b/packages/local-service/src/char/actions/price-table.ts @@ -15,6 +15,8 @@ * mods{ { cost:i costGold:i openCostGold:i } } * weapons{ { cost:i costGold:i } } * spare{ cost:i costGold:i } + * repair{ arcade{ cost:i } historical{ cost:i } simulation{ cost:i } } full repair cost per + * mode before modifications (0x10517b0, 0x90e0b0) * specialization{ spec_expert{ cost:i } spec_ace{ costGold:i } } * } * } @@ -42,6 +44,8 @@ import type { DecorShop } from '../../decor/decor-purchase.ts'; import type { TrophyCatalogue, TrophyDefinition, TrophyPrize } from '../../inventory/trophy-catalogue.ts'; import type { ItemCatalogue } from '../../items/item-catalogue.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; +import { REPAIR_MODES } from '../../game-data/datasets/vehicle-repair.ts'; +import type { RepairRules } from '../../repair/repair-rules.ts'; import type { TechTree } from '../../research/tech-tree.ts'; import type { UnlockShop } from '../../unlocks/unlock-purchase.ts'; @@ -56,6 +60,7 @@ export interface PriceTableSources { readonly unlocks: UnlockShop; readonly items: ItemCatalogue; readonly trophies: TrophyCatalogue; + readonly repair: RepairRules; } export function priceTable(sources: PriceTableSources): BlkBlock { @@ -67,7 +72,7 @@ export function priceTable(sources: PriceTableSources): BlkBlock { name: COMMON_SECTION, params: [], blocks: [ - vehicleSection(sources.techTree, sources.equipment, sources.crew), + vehicleSection(sources.techTree, sources.equipment, sources.crew, sources.repair), ...decorSections(sources.decor), skillPackSection(sources.crew), unlockSection(sources.unlocks), @@ -80,7 +85,7 @@ export function priceTable(sources: PriceTableSources): BlkBlock { }; } -function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue, crew: CrewSkillCatalogue): BlkBlock { +function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue, crew: CrewSkillCatalogue, repair: RepairRules): BlkBlock { const vehicles: BlkBlock[] = []; for (const vehicle of techTree.all()) { const entry: BlkBlock = { name: vehicle.name, params: priceParams(vehicle.silverLions, vehicle.goldenEagles), blocks: [] }; @@ -97,6 +102,12 @@ function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue, crew: if (weapons.length) entry.blocks.push({ name: 'weapons', params: [], blocks: weapons }); if (fitted.spare) entry.blocks.push({ name: 'spare', params: priceParams(fitted.spare.silverLions, fitted.spare.goldenEagles), blocks: [] }); } + const repairCost = repair.vehicle(vehicle.name)?.cost; + if (repairCost) { + const modes = REPAIR_MODES.filter((mode) => repairCost[mode] > 0) + .map((mode) => ({ name: mode.toLowerCase(), params: priceParams(repairCost[mode], 0), blocks: [] })); + if (modes.length) entry.blocks.push({ name: 'repair', params: [], blocks: modes }); + } const training = crew.training(vehicle.name); if (training && (training.expert > 0 || training.aceGoldenEagles > 0)) { const specBlocks: BlkBlock[] = []; diff --git a/packages/local-service/src/game-data/datasets/vehicle-repair.ts b/packages/local-service/src/game-data/datasets/vehicle-repair.ts new file mode 100644 index 0000000..3228567 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/vehicle-repair.ts @@ -0,0 +1,48 @@ +/** + * Dataset: what repairing each vehicle costs, char.vromfs.bin config/wpcost.blk: + * + * { + * repairCost:i full repair cost (Mode = Arcade, Historical, Simulation) + * repairCostPerMin:i repair cost per minute of the vehicle's lifetime in a battle + * modifications{ { repairCostCoef:r repairCostCoef:r } } added to the cost factor + * } + * + * The client reads the same fields: the full cost from the price table (cln_get_price_ex, + * aircrafts//repair//cost, aces.exe 2.61.0.37 0x10517b0), times 1 + the + * repairCostCoef (else repairCostCoef) of each modification the player has (0x964900). + */ +import type { BlkBlock } from '@wto/blk'; +import { blockAt, numberField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +export const REPAIR_MODES = ['Arcade', 'Historical', 'Simulation'] as const; +export type RepairMode = (typeof REPAIR_MODES)[number]; +export type PerRepairMode = Readonly>; + +export interface VehicleRepair { + readonly name: string; + readonly cost: PerRepairMode; + readonly costPerMin: PerRepairMode; + /** Modifications with a repair cost coefficient. */ + readonly modCoefs: Readonly>; +} + +export const vehicleRepair: Dataset = { + id: 'vehicle-repair', + version: 1, + extract: (source) => source.readBlk('char.vromfs.bin', 'config/wpcost.blk').blocks.flatMap((vehicle): VehicleRepair[] => { + const cost = perMode(vehicle, 'repairCost'); + if (REPAIR_MODES.every((mode) => cost[mode] <= 0)) return []; + const modCoefs: Record = {}; + for (const mod of blockAt(vehicle, 'modifications')?.blocks ?? []) { + const base = numberField(mod, 'repairCostCoef'); + const coefs = Object.fromEntries(REPAIR_MODES.map((mode) => [mode, numberField(mod, `repairCostCoef${mode}`) ?? base ?? 0])) as Record; + if (REPAIR_MODES.some((mode) => coefs[mode] !== 0)) modCoefs[mod.name] = coefs; + } + return [{ name: vehicle.name, cost, costPerMin: perMode(vehicle, 'repairCostPerMin'), modCoefs }]; + }), +}; + +function perMode(vehicle: BlkBlock, prefix: string): PerRepairMode { + return Object.fromEntries(REPAIR_MODES.map((mode) => [mode, Math.max(0, numberField(vehicle, `${prefix}${mode}`) ?? 0)])) as Record; +} diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index 94afbf4..e7d1a7c 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -28,6 +28,7 @@ import { decalTextures } from './game-data/datasets/decal-textures.ts'; import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts'; import { externalItemSources } from './game-data/datasets/external-item-sources.ts'; import { itemCatalogue } from './game-data/datasets/item-catalogue.ts'; +import { vehicleRepair } from './game-data/datasets/vehicle-repair.ts'; import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; import { shopCountries } from './game-data/datasets/shop-countries.ts'; import { storeBundles } from './game-data/datasets/store-bundles.ts'; @@ -43,6 +44,7 @@ import { InventoryCatalogue } from './inventory/itemdef-catalogue.ts'; import { MarketplaceService } from './inventory/marketplace-service.ts'; import { TrophyCatalogue } from './inventory/trophy-catalogue.ts'; import { ItemCatalogue } from './items/item-catalogue.ts'; +import { RepairRules } from './repair/repair-rules.ts'; import { LoginService } from './login/login-service.ts'; import { matchingRequests } from './matching/matching-requests.ts'; import type { MatchingService } from './matching/matching-service.ts'; @@ -173,6 +175,7 @@ function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles: decor: new DecorShop(datasets.load(decorCatalogue)), unlocks: new UnlockShop(datasets.load(unlockPrices)), items: new ItemCatalogue(classicItemDefs, tuning.limits.itemPiecesPerPurchase), + repair: new RepairRules(datasets.load(vehicleRepair)), store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store), inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning), trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies), diff --git a/packages/local-service/src/profile/profile-client-settings.ts b/packages/local-service/src/profile/profile-client-settings.ts index ffe494e..730e69d 100644 --- a/packages/local-service/src/profile/profile-client-settings.ts +++ b/packages/local-service/src/profile/profile-client-settings.ts @@ -32,6 +32,12 @@ export function isAutoRefillWeaponsEnabled(profile: BlkBlock): boolean { return param?.type === 'bool' ? param.value : true; } +/** Whether vehicles are repaired automatically after a battle (`EconomicState` +0xe978); `true` when absent (0x90b6a0). */ +export function isAutoRepairEnabled(profile: BlkBlock): boolean { + const param = findParam(profile, 'autoRepairAircrafts')?.value; + return param?.type === 'bool' ? param.value : true; +} + export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock): void { for (const name of BOOL_SETTINGS) { const param = findParam(request, name)?.value; diff --git a/packages/local-service/src/profile/profile-vehicle-condition.ts b/packages/local-service/src/profile/profile-vehicle-condition.ts new file mode 100644 index 0000000..8566686 --- /dev/null +++ b/packages/local-service/src/profile/profile-vehicle-condition.ts @@ -0,0 +1,58 @@ +/** + * A vehicle's damage in the profile: fields of its hangar entry (AircraftInfo::serialize, + * aces.exe 2.61.0.37 0x940510): + * + * hangar{ { hp:r time:i64 lastGameMode:i } } + * + * hp is the vehicle's condition (1 = intact, the default; 0x9406a2); time is stored with it + * (here: when the damage happened, server time); lastGameMode is the mode the damage was taken + * in, 1 arcade / 2 historical / 3 simulation (default 1, 0x9415b1), which picks the repair + * cost (getAircraftRepairCost 0x90e0b0 reads it at AircraftInfo+0xcc). + */ +import { findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; +import { removeParam } from './blk-fields.ts'; +import type { ServerTime } from './server-time.ts'; + +const HANGAR = 'hangar'; + +export interface VehicleCondition { + readonly hp: number; + /** 1 arcade, 2 historical, 3 simulation. */ + readonly lastGameMode: number; +} + +export function vehicleCondition(profile: BlkBlock, vehicle: string): VehicleCondition | undefined { + const entry = hangarEntry(profile, vehicle); + if (!entry) return undefined; + const hp = findParam(entry, 'hp')?.value; + const mode = findParam(entry, 'lastGameMode')?.value; + return { + hp: hp?.type === 'real' ? Math.min(1, Math.max(0, hp.value)) : 1, + lastGameMode: mode?.type === 'int' && mode.value >= 1 && mode.value <= 3 ? mode.value : 1, + }; +} + +export function isDamaged(profile: BlkBlock, vehicle: string): boolean { + const condition = vehicleCondition(profile, vehicle); + return condition !== undefined && condition.hp < 1; +} + +export function setVehicleDamage(profile: BlkBlock, vehicle: string, hp: number, lastGameMode: number, time: ServerTime): void { + const entry = hangarEntry(profile, vehicle); + if (!entry) return; + setParam(entry, 'hp', { type: 'real', value: hp }); + setParam(entry, 'time', { type: 'int64', value: time }); + setParam(entry, 'lastGameMode', { type: 'int', value: lastGameMode }); +} + +export function clearVehicleDamage(profile: BlkBlock, vehicle: string): void { + const entry = hangarEntry(profile, vehicle); + if (!entry) return; + removeParam(entry, 'hp'); + removeParam(entry, 'time'); +} + +function hangarEntry(profile: BlkBlock, vehicle: string): BlkBlock | undefined { + const hangar = findBlock(profile, HANGAR); + return hangar && findBlock(hangar, vehicle); +} diff --git a/packages/local-service/src/repair/repair-rules.ts b/packages/local-service/src/repair/repair-rules.ts new file mode 100644 index 0000000..108183b --- /dev/null +++ b/packages/local-service/src/repair/repair-rules.ts @@ -0,0 +1,70 @@ +/** + * Vehicle repair costs, computed as the client computes them so that what the player is charged + * is what the hangar shows (game data: game-data/datasets/vehicle-repair.ts). + * + * - Full repair cost (wp_get_repair_cost_by_mode, aces.exe 2.61.0.37 0x10517b0): the price + * table's aircrafts//repair//cost (repairCost) x (1 + the repair cost + * coefficients of the modifications the player has, 0x964900), truncated. The stat card shows it + * x avgRepairMul (warpoints.blk, 1.0). + * - Current repair cost of a damaged vehicle (wp_get_repair_cost -> getAircraftRepairCost + * 0x90e0b0): max(1, (1 - hp) x full cost in the mode it was damaged in (lastGameMode)); 0 when + * intact or when the full cost is 0 (reserve vehicles). The client would also cap the full cost + * at repairCostPerMin x a play time of its own (feature repairCostUsesPlayTime, a per-vehicle + * table at EconomicState+0xe838 whose source was not found; the local service never fills it), + * so the battle settlement puts the lifetime rule into hp instead (battle/battle-repair.ts). + */ +import type { BlkBlock } from '@wto/blk'; +import { REPAIR_MODES, type RepairMode, type VehicleRepair } from '../game-data/datasets/vehicle-repair.ts'; +import { ownsModification } from '../profile/profile-modifications.ts'; +import { vehicleCondition } from '../profile/profile-vehicle-condition.ts'; + +/** lastGameMode / the client's EGD index: 1 arcade, 2 historical, 3 simulation. */ +export function repairModeOf(lastGameMode: number): RepairMode { + return REPAIR_MODES[lastGameMode - 1] ?? 'Arcade'; +} + +export function gameModeIndexOf(mode: RepairMode): number { + return REPAIR_MODES.indexOf(mode) + 1; +} + +export class RepairRules { + readonly #vehicles: ReadonlyMap; + + constructor(data: readonly VehicleRepair[]) { + this.#vehicles = new Map(data.map((vehicle) => [vehicle.name, vehicle])); + } + + /** The vehicle's repair data; undefined for vehicles that repair for free. */ + vehicle(name: string): VehicleRepair | undefined { + return this.#vehicles.get(name); + } + + fullCost(profile: BlkBlock, vehicle: string, mode: RepairMode): number { + const data = this.#vehicles.get(vehicle); + if (!data) return 0; + return Math.trunc(data.cost[mode] * this.#modFactor(profile, data, mode)); + } + + /** Repair cost per minute of lifetime, scaled by the same modification factor as the full cost (inferred). */ + costPerMinute(profile: BlkBlock, vehicle: string, mode: RepairMode): number { + const data = this.#vehicles.get(vehicle); + if (!data) return 0; + return data.costPerMin[mode] * this.#modFactor(profile, data, mode); + } + + currentCost(profile: BlkBlock, vehicle: string): number { + const condition = vehicleCondition(profile, vehicle); + if (!condition || condition.hp >= 1) return 0; + const full = this.fullCost(profile, vehicle, repairModeOf(condition.lastGameMode)); + if (full < 1) return 0; + return Math.max(1, Math.trunc((1 - condition.hp) * full)); + } + + #modFactor(profile: BlkBlock, data: VehicleRepair, mode: RepairMode): number { + let factor = 1; + for (const [mod, coefs] of Object.entries(data.modCoefs)) { + if (ownsModification(profile, data.name, mod)) factor += coefs[mode]; + } + return factor; + } +}