diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index f780c2f..c9bcfbd 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -16,6 +16,7 @@ import { priceEx } from './price-actions.ts'; import { buyAircraft, buySlot } from './purchase-actions.ts'; import { convertExp, resetResearchable, setResearchable } from './research-actions.ts'; import { setStartingInfo } from './starting-info-actions.ts'; +import { activateBoosterAction, activateDiscountAction, applySpareItemAction, buyItemAction, startWagerAction } from './item-actions.ts'; export interface ActionDependencies { readonly profiles: PlayerProfiles; @@ -55,5 +56,10 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap { + const name = stringParam(payload, 'name'); + const pieces = intParam(payload, 'count'); + if (name === undefined || pieces === undefined) return undefined; + const offered = { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 }; + return (profile) => buyItem(profile, rules.items, name, pieces, offered, serverTimeNow()); + }); +} + +export function activateBoosterAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const uid = stringParam(payload, 'name'); + if (uid === undefined) return undefined; + return (profile) => activateBooster(profile, uid); + }); +} + +export function activateDiscountAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const uid = stringParam(payload, 'name'); + if (uid === undefined) return undefined; + return (profile) => activateDiscount(profile, rules.items, uid, serverTimeNow()); + }); +} + +export function startWagerAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const uid = stringParam(payload, 'name'); + const stake = intParam(payload, 'wager'); + if (uid === undefined || stake === undefined) return undefined; + return (profile) => startWager(profile, rules.items, uid, stake); + }); +} + +export function applySpareItemAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const uid = stringParam(payload, 'uid'); + const vehicle = stringParam(payload, 'unit'); + const pieces = intParam(payload, 'useItemsCount'); + if (uid === undefined || vehicle === undefined || pieces === undefined) return undefined; + return (profile) => applyUniversalSpares(profile, rules.items, rules.techTree, uid, vehicle, pieces); + }); +} diff --git a/packages/local-service/src/char/actions/price-actions.ts b/packages/local-service/src/char/actions/price-actions.ts index 97b3e19..877488a 100644 --- a/packages/local-service/src/char/actions/price-actions.ts +++ b/packages/local-service/src/char/actions/price-actions.ts @@ -9,6 +9,6 @@ import { priceTable } from '../../research/price-table.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; export function priceEx(rules: ResearchRules): CharActionHandler { - const table = priceTable(rules.techTree, rules.equipment, rules.decor, rules.crew, rules.unlocks); + const table = priceTable(rules); return () => ({ kind: 'data', blk: table }); } diff --git a/packages/local-service/src/game-data/datasets/item-catalogue.ts b/packages/local-service/src/game-data/datasets/item-catalogue.ts new file mode 100644 index 0000000..9cbc03d --- /dev/null +++ b/packages/local-service/src/game-data/datasets/item-catalogue.ts @@ -0,0 +1,155 @@ +/** + * Dataset: the classic items, char.vromfs.bin config/items.blk. + * One block per item, named after the item: + * + * { + * type:t rateBooster, personalDiscounts, wager, missionOrder, universalSpare + * cost:i costGold:i price of one piece; most items have none (prizes only) + * sell_count_step:i pieces per purchase + * purchase_feature:t sold only to players with that feature ("devItemShop") + * expiredTimeH:r lifetime in hours from when the player gets it + * expiredTimeHAfterActivation:r lifetime in hours from activation + * 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 ... } + * personalDiscountsParams{ purchasesMaxCount:i discountsDesc{ { :i aircrafts{ :i } } } } + * } + */ +import type { BlkBlock } from '@wto/blk'; +import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +const ITEMS = 'config/items.blk'; + +export interface SpareConditions { + readonly spares: number; + /** Empty: any country. */ + readonly countries: readonly string[]; + /** The client's lower-case unit type names (aircraft, tank, ship, helicopter, boat); empty: any. */ + readonly unitTypes: readonly string[]; + readonly minRank?: number; + readonly maxRank?: number; +} + +export interface WagerLimits { + readonly minStake: number; + readonly maxStake: number; + readonly stakeStep: number; + readonly goldenEagles: boolean; +} + +/** One category of a discount description: percentages by key, and by vehicle under "aircrafts". */ +export interface DiscountCategory { + readonly name: string; + readonly keys: Readonly>; + readonly vehicles: Readonly>; +} + +export interface DiscountDefinition { + readonly maxPurchases: number; + readonly categories: readonly DiscountCategory[]; +} + +export interface ItemDefinition { + readonly name: string; + readonly type: string; + readonly silverLions: number; + readonly goldenEagles: number; + readonly piecesPerPurchase: number; + readonly purchaseFeature?: string; + readonly lifetimeHours?: number; + readonly lifetimeHoursAfterActivation?: number; + /** Unix milliseconds. */ + readonly expiresAt?: number; + readonly stacks: boolean; + readonly spare?: SpareConditions; + readonly wager?: WagerLimits; + readonly discount?: DiscountDefinition; +} + +export const itemCatalogue: Dataset = { + id: 'item-catalogue', + version: 1, + extract: (source) => source.readBlk('char.vromfs.bin', ITEMS).blocks.flatMap(itemOf), +}; + +function itemOf(entry: BlkBlock): ItemDefinition[] { + const type = stringField(entry, 'type'); + if (type === undefined) return []; + const lifetimeHours = positive(numberField(entry, 'expiredTimeH')); + const lifetimeHoursAfterActivation = positive(numberField(entry, 'expiredTimeHAfterActivation')); + const expiresAt = utcTime(stringField(entry, 'expiredAt')); + const purchaseFeature = stringField(entry, 'purchase_feature'); + const spare = spareOf(blockAt(entry, 'universalSpareParams')); + const wager = wagerOf(blockAt(entry, 'wagerParams')); + const discount = discountOf(blockAt(entry, 'personalDiscountsParams')); + return [{ + name: entry.name, + type, + silverLions: Math.max(0, numberField(entry, 'cost') ?? 0), + goldenEagles: Math.max(0, numberField(entry, 'costGold') ?? 0), + piecesPerPurchase: Math.max(1, numberField(entry, 'sell_count_step') ?? 1), + stacks: boolField(entry, 'canPacked') ?? false, + ...(purchaseFeature ? { purchaseFeature } : {}), + ...(lifetimeHours !== undefined ? { lifetimeHours } : {}), + ...(lifetimeHoursAfterActivation !== undefined ? { lifetimeHoursAfterActivation } : {}), + ...(expiresAt !== undefined ? { expiresAt } : {}), + ...(spare ? { spare } : {}), + ...(wager ? { wager } : {}), + ...(discount ? { discount } : {}), + }]; +} + +function spareOf(params: BlkBlock | undefined): SpareConditions | undefined { + if (!params) return undefined; + const minRank = numberField(params, 'minRank'); + const maxRank = numberField(params, 'maxRank'); + return { + spares: Math.max(1, numberField(params, 'numSpares') ?? 1), + countries: stringList(params, 'country'), + unitTypes: stringList(params, 'unitType'), + ...(minRank !== undefined ? { minRank } : {}), + ...(maxRank !== undefined ? { maxRank } : {}), + }; +} + +function wagerOf(params: BlkBlock | undefined): WagerLimits | undefined { + if (!params) return undefined; + 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, + }; +} + +function discountOf(params: BlkBlock | undefined): DiscountDefinition | undefined { + if (!params) return undefined; + const description = blockAt(params, 'discountsDesc'); + return { + maxPurchases: numberField(params, 'purchasesMaxCount') ?? 0, + categories: (description?.blocks ?? []).map((category) => ({ + name: category.name, + keys: intsOf(category), + vehicles: intsOf(blockAt(category, 'aircrafts')), + })), + }; +} + +function intsOf(block: BlkBlock | undefined): Record { + if (!block) return {}; + return Object.fromEntries(block.params.flatMap((param) => param.value.type === 'int' ? [[param.name, param.value.value]] : [])); +} + +function positive(value: number | undefined): number | undefined { + return value !== undefined && value > 0 ? value : undefined; +} + +/** "YYYY-MM-DD hh:mm:ss" in UTC, as the scripts read it (getTimestampFromStringUtc). */ +function utcTime(text: string | undefined): number | undefined { + const match = text && /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/.exec(text.trim()); + if (!match) return undefined; + const [, year, month, day, hour, minute, second] = match.map(Number) as [number, number, number, number, number, number, number]; + return Date.UTC(year, month - 1, day, hour, minute, second); +} diff --git a/packages/local-service/src/items/item-activation.ts b/packages/local-service/src/items/item-activation.ts new file mode 100644 index 0000000..b8b8309 --- /dev/null +++ b/packages/local-service/src/items/item-activation.ts @@ -0,0 +1,67 @@ +/** + * Activating classic items. Each request names the item by uid. + * + * 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. + * 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). + * cln_set_current_wager name:t wager:i (itemWager.nut) + * The stake is paid now, in golden eagles for goldWager contracts and in silver lions + * 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. + */ +import { setParam, type BlkBlock } from '@wto/blk'; +import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; +import { activate, activeUids, itemRecord, ownedItem, removeItem, setItemExpiry } from '../profile/profile-items.ts'; +import { hoursToTicks, type ServerTime } from '../profile/server-time.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { ItemCatalogue } from './item-catalogue.ts'; + +export function activateBooster(profile: BlkBlock, uid: string): RuleOutcome { + const owned = ownedItem(profile, uid); + if (!owned || owned.type !== 'rateBooster' || owned.count < 1) return refused('BAD_PARAMS'); + if (activeUids(profile, 'itemActiveBoosters').includes(uid)) return refused('NOT_AVAILABLE'); + activate(profile, 'itemActiveBoosters', uid); + return ACCEPTED; +} + +export function activateDiscount(profile: BlkBlock, catalogue: ItemCatalogue, uid: string, now: ServerTime): RuleOutcome { + const owned = ownedItem(profile, uid); + const item = owned && catalogue.item(owned.id); + if (!owned || !item || owned.type !== 'personalDiscounts') return refused('BAD_PARAMS'); + if (activeUids(profile, 'itemActiveDiscounts').includes(uid)) return refused('NOT_AVAILABLE'); + if (item.lifetimeHoursAfterActivation !== undefined) { + const end = now + hoursToTicks(item.lifetimeHoursAfterActivation); + if (owned.expiresAt === undefined || end < owned.expiresAt) setItemExpiry(profile, uid, end); + } + activate(profile, 'itemActiveDiscounts', uid); + return ACCEPTED; +} + +export function startWager(profile: BlkBlock, catalogue: ItemCatalogue, uid: string, stake: number): RuleOutcome { + const owned = ownedItem(profile, uid); + const limits = owned && catalogue.item(owned.id)?.wager; + const record = itemRecord(profile, uid); + if (!owned || !limits || !record || owned.type !== 'wager') return refused('BAD_PARAMS'); + const current = activeUids(profile, 'itemActiveWagers'); + if (current.includes(uid)) return refused('NOT_AVAILABLE'); + if (!isOfferedStake(stake, limits.minStake, limits.maxStake, limits.stakeStep)) return refused('BAD_PARAMS'); + const price: Price = limits.goldenEagles ? { silverLions: 0, goldenEagles: stake } : { silverLions: stake, goldenEagles: 0 }; + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, price); + for (const replaced of current) removeItem(profile, replaced); + setParam(record, 'wager', { type: 'int', value: stake }); + setParam(record, 'numWins', { type: 'int', value: 0 }); + setParam(record, 'numBattles', { type: 'int', value: 0 }); + activate(profile, 'itemActiveWagers', uid); + return ACCEPTED; +} + +function isOfferedStake(stake: number, min: number, max: number, step: number): boolean { + if (max === 0 || max === min) return stake === min; + return stake >= min && stake <= max && ((stake - min) % step === 0 || stake === max); +} diff --git a/packages/local-service/src/items/item-catalogue.ts b/packages/local-service/src/items/item-catalogue.ts new file mode 100644 index 0000000..8014d42 --- /dev/null +++ b/packages/local-service/src/items/item-catalogue.ts @@ -0,0 +1,34 @@ +/** + * The classic items as the item rules see them: the definitions of + * config/items.blk by name, and which of them the shop sells. + * + * The shop sells an item that has a price and no purchase_feature: items behind a feature + * ("devItemShop") are only offered to accounts that have it (scripts items/itemsBase.nut + * checkPurchaseFeature), which players do not. + */ +import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts'; + +/** Item types the client's item storage knows (type table aces.exe 2.61.0.37 0x72b6240) that config/items.blk uses. */ +export const ITEM_TYPES = ['rateBooster', 'personalDiscounts', 'wager', 'missionOrder', 'universalSpare'] as const; + +export class ItemCatalogue { + readonly #items: ReadonlyMap; + + constructor(definitions: readonly ItemDefinition[]) { + const known = new Set(ITEM_TYPES); + this.#items = new Map(definitions.filter((item) => known.has(item.type)).map((item) => [item.name, item])); + } + + item(name: string): ItemDefinition | undefined { + return this.#items.get(name); + } + + /** Items the shop sells, with their price per piece. */ + forSale(): ItemDefinition[] { + return [...this.#items.values()].filter(isForSale); + } +} + +export function isForSale(item: ItemDefinition): boolean { + return item.purchaseFeature === undefined && (item.silverLions > 0 || item.goldenEagles > 0); +} diff --git a/packages/local-service/src/items/item-expiry.ts b/packages/local-service/src/items/item-expiry.ts new file mode 100644 index 0000000..9e240e9 --- /dev/null +++ b/packages/local-service/src/items/item-expiry.ts @@ -0,0 +1,14 @@ +/** + * Removing classic items whose time is up (items//expiredTimeH, implementation notes section + * 4.2), together with their place in the active lists. Run whenever a profile is handed out + * or changed, so the client never gets an expired item. + */ +import type { BlkBlock } from '@wto/blk'; +import { ownedItems, removeItem } from '../profile/profile-items.ts'; +import type { ServerTime } from '../profile/server-time.ts'; + +export function removeExpiredItems(profile: BlkBlock, now: ServerTime): void { + for (const item of ownedItems(profile)) { + if (item.expiresAt !== undefined && item.expiresAt <= now) removeItem(profile, item.uid); + } +} diff --git a/packages/local-service/src/items/item-grants.ts b/packages/local-service/src/items/item-grants.ts new file mode 100644 index 0000000..c2b4d6b --- /dev/null +++ b/packages/local-service/src/items/item-grants.ts @@ -0,0 +1,81 @@ +/** + * Giving the player classic items: purchases, the save editor and, + * later, rewards all go through here. + * + * Items that stack (canPacked: universal spares) are kept as one uid whose instCount grows; + * every other piece gets its own uid with instCount 1, because activation works per uid (the + * scripts activate uids[0] and the client marks a whole uid active), so pieces under one uid + * could not be activated one at a time. + * + * Expiry: expiredTimeH hours from now, but not after expiredAt (scripts items/itemsBase.nut + * takes the earlier of the two). + */ +import type { BlkBlock, BlkParam } from '@wto/blk'; +import type { DiscountDefinition, ItemDefinition } from '../game-data/datasets/item-catalogue.ts'; +import { addItem, ownedItems, setItemCount, type NewItem } from '../profile/profile-items.ts'; +import { hoursToTicks, serverTimeFromUnixMs, type ServerTime } from '../profile/server-time.ts'; + +export function grantItem(profile: BlkBlock, item: ItemDefinition, pieces: number, now: ServerTime): void { + if (!Number.isSafeInteger(pieces) || pieces < 1) throw new RangeError(`pieces out of range: ${pieces}`); + if (item.stacks) { + const stack = ownedItems(profile).find((owned) => owned.id === item.name); + if (stack) { + setItemCount(profile, stack.uid, stack.count + pieces); + return; + } + addItem(profile, newItem(item, pieces, now), now); + return; + } + for (let piece = 0; piece < pieces; piece++) addItem(profile, newItem(item, 1, now), now); +} + +/** When an item given now expires, or undefined for never. */ +export function expiryOf(item: ItemDefinition, now: ServerTime): ServerTime | undefined { + const fromLifetime = item.lifetimeHours !== undefined ? now + hoursToTicks(item.lifetimeHours) : undefined; + const fixed = item.expiresAt !== undefined ? serverTimeFromUnixMs(item.expiresAt) : undefined; + if (fromLifetime === undefined) return fixed; + if (fixed === undefined) return fromLifetime; + return fixed < fromLifetime ? fixed : fromLifetime; +} + +function newItem(item: ItemDefinition, count: number, now: ServerTime): NewItem { + const expiresAt = expiryOf(item, now); + return { + id: item.name, + type: item.type, + count, + ...(expiresAt !== undefined ? { expiresAt } : {}), + ...typeFields(item), + }; +} + +/** Per-type fields a new item starts with (the client's readers: implementation notes). */ +function typeFields(item: ItemDefinition): { params?: BlkParam[]; blocks?: BlkBlock[] } { + if (item.type === 'wager') return { params: [intParam('numWins', 0), intParam('numBattles', 0), intParam('wager', 0)] }; + if (item.type === 'personalDiscounts' && item.discount) { + return { + params: [intParam('purchasesCount', 0), intParam('purchasesMaxCount', item.discount.maxPurchases)], + blocks: [discountDescription(item.discount)], + }; + } + return {}; +} + +/** discountsDesc{ { :i aircrafts{ :i } } }, as config/items.blk has it. */ +function discountDescription(discount: DiscountDefinition): BlkBlock { + return { + name: 'discountsDesc', + params: [], + blocks: discount.categories.map((category) => ({ + name: category.name, + params: Object.entries(category.keys).map(([key, percent]) => intParam(key, percent)), + blocks: Object.keys(category.vehicles).length + ? [{ name: 'aircrafts', params: Object.entries(category.vehicles).map(([vehicle, percent]) => intParam(vehicle, percent)), blocks: [] }] + : [], + })), + }; +} + +function intParam(name: string, value: number): BlkParam { + return { name, value: { type: 'int', value } }; +} diff --git a/packages/local-service/src/items/item-purchase.ts b/packages/local-service/src/items/item-purchase.ts new file mode 100644 index 0000000..56b8de6 --- /dev/null +++ b/packages/local-service/src/items/item-purchase.ts @@ -0,0 +1,28 @@ +/** + * Buying classic items (cln_buy_item, implementation notes; scripts items/itemsBase.nut + * _requestBuy): name:t count:i cost:i costGold:i. + * + * The client prices a purchase as the price-table price of one piece times the pieces it buys + * (getCost: wp_get_item_cost x sell_count_step; count is sell_count_step), so the offered price + * must be the piece price times count. + */ +import type { BlkBlock } from '@wto/blk'; +import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; +import type { ServerTime } from '../profile/server-time.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import { isForSale, type ItemCatalogue } from './item-catalogue.ts'; +import { grantItem } from './item-grants.ts'; + +const MAX_PIECES = 1000; + +export function buyItem(profile: BlkBlock, catalogue: ItemCatalogue, name: string, pieces: number, offered: Price, now: ServerTime): RuleOutcome { + const item = catalogue.item(name); + if (!item || pieces < 1 || pieces > MAX_PIECES) return refused('BAD_PARAMS'); + if (!isForSale(item)) return refused('NOT_AVAILABLE'); + const price: Price = { silverLions: item.silverLions * pieces, goldenEagles: item.goldenEagles * pieces }; + if (price.silverLions !== offered.silverLions || price.goldenEagles !== offered.goldenEagles) return refused('PRICE_CHANGED'); + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, price); + grantItem(profile, item, pieces, now); + return ACCEPTED; +} diff --git a/packages/local-service/src/items/personal-discounts.ts b/packages/local-service/src/items/personal-discounts.ts new file mode 100644 index 0000000..5306696 --- /dev/null +++ b/packages/local-service/src/items/personal-discounts.ts @@ -0,0 +1,93 @@ +/** + * What active personal discounts take off a vehicle's price, the + * same way the client prices it (wp_get_cost -> aces.exe 2.61.0.37 0x9158a0, key lookup 0x908590). + * + * Every active discount item is looked up in its "buy" category; the largest percentage wins. + * Inside one item, keys are tried in this order and a later match replaces an earlier one + * ("premium" = the vehicle has a golden eagle price): + * all, all_premium (premium only), rank (premium: rank_premium), , + * _premium (premium only), _rank (premium: _rank_premium), + * aircrafts{ } + * The price is then cut by floor(price x percent / 100) in both currencies. + * + * The client keeps each item's own discountsDesc (items//discountsDesc), so the lookup + * reads the copy in the profile. A purchase made with a discount counts against the item that + * gave it (purchasesCount); when it reaches purchasesMaxCount the item is used up. + */ +import { findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; +import { activeUids, itemRecord, removeItem } from '../profile/profile-items.ts'; +import type { Price } from '../profile/profile-currency.ts'; +import type { TreeVehicle } from '../research/tech-tree.ts'; + +const BUY = 'buy'; + +export interface VehicleDiscount { + readonly percent: number; + /** The active item that gives it; undefined when there is no discount. */ + readonly uid?: string; +} + +export function vehicleDiscount(profile: BlkBlock, vehicle: TreeVehicle): VehicleDiscount { + let best: VehicleDiscount = { percent: 0 }; + for (const uid of activeUids(profile, 'itemActiveDiscounts')) { + const description = itemRecord(profile, uid); + const category = description && findBlock(findBlock(description, 'discountsDesc') ?? emptyBlock(), BUY); + if (!category) continue; + const percent = percentFor(category, vehicle); + if (percent > best.percent) best = { percent, uid }; + } + return best; +} + +export function discountedPrice(price: Price, percent: number): Price { + if (percent <= 0) return price; + return { silverLions: cut(price.silverLions, percent), goldenEagles: cut(price.goldenEagles, percent) }; +} + +/** Count a purchase against the discount item that gave the discount. */ +export function recordDiscountUse(profile: BlkBlock, uid: string): void { + const record = itemRecord(profile, uid); + if (!record) return; + const used = intOf(record, 'purchasesCount') + 1; + const allowed = intOf(record, 'purchasesMaxCount'); + if (allowed > 0 && used >= allowed) { + removeItem(profile, uid); + return; + } + setParam(record, 'purchasesCount', { type: 'int', value: used }); +} + +function percentFor(category: BlkBlock, vehicle: TreeVehicle): number { + const premium = vehicle.goldenEagles > 0; + const suffix = premium ? '_premium' : ''; + const keys = [ + 'all', + ...(premium ? ['all_premium'] : []), + ...(vehicle.rank > 0 ? [`rank${vehicle.rank}${suffix}`] : []), + vehicle.country, + ...(premium ? [`${vehicle.country}_premium`] : []), + ...(vehicle.rank > 0 ? [`${vehicle.country}_rank${vehicle.rank}${suffix}`] : []), + ]; + let percent = 0; + for (const key of keys) percent = found(category, key) ?? percent; + const byVehicle = findBlock(category, 'aircrafts'); + return (byVehicle && found(byVehicle, vehicle.name)) ?? percent; +} + +function found(block: BlkBlock, key: string): number | undefined { + const value = findParam(block, key)?.value; + return value?.type === 'int' && value.value >= 0 ? value.value : undefined; +} + +function cut(amount: number, percent: number): number { + return Math.max(0, amount - Math.floor((amount * percent) / 100)); +} + +function intOf(block: BlkBlock, name: string): number { + const value = findParam(block, name)?.value; + return value?.type === 'int' ? value.value : 0; +} + +function emptyBlock(): BlkBlock { + return { name: '', params: [], blocks: [] }; +} diff --git a/packages/local-service/src/items/universal-spares.ts b/packages/local-service/src/items/universal-spares.ts new file mode 100644 index 0000000..37fee79 --- /dev/null +++ b/packages/local-service/src/items/universal-spares.ts @@ -0,0 +1,48 @@ +/** + * Using universal spares on a vehicle (cln_apply_spare_item: uid:t unit:t useItemsCount:i; + * scripts items/itemsClasses/itemUniversalSpare.nut activateOnUnit). + * + * The vehicle must be owned and fit the item's conditions as the scripts check them + * (itemModBase.nut initConditions, itemUniversalSpare.nut canActivateOnUnit): one of its + * countries, its rank range, one of its unit types. Each piece used adds numSpares spares to + * hangar//spareAircraftsCount, which stays within MAX_SPARE_AMOUNT like bought spares. + */ +import type { BlkBlock } from '@wto/blk'; +import { ownsVehicle } from '../profile/profile-hangar.ts'; +import { ownedItem, removeItem, setItemCount } from '../profile/profile-items.ts'; +import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts'; +import { MAX_SPARE_AMOUNT } from '../modifications/spare-purchase.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { TechTree, TreeVehicle } from '../research/tech-tree.ts'; +import type { VehicleType } from '../research/vehicle-types.ts'; +import type { SpareConditions } from '../game-data/datasets/item-catalogue.ts'; +import type { ItemCatalogue } from './item-catalogue.ts'; + +/** The scripts' unitType.lowerName (scripts unit/unitTypesList.nut). */ +const UNIT_TYPE_NAME: Partial> = { + Aircraft: 'aircraft', Tank: 'tank', Ship: 'ship', Helicopter: 'helicopter', Boat: 'boat', +}; + +export function applyUniversalSpares(profile: BlkBlock, catalogue: ItemCatalogue, techTree: TechTree, + uid: string, vehicleName: string, pieces: number): RuleOutcome { + const owned = ownedItem(profile, uid); + const conditions = owned && catalogue.item(owned.id)?.spare; + const vehicle = techTree.vehicle(vehicleName); + if (!owned || !conditions || !vehicle || owned.type !== 'universalSpare') return refused('BAD_PARAMS'); + if (pieces < 1 || pieces > owned.count) return refused('BAD_PARAMS'); + if (!ownsVehicle(profile, vehicle.name) || !fits(vehicle, conditions)) return refused('NOT_AVAILABLE'); + const spares = spareCount(profile, vehicle.name) + conditions.spares * pieces; + if (spares > MAX_SPARE_AMOUNT) return refused('NOT_AVAILABLE'); + setSpareCount(profile, vehicle.name, spares); + if (owned.count === pieces) removeItem(profile, uid); + else setItemCount(profile, uid, owned.count - pieces); + return ACCEPTED; +} + +function fits(vehicle: TreeVehicle, conditions: SpareConditions): boolean { + if (conditions.countries.length && !conditions.countries.includes(vehicle.country)) return false; + if (conditions.minRank !== undefined && vehicle.rank < conditions.minRank) return false; + if (conditions.maxRank !== undefined && vehicle.rank > conditions.maxRank) return false; + const typeName = UNIT_TYPE_NAME[vehicle.type]; + return !conditions.unitTypes.length || (typeName !== undefined && conditions.unitTypes.includes(typeName)); +} diff --git a/packages/local-service/src/modifications/spare-purchase.ts b/packages/local-service/src/modifications/spare-purchase.ts index d7c5f1b..bc636f3 100644 --- a/packages/local-service/src/modifications/spare-purchase.ts +++ b/packages/local-service/src/modifications/spare-purchase.ts @@ -11,7 +11,7 @@ import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import type { EquipmentCatalogue } from './equipment-catalogue.ts'; -const MAX_SPARE_AMOUNT = 100; +export const MAX_SPARE_AMOUNT = 100; export function buySpares(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, amount: number, offered: Price): RuleOutcome { const spare = catalogue.vehicle(vehicle)?.spare; diff --git a/packages/local-service/src/player-card/showcase-rules.ts b/packages/local-service/src/player-card/showcase-rules.ts index 743b887..267e4da 100644 --- a/packages/local-service/src/player-card/showcase-rules.ts +++ b/packages/local-service/src/player-card/showcase-rules.ts @@ -43,6 +43,18 @@ const STORED_FIELDS: Readonly>>> tank_footballer: {}, }; +/** + * Fields every answer carries for a type even before the player saved it: the client keeps each + * type's block as a table and assigns some fields with `=`, which fails on a missing slot + * (favorite_unit's saveUnit does `showcase.unit = `; the unit picker broke on it). + */ +const DEFAULT_FIELDS: Readonly> = { + favorite_unit: [ + { name: 'unit', value: { type: 'string', value: '' } }, + { name: 'difficulty', value: { type: 'string', value: 'arcade' } }, + ], +}; + /** The client's unit type names (scripts unit/unitTypesList.nut). */ const SHOWCASE_UNIT_TYPE: Partial> = { Aircraft: 'aircraft', Tank: 'tank', Ship: 'ship', Helicopter: 'helicopter', Boat: 'boat', @@ -61,42 +73,48 @@ export function saveShowcase(profile: BlkBlock, request: BlkBlock): RuleOutcome if (type === ACE_OF_SPADES) { const filter = request.blocks.find((block) => block.name === ACED_FILTER); const saved = savedShowcases(profile).find((block) => block.name === ACE_OF_SPADES); - if (saved) saved.blocks = filter ? [{ ...filter, blocks: [] }] : []; + // An empty filter is still a saved choice (show nothing), unlike no filter at all. + if (saved) saved.blocks = [filter ? { ...filter, blocks: [] } : { name: ACED_FILTER, params: [], blocks: [] }]; } return ACCEPTED; } -/** The cln_get_showcases answer: current:t and one block per saved showcase type. */ +/** The cln_get_showcases answer: current:t and one block per showcase type, saved or not. */ export function showcasesAnswer(profile: BlkBlock, techTree: TechTree): BlkBlock { return { name: '', params: [{ name: 'current', value: { type: 'string', value: currentShowcase(profile) } }], - blocks: savedShowcases(profile).map((saved) => clientView(profile, techTree, saved)), + blocks: Object.keys(STORED_FIELDS).map((type) => clientView(profile, techTree, type)), }; } /** The current showcase for cln_get_users_terse_info: its type and its block named "showcase". */ export function currentShowcaseView(profile: BlkBlock, techTree: TechTree): { type: string; showcase: BlkBlock } { const type = currentShowcase(profile); - const saved = savedShowcases(profile).find((block) => block.name === type); - const view = saved ? clientView(profile, techTree, saved) : { name: type, params: [], blocks: [] }; - return { type, showcase: { ...view, name: 'showcase' } }; + return { type, showcase: { ...clientView(profile, techTree, type), name: 'showcase' } }; } -function clientView(profile: BlkBlock, techTree: TechTree, saved: BlkBlock): BlkBlock { - if (saved.name !== ACE_OF_SPADES) return { name: saved.name, params: saved.params, blocks: [] }; - const chosen = new Set((saved.blocks.find((block) => block.name === ACED_FILTER)?.params ?? []) +function clientView(profile: BlkBlock, techTree: TechTree, type: string): BlkBlock { + const saved = savedShowcases(profile).find((block) => block.name === type); + if (type !== ACE_OF_SPADES) { + const params = saved?.params ?? []; + const defaults = (DEFAULT_FIELDS[type] ?? []).filter((field) => !params.some((param) => param.name === field.name)); + return { name: type, params: [...defaults, ...params], blocks: [] }; + } + // Before the player saves a filter, every category with an ace is shown. + const filter = saved?.blocks.find((block) => block.name === ACED_FILTER); + const chosen = filter && new Set(filter.params .flatMap((param) => param.value.type === 'string' ? [`${param.value.value}/${param.name.replace(/^country_/, '')}`] : [])); const shown = new Map>(); const hidden = new Map>(); for (const [key, count] of acedVehicleCounts(profile, techTree)) { - const [type, country] = key.split('/') as [string, string]; - const target = chosen.has(key) ? shown : hidden; - let byCountry = target.get(type); - if (!byCountry) target.set(type, byCountry = new Map()); + const [unitType, country] = key.split('/') as [string, string]; + const target = !chosen || chosen.has(key) ? shown : hidden; + let byCountry = target.get(unitType); + if (!byCountry) target.set(unitType, byCountry = new Map()); byCountry.set(country, count); } - return { name: saved.name, params: [], blocks: [countBlock('aced_units', shown), countBlock('aced_units_hidden', hidden)] }; + return { name: type, params: [], blocks: [countBlock('aced_units', shown), countBlock('aced_units_hidden', hidden)] }; } /** "/" -> vehicles a crew is an ace on. */ diff --git a/packages/local-service/src/profile/client-profile.ts b/packages/local-service/src/profile/client-profile.ts index 5eedd4d..7e393c6 100644 --- a/packages/local-service/src/profile/client-profile.ts +++ b/packages/local-service/src/profile/client-profile.ts @@ -1,18 +1,23 @@ /** * The profile as the char service hands it to the client: the saved profile plus the - * account data the char server keeps outside the profile. + * account data and state the char server keeps outside the profile. * * charDrivenNick: the client reads the player's nick from this top-level string when it * loads a profile (name looked up at aces.exe 2.61.0.37 0x8fe0aa, value stored at 0x91874d). * A profile without it clears the nick, and the online initialisation then fails with * "[CONNECT] nick is empty" and error 0x81110017 (0x164e5cf), as seen in the lab runs. * The nick belongs to the account, so it is added here rather than kept in the save. + * + * serverTime:i64: the char server's clock; without it the client + * takes the server time as 0 and every expiry and time limit is wrong. */ import { setParam, type BlkBlock } from '@wto/blk'; import type { Account } from '../accounts/account-store.ts'; +import { serverTimeNow } from './server-time.ts'; export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { const profile = structuredClone(saved); setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick }); + setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() }); return profile; } diff --git a/packages/local-service/src/profile/profile-items.ts b/packages/local-service/src/profile/profile-items.ts new file mode 100644 index 0000000..eb0b6c1 --- /dev/null +++ b/packages/local-service/src/profile/profile-items.ts @@ -0,0 +1,148 @@ +/** + * The player's classic items in the profile (implementation notes; ItemStorage, aces.exe + * 2.61.0.37 0x8f2de0): + * + * items{ + * numTotalAddedItems:i=2 + * item_0000019b2f3c1a40_2{ block name = the item's uid + * id:t="booster_shop_wp_15_10mp" config/items.blk name + * type:t="rateBooster" + * expiredTimeH:i64= absolute expiry; missing = never + * instCount:i64=1 pieces under this uid + * ... per-type fields (wager: numWins numBattles wager; + * personalDiscounts: purchasesCount purchasesMaxCount discountsDesc{}) + * } + * } + * itemActiveBoosters{ itemUID:t= ... } active boosters, any number + * itemActiveDiscounts{ itemUID:t= ... } active personal discounts + * itemActiveWagers{ itemUID:t= } the current contract, at most one + * + * Every field is read by name (0x8f10d0 and the per-type readers), so order does not matter. + * New uids follow the client's own pattern item_%016llx_%x (0x8f2c87): a time stamp and the + * running count numTotalAddedItems. + */ +import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; +import type { ServerTime } from './server-time.ts'; + +const ITEMS = 'items'; +const ADDED_COUNT = 'numTotalAddedItems'; +const ACTIVE_UID = 'itemUID'; + +export type ActiveList = 'itemActiveBoosters' | 'itemActiveDiscounts' | 'itemActiveWagers'; +export const ACTIVE_LISTS: readonly ActiveList[] = ['itemActiveBoosters', 'itemActiveDiscounts', 'itemActiveWagers']; + +export interface OwnedItem { + readonly uid: string; + readonly id: string; + readonly type: string; + readonly count: number; + readonly expiresAt?: ServerTime; +} + +export interface NewItem { + readonly id: string; + readonly type: string; + readonly count: number; + readonly expiresAt?: ServerTime; + /** Per-type fields written after the common ones. */ + readonly params?: readonly BlkParam[]; + readonly blocks?: readonly BlkBlock[]; +} + +export function ownedItems(profile: BlkBlock): OwnedItem[] { + return (findBlock(profile, ITEMS)?.blocks ?? []).flatMap((record) => { + const item = itemOf(record); + return item ? [item] : []; + }); +} + +export function ownedItem(profile: BlkBlock, uid: string): OwnedItem | undefined { + const record = itemRecord(profile, uid); + return record && itemOf(record); +} + +/** The item's whole block, for per-type fields; undefined when the player does not have it. */ +export function itemRecord(profile: BlkBlock, uid: string): BlkBlock | undefined { + const items = findBlock(profile, ITEMS); + return items && findBlock(items, uid); +} + +/** Add an item under a new uid; returns the uid. */ +export function addItem(profile: BlkBlock, item: NewItem, now: ServerTime): string { + const items = ensureBlock(profile, ITEMS); + const added = intOf(items, ADDED_COUNT) + 1; + setParam(items, ADDED_COUNT, { type: 'int', value: added }); + const uid = `item_${now.toString(16).padStart(16, '0')}_${added.toString(16)}`; + items.blocks.push({ + name: uid, + params: [ + { name: 'id', value: { type: 'string', value: item.id } }, + { name: 'type', value: { type: 'string', value: item.type } }, + ...(item.expiresAt !== undefined ? [expiryParam(item.expiresAt)] : []), + countParam(item.count), + ...(item.params ?? []), + ], + blocks: [...(item.blocks ?? [])], + }); + return uid; +} + +export function setItemCount(profile: BlkBlock, uid: string, count: number): void { + const record = itemRecord(profile, uid); + if (record) setParam(record, 'instCount', countParam(count).value); +} + +export function setItemExpiry(profile: BlkBlock, uid: string, expiresAt: ServerTime): void { + const record = itemRecord(profile, uid); + if (record) setParam(record, 'expiredTimeH', expiryParam(expiresAt).value); +} + +/** Remove an item and every reference to it from the active lists. */ +export function removeItem(profile: BlkBlock, uid: string): void { + const items = findBlock(profile, ITEMS); + if (items) items.blocks = items.blocks.filter((record) => record.name !== uid); + for (const list of ACTIVE_LISTS) deactivate(profile, list, uid); +} + +export function activeUids(profile: BlkBlock, list: ActiveList): string[] { + return (findBlock(profile, list)?.params ?? []).flatMap((param) => + param.name === ACTIVE_UID && param.value.type === 'string' ? [param.value.value] : []); +} + +export function activate(profile: BlkBlock, list: ActiveList, uid: string): void { + if (activeUids(profile, list).includes(uid)) return; + ensureBlock(profile, list).params.push({ name: ACTIVE_UID, value: { type: 'string', value: uid } }); +} + +export function deactivate(profile: BlkBlock, list: ActiveList, uid: string): void { + const block = findBlock(profile, list); + if (block) block.params = block.params.filter((param) => !(param.name === ACTIVE_UID && param.value.type === 'string' && param.value.value === uid)); +} + +function itemOf(record: BlkBlock): OwnedItem | undefined { + const id = stringOf(record, 'id'); + const type = stringOf(record, 'type'); + if (id === undefined || type === undefined) return undefined; + const expiry = findParam(record, 'expiredTimeH')?.value; + const expiresAt = expiry?.type === 'int64' && expiry.value >= 0n ? expiry.value : undefined; + return { uid: record.name, id, type, count: intOf(record, 'instCount'), ...(expiresAt !== undefined ? { expiresAt } : {}) }; +} + +function countParam(count: number): BlkParam { + return { name: 'instCount', value: { type: 'int64', value: BigInt(count) } }; +} + +function expiryParam(expiresAt: ServerTime): BlkParam { + return { name: 'expiredTimeH', value: { type: 'int64', value: expiresAt } }; +} + +function stringOf(block: BlkBlock, name: string): string | undefined { + const value = findParam(block, name)?.value; + return value?.type === 'string' ? value.value : undefined; +} + +function intOf(block: BlkBlock, name: string): number { + const value = findParam(block, name)?.value; + if (value?.type === 'int64') return Number(value.value); + return value?.type === 'int' ? value.value : 0; +} diff --git a/packages/local-service/src/profile/server-time.ts b/packages/local-service/src/profile/server-time.ts new file mode 100644 index 0000000..1f9a128 --- /dev/null +++ b/packages/local-service/src/profile/server-time.ts @@ -0,0 +1,27 @@ +/** + * Time as the char server and the client count it: Windows FILETIME, + * 100-nanosecond ticks since 1601-01-01 UTC. The profile's serverTime:i64 sets the client's + * clock (set_charserver_time, aces.exe 2.61.0.37 0x904400; get_charserver_time_sec 0x15533a0 + * turns it back into Unix seconds), and item expiry times (items//expiredTimeH) are + * absolute times in the same unit. + */ + +export type ServerTime = bigint; + +const TICKS_PER_MILLISECOND = 10_000n; +const UNIX_EPOCH = 116_444_736_000_000_000n; + +export const TICKS_PER_HOUR = 36_000_000_000n; + +export function serverTimeFromUnixMs(milliseconds: number): ServerTime { + return BigInt(Math.trunc(milliseconds)) * TICKS_PER_MILLISECOND + UNIX_EPOCH; +} + +export function serverTimeNow(): ServerTime { + return serverTimeFromUnixMs(Date.now()); +} + +/** A whole or fractional number of hours as ticks. */ +export function hoursToTicks(hours: number): bigint { + return BigInt(Math.round(hours * 3_600_000)) * TICKS_PER_MILLISECOND; +} diff --git a/packages/local-service/src/profiles-setup.ts b/packages/local-service/src/profiles-setup.ts index a3fa270..16a2ede 100644 --- a/packages/local-service/src/profiles-setup.ts +++ b/packages/local-service/src/profiles-setup.ts @@ -1,7 +1,8 @@ /** * Assemble the players' profiles with the rules they depend on, the same way for the local * service and for the save editor (save-cli.ts): static data from the dataset cache, the - * save store with its format upgrades, and the research and modification state kept up to date. + * save store with its format upgrades, and the research and modification state kept up to date + * (expired classic items removed). */ import type { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { reserveVehicles } from './game-data/datasets/reserve-vehicles.ts'; @@ -11,6 +12,8 @@ import { PlayerProfiles } from './profile/player-profiles.ts'; import { profileUpgrades } from './profile/profile-upgrades.ts'; import type { StartingContent } from './profile/starting-content.ts'; import { refreshModuleState } from './modifications/module-state.ts'; +import { removeExpiredItems } from './items/item-expiry.ts'; +import { serverTimeNow } from './profile/server-time.ts'; import { refreshResearchState } from './research/research-state.ts'; import { loadResearchRules, type ResearchRules } from './research/research-rules.ts'; import { SaveStore } from './saves/save-store.ts'; @@ -27,6 +30,7 @@ export function setUpProfiles(dataFolder: string, gameFiles: GameFiles, datasets const profiles = new PlayerProfiles(saves, gameFiles, startingContent, (profile) => { refreshResearchState(profile, research); refreshModuleState(profile, research.equipment); + removeExpiredItems(profile, serverTimeNow()); }); return { profiles, research }; } diff --git a/packages/local-service/src/research/price-table.ts b/packages/local-service/src/research/price-table.ts index a37e966..9cd9f87 100644 --- a/packages/local-service/src/research/price-table.ts +++ b/packages/local-service/src/research/price-table.ts @@ -23,6 +23,8 @@ * attachable{ { ... } } * skills{ { costGold:i } } skill point packs (0x916380) * unlocks{ { cost:i costGold:i } } unlocks for sale (0x9170c0) + * items{ { cost:i costGold:i } } classic items for sale, price per piece + * (wp_get_item_cost, 0x10531e0; implementation notes) * } * * Every entry is read as cost:i (silver lions), costGold:i (golden eagles), discount:i (percent @@ -35,14 +37,29 @@ import type { BlkBlock, BlkParam } from '@wto/blk'; import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts'; import type { DecorShop } from '../decor/decor-purchase.ts'; +import type { ItemCatalogue } from '../items/item-catalogue.ts'; import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; import type { UnlockShop } from '../unlocks/unlock-purchase.ts'; +import type { ResearchRules } from './research-rules.ts'; import type { TechTree } from './tech-tree.ts'; /** The top-level block every client lookup falls back to (0x908e28). */ const COMMON_SECTION = 'Common'; -export function priceTable(techTree: TechTree, equipment: EquipmentCatalogue, decor: DecorShop, crew: CrewSkillCatalogue, unlocks: UnlockShop): BlkBlock { +export function priceTable(rules: ResearchRules): BlkBlock { + return { + name: '', + params: [], + blocks: [{ + name: COMMON_SECTION, + params: [], + blocks: [vehicleSection(rules.techTree, rules.equipment), ...decorSections(rules.decor), skillPackSection(rules.crew), + unlockSection(rules.unlocks), itemSection(rules.items)], + }], + }; +} + +function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue): BlkBlock { const vehicles: BlkBlock[] = []; for (const vehicle of techTree.all()) { const entry: BlkBlock = { name: vehicle.name, params: priceParams(vehicle.silverLions, vehicle.goldenEagles), blocks: [] }; @@ -61,8 +78,7 @@ export function priceTable(techTree: TechTree, equipment: EquipmentCatalogue, de } if (entry.blocks.length || vehicle.silverLions > 0 || vehicle.goldenEagles > 0) vehicles.push(entry); } - const common: BlkBlock = { name: COMMON_SECTION, params: [], blocks: [{ name: 'aircrafts', params: [], blocks: vehicles }, ...decorSections(decor), skillPackSection(crew), unlockSection(unlocks)] }; - return { name: '', params: [], blocks: [common] }; + return { name: 'aircrafts', params: [], blocks: vehicles }; } /** Zero prices are left out: the client reads a missing value as 0, and the table stays small. */ @@ -98,3 +114,7 @@ function skillPackSection(crew: CrewSkillCatalogue): BlkBlock { function unlockSection(unlocks: UnlockShop): BlkBlock { return { name: 'unlocks', params: [], blocks: [...unlocks.all()].map((price) => ({ name: price.id, params: priceParams(price.silverLions, price.goldenEagles), blocks: [] })) }; } + +function itemSection(items: ItemCatalogue): BlkBlock { + return { name: 'items', params: [], blocks: items.forSale().map((item) => ({ name: item.name, params: priceParams(item.silverLions, item.goldenEagles), blocks: [] })) }; +} diff --git a/packages/local-service/src/research/research-rules.ts b/packages/local-service/src/research/research-rules.ts index 0815686..8dec321 100644 --- a/packages/local-service/src/research/research-rules.ts +++ b/packages/local-service/src/research/research-rules.ts @@ -15,6 +15,8 @@ import { vehicleUnlocks, type UnlockDefinition } from '../game-data/datasets/veh import { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; import { unlockPrices } from '../game-data/datasets/unlock-prices.ts'; import { UnlockShop } from '../unlocks/unlock-purchase.ts'; +import { itemCatalogue } from '../game-data/datasets/item-catalogue.ts'; +import { ItemCatalogue } from '../items/item-catalogue.ts'; import { TechTree } from './tech-tree.ts'; export interface ResearchRules { @@ -31,6 +33,8 @@ export interface ResearchRules { readonly crew: CrewSkillCatalogue; /** Unlocks for sale: ship flags, profile icons and frames, awards. */ readonly unlocks: UnlockShop; + /** Classic items: boosters, personal discounts, contracts, universal spares. */ + readonly items: ItemCatalogue; } export function loadResearchRules(datasets: DatasetCache): ResearchRules { @@ -44,5 +48,6 @@ export function loadResearchRules(datasets: DatasetCache): ResearchRules { decor: new DecorShop(datasets.load(decorCatalogue)), crew: new CrewSkillCatalogue(datasets.load(crewSkillData)), unlocks: new UnlockShop(datasets.load(unlockPrices)), + items: new ItemCatalogue(datasets.load(itemCatalogue)), }; } diff --git a/packages/local-service/src/research/vehicle-purchase.ts b/packages/local-service/src/research/vehicle-purchase.ts index 9ae6d60..3dc0179 100644 --- a/packages/local-service/src/research/vehicle-purchase.ts +++ b/packages/local-service/src/research/vehicle-purchase.ts @@ -2,13 +2,14 @@ * Buying a vehicle (cln_buy_aircraft, implementation notes). * * The vehicle must be buyable (status "can buy"). Its price is config/wpcost.blk value - * (silver lions) and costGold (golden eagles): the client prices it the same way - * (wp_get_cost / wp_get_cost_gold, aces.exe 2.61.0.37 0x9158a0) and only applies discounts - * from the price table, which the local service sends empty. The client sends the price it - * showed; a different one is refused, as when a discount ended online. The parts of a split - * vehicle come with it. + * (silver lions) and costGold (golden eagles), less the best active personal discount: the + * client prices it the same way (wp_get_cost / wp_get_cost_gold, aces.exe 2.61.0.37 0x9158a0; + * implementation notes; the price table itself has no discounts). The client sends the price + * it showed; a different one is refused, as when a discount ended online. A purchase made with + * a discount counts against that discount item. The parts of a split vehicle come with it. */ import type { BlkBlock } from '@wto/blk'; +import { discountedPrice, recordDiscountUse, vehicleDiscount } from '../items/personal-discounts.ts'; import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; import { addOwnedVehicle } from '../profile/profile-hangar.ts'; import { currentStatus } from './research-state.ts'; @@ -20,10 +21,12 @@ export function buyVehicle(profile: BlkBlock, rules: ResearchRules, vehicleName: const vehicle = rules.techTree.vehicle(vehicleName); if (!vehicle) return refused('BAD_PARAMS'); if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_BUY) return refused('NOT_AVAILABLE'); - const price: Price = { silverLions: vehicle.silverLions, goldenEagles: vehicle.goldenEagles }; + const discount = vehicleDiscount(profile, vehicle); + const price = discountedPrice({ silverLions: vehicle.silverLions, goldenEagles: vehicle.goldenEagles }, discount.percent); if (offered.silverLions !== price.silverLions || offered.goldenEagles !== price.goldenEagles) return refused('PRICE_CHANGED'); if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); pay(profile, price); + if (discount.uid !== undefined) recordDiscountUse(profile, discount.uid); addOwnedVehicle(profile, vehicle.name); for (const part of vehicle.parts) addOwnedVehicle(profile, part); return ACCEPTED; diff --git a/packages/local-service/src/save-cli.ts b/packages/local-service/src/save-cli.ts index 5bdf52a..aaa1e11 100644 --- a/packages/local-service/src/save-cli.ts +++ b/packages/local-service/src/save-cli.ts @@ -4,19 +4,28 @@ * * node packages/local-service/src/save-cli.ts --game --data * --player [--silver ] [--gold ] [--free-rp ] + * [--give-item [:]]... * - * --free-rp sets the free research points. Without any amount it - * only prints the balance. The edit is written to the save; the - * game shows it after its next profile update (any action, or signing in again). + * --free-rp sets the free research points. --give-item gives classic + * items from config/items.blk, as a reward would; it can be repeated. + * Without any change it only prints the balance. The edit is written to the save; the game + * shows it after its next profile update (any action, or signing in again). */ import { parseArgs } from 'node:util'; import { AccountStore } from './accounts/account-store.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { GameFiles } from './game-data/game-files.ts'; +import type { ItemDefinition } from './game-data/datasets/item-catalogue.ts'; +import { grantItem } from './items/item-grants.ts'; import { balanceOf, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts'; +import { ownedItems } from './profile/profile-items.ts'; import { freeResearchPoints, setFreeResearchPoints } from './profile/profile-research-points.ts'; +import { serverTimeNow } from './profile/server-time.ts'; import { setUpProfiles } from './profiles-setup.ts'; +const USAGE = 'usage: save-cli.ts --game --data --player ' + + '[--silver ] [--gold ] [--free-rp ] [--give-item [:]]...'; + function main(): number { const { values } = parseArgs({ options: { @@ -26,10 +35,11 @@ function main(): number { silver: { type: 'string' }, gold: { type: 'string' }, 'free-rp': { type: 'string' }, + 'give-item': { type: 'string', multiple: true }, }, }); if (!values.game || !values.data || !values.player) { - console.error('usage: save-cli.ts --game --data --player [--silver ] [--gold ] [--free-rp ]'); + console.error(USAGE); return 2; } const silver = optionalAmount(values.silver); @@ -39,7 +49,6 @@ function main(): number { console.error('--silver, --gold and --free-rp take a whole number of 0 or more'); return 2; } - const accounts = new AccountStore(values.data); const account = accounts.byLogin(values.player) ?? accounts.byUserId(values.player); if (!account) { @@ -48,17 +57,32 @@ function main(): number { } const gameFiles = new GameFiles(values.game); const datasets = new DatasetCache(values.data, gameFiles, () => {}); - const { profiles } = setUpProfiles(values.data, gameFiles, datasets); - - const profile = silver === undefined && gold === undefined && freeRp === undefined + const { profiles, research } = setUpProfiles(values.data, gameFiles, datasets); + const gifts: { item: ItemDefinition; pieces: number }[] = []; + for (const request of values['give-item'] ?? []) { + const [name = '', piecesText = '1'] = request.split(':'); + const item = research.items.item(name); + const pieces = optionalAmount(piecesText); + if (!item || !pieces) { + console.error(`--give-item: no classic item "${name}", or pieces not a whole number of 1 or more`); + return 2; + } + gifts.push({ item, pieces }); + } + const changes = silver !== undefined || gold !== undefined || freeRp !== undefined || gifts.length > 0; + const profile = !changes ? profiles.profileOf(account.userId) : profiles.update(account.userId, (saved) => { if (silver !== undefined) setSilverLions(saved, silver); if (gold !== undefined) setGoldenEagles(saved, gold); if (freeRp !== undefined) setFreeResearchPoints(saved, freeRp); + const now = serverTimeNow(); + for (const gift of gifts) grantItem(saved, gift.item, gift.pieces, now); }); const balance = balanceOf(profile); console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${freeResearchPoints(profile)} free research points`); + const items = ownedItems(profile); + if (items.length) console.log(`items: ${items.map((item) => `${item.id} x${item.count}`).join(', ')}`); return 0; }