refactor(repo)!: move apps, shared packages, and patch definitions

Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.

BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 03:20:54 +08:00
1 parent 9c813ccf7d
commit 930ea07630
476 files changed
+275 -251

No files matched your search

@@ -0,0 +1,156 @@
/**
* Initial full stocking and `autoRefillWeapons` Silver-Lion top-up for an owned vehicle's
* modifications, ammunition belts/shells, expendables (`tank_medical_kit_expendable`), and
* secondary weapon presets.
*
* Rules:
* 1. Zero-cost modifications (`isFree`) whose `requires` are all owned cannot be bought by the
* client (`weaponsPurchase.nut` `canBuyItem` rejects zero cost) and receive `count = 1` in
* name + topological order, honoring `defaultEnabled` and non-bullet `exclusiveGroup` mutual
* exclusion.
* 2. Free secondary weapon presets (`isFreeWeapon`, excluding `isWeaponForCustomSlot` containers)
* whose `requires` (direct + `sum_weapons` container inheritance) are all owned receive
* `count = 1` so `shop_is_weapon_purchased` allows selecting them.
* 3. Silver-Lion counted modifications (`isCounted` with `goldenEagles === 0`, covering all
* 12,800 shells, gun belts, and `tank_medical_kit_expendable`) and paid weapon presets
* (`isPaidWeapon` with `goldenEagles === 0`) whose `requires` are all owned:
* - When no profile record exists yet (`record === undefined`, i.e. newly acquired vehicle or
* newly unlocked prerequisite modification), receive their initial full load (`maxCount`)
* at no extra Silver-Lion charge (`itemInfo.nut` `getAllModsCost` skips `maxAmount > 1`).
* - When a record already exists with `count < maxCount` (consumed in battle) and hangar
* `autoRefillWeapons` is enabled, buy as many missing pieces with Silver Lions in
* deterministic name order as the player's balance affords.
*
* Returns the Silver Lions spent on refilling (0 for the initial free stock and when
* autoRefill is off); battle settlement lists it as the automatic refill cost.
*/
import type { BlkBlock } from '@wto/blk';
import type { ModificationFacts, VehicleEquipment, WeaponFacts } from '../game-data/datasets/vehicle-equipment.ts';
import { balanceOf, pay } from '../profile/profile-currency.ts';
import { modificationRecord, ownsModification, writeModificationRecord } from '../profile/profile-modifications.ts';
import { weaponRecord, writeWeaponRecord } from '../profile/profile-weapons.ts';
import { isCounted, isFree, isFreeWeapon, isPaidWeapon } from './equipment-catalogue.ts';
import { arePrerequisitesOwned } from './module-status.ts';
export interface EquipmentRefillResult {
readonly silverLionsSpent: number;
}
export function stockAndRefillEquipment(
profile: BlkBlock,
equipment: VehicleEquipment,
autoRefill: boolean,
): EquipmentRefillResult {
const modifications = [...equipment.modifications].sort((a, b) => a.name.localeCompare(b.name));
const weapons = [...equipment.weapons].sort((a, b) => a.name.localeCompare(b.name));
grantUnlockedFreeModifications(profile, equipment.vehicle, modifications);
grantUnlockedFreeWeapons(profile, equipment.vehicle, weapons);
let silverLionsSpent = 0;
for (const modification of modifications) {
silverLionsSpent += stockOrRefillCountedModification(profile, equipment.vehicle, modification, autoRefill);
}
for (const weapon of weapons) {
silverLionsSpent += stockOrRefillPaidWeapon(profile, equipment.vehicle, weapon, autoRefill);
}
return { silverLionsSpent };
}
function grantUnlockedFreeModifications(profile: BlkBlock, vehicle: string, modifications: readonly ModificationFacts[]): void {
let progressed = false;
do {
progressed = false;
for (const modification of modifications) {
if (!isFree(modification) || ownsModification(profile, vehicle, modification.name)) continue;
if (!arePrerequisitesOwned(profile, vehicle, modification.requires)) continue;
const enabled = modification.defaultEnabled && !hasEnabledExclusivePeer(profile, vehicle, modifications, modification.exclusiveGroup);
writeModificationRecord(profile, vehicle, modification.name, {
silverLionsSpent: 0,
goldenEaglesSpent: 0,
enabled,
count: Math.max(1, modification.maxCount),
});
progressed = true;
}
} while (progressed);
}
function hasEnabledExclusivePeer(
profile: BlkBlock,
vehicle: string,
modifications: readonly ModificationFacts[],
exclusiveGroup: string | undefined,
): boolean {
if (!exclusiveGroup) return false;
return modifications.some((peer) => peer.exclusiveGroup === exclusiveGroup && modificationRecord(profile, vehicle, peer.name)?.enabled === true);
}
function grantUnlockedFreeWeapons(profile: BlkBlock, vehicle: string, weapons: readonly WeaponFacts[]): void {
for (const weapon of weapons) {
if (!isFreeWeapon(weapon) || weaponRecord(profile, vehicle, weapon.name)) continue;
if (!arePrerequisitesOwned(profile, vehicle, weapon.requires)) continue;
writeWeaponRecord(profile, vehicle, weapon.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, count: 1 });
}
}
function stockOrRefillCountedModification(
profile: BlkBlock,
vehicle: string,
modification: ModificationFacts,
autoRefill: boolean,
): number {
if (!isCounted(modification) || modification.goldenEagles > 0) return 0;
if (!arePrerequisitesOwned(profile, vehicle, modification.requires)) return 0;
const record = modificationRecord(profile, vehicle, modification.name);
if (record === undefined) {
writeModificationRecord(profile, vehicle, modification.name, {
silverLionsSpent: 0,
goldenEaglesSpent: 0,
enabled: modification.defaultEnabled,
count: modification.maxCount,
});
return 0;
}
if (!autoRefill || record.count >= modification.maxCount) return 0;
const toBuy = affordableUnits(profile, modification.maxCount - record.count, modification.silverLions);
if (toBuy <= 0) return 0;
const cost = toBuy * modification.silverLions;
if (cost > 0) pay(profile, { silverLions: cost, goldenEagles: 0 });
writeModificationRecord(profile, vehicle, modification.name, {
...record,
silverLionsSpent: record.silverLionsSpent + cost,
count: record.count + toBuy,
});
return cost;
}
function stockOrRefillPaidWeapon(
profile: BlkBlock,
vehicle: string,
weapon: WeaponFacts,
autoRefill: boolean,
): number {
if (!isPaidWeapon(weapon) || weapon.goldenEagles > 0) return 0;
if (!arePrerequisitesOwned(profile, vehicle, weapon.requires)) return 0;
const record = weaponRecord(profile, vehicle, weapon.name);
if (record === undefined) {
writeWeaponRecord(profile, vehicle, weapon.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, count: weapon.maxCount });
return 0;
}
if (!autoRefill || record.count >= weapon.maxCount) return 0;
const toBuy = affordableUnits(profile, weapon.maxCount - record.count, weapon.silverLions);
if (toBuy <= 0) return 0;
const cost = toBuy * weapon.silverLions;
if (cost > 0) pay(profile, { silverLions: cost, goldenEagles: 0 });
writeWeaponRecord(profile, vehicle, weapon.name, {
silverLionsSpent: record.silverLionsSpent + cost,
goldenEaglesSpent: record.goldenEaglesSpent,
count: record.count + toBuy,
});
return cost;
}
function affordableUnits(profile: BlkBlock, missing: number, unitSilverCost: number): number {
if (missing <= 0) return 0;
if (unitSilverCost <= 0) return missing;
return Math.min(missing, Math.floor(balanceOf(profile).silverLions / unitSilverCost));
}
@@ -0,0 +1,70 @@
/**
* Lookup over the vehicle-equipment dataset (game-data/datasets/vehicle-equipment.ts), plus the
* classifications the rules need.
*/
import type { ModificationFacts, VehicleEquipment, WeaponFacts } from '../game-data/datasets/vehicle-equipment.ts';
export class EquipmentCatalogue {
readonly #byVehicle: ReadonlyMap<string, VehicleEquipment>;
constructor(equipment: readonly VehicleEquipment[]) {
this.#byVehicle = new Map(equipment.map((entry) => [entry.vehicle, entry]));
}
vehicle(name: string): VehicleEquipment | undefined {
return this.#byVehicle.get(name);
}
modification(vehicle: string, name: string): ModificationFacts | undefined {
return this.#byVehicle.get(vehicle)?.modifications.find((modification) => modification.name === name);
}
weapon(vehicle: string, name: string): WeaponFacts | undefined {
return this.#byVehicle.get(vehicle)?.weapons.find((weapon) => weapon.name === name);
}
}
/** Bought by the piece (bombs, rockets): has a price and a maxCount. */
export function isPaidWeapon(weapon: WeaponFacts): boolean {
return (weapon.silverLions > 0 || weapon.goldenEagles > 0) && weapon.maxCount > 0;
}
/**
* Comes with the vehicle. The client lets a preset be chosen only when the player has some of
* it (scripts weaponry/weaponryPresetsWnd.nut doItemAction: getItemAmount, which is
* shop_is_weapon_purchased, the record's count), so a free preset needs a record too.
*/
export function isFreeWeapon(weapon: WeaponFacts): boolean {
return weapon.silverLions === 0 && weapon.goldenEagles === 0;
}
/** Has to be researched before it can be bought (`reqExp > 0`, including tier-0 `allowPremDecals`). */
export function isResearchable(modification: ModificationFacts): boolean {
return modification.researchPoints > 0;
}
/**
* Counts towards opening the next tier: the client's isModificationInTree (scripts
* weaponry/modsTree.nut) leaves out tier-0 (`allowPremDecals`), hidden, golden-eagle and
* ammunition modifications.
*/
export function countsForTier(modification: ModificationFacts): boolean {
return modification.tier >= 1 && isResearchable(modification) && modification.goldenEagles === 0 && !modification.ammunition;
}
/**
* Zero-cost, unresearched modification (no Silver Lions, Golden Eagles, outright GE, or RP):
* includes both ungated modifications on reserve/premium vehicles and prerequisite-gated free
* modifications such as chaff belts (`countermeasures_launcher_chaff`) or premium gun upgrades.
* Because `weaponsPurchase.nut` `canBuyItem` refuses zero-cost purchases, the server grants the
* owned record automatically once all `requires` are owned.
*/
export function isFree(modification: ModificationFacts): boolean {
return modification.silverLions === 0 && modification.goldenEagles === 0
&& modification.openGoldenEagles === 0 && modification.researchPoints === 0;
}
/** Bought in amounts (ammunition, expendables): maxCount above 1. */
export function isCounted(modification: ModificationFacts): boolean {
return modification.maxCount > 1;
}
@@ -0,0 +1,156 @@
/**
* Buying and switching modifications:
*
* cln_buy_modification one modification, ammunition or expendable; with open:b=yes a
* researchable one is bought outright for golden eagles
* cln_buy_all_modification everything the vehicle can buy now (forceOpen: also outright)
* cln_enable_modifications switch bought modifications on or off
*
* Prices: silver lions and golden eagles from wpcost.blk times the amount; the outright price is
* max(1, openCostGold * (reqExp - points so far) / reqExp), points capped at reqExp, rounded
* down (aces.exe 0xec0910). A plain modification is bought once and comes mounted; counted ones
* (maxCount above 1) add to the amount up to maxCount.
*/
import type { BlkBlock } from '@wto/blk';
import type { ModificationFacts } from '../game-data/datasets/vehicle-equipment.ts';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { ownsVehicle } from '../profile/profile-hangar.ts';
import { modificationRecord, writeModificationRecord } from '../profile/profile-modifications.ts';
import { moduleResearchPoints, removeModuleResearch } from '../profile/profile-module-research.ts';
import { moduleResearchTarget, setModuleResearchTarget } from '../profile/profile-vehicle-state.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
import { currentModuleStatus } from './module-state.ts';
import { ModuleStatus } from './module-status.ts';
export interface ModificationOrder {
readonly vehicle: string;
readonly modification: string;
/** Bought outright for golden eagles instead of after research. */
readonly outright: boolean;
readonly amount: number;
readonly offered: Price;
}
export function buyModification(profile: BlkBlock, catalogue: EquipmentCatalogue, order: ModificationOrder): RuleOutcome {
const modification = catalogue.modification(order.vehicle, order.modification);
if (!modification || !ownsVehicle(profile, order.vehicle) || order.amount < 1) return refused('BAD_PARAMS');
const purchase = order.outright ? outrightPurchase(profile, order.vehicle, modification, catalogue)
: regularPurchase(profile, order.vehicle, modification, catalogue, order.amount);
if (!purchase) return refused('NOT_AVAILABLE');
if (purchase.price.silverLions !== order.offered.silverLions || purchase.price.goldenEagles !== order.offered.goldenEagles) return refused('PRICE_CHANGED');
if (!canAfford(profile, purchase.price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, purchase.price);
addToRecord(profile, catalogue, order.vehicle, modification, purchase);
return ACCEPTED;
}
export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome {
const equipment = catalogue.vehicle(vehicle);
if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS');
const purchases = equipment.modifications.flatMap((modification) => {
const purchase = buyAllEntry(profile, vehicle, modification, catalogue, outright);
return purchase ? [{ modification, purchase }] : [];
});
const price = purchases.reduce<Price>((sum, { purchase }) => ({
silverLions: sum.silverLions + purchase.price.silverLions,
goldenEagles: sum.goldenEagles + purchase.price.goldenEagles,
}), { silverLions: 0, goldenEagles: 0 });
if (purchases.length === 0) return refused('NOT_AVAILABLE');
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);
for (const { modification, purchase } of purchases) addToRecord(profile, catalogue, vehicle, modification, purchase);
return ACCEPTED;
}
/** Switches are applied to bought modifications only; enabling an exclusive-group mod unmounts peers. */
export function enableModifications(
profile: BlkBlock,
catalogue: EquipmentCatalogue,
switches: readonly { vehicle: string; modification: string; enabled: boolean }[],
): RuleOutcome {
for (const { vehicle, modification, enabled } of switches) {
const record = modificationRecord(profile, vehicle, modification);
if (!record) continue;
if (record.enabled !== enabled) writeModificationRecord(profile, vehicle, modification, { ...record, enabled });
const facts = catalogue.modification(vehicle, modification);
if (enabled && facts) disableExclusiveGroupPeers(profile, catalogue, vehicle, facts);
}
return ACCEPTED;
}
/** The outright price (aces.exe 0xec0910). */
export function outrightPrice(profile: BlkBlock, vehicle: string, modification: ModificationFacts): number {
const required = modification.researchPoints;
if (required <= 0 || modification.openGoldenEagles <= 0) return modification.openGoldenEagles;
const earned = Math.min(moduleResearchPoints(profile, vehicle, modification.name), required);
return Math.max(1, Math.floor(modification.openGoldenEagles * (required - earned) / required));
}
interface Purchase {
readonly price: Price;
readonly amount: number;
}
function regularPurchase(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue, amount: number): Purchase | undefined {
const record = modificationRecord(profile, vehicle, modification.name);
if (record) {
if (!isCounted(modification) || record.count + amount > modification.maxCount) return undefined;
}
else if (currentModuleStatus(profile, catalogue, vehicle, modification.name) !== ModuleStatus.CAN_BUY) return undefined;
if (!isCounted(modification) && amount !== 1) return undefined;
if (isCounted(modification) && amount > modification.maxCount) return undefined;
return { price: { silverLions: modification.silverLions * amount, goldenEagles: modification.goldenEagles * amount }, amount };
}
function outrightPurchase(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue): Purchase | undefined {
if (!isResearchable(modification) || modification.openGoldenEagles <= 0) return undefined;
const status = currentModuleStatus(profile, catalogue, vehicle, modification.name);
if (status !== ModuleStatus.CAN_RESEARCH && status !== ModuleStatus.CAN_BUY) return undefined;
return { price: { silverLions: 0, goldenEagles: outrightPrice(profile, vehicle, modification) }, amount: 1 };
}
/**
* One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost):
* skip what is at its maximum; with forceOpen every modification starts at its outright price
* (whatever its status); a buyable one (canBuyMod) with a non-zero price takes its own price
* instead, and is skipped altogether when counted or priced in golden eagles.
*/
function buyAllEntry(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue, outright: boolean): Purchase | undefined {
const record = modificationRecord(profile, vehicle, modification.name);
const maxAmount = Math.max(1, modification.maxCount);
if ((record?.count ?? 0) >= maxAmount) return undefined;
let purchase: Purchase | undefined;
const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0;
if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 };
const buyable = record !== undefined || currentModuleStatus(profile, catalogue, vehicle, modification.name) === ModuleStatus.CAN_BUY;
if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) {
if (isCounted(modification) || modification.goldenEagles > 0) return undefined;
purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 };
}
return purchase;
}
function addToRecord(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, modification: ModificationFacts, purchase: Purchase): void {
const record = modificationRecord(profile, vehicle, modification.name);
const enabled = record?.enabled ?? modification.defaultEnabled;
writeModificationRecord(profile, vehicle, modification.name, {
silverLionsSpent: (record?.silverLionsSpent ?? 0) + purchase.price.silverLions,
goldenEaglesSpent: (record?.goldenEaglesSpent ?? 0) + purchase.price.goldenEagles,
enabled,
count: (record?.count ?? 0) + purchase.amount,
});
if (enabled) disableExclusiveGroupPeers(profile, catalogue, vehicle, modification);
removeModuleResearch(profile, vehicle, modification.name);
if (moduleResearchTarget(profile, vehicle) === modification.name) setModuleResearchTarget(profile, vehicle, '');
}
function disableExclusiveGroupPeers(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, active: ModificationFacts): void {
if (!active.exclusiveGroup) return;
for (const peer of catalogue.vehicle(vehicle)?.modifications ?? []) {
if (peer.name === active.name || peer.exclusiveGroup !== active.exclusiveGroup) continue;
const peerRecord = modificationRecord(profile, vehicle, peer.name);
if (peerRecord?.enabled) writeModificationRecord(profile, vehicle, peer.name, { ...peerRecord, enabled: false });
}
}
@@ -0,0 +1,69 @@
/**
* Choosing the modification a vehicle researches: cln_set_researchable
* with unit:t and mod:t (script shop_set_researchable_unit_module). The modification has to be
* researchable now; it goes into hangar/<vehicle>/investMode, and the client shows it as "in
* research" from there. cln_move_exp_to_module (scripts/unit/unitActions.nut
* flushExcessExpToModule, unit:t mod:t) puts the vehicle's banked excessExp into a modification.
*/
import type { BlkBlock } from '@wto/blk';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { moduleResearchPoints, setModuleResearchPoints } from '../profile/profile-module-research.ts';
import {
setFinishedModuleResearch,
setModuleResearchTarget,
setVehicleExcessRp,
vehicleExcessRp,
} from '../profile/profile-vehicle-state.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
import { currentModuleStatus } from './module-state.ts';
import { ModuleStatus } from './module-status.ts';
export function chooseModuleResearch(
profile: BlkBlock,
catalogue: EquipmentCatalogue,
vehicle: string,
modification: string,
): RuleOutcome {
if (modification === '') {
if (!catalogue.vehicle(vehicle) || !ownedVehicles(profile).has(vehicle)) return refused('BAD_PARAMS');
setModuleResearchTarget(profile, vehicle, '');
setFinishedModuleResearch(profile, vehicle, '');
return ACCEPTED;
}
if (!catalogue.modification(vehicle, modification)) return refused('BAD_PARAMS');
if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) {
return refused('NOT_AVAILABLE');
}
setModuleResearchTarget(profile, vehicle, modification);
setFinishedModuleResearch(profile, vehicle, '');
return ACCEPTED;
}
export function moveExcessExpToModule(
profile: BlkBlock,
catalogue: EquipmentCatalogue,
vehicle: string,
modification: string,
): RuleOutcome {
const modFacts = catalogue.modification(vehicle, modification);
if (!modFacts || modFacts.researchPoints <= 0) return refused('BAD_PARAMS');
if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) {
return refused('NOT_AVAILABLE');
}
const available = vehicleExcessRp(profile, vehicle);
const before = moduleResearchPoints(profile, vehicle, modification);
const moved = Math.min(available, Math.max(0, modFacts.researchPoints - before));
if (moved <= 0) return ACCEPTED;
const remaining = available - moved;
setVehicleExcessRp(profile, vehicle, remaining);
setModuleResearchPoints(profile, vehicle, modification, before + moved);
if (before + moved >= modFacts.researchPoints) {
setModuleResearchTarget(profile, vehicle, '');
setFinishedModuleResearch(profile, vehicle, '');
} else {
setModuleResearchTarget(profile, vehicle, modification);
setFinishedModuleResearch(profile, vehicle, '');
}
return ACCEPTED;
}
@@ -0,0 +1,97 @@
/**
* Bringing the modification state of a profile up to date, like research/research-state.ts does
* for vehicles: whenever a profile is handed out or changed (profiles-setup.ts), for every owned
* vehicle (sorted by name for deterministic auto-refill deduction):
* modifications & weapons unlocked free items, initial full stock of newly unlocked
* ammunition / expendables / paid presets, and Silver-Lion
* top-ups when `autoRefillWeapons` is enabled (ammo-refill.ts)
* hangar/<vehicle>/tierNumber the highest open tier
* modsResearch the status of every modification not owned yet; locked ones
* only keep an entry while they hold research points
* hangar/<vehicle>/investMode cleared when that modification is no longer researchable
*. After a modification finished
* (investModePrev set) a new one is picked while some remain, so
* the stock prompt opens WeaponsModalHandler in researchMode
* (or reports isResearchLast with investMode "" when the vehicle
* has nothing left); with banked hangar/<vehicle>/excessExp and
* nothing just finished it stays empty for the player to choose.
*/
import type { BlkBlock } from '@wto/blk';
import type { VehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts';
import { isAutoRefillWeaponsEnabled } from '../profile/profile-client-settings.ts';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { moduleResearchPoints, removeModuleResearch, setModuleStatus } from '../profile/profile-module-research.ts';
import {
finishedModuleResearch,
moduleResearchTarget,
setModuleResearchTarget,
setOpenTier,
setVehicleExcessRp,
vehicleExcessRp,
} from '../profile/profile-vehicle-state.ts';
import { stockAndRefillEquipment } from './ammo-refill.ts';
import { isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
import { isModuleResearched, ModuleStatus, vehicleModuleState, type VehicleModuleState } from './module-status.ts';
export function refreshModuleState(profile: BlkBlock, catalogue: EquipmentCatalogue): void {
const autoRefill = isAutoRefillWeaponsEnabled(profile);
const owned = [...ownedVehicles(profile)].sort((a, b) => a.localeCompare(b));
for (const vehicle of owned) {
const equipment = catalogue.vehicle(vehicle);
if (!equipment) continue;
stockAndRefillEquipment(profile, equipment, autoRefill);
const state = vehicleModuleState(profile, equipment);
setOpenTier(profile, vehicle, state.openTier);
for (const modification of equipment.modifications) {
const status = state.statuses.get(modification.name);
if (status === undefined || (status === ModuleStatus.LOCKED && moduleResearchPoints(profile, vehicle, modification.name) === 0)) {
removeModuleResearch(profile, vehicle, modification.name);
} else {
setModuleStatus(profile, vehicle, modification.name, status);
}
}
syncVehicleInvestMode(profile, equipment, state);
}
}
function syncVehicleInvestMode(profile: BlkBlock, equipment: VehicleEquipment, state: VehicleModuleState): void {
const vehicle = equipment.vehicle;
const target = moduleResearchTarget(profile, vehicle);
if (target && state.statuses.get(target) === ModuleStatus.CAN_RESEARCH) return;
const hasAnyUnresearched = equipment.modifications.some(
(mod) => isResearchable(mod) && !isModuleResearched(profile, vehicle, mod),
);
if (!hasAnyUnresearched) {
setModuleResearchTarget(profile, vehicle, '');
setVehicleExcessRp(profile, vehicle, 0);
return;
}
const nextMod = pickDefaultResearchableModule(equipment, state);
const prevMod = finishedModuleResearch(profile, vehicle);
const excess = vehicleExcessRp(profile, vehicle);
if (prevMod !== '' || excess === 0) {
setModuleResearchTarget(profile, vehicle, nextMod);
} else {
setModuleResearchTarget(profile, vehicle, '');
}
}
export function pickDefaultResearchableModule(equipment: VehicleEquipment, state: VehicleModuleState): string {
const ordered = [...equipment.modifications]
.filter((mod) => isResearchable(mod) && state.statuses.get(mod.name) === ModuleStatus.CAN_RESEARCH)
.sort((a, b) => (a.tier !== b.tier ? a.tier - b.tier : a.name.localeCompare(b.name)));
return ordered[0]?.name ?? '';
}
export function currentModuleStatus(
profile: BlkBlock,
catalogue: EquipmentCatalogue,
vehicle: string,
modification: string,
): ModuleStatus | undefined {
const equipment = catalogue.vehicle(vehicle);
if (!equipment || !ownedVehicles(profile).has(vehicle)) return undefined;
return vehicleModuleState(profile, equipment).statuses.get(modification);
}
@@ -0,0 +1,78 @@
/**
* The status of each modification of an owned vehicle. The client
* works out "owned" and "mounted" from the modifications records and "in research" from
* `investMode` itself; the server supplies the rest through `modsResearch`:
*
* researchable modification (tier 1+, research points)
* tier not open LOCKED
* research points reached CAN_BUY
* otherwise CAN_RESEARCH
* other modification (ammunition, expendables, premium)
* every required modification bought CAN_BUY
* otherwise LOCKED
*
* Tiers: tier 1 is open; tier N+1 opens once tier N is open and at least
* needBuyToOpenNextInTier<N> of its counted modifications are researched (scripts
* weaponry/bulletsInfo.nut isWeaponTierAvailable, weaponry/modsTree.nut getNextTierModsCount).
*/
import type { BlkBlock } from '@wto/blk';
import type { ModificationFacts, VehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts';
import { ownsModification } from '../profile/profile-modifications.ts';
import { moduleResearchPoints } from '../profile/profile-module-research.ts';
import { countsForTier, isResearchable } from './equipment-catalogue.ts';
/** shopItemConsts ES_ITEM_STATUS_*; the same values as the vehicle statuses. */
export const ModuleStatus = {
LOCKED: 1,
CAN_RESEARCH: 2,
CAN_BUY: 8,
} as const;
export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus];
export interface VehicleModuleState {
/** The highest open tier (hangar tierNumber). */
readonly openTier: number;
/** Status of every modification the player does not own. */
readonly statuses: ReadonlyMap<string, ModuleStatus>;
}
export function vehicleModuleState(profile: BlkBlock, equipment: VehicleEquipment): VehicleModuleState {
const openTier = openTierOf(profile, equipment);
const statuses = new Map<string, ModuleStatus>();
for (const modification of equipment.modifications) {
if (ownsModification(profile, equipment.vehicle, modification.name)) continue;
statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier));
}
return { openTier, statuses };
}
export function isModuleResearched(profile: BlkBlock, vehicle: string, modification: ModificationFacts): boolean {
return ownsModification(profile, vehicle, modification.name)
|| moduleResearchPoints(profile, vehicle, modification.name) >= modification.researchPoints;
}
export function arePrerequisitesOwned(profile: BlkBlock, vehicle: string, requires: readonly string[]): boolean {
return requires.every((required) => ownsModification(profile, vehicle, required));
}
function openTierOf(profile: BlkBlock, equipment: VehicleEquipment): number {
let tier = 1;
while (tier <= equipment.tierRequirements.length) {
const needed = equipment.tierRequirements[tier - 1] ?? 0;
const tierModifications = equipment.modifications.filter((modification) => modification.tier === tier && countsForTier(modification));
if (tierModifications.length === 0) break;
const researched = tierModifications.filter((modification) => isModuleResearched(profile, equipment.vehicle, modification)).length;
if (researched < needed) break;
tier++;
}
return tier;
}
function statusOf(profile: BlkBlock, vehicle: string, modification: ModificationFacts, openTier: number): ModuleStatus {
if (isResearchable(modification)) {
if (modification.tier > openTier) return ModuleStatus.LOCKED;
return isModuleResearched(profile, vehicle, modification) ? ModuleStatus.CAN_BUY : ModuleStatus.CAN_RESEARCH;
}
return arePrerequisitesOwned(profile, vehicle, modification.requires) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED;
}
@@ -0,0 +1,27 @@
/**
* Buying spares (cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i, scripts
* weaponry/weaponsPurchase.nut): the wpcost.blk spare price times the amount, added to
* hangar/<vehicle>/spareAircraftsCount, at most MAX_SPARE_AMOUNT (scripts
* weaponry/weaponryConsts.nut).
*/
import type { BlkBlock } from '@wto/blk';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { ownsVehicle } from '../profile/profile-hangar.ts';
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';
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;
if (!spare || !ownsVehicle(profile, vehicle) || amount < 1) return refused('BAD_PARAMS');
const owned = spareCount(profile, vehicle);
if (owned + amount > MAX_SPARE_AMOUNT) return refused('NOT_AVAILABLE');
const price: Price = { silverLions: spare.silverLions * amount, goldenEagles: spare.goldenEagles * amount };
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);
setSpareCount(profile, vehicle, owned + amount);
return ACCEPTED;
}
@@ -0,0 +1,50 @@
/**
* The modifications the mission support planes' forced presets need (gameplay.blk
* missionSupportPlane <country>{ unitName weapon }, e.g. f_16a_block_15_adf_killstreak with
* f_16a_block_15_adf_killstreak_b61_30kt_nt, whose bombguns_us_b61_30kt has reqModification
* us_500lb_mk82 in wpcost.blk), kept in every profile as owned.
*
* The respawn screen lists a preset only when shop_is_weapon_available passes (aces.exe 2.61.0.37
* 0x17a38a0 -> 0x912d20 -> 0x90f2c0 / 0x9662f0): every reqModification of the preset and of the
* weapons in its sum_weapons must be a bought modification of the unit in the profile; the unit's
* killStreak flag adds a condition but does not lift this one. Without the records the support
* plane's loadout box is empty. The player never owns these units, so online the server has to
* provide the records (inferred; not observed).
*/
import type { BlkBlock } from '@wto/blk';
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
import { ownsModification, writeModificationRecord } from '../profile/profile-modifications.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
export interface SupportPlaneModification {
readonly vehicle: string;
readonly modification: string;
}
export function supportPlaneModifications(
rules: Pick<BattleSpawnRulesData, 'supportPlanes'>,
catalogue: EquipmentCatalogue,
): readonly SupportPlaneModification[] {
const seen = new Set<string>();
const out: SupportPlaneModification[] = [];
for (const presets of Object.values(rules.supportPlanes)) {
for (const preset of presets) {
for (const { unitName, weapon } of Object.values(preset.units)) {
for (const modification of catalogue.weapon(unitName, weapon)?.requires ?? []) {
const key = `${unitName}/${modification}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({ vehicle: unitName, modification });
}
}
}
}
return out;
}
export function grantSupportPlaneModifications(profile: BlkBlock, grants: readonly SupportPlaneModification[]): void {
for (const { vehicle, modification } of grants) {
if (ownsModification(profile, vehicle, modification)) continue;
writeModificationRecord(profile, vehicle, modification, { silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: true, count: 1 });
}
}
@@ -0,0 +1,95 @@
/**
* Saving, renaming and deleting custom secondary weapon presets (`cln_save_weapon_presets`,
* scripts/unit/unitWeaponryCustomPresets.nut `savePresetInProfile`; implementation notes).
*
* Sent via `charSendBlk` (job type 13 -> full profile update). Request payload:
* <vehicle>{ <presetId>{ name:t="..." Weapon{ preset:t="..." slot:i=... } ... } }
* - Add / copy / edit / rename: `<presetId>` (`custom0`, `custom1`, ...) carries `name:t` and
* zero or more `Weapon{ preset:t, slot:i }` (or infantry `soldier{ index:i, weapon{...} }`)
* blocks -> upserts that single preset under `weaponPresets/<vehicle>`.
* - Delete (`deleteCustomPreset`): `<presetId>{}` is an empty block -> removes that preset.
*/
import { findParam, type BlkBlock } from '@wto/blk';
import { ownsVehicle } from '../profile/profile-hangar.ts';
import {
clearVehicleWeaponPresets,
deleteVehicleWeaponPreset,
upsertVehicleWeaponPreset,
vehicleWeaponPresets,
} from '../profile/profile-weapon-presets.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
/** Client limit (`scripts/weaponry/weaponryPresets.nut` line 7 `MAX_PRESETS_NUM = 20`). */
export const MAX_CUSTOM_PRESETS = 20;
const CUSTOM_PRESET_ID = /^custom\d+$/;
export function saveWeaponPresets(profile: BlkBlock, catalogue: EquipmentCatalogue, request: BlkBlock): RuleOutcome {
if (request.params.length > 0 || request.blocks.length === 0) return refused('BAD_PARAMS');
for (const vehicleBlock of request.blocks) {
const check = validateVehiclePresets(profile, catalogue, vehicleBlock);
if (!check.ok) return check;
}
for (const vehicleBlock of request.blocks) applyVehiclePresets(profile, vehicleBlock);
return ACCEPTED;
}
function validateVehiclePresets(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicleBlock: BlkBlock): RuleOutcome {
if (!vehicleBlock.name || vehicleBlock.params.length > 0 || !catalogue.vehicle(vehicleBlock.name)) {
return refused('BAD_PARAMS');
}
if (!ownsVehicle(profile, vehicleBlock.name) || !catalogue.weapon(vehicleBlock.name, 'custom_presets')) {
return refused('NOT_AVAILABLE');
}
const projected = new Set(vehicleWeaponPresets(profile, vehicleBlock.name).map((preset) => preset.name));
if (vehicleBlock.blocks.length === 0) return ACCEPTED;
for (const presetBlock of vehicleBlock.blocks) {
if (!CUSTOM_PRESET_ID.test(presetBlock.name)) return refused('BAD_PARAMS');
if (isEmptyBlock(presetBlock)) {
projected.delete(presetBlock.name);
continue;
}
if (!isValidPresetPayload(presetBlock)) return refused('BAD_PARAMS');
projected.add(presetBlock.name);
}
return projected.size <= MAX_CUSTOM_PRESETS ? ACCEPTED : refused('NOT_AVAILABLE');
}
function applyVehiclePresets(profile: BlkBlock, vehicleBlock: BlkBlock): void {
if (vehicleBlock.blocks.length === 0) {
clearVehicleWeaponPresets(profile, vehicleBlock.name);
return;
}
for (const presetBlock of vehicleBlock.blocks) {
if (isEmptyBlock(presetBlock)) deleteVehicleWeaponPreset(profile, vehicleBlock.name, presetBlock.name);
else upsertVehicleWeaponPreset(profile, vehicleBlock.name, presetBlock);
}
}
function isEmptyBlock(block: BlkBlock): boolean {
return block.params.length === 0 && block.blocks.length === 0;
}
function isValidPresetPayload(preset: BlkBlock): boolean {
if (preset.params.length !== 1 || findParam(preset, 'name')?.value.type !== 'string') return false;
return preset.blocks.every((sub) => isValidWeaponSlot(sub) || isValidInfantrySoldier(sub));
}
function isValidWeaponSlot(block: BlkBlock): boolean {
return block.name === 'Weapon'
&& block.blocks.length === 0
&& block.params.length === 2
&& findParam(block, 'preset')?.value.type === 'string'
&& findParam(block, 'slot')?.value.type === 'int';
}
function isValidInfantrySoldier(block: BlkBlock): boolean {
if (block.name !== 'soldier' || block.params.length !== 1 || findParam(block, 'index')?.value.type !== 'int') return false;
return block.blocks.every((weapon) =>
weapon.name === 'weapon'
&& weapon.blocks.length === 0
&& weapon.params.length === 2
&& findParam(weapon, 'slot')?.value.type === 'int'
&& findParam(weapon, 'preset')?.value.type === 'string');
}
@@ -0,0 +1,42 @@
/**
* Buying weapon presets (cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i, scripts
* weaponry/weaponsPurchase.nut sendPurchaseWeaponRequest; implementation notes).
*
* Paid presets (bombs, rockets) are bought by the piece: the price is the wpcost.blk value times
* the amount, and the player holds at most maxCount pieces (wp_get_weapon_max_count; the client
* offers maxCount minus what it has). Pieces are spent in battle. Free presets come with the
* vehicle (module-state.ts) and are never bought.
*/
import type { BlkBlock } from '@wto/blk';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { ownsVehicle } from '../profile/profile-hangar.ts';
import { weaponRecord, writeWeaponRecord } from '../profile/profile-weapons.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import { isPaidWeapon, type EquipmentCatalogue } from './equipment-catalogue.ts';
import { arePrerequisitesOwned } from './module-status.ts';
export interface WeaponOrder {
readonly vehicle: string;
readonly weapon: string;
readonly amount: number;
readonly offered: Price;
}
export function buyWeapons(profile: BlkBlock, catalogue: EquipmentCatalogue, order: WeaponOrder): RuleOutcome {
const weapon = catalogue.weapon(order.vehicle, order.weapon);
if (!weapon || !ownsVehicle(profile, order.vehicle) || order.amount < 1) return refused('BAD_PARAMS');
if (!isPaidWeapon(weapon) || !arePrerequisitesOwned(profile, order.vehicle, weapon.requires)) return refused('NOT_AVAILABLE');
const record = weaponRecord(profile, order.vehicle, order.weapon);
const held = record?.count ?? 0;
if (held + order.amount > weapon.maxCount) return refused('NOT_AVAILABLE');
const price: Price = { silverLions: weapon.silverLions * order.amount, goldenEagles: weapon.goldenEagles * order.amount };
if (price.silverLions !== order.offered.silverLions || price.goldenEagles !== order.offered.goldenEagles) return refused('PRICE_CHANGED');
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
writeWeaponRecord(profile, order.vehicle, order.weapon, {
silverLionsSpent: (record?.silverLionsSpent ?? 0) + price.silverLions,
goldenEaglesSpent: (record?.goldenEaglesSpent ?? 0) + price.goldenEagles,
count: held + order.amount,
});
return ACCEPTED;
}