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

+29
View File
@@ -0,0 +1,29 @@
/**
* Shared typed field readers and mutators for profile DataBlocks.
*/
import { findParam, type BlkBlock } from '@wto/blk';
export const EMPTY_BLK: BlkBlock = { name: '', params: [], blocks: [] };
export function intField(block: BlkBlock | undefined, name: string, fallback = 0): number {
const value = block && findParam(block, name)?.value;
if (value?.type === 'int') return value.value;
if (value?.type === 'int64') return Number(value.value);
return fallback;
}
export function int64Field(block: BlkBlock | undefined, name: string, fallback = 0n): bigint {
const value = block && findParam(block, name)?.value;
if (value?.type === 'int64') return value.value;
if (value?.type === 'int') return BigInt(value.value);
return fallback;
}
export function stringField(block: BlkBlock | undefined, name: string, fallback = ''): string {
const value = block && findParam(block, name)?.value;
return value?.type === 'string' ? value.value : fallback;
}
export function removeParam(block: BlkBlock, name: string): void {
block.params = block.params.filter((param) => param.name !== name);
}
+22
View File
@@ -0,0 +1,22 @@
/**
* The profile as the char service hands it to the client: the saved profile plus the
* account data and server clock the char server attaches on the wire.
*
* 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).
*
* 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 { clearStoreCart } from './profile-store-cart.ts';
import { serverTimeNow } from './server-time.ts';
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
const profile = structuredClone(saved);
clearStoreCart(profile);
setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick });
setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() });
return profile;
}
+38
View File
@@ -0,0 +1,38 @@
/**
* Putting vehicles into crew slots: the first choice (cln_set_starting_info) and applying a
* slotbar preset (cln_bulk_train_aircraft) send a list of crew slot -> vehicle (gui.vromfs.bin
* scripts/crew/crewTrain.nut createBatchTrainCrewRequestBlk); taking a vehicle into one slot
* or clearing it (cln_train_aircraft) sends a single one. An empty vehicle name leaves the
* slot empty.
*
* A slot can only take a vehicle the player owns, as online. Training a crew for a vehicle
* costs nothing yet: the economy rules do not exist so far.
*/
import type { BlkBlock } from '@wto/blk';
import { crewOf, emptyCrewSlot, putVehicleInCrew, trainCrewFor } from './profile-crews.ts';
import { ownsVehicle } from './profile-hangar.ts';
export interface CrewSlotAssignment {
readonly crewId: number;
/** Empty: leave the slot empty. */
readonly vehicle: string;
}
/** Every crew exists and every vehicle is owned. */
export function canAssignCrewSlots(profile: BlkBlock, assignments: readonly CrewSlotAssignment[]): boolean {
return assignments.every(({ crewId, vehicle }) => crewOf(profile, crewId) !== undefined && (vehicle === '' || ownsVehicle(profile, vehicle)));
}
/** Apply assignments that canAssignCrewSlots accepted. */
export function assignCrewSlots(profile: BlkBlock, assignments: readonly CrewSlotAssignment[]): void {
for (const { crewId, vehicle } of assignments) {
const crew = crewOf(profile, crewId)!;
if (vehicle === '') emptyCrewSlot(crew);
else putVehicleInCrew(crew, vehicle);
}
}
/** Train one crew for a vehicle without changing its slot; the assignment must have passed canAssignCrewSlots. */
export function trainCrewKeepingSlot(profile: BlkBlock, { crewId, vehicle }: CrewSlotAssignment): void {
if (vehicle !== '') trainCrewFor(crewOf(profile, crewId)!, vehicle);
}
@@ -0,0 +1,17 @@
/** Typed starting balances loaded from tuning/new-profile.jsonc. */
import type { TuningReader } from '../tuning/tuning-reader.ts';
import type { Balance } from './profile-currency.ts';
export interface NewProfileTuning {
readonly startingBalance: Balance;
}
export function readNewProfileTuning(file: TuningReader): NewProfileTuning {
return {
startingBalance: {
silverLions: file.int('silverLions', { min: 0 }),
goldenEagles: file.int('goldenEagles', { min: 0, max: 0x7fffffff }),
gjnCents: file.money('gjn', { min: 0 }),
},
};
}
+17
View File
@@ -0,0 +1,17 @@
/**
* A new account's profile: Gaijin's own new-account template from the player's game files
* (config/default_user.blk), plus the offline starting content (starting-content.ts) and the
* starting balances defined separately in tuning/new-profile.jsonc.
*/
import type { BlkBlock } from '@wto/blk';
import { setGjnCents, setGoldenEagles, setSilverLions } from './profile-currency.ts';
import { applyStartingContent, type StartingContent } from './starting-content.ts';
export function newProfile(template: BlkBlock, content: StartingContent): BlkBlock {
const profile = structuredClone(template);
applyStartingContent(profile, content);
setSilverLions(profile, content.startingBalance.silverLions);
setGoldenEagles(profile, content.startingBalance.goldenEagles);
setGjnCents(profile, content.startingBalance.gjnCents);
return profile;
}
@@ -0,0 +1,57 @@
/**
* The one way services get a player's profile: the saved one, or a new one that is written
* to the save before it is handed out.
*
* State that follows from the rest of the profile (clan sync, statuses, open ranks, earned
* unlocks: research/research-state.ts) is brought up to date every time a profile is handed
* out or changed, and saved with it, so every action returns a consistent persisted profile.
*/
import type { BlkBlock } from '@wto/blk';
import type { GameFiles } from '../game-data/game-files.ts';
import type { SaveStore } from '../saves/save-store.ts';
import { newProfile } from './new-profile.ts';
import type { StartingContent } from './starting-content.ts';
/** Brings the derived state of a profile up to date, in place. */
export type ProfileRefresh = (profile: BlkBlock, userId: string) => void;
export class PlayerProfiles {
readonly #saves: SaveStore;
readonly #gameFiles: GameFiles;
readonly #startingContent: StartingContent;
readonly #refresh: ProfileRefresh;
constructor(saves: SaveStore, gameFiles: GameFiles, startingContent: StartingContent, refresh: ProfileRefresh) {
this.#saves = saves;
this.#gameFiles = gameFiles;
this.#startingContent = startingContent;
this.#refresh = refresh;
}
profileOf(userId: string): BlkBlock {
const profile = this.#saves.loadProfile(userId) ?? newProfile(this.#gameFiles.newAccountTemplate(), this.#startingContent);
this.#refresh(profile, userId);
this.#saves.saveProfile(userId, profile);
return profile;
}
/** Change the player's profile and write it to the save before returning it. */
update(userId: string, change: (profile: BlkBlock) => void): BlkBlock {
return this.updateWhen(userId, (profile) => {
change(profile);
return true;
})!;
}
/**
* Change the player's profile if `change` accepts (returns true); the change must not touch
* the profile when it refuses. Returns the saved profile, or undefined when refused.
*/
updateWhen(userId: string, change: (profile: BlkBlock) => boolean): BlkBlock | undefined {
const profile = this.profileOf(userId);
if (!change(profile)) return undefined;
this.#refresh(profile, userId);
this.#saves.saveProfile(userId, profile);
return profile;
}
}
@@ -0,0 +1,38 @@
/**
* The player's card in the profile:
* title:t the chosen title (profile top level, read by the client's
* profile serializer)
* pilotAppearance{ pilotIcon:t background:t frame:t }
* what cln_save_pilot_appearance sets; the client itself reads
* it back through cln_get_users_terse_info, so the block is the
* local server's own record
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const TITLE = 'title';
const APPEARANCE = 'pilotAppearance';
export const APPEARANCE_FIELDS = ['pilotIcon', 'background', 'frame'] as const;
export type AppearanceField = (typeof APPEARANCE_FIELDS)[number];
export function chosenTitle(profile: BlkBlock): string {
const value = findParam(profile, TITLE)?.value;
return value?.type === 'string' ? value.value : '';
}
export function setChosenTitle(profile: BlkBlock, title: string): void {
setParam(profile, TITLE, { type: 'string', value: title });
}
export function appearance(profile: BlkBlock): Partial<Record<AppearanceField, string>> {
const block = findBlock(profile, APPEARANCE);
const result: Partial<Record<AppearanceField, string>> = {};
for (const field of APPEARANCE_FIELDS) {
const value = block && findParam(block, field)?.value;
if (value?.type === 'string') result[field] = value.value;
}
return result;
}
export function setAppearance(profile: BlkBlock, field: AppearanceField, image: string): void {
setParam(ensureBlock(profile, APPEARANCE), field, { type: 'string', value: image });
}
+136
View File
@@ -0,0 +1,136 @@
/**
* Squadron (clan) membership and squadron vehicle research fields in `profile.blk`
* (implementation notes; aces.exe 0x91fa31..0x91fd00 and 0x906790..0x906ac5).
*/
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { int64Field, intField, removeParam, stringField } from './blk-fields.ts';
const CLAN_RESEARCH_BLOCK = 'clanResearchUnits';
export type ClanKind = 'normal' | 'battalion';
export interface ProfileClanMembership {
readonly clanId: string;
readonly clanTag: string;
readonly clanName: string;
readonly clanType: ClanKind;
readonly role: number;
readonly requestedClanId: string;
}
export interface SquadronResearchState {
readonly researchUnitName: string;
readonly spentExp: number;
readonly adminExp: number;
readonly storedLastEarnedExp: number;
}
export function clanMembershipOf(profile: BlkBlock): ProfileClanMembership {
const clanIdNum = int64Field(profile, 'clanId', -1n);
const reqNum = int64Field(profile, 'storedRequestClanId', -1n);
return {
clanId: clanIdNum > 0n ? clanIdNum.toString() : '-1',
clanTag: stringField(profile, 'clanTag'),
clanName: stringField(profile, 'clanName'),
clanType: stringField(profile, 'clanType') === 'battalion' ? 'battalion' : 'normal',
role: intField(profile, 'clanMemberRole'),
requestedClanId: clanIdNum <= 0n && reqNum > 0n ? reqNum.toString() : '-1',
};
}
export function setClanMembership(
profile: BlkBlock,
clan: { readonly clanId: string; readonly clanTag: string; readonly clanName: string; readonly clanType: ClanKind; readonly role: number },
): void {
setParam(profile, 'clanId', { type: 'int64', value: BigInt(clan.clanId) });
setParam(profile, 'clanMemberRole', { type: 'int', value: clan.role });
setParam(profile, 'clanType', { type: 'string', value: clan.clanType });
setParam(profile, 'clanTag', { type: 'string', value: clan.clanTag });
setParam(profile, 'clanName', { type: 'string', value: clan.clanName });
removeParam(profile, 'storedRequestClanId');
}
export function clearClanMembership(profile: BlkBlock): void {
removeParam(profile, 'clanId');
removeParam(profile, 'clanMemberRole');
removeParam(profile, 'clanType');
removeParam(profile, 'clanTag');
removeParam(profile, 'clanName');
removeParam(profile, 'storedRequestClanId');
}
export function setPendingClanRequest(
profile: BlkBlock,
request: { readonly clanId: string; readonly clanTag: string; readonly clanName: string } | undefined,
): void {
clearClanMembership(profile);
if (!request) return;
setParam(profile, 'storedRequestClanId', { type: 'int64', value: BigInt(request.clanId) });
setParam(profile, 'clanTag', { type: 'string', value: request.clanTag });
setParam(profile, 'clanName', { type: 'string', value: request.clanName });
}
export function squadronResearchOf(profile: BlkBlock): SquadronResearchState {
const block = findBlock(profile, CLAN_RESEARCH_BLOCK);
return {
researchUnitName: stringField(block, 'researchUnitName'),
spentExp: intField(block, 'spentExp'),
adminExp: intField(block, 'adminExp'),
storedLastEarnedExp: intField(block, 'storedLastEarnedExp'),
};
}
/** Exact formula of `clan_get_exp` at aces.exe 0x1780ba0..0x1780be5. */
export function availableSquadronRp(profile: BlkBlock, clanActivityEarnedExp = 0): number {
const state = squadronResearchOf(profile);
const earned = Math.max(clanActivityEarnedExp, state.storedLastEarnedExp);
return Math.max(0, earned + state.adminExp - state.spentExp);
}
export function setSquadronResearchTarget(profile: BlkBlock, unitName: string): void {
const block = ensureClanResearchBlock(profile);
setParam(block, 'researchUnitName', { type: 'string', value: unitName });
}
export function syncStoredClanEarnedExp(profile: BlkBlock, clanEarnedExp: number): void {
if (clanEarnedExp <= 0) return;
const state = squadronResearchOf(profile);
if (clanEarnedExp > state.storedLastEarnedExp) {
const block = ensureClanResearchBlock(profile);
setParam(block, 'storedLastEarnedExp', { type: 'int', value: clanEarnedExp });
}
}
export function spendSquadronRp(profile: BlkBlock, amount: number): void {
if (amount <= 0) return;
const state = squadronResearchOf(profile);
const block = ensureClanResearchBlock(profile);
setParam(block, 'spentExp', { type: 'int', value: state.spentExp + amount });
}
/** Set the player's available squadron RP directly (for save-cli.ts / save editor). */
export function setAvailableSquadronRp(profile: BlkBlock, desiredRp: number, clanActivityEarnedExp = 0): void {
const target = Math.max(0, Math.trunc(desiredRp));
const state = squadronResearchOf(profile);
const block = ensureClanResearchBlock(profile);
const earnedBase = Math.max(clanActivityEarnedExp, state.storedLastEarnedExp);
if (earnedBase + state.adminExp - state.spentExp === target) return;
if (target >= earnedBase) {
setParam(block, 'spentExp', { type: 'int', value: 0 });
setParam(block, 'adminExp', { type: 'int', value: target - earnedBase });
} else {
setParam(block, 'adminExp', { type: 'int', value: 0 });
setParam(block, 'spentExp', { type: 'int', value: earnedBase - target });
}
}
function ensureClanResearchBlock(profile: BlkBlock): BlkBlock {
const existing = findBlock(profile, CLAN_RESEARCH_BLOCK);
if (existing) return existing;
const block = ensureBlock(profile, CLAN_RESEARCH_BLOCK);
setParam(block, 'researchUnitName', { type: 'string', value: '' });
setParam(block, 'spentExp', { type: 'int', value: 0 });
setParam(block, 'adminExp', { type: 'int', value: 0 });
setParam(block, 'storedLastEarnedExp', { type: 'int', value: 0 });
return block;
}
@@ -0,0 +1,70 @@
/**
* Client-writable profile preferences persisted via `cln_update`
* (aces.exe 2.61.0.37 `ClientEconomicState::saveOnline` -> `EconomicState::serialize` 0x917870,
* mode 0x80 `CHARSRV_GET_FROM_CLIENT`):
* - hangar toggles `autoRefillWeapons:b`, `autoRepairAircrafts:b`, `autoBuyModifications:b` (0x918ef0);
* - privacy / save metadata `onlineSaveVersion:i`, `allowToBeAddedToContacts:b`, `allowToBeAddedToLB:b` (0x9179d4..0x917a4c);
* - `classinessMarkPriorities:i64` (0x92b2cb);
* - sub-block `mapPreferences` (0x927530 -> 0x9483d0).
*
* Empty shell blocks that `saveOnline` (mode 0x20) also emits (`entitlementsInfo{}`,
* `pveProgress{}`, `weaponPresets{}` — custom weapon presets use `cln_save_weapon_presets`, and
* mode 0x80 skips `weaponPresets` at 0x9677d8) are intentionally ignored so server-authoritative
* state is preserved.
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import { disableUserLogs } from './profile-trophies-log.ts';
const BOOL_SETTINGS = [
'autoRefillWeapons',
'autoRepairAircrafts',
'autoBuyModifications',
'allowToBeAddedToContacts',
'allowToBeAddedToLB',
] as const;
/**
* Whether hangar ammunition/expendable auto-refill is enabled (`EconomicState` +0xe979).
* Defaults to `true` when absent from `profile.blk`, matching `aces.exe` 0x90b6a0 and 0x918ef0.
*/
export function isAutoRefillWeaponsEnabled(profile: BlkBlock): boolean {
const param = findParam(profile, 'autoRefillWeapons')?.value;
return param?.type === 'bool' ? param.value : true;
}
/** Whether vehicles are repaired automatically after a battle (`EconomicState` +0xe978); `true` when absent (0x90b6a0). */
export function isAutoRepairEnabled(profile: BlkBlock): boolean {
const param = findParam(profile, 'autoRepairAircrafts')?.value;
return param?.type === 'bool' ? param.value : true;
}
export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock): void {
for (const name of BOOL_SETTINGS) {
const param = findParam(request, name)?.value;
if (param?.type === 'bool') setParam(profile, name, param);
}
const onlineSaveVer = findParam(request, 'onlineSaveVersion')?.value;
if (onlineSaveVer?.type === 'int') setParam(profile, 'onlineSaveVersion', onlineSaveVer);
const markPriorities = findParam(request, 'classinessMarkPriorities')?.value;
if (markPriorities?.type === 'int64') setParam(profile, 'classinessMarkPriorities', markPriorities);
const mapPreferences = findBlock(request, 'mapPreferences');
if (mapPreferences) {
const target = ensureBlock(profile, 'mapPreferences');
const cloned = structuredClone(mapPreferences);
target.params = cloned.params;
target.blocks = cloned.blocks;
}
const userlogs = findBlock(request, 'userlogs');
if (userlogs) {
const idsToDisable = userlogs.blocks
.filter((entry) => {
const flag = findParam(entry, 'haveToDisable')?.value;
return flag?.type === 'bool' && flag.value;
})
.map((entry) => entry.name);
if (idsToDisable.length > 0) disableUserLogs(profile, idsToDisable);
}
}
@@ -0,0 +1,114 @@
/**
* Crew skills, skill points, specializations, and Expert-to-Ace RP inside a crew block
*:
*
* crews{
* c0{
* country:t="country_usa"
* aircrafts{ trained:t="us_m2a4" spec:i=1 trained:t="us_m22_locust" spec:i=0 current:t="us_m2a4" }
* expertToAceProgress{ us_m2a4:i=12000 }
* commander{ crewMember_0{ eyesight:i64=5 field_repair:i64=2 } }
* skillPointsStat:i64=0
* skillPointsManualChanges:i64=150000
* }
* }
*
* Skill levels sit in <page>/crewMember_0 as i64 (aces.exe 0x939b40..0x939c62). Skill points are
* kept times 100: the client shows (skillPointsStat + skillPointsManualChanges) / 100
* (get_crew_info, 0x179dbac); the local server books what the player buys and spends in
* skillPointsManualChanges. Every trained vehicle is followed by its spec (0 none, 1 expert,
* 2 ace), as the client writes them (0x939ed0..0x939f55), and per-vehicle Expert-to-Ace RP sits
* in expertToAceProgress/<vehicle>:i (0x93b0d0..0x93b4eb).
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
const MEMBER = 'crewMember_0';
const EARNED_POINTS = 'skillPointsStat';
const BOOKED_POINTS = 'skillPointsManualChanges';
const POINTS_SCALE = 100;
const VEHICLES = 'aircrafts';
const TRAINED = 'trained';
const SPEC = 'spec';
const ACE_PROGRESS = 'expertToAceProgress';
export function skillLevel(crew: BlkBlock, page: string, skill: string): number {
const pageBlock = findBlock(crew, page);
const member = pageBlock && findBlock(pageBlock, MEMBER);
return member ? intOf(member, skill) : 0;
}
export function setSkillLevel(crew: BlkBlock, page: string, skill: string, level: number): void {
setParam(ensureBlock(ensureBlock(crew, page), MEMBER), skill, { type: 'int64', value: BigInt(level) });
}
/** Skill points as the player sees them. */
export function skillPoints(crew: BlkBlock): number {
return Math.floor((intOf(crew, EARNED_POINTS) + intOf(crew, BOOKED_POINTS)) / POINTS_SCALE);
}
export function addSkillPoints(crew: BlkBlock, points: number): void {
setParam(crew, BOOKED_POINTS, { type: 'int64', value: BigInt(intOf(crew, BOOKED_POINTS) + points * POINTS_SCALE) });
}
/** Skill points the crew earned in battle (kept apart from bought or spent points, as the client does). */
export function addEarnedSkillPoints(crew: BlkBlock, points: number): void {
setParam(crew, EARNED_POINTS, { type: 'int64', value: BigInt(intOf(crew, EARNED_POINTS) + Math.round(points * POINTS_SCALE)) });
}
export function isTrainedFor(crew: BlkBlock, vehicle: string): boolean {
return (findBlock(crew, VEHICLES)?.params ?? []).some((param) => param.name === TRAINED && param.value.type === 'string' && param.value.value === vehicle);
}
export function specializationOf(crew: BlkBlock, vehicle: string): number {
return trainedPairs(crew).find((pair) => pair.vehicle === vehicle)?.spec ?? 0;
}
export function setSpecialization(crew: BlkBlock, vehicle: string, spec: number): void {
const vehicles = ensureBlock(crew, VEHICLES);
const pairs = trainedPairs(crew).map((pair) => pair.vehicle === vehicle ? { ...pair, spec } : pair);
const rest = vehicles.params.filter((param) => param.name !== TRAINED && param.name !== SPEC);
vehicles.params = [
...pairs.flatMap((pair): BlkParam[] => [
{ name: TRAINED, value: { type: 'string', value: pair.vehicle } },
{ name: SPEC, value: { type: 'int', value: pair.spec } },
]),
...rest,
];
}
/** trained/spec pairs in order; a trained vehicle without a following spec has spec 0. */
/** The vehicles the crew is trained for, each with its specialization (0 none, 1 expert, 2 ace). */
export function trainedPairs(crew: BlkBlock): { vehicle: string; spec: number }[] {
const pairs: { vehicle: string; spec: number }[] = [];
for (const param of findBlock(crew, VEHICLES)?.params ?? []) {
if (param.name === TRAINED && param.value.type === 'string') pairs.push({ vehicle: param.value.value, spec: 0 });
else if (param.name === SPEC && param.value.type === 'int' && pairs.length) pairs[pairs.length - 1]!.spec = param.value.value;
}
return pairs;
}
export function expertToAceRp(crew: BlkBlock, vehicle: string): number {
const progress = findBlock(crew, ACE_PROGRESS);
return progress ? intOf(progress, vehicle) : 0;
}
export function addExpertToAceRp(crew: BlkBlock, vehicle: string, deltaRp: number, maxRp: number): void {
if (deltaRp <= 0 || maxRp <= 0) return;
const current = expertToAceRp(crew, vehicle);
const next = Math.min(maxRp, Math.max(0, current + Math.trunc(deltaRp)));
if (next !== current) setParam(ensureBlock(crew, ACE_PROGRESS), vehicle, { type: 'int', value: next });
}
/** Drop the vehicle's Expert-to-Ace RP, and the block when it is empty (as the client does, 0x93b4eb). */
export function clearExpertToAceRp(crew: BlkBlock, vehicle: string): void {
const progress = findBlock(crew, ACE_PROGRESS);
if (!progress) return;
progress.params = progress.params.filter((param) => param.name !== vehicle);
if (progress.params.length === 0 && progress.blocks.length === 0) crew.blocks = crew.blocks.filter((block) => block !== progress);
}
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;
}
+101
View File
@@ -0,0 +1,101 @@
/**
* Crews in the profile, as in Gaijin's config/default_user.blk:
*
* crews{
* c0{
* country:t="country_usa"
* aircrafts{ trained:t="bf2c_1" trained:t="p-26a_34_m2" current:t="bf2c_1" }
* }
* }
*
* "trained" lists the vehicles the crew is trained for (repeated), "current" is the vehicle
* in its slot.
*/
import { ensureBlock, type BlkBlock } from '@wto/blk';
const CREWS = 'crews';
const VEHICLES = 'aircrafts';
const TRAINED = 'trained';
const CURRENT = 'current';
const CREW_NAME = /^c(\d+)$/;
export function crewOf(profile: BlkBlock, crewId: number): BlkBlock | undefined {
return profile.blocks.find((block) => block.name === CREWS)?.blocks.find((crew) => crew.name === `c${crewId}`);
}
/** Every crew block, in profile order. */
export function allCrews(profile: BlkBlock): readonly BlkBlock[] {
return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => CREW_NAME.test(crew.name));
}
export function crewCountOf(profile: BlkBlock, country: string): number {
return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => crewCountry(crew) === country).length;
}
/** Non-empty vehicles currently slotted in the country's crews, in profile order. */
export function crewVehiclesOfCountry(profile: BlkBlock, country: string): string[] {
return allCrews(profile)
.filter((crew) => crewCountry(crew) === country)
.flatMap((crew) => {
const current = crew.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value.length > 0 ? [current.value] : [];
});
}
/** Vehicle slotted in the country's `slotIndex`-th crew (`idInCountry`), if non-empty. */
export function crewSlotVehicleOfCountry(profile: BlkBlock, country: string, slotIndex: number): string | undefined {
if (!Number.isInteger(slotIndex) || slotIndex < 0) return undefined;
const crew = allCrews(profile).filter((entry) => crewCountry(entry) === country)[slotIndex];
const current = crew?.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value.length > 0 ? current.value : undefined;
}
/** Crew block in `country` currently equipping `vehicle` (or trained for it as fallback). */
export function crewForVehicleInCountry(profile: BlkBlock, country: string, vehicle: string): BlkBlock | undefined {
const crews = allCrews(profile).filter((entry) => crewCountry(entry) === country);
const slotted = crews.find((entry) => {
const current = entry.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value === vehicle;
});
if (slotted) return slotted;
return crews.find((entry) =>
(entry.blocks.find((block) => block.name === VEHICLES)?.params ?? []).some(
(param) => param.name === TRAINED && param.value.type === 'string' && param.value.value === vehicle,
));
}
/** Add an empty crew for the country, numbered after every existing crew; returns its id. */
export function addCrew(profile: BlkBlock, country: string): number {
const crews = ensureBlock(profile, CREWS);
const id = crews.blocks.reduce((highest, crew) => Math.max(highest, Number(CREW_NAME.exec(crew.name)?.[1] ?? -1)), -1) + 1;
crews.blocks.push({ name: `c${id}`, params: [{ name: 'country', value: { type: 'string', value: country } }], blocks: [{ name: VEHICLES, params: [], blocks: [] }] });
return id;
}
function crewCountry(crew: BlkBlock): string | undefined {
const value = crew.params.find((param) => param.name === 'country')?.value;
return value?.type === 'string' ? value.value : undefined;
}
/** Leave the crew's slot empty; the vehicles it is trained for stay trained. */
export function emptyCrewSlot(crew: BlkBlock): void {
const vehicles = crew.blocks.find((block) => block.name === VEHICLES);
if (vehicles) vehicles.params = vehicles.params.filter((param) => param.name !== CURRENT);
}
/** Train the crew for the vehicle, if it is not yet; the vehicle in its slot stays. "current" stays last, as in Gaijin's profiles. */
export function trainCrewFor(crew: BlkBlock, vehicle: string): void {
const vehicles = ensureBlock(crew, VEHICLES);
const trained = vehicles.params.some((param) => param.name === TRAINED && param.value.type === 'string' && param.value.value === vehicle);
if (trained) return;
const current = vehicles.params.filter((param) => param.name === CURRENT);
vehicles.params = [...vehicles.params.filter((param) => param.name !== CURRENT), { name: TRAINED, value: { type: 'string', value: vehicle } }, ...current];
}
/** Train the crew for the vehicle (if it is not yet) and put the vehicle in its slot. */
export function putVehicleInCrew(crew: BlkBlock, vehicle: string): void {
emptyCrewSlot(crew);
trainCrewFor(crew, vehicle);
ensureBlock(crew, VEHICLES).params.push({ name: CURRENT, value: { type: 'string', value: vehicle } });
}
@@ -0,0 +1,99 @@
/**
* The player's money in the profile (implementation notes; read by aces.exe 2.61.0.37
* 0x919060):
*
* warpointsPos:i64 silver lions earned in total
* warpointsNeg:i64 silver lions spent in total
* goldBalance:i golden eagles (read and written as a 32-bit integer, 0x91b570 / 0x91b5cb)
* gjnBalanceCents:i64 GJN balance in hundredths (GJN prices have two decimals, like the USD
* price they equal); offline store and market only (implementation notes section
* 5.1), the client ignores it
*
* The silver lion balance is warpointsPos - warpointsNeg; setting it keeps the amount spent
* and adjusts the amount earned.
*/
import { setParam, type BlkBlock } from '@wto/blk';
import { intField } from './blk-fields.ts';
const EARNED = 'warpointsPos';
const SPENT = 'warpointsNeg';
const GOLD = 'goldBalance';
const GJN = 'gjnBalanceCents';
const MAX_GOLD = 0x7fffffff;
export interface Balance {
readonly silverLions: number;
readonly goldenEagles: number;
/** GJN in hundredths. */
readonly gjnCents: number;
}
export function balanceOf(profile: BlkBlock): Balance {
return {
silverLions: intField(profile, EARNED) - intField(profile, SPENT),
goldenEagles: intField(profile, GOLD),
gjnCents: intField(profile, GJN),
};
}
export function setSilverLions(profile: BlkBlock, amount: number): void {
requireAmount(amount, Number.MAX_SAFE_INTEGER);
setParam(profile, EARNED, { type: 'int64', value: BigInt(amount + intField(profile, SPENT)) });
}
export function setGoldenEagles(profile: BlkBlock, amount: number): void {
requireAmount(amount, MAX_GOLD);
setParam(profile, GOLD, { type: 'int', value: amount });
}
export function setGjnCents(profile: BlkBlock, amount: number): void {
requireAmount(amount, Number.MAX_SAFE_INTEGER);
setParam(profile, GJN, { type: 'int64', value: BigInt(amount) });
}
export function addGoldenEagles(profile: BlkBlock, amount: number): void {
requireAmount(amount, MAX_GOLD);
const next = Math.min(MAX_GOLD, intField(profile, GOLD) + amount);
setGoldenEagles(profile, next);
}
export function addSilverLions(profile: BlkBlock, amount: number): void {
requireAmount(amount, Number.MAX_SAFE_INTEGER);
setParam(profile, EARNED, { type: 'int64', value: BigInt(intField(profile, EARNED) + amount) });
}
export function addGjnCents(profile: BlkBlock, amount: number): void {
requireAmount(amount, Number.MAX_SAFE_INTEGER);
setGjnCents(profile, intField(profile, GJN) + amount);
}
export function payGjnCents(profile: BlkBlock, amount: number): void {
requireAmount(amount, Number.MAX_SAFE_INTEGER);
const current = intField(profile, GJN);
if (current < amount) throw new RangeError('the player cannot afford this GJN price');
setGjnCents(profile, current - amount);
}
/** A price in the two in-game currencies. */
export interface Price {
readonly silverLions: number;
readonly goldenEagles: number;
}
export function canAfford(profile: BlkBlock, price: Price): boolean {
const balance = balanceOf(profile);
return balance.silverLions >= price.silverLions && balance.goldenEagles >= price.goldenEagles;
}
/** Pay a price the player can afford (callers check canAfford first): silver lions count as spent, golden eagles leave the balance. */
export function pay(profile: BlkBlock, price: Price): void {
requireAmount(price.silverLions, Number.MAX_SAFE_INTEGER);
requireAmount(price.goldenEagles, MAX_GOLD);
if (!canAfford(profile, price)) throw new RangeError('the player cannot afford this price');
if (price.silverLions > 0) setParam(profile, SPENT, { type: 'int64', value: BigInt(intField(profile, SPENT) + price.silverLions) });
if (price.goldenEagles > 0) setGoldenEagles(profile, intField(profile, GOLD) - price.goldenEagles);
}
function requireAmount(amount: number, max: number): void {
if (!Number.isSafeInteger(amount) || amount < 0 || amount > max) throw new RangeError(`amount out of range: ${amount}`);
}
@@ -0,0 +1,32 @@
/**
* Decal and attachable layouts in the profile:
*
* decals{ <vehicle>{ <skin>{ <slot params ...> skin_condition:r camo_scale:r camo_rotation:r } } }
* attachables{ <vehicle>{ <skin>{ ... } } }
*
* The client keeps each block whole as its own copy (aces.exe: profile "decals" -> save data
* +0x140, "attachables" -> +0x160) and edits it in the customization window; the local server
* only stores what the client sends, per vehicle and skin.
*/
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
export type DecorLayoutKind = 'decals' | 'attachables';
/** The layouts of one kind, as the client keeps them (a root holding the vehicle blocks). */
export function decorLayouts(profile: BlkBlock, kind: DecorLayoutKind): BlkBlock {
return { name: '', params: [], blocks: structuredClone(findBlock(profile, kind)?.blocks ?? []) };
}
/** Replace the given skins' layouts: changes = { <vehicle>{ <skin>{ ... } } }. */
export function saveDecorLayouts(profile: BlkBlock, kind: DecorLayoutKind, changes: BlkBlock): void {
const layouts = ensureBlock(profile, kind);
for (const vehicle of changes.blocks) {
const saved = ensureBlock(layouts, vehicle.name);
for (const skin of vehicle.blocks) {
const copy = structuredClone(skin);
const index = saved.blocks.findIndex((existing) => existing.name === skin.name);
if (index >= 0) saved.blocks[index] = copy;
else saved.blocks.push(copy);
}
}
}
@@ -0,0 +1,81 @@
/**
* Cross-branch research-point redirection in profile.blk ("Research helicopters by playing
* ground vehicles", gui.vromfs.bin scripts/shop/shop.nut:2341-2354).
*
* Profile contract (verified in aces.exe 2.61.0.37 0x930150..0x93082a & 0x903ca0):
* researchUnits{
* country_usa{
* destTypeRPTank:t="Helicopter"
* }
* }
* - Reader (0x93020e..0x930247): reads "destTypeRP<SrcType>" inside researchUnits.<country>
* and maps it against VEHICLE_TYPES (0..6); missing or unrecognized values become -1
* (ES_UNIT_TYPE_INVALID), exposed to Squirrel by getDestinationRPUnitType (0x15532f0).
* - Writer (0x9307eb..0x93082a): writes "destTypeRP<SrcType>" only when 0 <= destType <= 6
* and omits the parameter when disabled (-1).
* Battle settlement applies it in battle/battle-rp-investment.ts.
*/
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { TechTree } from '../research/tech-tree.ts';
import { VEHICLE_TYPES, vehicleTypeById, type VehicleType } from '../research/vehicle-types.ts';
import { removeParam, stringField } from './blk-fields.ts';
const RESEARCH_UNITS = 'researchUnits';
const DEST_TYPE_PREFIX = 'destTypeRP';
const INVALID_UNIT_TYPE = -1;
export type VehicleDomain = VehicleType;
const VALID_DOMAINS: ReadonlySet<string> = new Set<string>(VEHICLE_TYPES);
export function destinationRpDomain(
profile: BlkBlock,
country: string,
sourceDomain: VehicleDomain,
): VehicleDomain | undefined {
const countryBlock = findBlock(findBlock(profile, RESEARCH_UNITS) ?? { name: '', params: [], blocks: [] }, country);
const raw = stringField(countryBlock, `${DEST_TYPE_PREFIX}${sourceDomain}`);
if (!raw || !VALID_DOMAINS.has(raw) || raw === sourceDomain) return undefined;
return raw as VehicleDomain;
}
export function setDestinationRpDomain(
profile: BlkBlock,
country: string,
sourceDomain: VehicleDomain,
destinationDomain: VehicleDomain | undefined,
): void {
const countryBlock = ensureBlock(ensureBlock(profile, RESEARCH_UNITS), country);
const paramName = `${DEST_TYPE_PREFIX}${sourceDomain}`;
if (!destinationDomain || destinationDomain === sourceDomain) {
removeParam(countryBlock, paramName);
return;
}
removeParam(countryBlock, paramName);
countryBlock.params.push({ name: paramName, value: { type: 'string', value: destinationDomain } });
}
/** Validate and apply cln_set_dest_rp_unit_type (country:t, srcType:i, destType:i). */
export function applySetDestinationRpRule(
profile: BlkBlock,
techTree: TechTree,
country: string,
srcTypeId: number,
destTypeId: number,
): RuleOutcome {
const sourceDomain = vehicleTypeById(srcTypeId);
if (!country || !techTree.hasCountry(country) || !sourceDomain) return refused('BAD_PARAMS');
if (destTypeId === INVALID_UNIT_TYPE) {
setDestinationRpDomain(profile, country, sourceDomain, undefined);
return ACCEPTED;
}
const destinationDomain = vehicleTypeById(destTypeId);
if (!destinationDomain || destinationDomain === sourceDomain) return refused('BAD_PARAMS');
const hasDestinationBranch = techTree.branches().some(
(branch) => branch.country === country && branch.type === destinationDomain,
);
if (!hasDestinationBranch) return refused('NOT_AVAILABLE');
setDestinationRpDomain(profile, country, sourceDomain, destinationDomain);
return ACCEPTED;
}
@@ -0,0 +1,55 @@
/**
* Entitlements and Premium Account in the profile (implementation notes; read by aces.exe
* 2.61.0.37 0x91daf0..0x91e474, has_entitlement 0x179ec70, entitlement_expires_in 0x179ed60):
*
* entitlementsInfo{
* PremiumAccount{
* count:i=1
* expiredTime:i64=<Windows FILETIME>
* }
* wto_pack_f-5c{
* count:i=1
* }
* }
*/
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { EMPTY_BLK, int64Field, intField } from './blk-fields.ts';
const ENTITLEMENTS_INFO = 'entitlementsInfo';
export const PREMIUM_ACCOUNT_ENTITLEMENT = 'PremiumAccount';
const TICKS_PER_SECOND = 10_000_000n;
const TICKS_PER_DAY = 86_400n * TICKS_PER_SECOND;
export function hasEntitlement(profile: BlkBlock, name: string, nowFiletime: bigint): boolean {
const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? EMPTY_BLK, name);
if (!entry) return false;
const count = intField(entry, 'count');
if (count <= 0) return false;
const expires = int64Field(entry, 'expiredTime');
return expires === 0n || expires > nowFiletime;
}
export function recordEntitlementPurchase(profile: BlkBlock, name: string): void {
const entry = ensureBlock(ensureBlock(profile, ENTITLEMENTS_INFO), name);
const previous = intField(entry, 'count');
setParam(entry, 'count', { type: 'int', value: previous + 1 });
}
export function extendPremiumAccount(profile: BlkBlock, days: number, nowFiletime: bigint): void {
if (!Number.isSafeInteger(days) || days <= 0) throw new RangeError(`invalid premium days: ${days}`);
const entry = ensureBlock(ensureBlock(profile, ENTITLEMENTS_INFO), PREMIUM_ACCOUNT_ENTITLEMENT);
const previousCount = intField(entry, 'count');
const previousExpiry = int64Field(entry, 'expiredTime');
const base = previousExpiry > nowFiletime ? previousExpiry : nowFiletime;
setParam(entry, 'count', { type: 'int', value: previousCount + 1 });
setParam(entry, 'expiredTime', { type: 'int64', value: base + BigInt(days) * TICKS_PER_DAY });
}
/** Remaining whole days (rounded up) of Premium Account, or 0 when inactive. */
export function remainingPremiumDays(profile: BlkBlock, nowFiletime: bigint): number {
const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? EMPTY_BLK, PREMIUM_ACCOUNT_ENTITLEMENT);
if (!entry || intField(entry, 'count') <= 0) return 0;
const expires = int64Field(entry, 'expiredTime');
if (expires <= nowFiletime) return 0;
return Number((expires - nowFiletime + TICKS_PER_DAY - 1n) / TICKS_PER_DAY);
}
+31
View File
@@ -0,0 +1,31 @@
/**
* The ranks open for research, per country and vehicle type.
*
* eras{
* Aircraft_country_usa:i=1
* Tank_country_germany:i=1
* }
*
* Read and written by the client's profile serializer (aces.exe 2.61.0.37 0x919060, from
* 0x921b86): for each vehicle type it builds the parameter name "<type>_<country>" from the
* table at 0x72b6d58 (Aircraft, Tank, Ship, Helicopter, Boat, Human, Transport) and keeps an
* integer, the highest rank open. The stock tech tree greys out and locks every rank above it
* (gui.vromfs.bin scripts/shop/shop.nut, is_era_available).
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const ERAS = 'eras';
/** The highest rank open for research in a country for a vehicle type ("Tank", ...); 0 when none is. */
export function openRank(profile: BlkBlock, country: string, vehicleType: string): number {
const eras = findBlock(profile, ERAS);
const value = eras && findParam(eras, `${vehicleType}_${country}`)?.value;
return value?.type === 'int' ? value.value : 0;
}
/** Open ranks up to this one; a higher rank already open stays open. Returns whether anything changed. */
export function openRanksUpTo(profile: BlkBlock, country: string, vehicleType: string, rank: number): boolean {
if (openRank(profile, country, vehicleType) >= rank) return false;
setParam(ensureBlock(profile, ERAS), `${vehicleType}_${country}`, { type: 'int', value: rank });
return true;
}
@@ -0,0 +1,109 @@
/**
* External inventory items stored in the player's save.
*
* Stored under top-level block `extInventory` in `profile.blk` (ignored by aces.exe's profile
* reader 0x919060), keeping every player's save self-contained in a single directory:
*
* extInventory{
* nextItemId:i=4
* item{ itemId:t="1" itemDefId:i=50221 quantity:i=1 timestamp:t="2026-11-25T00:00:00Z" }
* }
*/
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { intField, stringField } from './blk-fields.ts';
const EXT_INVENTORY = 'extInventory';
const NEXT_ID = 'nextItemId';
const ITEM_BLOCK = 'item';
export interface StoredExternalItem {
readonly itemId: string;
readonly itemDefId: number;
readonly quantity: number;
readonly timestamp: string;
}
export function externalInventoryItems(profile: BlkBlock): StoredExternalItem[] {
const root = findBlock(profile, EXT_INVENTORY);
if (!root) return [];
const items: StoredExternalItem[] = [];
for (const child of root.blocks) {
if (child.name !== ITEM_BLOCK) continue;
const itemId = stringField(child, 'itemId');
const itemDefId = intField(child, 'itemDefId');
const quantity = intField(child, 'quantity');
const timestamp = stringField(child, 'timestamp') || new Date().toISOString();
if (itemId && itemDefId > 0 && quantity > 0) {
items.push({ itemId, itemDefId, quantity, timestamp });
}
}
return items;
}
export function externalItemByUid(profile: BlkBlock, itemId: string): StoredExternalItem | undefined {
return externalInventoryItems(profile).find((item) => item.itemId === itemId);
}
/**
* Add quantity to an existing stack of the same itemDefId, or allocate a new itemId stack.
* Returns the updated or newly created item record.
*/
export function grantExternalItem(
profile: BlkBlock,
itemDefId: number,
quantity: number,
nowIso = new Date().toISOString(),
): StoredExternalItem {
const root = ensureBlock(profile, EXT_INVENTORY);
const existing = root.blocks.find((block) => block.name === ITEM_BLOCK && intField(block, 'itemDefId') === itemDefId);
if (existing) {
const newQty = Math.max(0, intField(existing, 'quantity')) + quantity;
setParam(existing, 'quantity', { type: 'int', value: newQty });
setParam(existing, 'timestamp', { type: 'string', value: nowIso });
return { itemId: stringField(existing, 'itemId'), itemDefId, quantity: newQty, timestamp: nowIso };
}
const nextId = Math.max(1, intField(root, NEXT_ID) + 1);
setParam(root, NEXT_ID, { type: 'int', value: nextId });
const itemId = String(nextId);
root.blocks.push({
name: ITEM_BLOCK,
params: [
{ name: 'itemId', value: { type: 'string', value: itemId } },
{ name: 'itemDefId', value: { type: 'int', value: itemDefId } },
{ name: 'quantity', value: { type: 'int', value: quantity } },
{ name: 'timestamp', value: { type: 'string', value: nowIso } },
],
blocks: [],
});
return { itemId, itemDefId, quantity, timestamp: nowIso };
}
/**
* Consume up to `quantity` from a specific `itemId` stack. Returns undefined if the player
* does not hold enough in that stack; otherwise returns the post-consumption quantity (0 when
* removed).
*/
export function consumeExternalItem(
profile: BlkBlock,
itemId: string,
quantity: number,
nowIso = new Date().toISOString(),
): { readonly itemDefId: number; readonly remaining: number; readonly timestamp: string } | undefined {
if (quantity <= 0) return undefined;
const root = findBlock(profile, EXT_INVENTORY);
if (!root) return undefined;
const idx = root.blocks.findIndex((block) => block.name === ITEM_BLOCK && stringField(block, 'itemId') === itemId);
if (idx < 0) return undefined;
const target = root.blocks[idx]!;
const itemDefId = intField(target, 'itemDefId');
const current = intField(target, 'quantity');
if (current < quantity) return undefined;
const remaining = current - quantity;
if (remaining === 0) {
root.blocks.splice(idx, 1);
} else {
setParam(target, 'quantity', { type: 'int', value: remaining });
setParam(target, 'timestamp', { type: 'string', value: nowIso });
}
return { itemDefId, remaining, timestamp: nowIso };
}
+27
View File
@@ -0,0 +1,27 @@
/**
* Owned vehicles in the profile, as in Gaijin's
* config/default_user.blk: one empty sub-block per vehicle the player owns.
*
* hangar{
* bf2c_1{
* }
* }
*/
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
const HANGAR = 'hangar';
export function ownsVehicle(profile: BlkBlock, vehicle: string): boolean {
const hangar = findBlock(profile, HANGAR);
return hangar !== undefined && findBlock(hangar, vehicle) !== undefined;
}
export function ownedVehicles(profile: BlkBlock): Set<string> {
return new Set((findBlock(profile, HANGAR)?.blocks ?? []).map((owned) => owned.name));
}
/** Add the vehicle to the owned vehicles; nothing changes when the player owns it already. */
export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void {
const hangar = ensureBlock(profile, HANGAR);
if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] });
}
+148
View File
@@ -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=<FILETIME> 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=<uid> ... } active boosters, any number
* itemActiveDiscounts{ itemUID:t=<uid> ... } active personal discounts
* itemActiveWagers{ itemUID:t=<uid> } 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;
}
@@ -0,0 +1,32 @@
/**
* Mission completion in the profile: which difficulties the player has completed a mission
* on (tutorials and other single-player missions).
*
* pveProgress{
* missions{
* "tutorial/tutorialB_takeoff_and_landing"{ diff_0:b=yes diff_1:b=yes diff_2:b=yes }
* }
* }
*
* Read by the client's profile serializer (aces.exe 2.61.0.37 0x92bd40: "pveProgress" ->
* "missions", one sub-block per mission, 0x92f090), each entry by 0x92f7d0:
* onlineDiff:i, singleDiff:i optional, -1 when missing
* timesCompleted:i, timesPlayed:i optional, 0 when missing
* diff_0:b, diff_1:b, diff_2:b completed on arcade, historical, simulator
* The entry's name is the mission's full name, "<chapter>/<mission>", the key that the
* script function get_mission_progress (0x179c900 -> 0xebad60) looks up. It returns the
* highest difficulty completed (0, 1, 2), or 3 or more when there is none.
*/
import { ensureBlock, setParam, type BlkBlock } from '@wto/blk';
const PVE_PROGRESS = 'pveProgress';
const MISSIONS = 'missions';
const DIFFICULTIES = [0, 1, 2] as const;
/** Record the mission as completed on every difficulty up to and including `highest` (0, 1 or 2). */
export function recordMissionCompleted(profile: BlkBlock, fullMissionName: string, highest: 0 | 1 | 2): void {
const entry = ensureBlock(ensureBlock(ensureBlock(profile, PVE_PROGRESS), MISSIONS), fullMissionName);
for (const difficulty of DIFFICULTIES) {
if (difficulty <= highest) setParam(entry, `diff_${difficulty}`, { type: 'bool', value: true });
}
}
@@ -0,0 +1,71 @@
/**
* Bought modifications in the profile:
*
* modifications{
* us_m22_locust_tank_tool_kit{ count:i64=1 }
* us_m22_locust_37mm_usa_m3_APC{ wpSpent:i=450 count:i64=150 }
* us_m22_locust_new_tank_tracks{ enabled:b=no count:i64=1 }
* }
*
* One block per bought modification, named <vehicle>_<modification>; having a block means the
* modification is owned. The client reads a block's params strictly in this order and stops at
* the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole:
* wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i
* Absent values are left out; enabled is only written when false (the default is enabled).
*/
import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk';
const MODIFICATIONS = 'modifications';
export interface ModificationRecord {
readonly silverLionsSpent: number;
readonly goldenEaglesSpent: number;
readonly enabled: boolean;
/** How many the player has: 1 for a plain modification, the number of rounds or uses for counted ones. */
readonly count: number;
}
export function recordName(vehicle: string, modification: string): string {
return `${vehicle}_${modification}`;
}
export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined {
const block = findBlock(profile, MODIFICATIONS);
const record = block && findBlock(block, recordName(vehicle, modification));
if (!record) return undefined;
return {
silverLionsSpent: intOf(record, 'wpSpent'),
goldenEaglesSpent: intOf(record, 'goldSpent'),
enabled: boolOf(record, 'enabled') ?? true,
count: intOf(record, 'count'),
};
}
export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean {
return modificationRecord(profile, vehicle, modification) !== undefined;
}
export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void {
const block = ensureBlock(ensureBlock(profile, MODIFICATIONS), recordName(vehicle, modification));
block.params = orderedParams(record);
}
function orderedParams(record: ModificationRecord): BlkParam[] {
const params: BlkParam[] = [];
if (record.silverLionsSpent) params.push({ name: 'wpSpent', value: { type: 'int', value: record.silverLionsSpent } });
if (record.goldenEaglesSpent) params.push({ name: 'goldSpent', value: { type: 'int', value: record.goldenEaglesSpent } });
if (!record.enabled) params.push({ name: 'enabled', value: { type: 'bool', value: false } });
if (record.count) params.push({ name: 'count', value: { type: 'int64', value: BigInt(record.count) } });
return params;
}
function intOf(block: BlkBlock, name: string): number {
const value = block.params.find((param) => param.name === name)?.value;
if (value?.type === 'int64') return Number(value.value);
return value?.type === 'int' ? value.value : 0;
}
function boolOf(block: BlkBlock, name: string): boolean | undefined {
const value = block.params.find((param) => param.name === name)?.value;
return value?.type === 'bool' ? value.value : undefined;
}
@@ -0,0 +1,58 @@
/**
* Modification research in the profile:
*
* modsResearch{ us_m22_locust_new_tank_tracks{ exp:i64=120 modStatus:i=2 } }
*
* One block per modification of an owned vehicle that is not bought yet, named
* <vehicle>_<modification>. The client reads each block with aces.exe 0x9403b0, by name:
* exp:i64 research points already put into it
* modStatus:i the status the server works out; 1 (locked) when absent
* (it also reads goldSpent:i, which the offline service never sets). An entry is always
* rewritten whole, so it holds nothing else.
*/
import { ensureBlock, findBlock, findParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { recordName } from './profile-modifications.ts';
const MODS_RESEARCH = 'modsResearch';
const STATUS = 'modStatus';
const RESEARCH_POINTS = 'exp';
const LOCKED = 1;
export function moduleResearchPoints(profile: BlkBlock, vehicle: string, modification: string): number {
const entry = entryOf(profile, vehicle, modification);
const value = entry && findParam(entry, RESEARCH_POINTS)?.value;
if (value?.type === 'int64') return Number(value.value);
return value?.type === 'int' ? value.value : 0;
}
export function setModuleResearchPoints(profile: BlkBlock, vehicle: string, modification: string, amount: number): void {
writeEntry(profile, vehicle, modification, amount, moduleStatusOf(profile, vehicle, modification));
}
export function setModuleStatus(profile: BlkBlock, vehicle: string, modification: string, status: number): void {
writeEntry(profile, vehicle, modification, moduleResearchPoints(profile, vehicle, modification), status);
}
export function removeModuleResearch(profile: BlkBlock, vehicle: string, modification: string): void {
const block = findBlock(profile, MODS_RESEARCH);
const name = recordName(vehicle, modification);
if (block) block.blocks = block.blocks.filter((entry) => entry.name !== name);
}
function moduleStatusOf(profile: BlkBlock, vehicle: string, modification: string): number {
const entry = entryOf(profile, vehicle, modification);
const value = entry && findParam(entry, STATUS)?.value;
return value?.type === 'int' ? value.value : LOCKED;
}
function writeEntry(profile: BlkBlock, vehicle: string, modification: string, researchPoints: number, status: number): void {
const params: BlkParam[] = [];
if (researchPoints) params.push({ name: RESEARCH_POINTS, value: { type: 'int64', value: BigInt(researchPoints) } });
params.push({ name: STATUS, value: { type: 'int', value: status } });
ensureBlock(ensureBlock(profile, MODS_RESEARCH), recordName(vehicle, modification)).params = params;
}
function entryOf(profile: BlkBlock, vehicle: string, modification: string): BlkBlock | undefined {
const block = findBlock(profile, MODS_RESEARCH);
return block && findBlock(block, recordName(vehicle, modification));
}
@@ -0,0 +1,41 @@
/**
* Vehicle Research Bonus battles used today, per country and vehicle type (research/
* research-efficiency.ts). Kept in a block of the local server's own; the client's profile
* parser ignores it:
*
* wtoResearchBonus{ day:i=<days since 1970-01-01 UTC> country_usa{ Tank:i=2 } }
*
* The count resets when the UTC day changes (the bonus battles reset at 00:00 GMT).
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const BLOCK = 'wtoResearchBonus';
const DAY = 'day';
const SECONDS_PER_DAY = 86_400;
export function researchBonusBattlesUsed(profile: BlkBlock, country: string, vehicleType: string, nowUnixSec: number): number {
const block = findBlock(profile, BLOCK);
if (!block || intParam(block, DAY) !== dayOf(nowUnixSec)) return 0;
const countryBlock = findBlock(block, country);
return countryBlock ? intParam(countryBlock, vehicleType) : 0;
}
export function useResearchBonusBattle(profile: BlkBlock, country: string, vehicleType: string, nowUnixSec: number): void {
const used = researchBonusBattlesUsed(profile, country, vehicleType, nowUnixSec);
const block = ensureBlock(profile, BLOCK);
const day = dayOf(nowUnixSec);
if (intParam(block, DAY) !== day) {
block.blocks.length = 0;
setParam(block, DAY, { type: 'int', value: day });
}
setParam(ensureBlock(block, country), vehicleType, { type: 'int', value: used + 1 });
}
function dayOf(unixSec: number): number {
return Math.floor(unixSec / SECONDS_PER_DAY);
}
function intParam(block: BlkBlock, name: string): number {
const value = findParam(block, name)?.value;
return value?.type === 'int' ? value.value : 0;
}
@@ -0,0 +1,57 @@
/**
* Free research points in the profile.
*
* The client shows shop_get_free_exp (aces.exe 2.61.0.37 0x17a4f40): the total of the
* experience counters (0x933190) minus "converted". The counters are top-level i64
* parameters read and written by 0x9331b0: experience, experienceOffline, valUnlocks,
* presented and valTrophy count into the total; Gaijin's new-account template has
* experience:i64=0. Free research points are earned into "experience" and spending them
* raises "converted".
*/
import { findParam, setParam, type BlkBlock } from '@wto/blk';
const EARNED = 'experience';
const OTHER_EARNED = ['experienceOffline', 'valUnlocks', 'presented', 'valTrophy'] as const;
const SPENT = 'converted';
export function freeResearchPoints(profile: BlkBlock): number {
return earnedTotal(profile) - counter(profile, SPENT);
}
/** Spend free research points the player has (callers check freeResearchPoints first). */
export function spendFreeResearchPoints(profile: BlkBlock, amount: number): void {
setCounter(profile, SPENT, counter(profile, SPENT) + amount);
}
/** Credit convertible (free) research points earned in battle (`experience:i64`). */
export function addFreeResearchPoints(profile: BlkBlock, amount: number): void {
if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`);
if (amount > 0) setCounter(profile, EARNED, counter(profile, EARNED) + amount);
}
/** Make the free research points this amount (the save editor). */
export function setFreeResearchPoints(profile: BlkBlock, amount: number): void {
if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`);
const others = earnedTotal(profile) - counter(profile, EARNED);
const earned = amount + counter(profile, SPENT) - others;
if (earned >= 0) {
setCounter(profile, EARNED, earned);
} else {
setCounter(profile, EARNED, 0);
setCounter(profile, SPENT, counter(profile, SPENT) - earned);
}
}
function earnedTotal(profile: BlkBlock): number {
return [EARNED, ...OTHER_EARNED].reduce((sum, name) => sum + counter(profile, name), 0);
}
function counter(profile: BlkBlock, name: string): number {
const value = findParam(profile, name)?.value;
if (value?.type === 'int64') return Number(value.value);
return value?.type === 'int' ? value.value : 0;
}
function setCounter(profile: BlkBlock, name: string, amount: number): void {
setParam(profile, name, { type: 'int64', value: BigInt(amount) });
}
@@ -0,0 +1,70 @@
/**
* Current research target, just-finished research vehicle, and banked excess RP per country
* and vehicle type (implementation notes; `aces.exe` `0x930150`):
*
* researchUnits{
* country_usa{
* currUnitTank:t="us_m2_medium"
* prevUnitTank:t=""
* }
* }
*
* Read by aces.exe 2.61.0.37 0x930150 for each country block: the parameter names are the
* field name followed by the vehicle type from the table at 0x72b6d98 (Aircraft, Tank, Ship,
* Helicopter, Boat, Human, Transport).
* - currUnit: the vehicle being researched (shop_get_researchable_unit_name, 0x17a3f80); the
* status function shows a researchable vehicle as "in research" when it is this one.
* - prevUnit: a vehicle whose research just finished; while it is set the stock scripts open
* the "choose the next research" window (shop_get_countries_list_with_autoset_units,
* 0x17a45e0; scripts/researches/researchActions.nut checkNonApprovedResearches).
* "" means none.
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const RESEARCH_UNITS = 'researchUnits';
const CURRENT = 'currUnit';
const FINISHED = 'prevUnit';
const EXCESS_EXP = 'exp';
export function researchTarget(profile: BlkBlock, country: string, vehicleType: string): string {
return field(profile, country, `${CURRENT}${vehicleType}`);
}
export function setResearchTarget(profile: BlkBlock, country: string, vehicleType: string, vehicle: string): void {
setField(profile, country, `${CURRENT}${vehicleType}`, vehicle);
}
export function finishedResearch(profile: BlkBlock, country: string, vehicleType: string): string {
return field(profile, country, `${FINISHED}${vehicleType}`);
}
export function setFinishedResearch(profile: BlkBlock, country: string, vehicleType: string, vehicle: string): void {
setField(profile, country, `${FINISHED}${vehicleType}`, vehicle);
}
export function branchExcessRp(profile: BlkBlock, country: string, vehicleType: string): number {
const units = findBlock(profile, RESEARCH_UNITS);
const block = units && findBlock(units, country);
const value = block && findParam(block, `${EXCESS_EXP}${vehicleType}`)?.value;
if (value?.type === 'int64') return Math.max(0, Number(value.value));
return value?.type === 'int' ? Math.max(0, value.value) : 0;
}
export function setBranchExcessRp(profile: BlkBlock, country: string, vehicleType: string, amount: number): void {
const clamped = Math.max(0, Math.trunc(amount));
setParam(ensureBlock(ensureBlock(profile, RESEARCH_UNITS), country), `${EXCESS_EXP}${vehicleType}`, {
type: 'int64',
value: BigInt(clamped),
});
}
function field(profile: BlkBlock, country: string, name: string): string {
const units = findBlock(profile, RESEARCH_UNITS);
const block = units && findBlock(units, country);
const value = block && findParam(block, name)?.value;
return value?.type === 'string' ? value.value : '';
}
function setField(profile: BlkBlock, country: string, name: string, vehicle: string): void {
setParam(ensureBlock(ensureBlock(profile, RESEARCH_UNITS), country), name, { type: 'string', value: vehicle });
}
@@ -0,0 +1,26 @@
/**
* Bought decorations in the profile:
*
* resourcesInfo{ core{ "us_m22_locust/us_camo_olive"{ spendGold:i=200 } cow_skull{ spendGold:i=500 } } }
*
* A generic name-keyed storage (FastStrMapStorageBase, aces.exe 0x93da88): one block per bought
* decoration under core, named by the client's key; having a block means owned (player_have_skin,
* player_have_decal, player_have_attachable -> 0x95dfc0). Each entry's params are read by name
* (0x95eaa0): flags:i, spendWP:i, spendGold:i, exteriorInfoParams.
*/
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
const RESOURCES = 'resourcesInfo';
const CORE = 'core';
export function ownsResource(profile: BlkBlock, key: string): boolean {
const resources = findBlock(profile, RESOURCES);
const core = resources && findBlock(resources, CORE);
return core !== undefined && findBlock(core, key) !== undefined;
}
export function addResource(profile: BlkBlock, key: string, spent: { silverLions: number; goldenEagles: number }): void {
const entry = ensureBlock(ensureBlock(ensureBlock(profile, RESOURCES), CORE), key);
if (spent.silverLions) setParam(entry, 'spendWP', { type: 'int', value: spent.silverLions });
if (spent.goldenEagles) setParam(entry, 'spendGold', { type: 'int', value: spent.goldenEagles });
}
@@ -0,0 +1,36 @@
/**
* The player's profile showcase, kept in the profile in the form the
* client reads it back from cln_get_showcases and cln_get_users_terse_info:
*
* wtoShowcase{
* current:t="favorite_unit"
* favorite_unit{ unit:t="us_m22_locust" difficulty:t="arcade" }
* medalist{ medals:t="..." medals:t="..." }
* }
*
* Stored under `wtoShowcase` rather than `showcase`: the client's native profile serializer
* (aces.exe 2.61.0.37 0x917e30 -> 0x9492c0) reads a top-level `showcase` block with a different
* flat schema and fatal-aborts if `favoriteUnitDifficulty:t` is absent (0x949b49), while the UI
* scripts read showcase data exclusively through cln_get_showcases and cln_get_users_terse_info.
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
const SHOWCASE = 'wtoShowcase';
const CURRENT = 'current';
export function currentShowcase(profile: BlkBlock): string {
const value = findParam(findBlock(profile, SHOWCASE) ?? { name: '', params: [], blocks: [] }, CURRENT)?.value;
return value?.type === 'string' ? value.value : '';
}
/** Every saved showcase, by type. */
export function savedShowcases(profile: BlkBlock): readonly BlkBlock[] {
return findBlock(profile, SHOWCASE)?.blocks ?? [];
}
/** Replace the fields of one showcase type and make it the current one. */
export function writeShowcase(profile: BlkBlock, type: string, fields: readonly BlkParam[]): void {
const showcase = ensureBlock(profile, SHOWCASE);
setParam(showcase, CURRENT, { type: 'string', value: type });
ensureBlock(showcase, type).params = [...fields];
}
@@ -0,0 +1,26 @@
/** The local web store cart is saved with the profile so checkout can clear it with the purchase. */
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
const STORE_CART = 'wtoStoreCart';
export function storeCartIds(profile: BlkBlock): readonly string[] {
return findBlock(profile, STORE_CART)?.params.flatMap((param) =>
param.name === 'productId' && param.value.type === 'string' ? [param.value.value] : [],
) ?? [];
}
export function setStoreCart(profile: BlkBlock, productIds: readonly string[]): void {
if (productIds.length === 0) {
clearStoreCart(profile);
return;
}
ensureBlock(profile, STORE_CART).params = productIds.map((id) => ({
name: 'productId',
value: { type: 'string', value: id },
}));
}
export function clearStoreCart(profile: BlkBlock): void {
const index = profile.blocks.findIndex((block) => block.name === STORE_CART);
if (index !== -1) profile.blocks.splice(index, 1);
}
@@ -0,0 +1,130 @@
/**
* Trophy open counts and UserLog entries in the profile:
* - `trophies{ <trophyId>{ count:i=<openCount> } }` (aces.exe 0x92d16b, 0x92d4df);
* - `userlogs{ <16-hex-id>{ type:i=<EULT> time:i=<unixSec> roomId:i64=0 [disabled:b=yes] body{ ... } } }`
* (UserLog::serialize 0x95f160, entry fields 0x95ec30; EULT_OPEN_TROPHY = 30 at 0x1a5599b).
*/
import { appendParam, emptyBlock, ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { intField } from './blk-fields.ts';
import { serverTimeToUnixSeconds, type ServerTime } from './server-time.ts';
const TROPHIES = 'trophies';
const USERLOGS = 'userlogs';
const PURCHASE_RECEIPT = 'purchaseReceipt';
// Registered by the client at 0x1a554dc / 0x1a5569e / 0x1a5599b (2.61.0.37).
export const EULT_SESSION_RESULT = 2;
const EULT_BUYENTITLEMENT = 13;
export const EULT_OPEN_TROPHY = 30;
export const EULT_BUY_TROPHY = 20;
// Registered by the client at 0x1a558ba / 0x1a55ad6 (2.61.0.37).
export const EULT_CHARD_AWARD = 25;
export const EULT_REMOVE_ITEM = 37;
export function trophyOpenCount(profile: BlkBlock, trophyId: string): number {
const trophies = findBlock(profile, TROPHIES);
return intField(trophies && findBlock(trophies, trophyId), 'count');
}
export function incrementTrophyOpenCount(profile: BlkBlock, trophyId: string, delta = 1): number {
const entry = ensureBlock(ensureBlock(profile, TROPHIES), trophyId);
const next = trophyOpenCount(profile, trophyId) + delta;
setParam(entry, 'count', { type: 'int', value: next });
return next;
}
export interface NewUserLogEntry {
readonly type: number;
readonly timeSec: number;
readonly roomId?: bigint;
readonly bodyParams: readonly BlkParam[];
readonly bodyBlocks?: readonly BlkBlock[];
}
export function appendUserLog(profile: BlkBlock, entry: NewUserLogEntry): string {
const logs = ensureBlock(profile, USERLOGS);
const timeId = BigInt(entry.timeSec) * 1000n;
// Older entries may be out of timestamp order after a system clock correction.
let highestId = 0n;
for (const log of logs.blocks) {
if (!/^[0-9a-f]{16}$/i.test(log.name)) continue;
const logId = BigInt('0x' + log.name);
if (logId > highestId) highestId = logId;
}
const id = timeId > highestId ? timeId : highestId + 1n;
const idHex = id.toString(16).padStart(16, '0');
logs.blocks.push({
name: idHex,
params: [
{ name: 'type', value: { type: 'int', value: entry.type } },
{ name: 'time', value: { type: 'int', value: entry.timeSec } },
{ name: 'roomId', value: { type: 'int64', value: entry.roomId ?? 0n } },
],
blocks: [{
name: 'body',
params: [...entry.bodyParams],
blocks: [...(entry.bodyBlocks ?? [])],
}],
});
return idHex;
}
interface EntitlementPurchase {
readonly productId: string;
readonly goldenEagleCost: number | undefined;
readonly goldenEagles: number;
readonly silverLions: number;
readonly premiumDays: number;
readonly vehicles: readonly string[];
}
export function appendEntitlementPurchase(
profile: BlkBlock, purchase: EntitlementPurchase, time: ServerTime,
): void {
const bodyParams: BlkParam[] = [
{ name: 'name', value: { type: 'string', value: purchase.productId } },
];
if (purchase.goldenEagleCost !== undefined) {
bodyParams.push({ name: 'cost', value: { type: 'int', value: purchase.goldenEagleCost } });
}
const receipt = emptyBlock(PURCHASE_RECEIPT);
if (purchase.goldenEagles > 0) setParam(receipt, 'goldIncome', { type: 'int', value: purchase.goldenEagles });
if (purchase.silverLions > 0) setParam(receipt, 'wpIncome', { type: 'int64', value: BigInt(purchase.silverLions) });
if (purchase.premiumDays > 0) setParam(receipt, 'premiumDays', { type: 'int', value: purchase.premiumDays });
for (const vehicle of purchase.vehicles) {
appendParam(receipt, 'aircraftGift', { type: 'string', value: vehicle });
}
appendUserLog(profile, {
type: EULT_BUYENTITLEMENT,
timeSec: serverTimeToUnixSeconds(time),
bodyParams,
bodyBlocks: [receipt],
});
}
/** Mark seen user logs as disabled (`cln_update` `haveToDisable:b=yes` -> `disabled:b=yes`, 0x95ed29/0x95ed66). */
export function disableUserLogs(profile: BlkBlock, ids: Iterable<string>): void {
const logs = findBlock(profile, USERLOGS);
if (!logs) return;
const targets = new Set(ids);
for (const entry of logs.blocks) {
if (targets.has(entry.name)) setParam(entry, 'disabled', { type: 'bool', value: true });
}
}
function isPendingPurchaseReceipt(log: BlkBlock): boolean {
if (intField(log, 'type') !== EULT_BUYENTITLEMENT) return false;
const disabled = findParam(log, 'disabled')?.value;
if (disabled?.type === 'bool' && disabled.value) return false;
const body = findBlock(log, 'body');
return body !== undefined && findBlock(body, PURCHASE_RECEIPT) !== undefined;
}
/** Keep the newest `keep` user logs and any purchase receipts the client has not seen. */
export function trimUserLogs(profile: BlkBlock, keep: number): void {
const logs = findBlock(profile, USERLOGS);
if (!logs || logs.blocks.length <= keep) return;
const cutoff = logs.blocks.length - keep;
logs.blocks = logs.blocks.filter((log, index) => index >= cutoff || isPendingPurchaseReceipt(log));
}
@@ -0,0 +1,63 @@
/**
* Earned unlocks in the profile.
*
* unlocks{
* unlock{ item:t="country_usa" cachedIndex:i=-1 expired:b=no earned:b=yes }
* }
*
* The client's profile reader (aces.exe 2.61.0.37 0x919060, from 0x91bad2) walks the
* sub-blocks of "unlocks" named "unlock" and reads each one's parameters in this order,
* matching every position by name:
* item:t the unlock's id from config/unlocks.blk; must come first
* ("TROPHY: Bad DataBlock for unlock - NO id param" otherwise)
* cachedIndex:i optional; the unlock's position in the client's table, only a
* lookup hint: a negative value makes the client look it up by name
* (0x91c052)
* expired:b optional
* removeTimeMinutes:i optional
* earned:b only "earned:b=yes" marks the unlock earned (0x91c289..0x91c2b7
* sets the flag that the script function is_unlocked, 0x179eae0,
* reads); without it the unlock is registered but not earned
* The client's own profile writer (0x91cd6f..) emits the same head: item, cachedIndex,
* expired, then removeTimeMinutes when set, then earned.
*/
import { ensureBlock, findParam, type BlkBlock, type BlkParam } from '@wto/blk';
const UNLOCKS = 'unlocks';
const UNLOCK = 'unlock';
const ITEM = 'item';
/** The unlocks recorded as earned. */
export function earnedUnlocks(profile: BlkBlock): Set<string> {
const unlocks = profile.blocks.find((block) => block.name === UNLOCKS);
const earned = new Set<string>();
for (const unlock of unlocks?.blocks ?? []) {
const name = unlockName(unlock);
const flag = findParam(unlock, 'earned')?.value;
if (name !== undefined && flag?.type === 'bool' && flag.value) earned.add(name);
}
return earned;
}
/** Record the unlock as earned, rewriting an existing entry for it. */
export function addUnlock(profile: BlkBlock, name: string): void {
const unlocks = ensureBlock(profile, UNLOCKS);
const existing = unlocks.blocks.find((unlock) => unlockName(unlock) === name);
if (existing) existing.params = earnedUnlockParams(name);
else unlocks.blocks.push({ name: UNLOCK, params: earnedUnlockParams(name), blocks: [] });
}
function earnedUnlockParams(name: string): BlkParam[] {
return [
{ name: ITEM, value: { type: 'string', value: name } },
{ name: 'cachedIndex', value: { type: 'int', value: -1 } },
{ name: 'expired', value: { type: 'bool', value: false } },
{ name: 'earned', value: { type: 'bool', value: true } },
];
}
function unlockName(unlock: BlkBlock): string | undefined {
if (unlock.name !== UNLOCK) return undefined;
const item = findParam(unlock, ITEM)?.value;
return item?.type === 'string' ? item.value : undefined;
}
@@ -0,0 +1,18 @@
/**
* The save format's upgrade steps (saves/save-upgrades.ts), in version order. A later change
* to what saves hold adds a new step; released steps are not removed.
*/
import { SaveUpgrades } from '../saves/save-upgrades.ts';
import { applyStartingContent, type StartingContent } from './starting-content.ts';
export function profileUpgrades(content: StartingContent): SaveUpgrades {
// Applying the starting content is idempotent, so each step brings the save up to the
// starting content of this release.
const addStartingContent = (profile: Parameters<typeof applyStartingContent>[0]): void => applyStartingContent(profile, content);
return new SaveUpgrades([
// 1 -> 2: reserve vehicles of every branch, completed difficulty-gating tutorials.
addStartingContent,
// 2 -> 3: rank I open in every branch.
addStartingContent,
]);
}
@@ -0,0 +1,70 @@
/**
* A vehicle's damage in the profile: fields of its hangar entry (AircraftInfo::serialize,
* aces.exe 2.61.0.37 0x940510):
*
* hangar{ <vehicle>{ hp:r time:i64 lastGameMode:i } }
*
* hp is the vehicle's condition (1 = intact, the default; 0x9406a2); time is stored with it
* (here: when hp was last set, server time, which the free repair counts from:
* repair/repair-over-time.ts; the client does not read it for the repair timer); lastGameMode is the mode the damage was taken
* in, 1 arcade / 2 historical / 3 simulation (default 1, 0x9415b1), which picks the repair
* cost (getAircraftRepairCost 0x90e0b0 reads it at AircraftInfo+0xcc).
*/
import { findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import { removeParam } from './blk-fields.ts';
import type { ServerTime } from './server-time.ts';
const HANGAR = 'hangar';
export interface VehicleCondition {
readonly hp: number;
/** 1 arcade, 2 historical, 3 simulation. */
readonly lastGameMode: number;
}
export function vehicleCondition(profile: BlkBlock, vehicle: string): VehicleCondition | undefined {
const entry = hangarEntry(profile, vehicle);
if (!entry) return undefined;
const hp = findParam(entry, 'hp')?.value;
const mode = findParam(entry, 'lastGameMode')?.value;
return {
hp: hp?.type === 'real' ? Math.min(1, Math.max(0, hp.value)) : 1,
lastGameMode: mode?.type === 'int' && mode.value >= 1 && mode.value <= 3 ? mode.value : 1,
};
}
/** The damaged vehicles of the hangar. */
export function damagedVehicles(profile: BlkBlock): string[] {
return (findBlock(profile, HANGAR)?.blocks ?? []).map((entry) => entry.name).filter((vehicle) => isDamaged(profile, vehicle));
}
/** When the vehicle's hp was last set; undefined when the entry has no time. */
export function damageTime(profile: BlkBlock, vehicle: string): ServerTime | undefined {
const time = hangarEntry(profile, vehicle) && findParam(hangarEntry(profile, vehicle)!, 'time')?.value;
return time?.type === 'int64' ? time.value : undefined;
}
export function isDamaged(profile: BlkBlock, vehicle: string): boolean {
const condition = vehicleCondition(profile, vehicle);
return condition !== undefined && condition.hp < 1;
}
export function setVehicleDamage(profile: BlkBlock, vehicle: string, hp: number, lastGameMode: number, time: ServerTime): void {
const entry = hangarEntry(profile, vehicle);
if (!entry) return;
setParam(entry, 'hp', { type: 'real', value: hp });
setParam(entry, 'time', { type: 'int64', value: time });
setParam(entry, 'lastGameMode', { type: 'int', value: lastGameMode });
}
export function clearVehicleDamage(profile: BlkBlock, vehicle: string): void {
const entry = hangarEntry(profile, vehicle);
if (!entry) return;
removeParam(entry, 'hp');
removeParam(entry, 'time');
}
function hangarEntry(profile: BlkBlock, vehicle: string): BlkBlock | undefined {
const hangar = findBlock(profile, HANGAR);
return hangar && findBlock(hangar, vehicle);
}
@@ -0,0 +1,52 @@
/**
* The research state of the vehicles the player does not own.
*
* unitResearch{
* us_m2_medium{
* unitStatus:i=2
* exp:i64=1200
* }
* }
*
* Read by aces.exe 2.61.0.37 0x937a50 (block) and 0x943990 (each entry): unitStatus (default
* 1, locked) is what the status function shop_unit_research_status returns for a vehicle the
* player does not own (0xebf7a0); exp is the vehicle's research points (shop_get_unit_exp,
* 0x17a3980). A vehicle without an entry is locked and has no research points. Other
* parameters of an entry (attempts, wpSpent, goldSpent, hasScheme) are left as they are.
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const UNIT_RESEARCH = 'unitResearch';
const STATUS = 'unitStatus';
const RESEARCH_POINTS = 'exp';
export function researchPointsOf(profile: BlkBlock, vehicle: string): number {
const entry = entryOf(profile, vehicle);
const value = entry && findParam(entry, RESEARCH_POINTS)?.value;
if (value?.type === 'int64') return Number(value.value);
return value?.type === 'int' ? value.value : 0;
}
export function setResearchPoints(profile: BlkBlock, vehicle: string, amount: number): void {
setParam(ensureEntry(profile, vehicle), RESEARCH_POINTS, { type: 'int64', value: BigInt(amount) });
}
/** Record the vehicle's status; the entry keeps its research points. */
export function setVehicleStatus(profile: BlkBlock, vehicle: string, status: number): void {
setParam(ensureEntry(profile, vehicle), STATUS, { type: 'int', value: status });
}
/** Drop the vehicle's entry: it is owned, or locked with no research points. */
export function removeVehicleResearch(profile: BlkBlock, vehicle: string): void {
const block = findBlock(profile, UNIT_RESEARCH);
if (block) block.blocks = block.blocks.filter((entry) => entry.name !== vehicle);
}
function entryOf(profile: BlkBlock, vehicle: string): BlkBlock | undefined {
const block = findBlock(profile, UNIT_RESEARCH);
return block && findBlock(block, vehicle);
}
function ensureEntry(profile: BlkBlock, vehicle: string): BlkBlock {
return ensureBlock(ensureBlock(profile, UNIT_RESEARCH), vehicle);
}
@@ -0,0 +1,87 @@
/**
* Per-vehicle fields of owned vehicles: hangar{ <vehicle>{ ... } },
* read by name by AircraftInfo::serialize (aces.exe 2.61.0.37 0x940510). Only the fields the
* local server maintains are handled here:
* investMode:t the modification being researched, empty = none (AircraftInfo+0x100)
* investModePrev:t the modification whose research just finished (+0x108)
* tierNumber:i the highest open modification tier (script is_tier_available)
* spareAircraftsCount:i spares the player has for this vehicle
* excessExp:i64 banked modification research points (+0x70)
* freeRepairs:i64 free repairs used (0x941cef; shop_get_free_repairs_used at 0x17a4b80)
*/
import { findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import { intField } from './blk-fields.ts';
const HANGAR = 'hangar';
const FREE_REPAIRS = 'freeRepairs';
const RESEARCH_TARGET = 'investMode';
const FINISHED_TARGET = 'investModePrev';
const OPEN_TIER = 'tierNumber';
const SPARES = 'spareAircraftsCount';
const EXCESS_EXP = 'excessExp';
export function moduleResearchTarget(profile: BlkBlock, vehicle: string): string {
const value = fieldOf(profile, vehicle, RESEARCH_TARGET);
return value?.type === 'string' ? value.value : '';
}
export function setModuleResearchTarget(profile: BlkBlock, vehicle: string, modification: string): void {
const entry = vehicleEntry(profile, vehicle);
if (entry) setParam(entry, RESEARCH_TARGET, { type: 'string', value: modification });
}
export function finishedModuleResearch(profile: BlkBlock, vehicle: string): string {
const value = fieldOf(profile, vehicle, FINISHED_TARGET);
return value?.type === 'string' ? value.value : '';
}
export function setFinishedModuleResearch(profile: BlkBlock, vehicle: string, modification: string): void {
const entry = vehicleEntry(profile, vehicle);
if (entry) setParam(entry, FINISHED_TARGET, { type: 'string', value: modification });
}
export function setOpenTier(profile: BlkBlock, vehicle: string, tier: number): void {
const entry = vehicleEntry(profile, vehicle);
if (entry) setParam(entry, OPEN_TIER, { type: 'int', value: tier });
}
export function spareCount(profile: BlkBlock, vehicle: string): number {
const value = fieldOf(profile, vehicle, SPARES);
return value?.type === 'int' ? value.value : 0;
}
export function setSpareCount(profile: BlkBlock, vehicle: string, count: number): void {
const entry = vehicleEntry(profile, vehicle);
if (entry) setParam(entry, SPARES, { type: 'int', value: count });
}
/** Uses one free repair on an owned vehicle if it still has an allowance. */
export function consumeFreeRepair(profile: BlkBlock, vehicle: string, allowance: number): boolean {
const entry = vehicleEntry(profile, vehicle);
if (!entry) return false;
const used = Math.max(0, intField(entry, FREE_REPAIRS));
if (used >= allowance) return false;
setParam(entry, FREE_REPAIRS, { type: 'int64', value: BigInt(used + 1) });
return true;
}
export function vehicleExcessRp(profile: BlkBlock, vehicle: string): number {
const value = fieldOf(profile, vehicle, EXCESS_EXP);
if (value?.type === 'int64') return Math.max(0, Number(value.value));
return value?.type === 'int' ? Math.max(0, value.value) : 0;
}
export function setVehicleExcessRp(profile: BlkBlock, vehicle: string, amount: number): void {
const entry = vehicleEntry(profile, vehicle);
if (entry) setParam(entry, EXCESS_EXP, { type: 'int64', value: BigInt(Math.max(0, Math.trunc(amount))) });
}
function fieldOf(profile: BlkBlock, vehicle: string, name: string) {
const entry = vehicleEntry(profile, vehicle);
return entry && findParam(entry, name)?.value;
}
function vehicleEntry(profile: BlkBlock, vehicle: string): BlkBlock | undefined {
const hangar = findBlock(profile, HANGAR);
return hangar && findBlock(hangar, vehicle);
}
@@ -0,0 +1,53 @@
/**
* Custom weapon presets in the profile:
*
* weaponPresets{
* fa_18d_late{
* custom0{
* name:t="Custom preset #1"
* Weapon{ preset:t="aim_120_default_slot4" slot:i=4 }
* ...
* }
* }
* }
*
* `EconomicState::serialize` (aces.exe 0x937a50 at 0x93e62e) delegates top-level `weaponPresets`
* to 0x9675e0 (`GameSaveData + 0x1a0`), which calls `DataBlock::setFrom` (0x30934e0) in client
* read mode (0x8) ONLY when a `weaponPresets` sub-block is present in `profile.blk`; if the
* sub-block is absent, 0x9675e0 returns without clearing `GameSaveData + 0x1a0`. Keeping the
* top-level `weaponPresets{}` block present even after the last preset is deleted ensures the
* client clears its in-memory custom preset table on profile update.
*/
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
const WEAPON_PRESETS = 'weaponPresets';
export function vehicleWeaponPresets(profile: BlkBlock, vehicle: string): readonly BlkBlock[] {
const root = findBlock(profile, WEAPON_PRESETS);
const unitBlock = root && findBlock(root, vehicle);
return unitBlock?.blocks ?? [];
}
export function upsertVehicleWeaponPreset(profile: BlkBlock, vehicle: string, preset: BlkBlock): void {
const root = ensureBlock(profile, WEAPON_PRESETS);
const unitBlock = ensureBlock(root, vehicle);
const copy = structuredClone(preset);
const existingIndex = unitBlock.blocks.findIndex((entry) => entry.name === preset.name);
if (existingIndex >= 0) unitBlock.blocks[existingIndex] = copy;
else unitBlock.blocks.push(copy);
}
export function deleteVehicleWeaponPreset(profile: BlkBlock, vehicle: string, presetName: string): void {
const root = ensureBlock(profile, WEAPON_PRESETS);
const unitBlock = findBlock(root, vehicle);
if (!unitBlock) return;
unitBlock.blocks = unitBlock.blocks.filter((entry) => entry.name !== presetName);
if (unitBlock.blocks.length === 0 && unitBlock.params.length === 0) {
root.blocks = root.blocks.filter((entry) => entry !== unitBlock);
}
}
export function clearVehicleWeaponPresets(profile: BlkBlock, vehicle: string): void {
const root = ensureBlock(profile, WEAPON_PRESETS);
root.blocks = root.blocks.filter((entry) => entry.name !== vehicle);
}
@@ -0,0 +1,53 @@
/**
* Weapon presets the player has, in the profile:
*
* weapons{
* p-26a_34_m2_P-26A_1934_default{ count:i64=1 }
* p-26a_34_m2_P-26A_1934_2x100lbs{ wpSpent:i=450 count:i64=30 }
* }
*
* One block per preset, named <vehicle>_<preset> (aces.exe 0x15562f0 shop_is_weapon_purchased
* builds the same key; presets named custom... share <vehicle>_custom_presets). The client reads
* a block's params strictly in this order and stops at the first that does not match
* (0x942040, log "WEAPONS: Not all params was read"), so a record is always rewritten whole:
* wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i count:i64
* count is what shop_is_weapon_purchased returns: the pieces the player has; no block means 0.
*/
import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk';
const WEAPONS = 'weapons';
export interface WeaponRecord {
readonly silverLionsSpent: number;
readonly goldenEaglesSpent: number;
readonly count: number;
}
export function weaponRecord(profile: BlkBlock, vehicle: string, weapon: string): WeaponRecord | undefined {
const block = findBlock(profile, WEAPONS);
const record = block && findBlock(block, recordName(vehicle, weapon));
if (!record) return undefined;
return { silverLionsSpent: intOf(record, 'wpSpent'), goldenEaglesSpent: intOf(record, 'goldSpent'), count: intOf(record, 'count') };
}
export function writeWeaponRecord(profile: BlkBlock, vehicle: string, weapon: string, record: WeaponRecord): void {
ensureBlock(ensureBlock(profile, WEAPONS), recordName(vehicle, weapon)).params = orderedParams(record);
}
function recordName(vehicle: string, weapon: string): string {
return `${vehicle}_${weapon}`;
}
function orderedParams(record: WeaponRecord): BlkParam[] {
const params: BlkParam[] = [];
if (record.silverLionsSpent) params.push({ name: 'wpSpent', value: { type: 'int', value: record.silverLionsSpent } });
if (record.goldenEaglesSpent) params.push({ name: 'goldSpent', value: { type: 'int', value: record.goldenEaglesSpent } });
if (record.count) params.push({ name: 'count', value: { type: 'int64', value: BigInt(record.count) } });
return params;
}
function intOf(block: BlkBlock, name: string): number {
const value = block.params.find((param) => param.name === name)?.value;
if (value?.type === 'int64') return Number(value.value);
return value?.type === 'int' ? value.value : 0;
}
@@ -0,0 +1,98 @@
/**
* Vehicle wishlist persistence in profile.blk (cln_add_to_wish_list / cln_remove_from_wish_list).
*
* Binary & script contract (verified in aces.exe 2.61.0.37 0x967c30..0x96891b, getWishList
* 0x1553470, and gui.vromfs.bin scripts/wishlist/wishlistManager.nut):
* wishList{
* units{
* us_m1_abrams{
* cmnts:t="optional note"
* ts:i64=1764260000
* }
* }
* }
* - When reading profile.blk (0x967c40..0x967d8a), if top-level "wishList" is absent the client
* returns early without clearing its in-memory wishlist vector ([econ + 0xe868]). Keeping an
* empty wishList { units {} } block on removal ensures 0x967ebd..0x967f19 clears the client's
* vector immediately upon profile sync.
* - Static limits come from char.vromfs.bin config/warpoints.blk: maxWishListSize:i=100 and
* maxWishListCommentSize:i=100 (exposed via getMaxWishListSize 0x1553450 and
* getMaxWishListCommentSize 0x1553460).
*/
import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { TechTree } from '../research/tech-tree.ts';
import { int64Field, stringField } from './blk-fields.ts';
import { ownsVehicle } from './profile-hangar.ts';
const WISH_LIST_BLOCK = 'wishList';
const UNITS_BLOCK = 'units';
const COMMENT_PARAM = 'cmnts';
const TIMESTAMP_PARAM = 'ts';
/** Limits defined in char.vromfs.bin config/warpoints.blk (maxWishListSize / maxWishListCommentSize). */
export const DEFAULT_WISHLIST_LIMITS: WishlistLimits = {
maxSize: 100,
maxCommentLength: 100,
};
export interface WishlistLimits {
readonly maxSize: number;
readonly maxCommentLength: number;
}
export interface WishlistEntry {
readonly unit: string;
readonly comment: string;
readonly timestampSec: number;
}
export function readWishlist(profile: BlkBlock): WishlistEntry[] {
const unitsBlock = findBlock(findBlock(profile, WISH_LIST_BLOCK) ?? { name: '', params: [], blocks: [] }, UNITS_BLOCK);
if (!unitsBlock) return [];
return unitsBlock.blocks
.filter((entry) => entry.name.length > 0)
.map((entry) => ({
unit: entry.name,
comment: stringField(entry, COMMENT_PARAM),
timestampSec: Number(int64Field(entry, TIMESTAMP_PARAM, 0n)),
}));
}
export function hasWishlistUnit(profile: BlkBlock, unit: string): boolean {
const unitsBlock = findBlock(findBlock(profile, WISH_LIST_BLOCK) ?? { name: '', params: [], blocks: [] }, UNITS_BLOCK);
return unitsBlock !== undefined && unitsBlock.blocks.some((entry) => entry.name === unit);
}
export function addWishlistUnit(
profile: BlkBlock,
techTree: TechTree,
unit: string,
comment: string,
timestampSec: number,
limits: WishlistLimits = DEFAULT_WISHLIST_LIMITS,
): RuleOutcome {
if (!unit || [...comment].length > limits.maxCommentLength) return refused('BAD_PARAMS');
const vehicle = techTree.vehicle(unit);
if (!vehicle || vehicle.kind === 'part' || vehicle.kind === 'hidden') return refused('BAD_PARAMS');
if (ownsVehicle(profile, unit) || hasWishlistUnit(profile, unit)) return refused('NOT_AVAILABLE');
const unitsBlock = ensureWishlistUnitsBlock(profile);
if (unitsBlock.blocks.length >= limits.maxSize) return refused('NOT_AVAILABLE');
const params: BlkParam[] = [];
if (comment.length > 0) params.push({ name: COMMENT_PARAM, value: { type: 'string', value: comment } });
params.push({ name: TIMESTAMP_PARAM, value: { type: 'int64', value: BigInt(Math.max(0, Math.trunc(timestampSec))) } });
unitsBlock.blocks.push({ name: unit, params, blocks: [] });
return ACCEPTED;
}
export function removeWishlistUnit(profile: BlkBlock, unit: string): RuleOutcome {
if (!unit) return refused('BAD_PARAMS');
const unitsBlock = ensureWishlistUnitsBlock(profile);
unitsBlock.blocks = unitsBlock.blocks.filter((entry) => entry.name !== unit);
return ACCEPTED;
}
function ensureWishlistUnitsBlock(profile: BlkBlock): BlkBlock {
return ensureBlock(ensureBlock(profile, WISH_LIST_BLOCK), UNITS_BLOCK);
}
+31
View File
@@ -0,0 +1,31 @@
/**
* 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/<uid>/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());
}
export function serverTimeToUnixSeconds(time: ServerTime): number {
return Number((time - UNIX_EPOCH) / (1000n * TICKS_PER_MILLISECOND));
}
/** 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;
}
@@ -0,0 +1,50 @@
/**
* What every account starts with besides Gaijin's new-account template
* (config/default_user.blk), which owns only reserve aircraft and opens no rank.
*
* - Every reserve vehicle of every country and branch (aircraft, ground vehicles, boats,
* ships), as accounts have them online. The stock first-choice window and the slotbar
* only offer reserve vehicles the player owns (scripts/slotbar/slotbarStateData.nut
* checkReserveUnit: isBought), so without them a new player only has aircraft.
* - Rank I open for research in every country's branches (profile-eras.ts), as online;
* this allows research to start immediately. Higher ranks open through
* research.
* - The base tutorials that gate a difficulty count as completed on every difficulty, so no
* game mode requires a tutorial first. The tutorials remain playable.
* The stock rule (gui.vromfs.bin scripts/tutorials/tutorialsState.nut isDiffUnlocked)
* locks historical and simulator battles for a vehicle type until the player has either
* played 60 s in one of them or completed the type's required tutorial on that difficulty;
* the required tutorials are the table reqTutorial there (2.61.0.37: aircraft only,
* tutorialB_takeoff_and_landing, chapter "tutorial" in char.vromfs.bin config/mislist.blk
* block "training").
*
* Applying it again changes nothing, so it also brings older saves up to date
* (profile-upgrades.ts). The starting money is only for new accounts (new-profile.ts).
*/
import type { Balance } from './profile-currency.ts';
import type { BlkBlock } from '@wto/blk';
import type { ReserveVehicle } from '../game-data/datasets/reserve-vehicles.ts';
import type { ShopBranches } from '../game-data/datasets/shop-branches.ts';
import { vehicleTypeOfBranch } from '../research/vehicle-types.ts';
import { openRanksUpTo } from './profile-eras.ts';
import { addOwnedVehicle } from './profile-hangar.ts';
import { recordMissionCompleted } from './profile-mission-progress.ts';
const DIFFICULTY_GATING_TUTORIALS = ['tutorial/tutorialB_takeoff_and_landing'] as const;
const HIGHEST_DIFFICULTY = 2;
const FIRST_RANK = 1;
export interface StartingContent {
readonly reserveVehicles: readonly ReserveVehicle[];
readonly branches: ShopBranches;
/** Starting money (tuning/new-profile.jsonc). */
readonly startingBalance: Balance;
}
export function applyStartingContent(profile: BlkBlock, content: StartingContent): void {
for (const vehicle of content.reserveVehicles) addOwnedVehicle(profile, vehicle.name);
for (const [country, branches] of Object.entries(content.branches)) {
for (const branch of branches) openRanksUpTo(profile, country, vehicleTypeOfBranch(branch), FIRST_RANK);
}
for (const tutorial of DIFFICULTY_GATING_TUTORIALS) recordMissionCompleted(profile, tutorial, HIGHEST_DIFFICULTY);
}