diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index 7600082..455368b 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -3,6 +3,7 @@ import type { AccountStore } from '../../accounts/account-store.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { CharActionHandler } from '../char-action.ts'; import { acceptEula } from './agreement-actions.ts'; +import { bulkTrainCrews, trainCrew } from './crew-actions.ts'; import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; import { setStartingInfo } from './starting-info-actions.ts'; @@ -18,5 +19,7 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap withAccount(context, accounts, (account) => { + const assignments = context.payload && readCrewSlots(context.payload); + if (!assignments || !canAssignCrewSlots(profiles.profileOf(account.userId), assignments)) return { kind: 'error', code: 'BAD_PARAMS' }; + const profile = profiles.update(account.userId, (saved) => assignCrewSlots(saved, assignments)); + return { kind: 'data', blk: clientProfile(profile, account) }; + }); +} + +export function trainCrew(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const request = context.payload && readTrainCrew(context.payload); + if (!request || (request.keepCurrent && request.vehicle === '')) return { kind: 'error', code: 'BAD_PARAMS' }; + const { keepCurrent, ...assignment } = request; + if (!canAssignCrewSlots(profiles.profileOf(account.userId), [assignment])) return { kind: 'error', code: 'BAD_PARAMS' }; + const profile = profiles.update(account.userId, (saved) => { + if (keepCurrent) trainCrewKeepingSlot(saved, assignment); + else assignCrewSlots(saved, [assignment]); + }); + return { kind: 'data', blk: clientProfile(profile, account) }; + }); +} + +function readTrainCrew(payload: BlkBlock): (CrewSlotAssignment & { readonly keepCurrent: boolean }) | undefined { + const vehicle = findParam(payload, 'aircraft')?.value; + const crewId = findParam(payload, 'idx')?.value; + const keepCurrent = findParam(payload, 'keep_curr')?.value; + if (vehicle?.type !== 'string' || crewId?.type !== 'int') return undefined; + return { crewId: crewId.value, vehicle: vehicle.value, keepCurrent: keepCurrent?.type === 'bool' && keepCurrent.value }; +} diff --git a/packages/local-service/src/char/actions/crew-slots-payload.ts b/packages/local-service/src/char/actions/crew-slots-payload.ts new file mode 100644 index 0000000..468541a --- /dev/null +++ b/packages/local-service/src/char/actions/crew-slots-payload.ts @@ -0,0 +1,26 @@ +/** + * The crew slot list in a char request body, written by the stock scripts + * (gui.vromfs.bin scripts/crew/crewTrain.nut createBatchTrainCrewRequestBlk): + * + * batchTrainCrew{ + * trainCrew{ crewId:i=10 unitName:t="cr_32" } + * trainCrew{ crewId:i=11 unitName:t="" } empty: leave the slot empty + * } + */ +import { findBlock, findParam, type BlkBlock } from '@wto/blk'; +import type { CrewSlotAssignment } from '../../profile/crew-slots.ts'; + +/** The list, empty when the body has none, or undefined when an entry is malformed. */ +export function readCrewSlots(payload: BlkBlock): CrewSlotAssignment[] | undefined { + const batch = findBlock(payload, 'batchTrainCrew'); + if (!batch) return []; + const result: CrewSlotAssignment[] = []; + for (const entry of batch.blocks) { + if (entry.name !== 'trainCrew') continue; + const crewId = findParam(entry, 'crewId')?.value; + const vehicle = findParam(entry, 'unitName')?.value; + if (crewId?.type !== 'int' || vehicle?.type !== 'string') return undefined; + result.push({ crewId: crewId.value, vehicle: vehicle.value }); + } + return result; +} diff --git a/packages/local-service/src/char/actions/starting-info-actions.ts b/packages/local-service/src/char/actions/starting-info-actions.ts index ebdac86..0bbc983 100644 --- a/packages/local-service/src/char/actions/starting-info-actions.ts +++ b/packages/local-service/src/char/actions/starting-info-actions.ts @@ -7,7 +7,7 @@ * unitType:i the vehicle type picked * unlock:t repeated: every country, and "chosen_unit_type_" for the type picked * batchTrainCrew{ trainCrew{ crewId:i unitName:t } ... } the vehicle for every crew slot - * ("" leaves the slot empty) + * (crew-slots-payload.ts; "" leaves the slot empty) * The login script waits until the vehicle type counts as chosen, which the client reads as * the unlock "chosen_unit_type_" being earned (scripts/unit/unitTypesList.nut * isFirstChosen). The client applies the answer as a profile update @@ -22,19 +22,15 @@ * chosen, they offer the tutorial instead, which the player may skip (local verification; the * skip itself is the feature AllowedToSkipBaseTutorials, set by the build). */ -import { findBlock, findParam, type BlkBlock } from '@wto/blk'; +import { findParam } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; import { clientProfile } from '../../profile/client-profile.ts'; -import { crewOf, putVehicleInCrew } from '../../profile/profile-crews.ts'; +import { assignCrewSlots, canAssignCrewSlots } from '../../profile/crew-slots.ts'; import { addUnlock } from '../../profile/profile-unlocks.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; - -interface CrewVehicle { - readonly crewId: number; - readonly vehicle: string; -} +import { readCrewSlots } from './crew-slots-payload.ts'; export function setStartingInfo(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { @@ -42,35 +38,17 @@ export function setStartingInfo(profiles: PlayerProfiles, accounts: AccountStore if (!payload) return { kind: 'error', code: 'BAD_PARAMS' }; const unlocks = payload.params.flatMap((param) => (param.name === 'unlock' && param.value.type === 'string' ? [param.value.value] : [])); const country = findParam(payload, 'country')?.value; - const crews = crewVehicles(findBlock(payload, 'batchTrainCrew')); - if (unlocks.length === 0 || crews === undefined || country?.type !== 'string' || !country.value.startsWith('country_')) { + const assignments = readCrewSlots(payload); + if (unlocks.length === 0 || assignments === undefined || country?.type !== 'string' || !country.value.startsWith('country_')) { return { kind: 'error', code: 'BAD_PARAMS' }; } unlocks.push(`chosen_${country.value}`); - - const current = profiles.profileOf(account.userId); - if (crews.some(({ crewId }) => crewOf(current, crewId) === undefined)) return { kind: 'error', code: 'BAD_PARAMS' }; + if (!canAssignCrewSlots(profiles.profileOf(account.userId), assignments)) return { kind: 'error', code: 'BAD_PARAMS' }; const profile = profiles.update(account.userId, (saved) => { for (const unlock of unlocks) addUnlock(saved, unlock); - for (const { crewId, vehicle } of crews) { - if (vehicle !== '') putVehicleInCrew(crewOf(saved, crewId)!, vehicle); - } + assignCrewSlots(saved, assignments); }); return { kind: 'data', blk: clientProfile(profile, account) }; }); } - -/** The crew slots of batchTrainCrew, or undefined when an entry is malformed. */ -function crewVehicles(batch: BlkBlock | undefined): CrewVehicle[] | undefined { - if (!batch) return []; - const result: CrewVehicle[] = []; - for (const entry of batch.blocks) { - if (entry.name !== 'trainCrew') continue; - const crewId = findParam(entry, 'crewId')?.value; - const vehicle = findParam(entry, 'unitName')?.value; - if (crewId?.type !== 'int' || vehicle?.type !== 'string') return undefined; - result.push({ crewId: crewId.value, vehicle: vehicle.value }); - } - return result; -} diff --git a/packages/local-service/src/game-data/datasets/reserve-vehicles.ts b/packages/local-service/src/game-data/datasets/reserve-vehicles.ts new file mode 100644 index 0000000..e177135 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/reserve-vehicles.ts @@ -0,0 +1,64 @@ +/** + * Dataset: the reserve vehicles, the free rank-I vehicles of each country and branch. + * + * The client decides what counts as a reserve vehicle with the native script function + * is_default_aircraft (aces.exe 2.61.0.37 0x17a5d50 -> 0x9640c0). It looks the vehicle up in + * char.vromfs.bin config/wpcost.blk and reads repairCostArcade, repairCostHistorical and + * repairCostSimulation: a vehicle is a reserve vehicle unless one of them is above 0 (a + * missing value counts as 0). The stock UI then only offers reserve vehicles that are also in + * the tech tree (scripts/slotbar/slotbarStateData.nut checkReserveUnit: isVisibleInShop), so + * only vehicles listed in config/shop.blk are taken; the shop also gives each one's country. + * + * 2.61.0.37: 56 vehicles; every country except Israel has reserve aircraft and ground + * vehicles, and all but China and Sweden have reserve boats and ships. No helicopter is a + * reserve vehicle. + */ +import type { BlkBlock } from '@wto/blk'; +import type { Dataset } from './dataset.ts'; +import { numberField } from './blk-fields.ts'; + +const VEHICLE_ECONOMY = 'config/wpcost.blk'; +const SHOP = 'config/shop.blk'; +const REPAIR_COSTS = ['repairCostArcade', 'repairCostHistorical', 'repairCostSimulation'] as const; + +export interface ReserveVehicle { + readonly name: string; + readonly country: string; +} + +export const reserveVehicles: Dataset = { + id: 'reserve-vehicles', + version: 1, + extract: (source) => { + const economy = new Map(source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => [vehicle.name, vehicle])); + const result: ReserveVehicle[] = []; + for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) { + for (const name of vehiclesInTree(country)) { + const vehicle = economy.get(name); + if (vehicle && isReserve(vehicle) && !result.some((known) => known.name === name)) result.push({ name, country: country.name }); + } + } + return result; + }, +}; + +function isReserve(vehicle: BlkBlock): boolean { + return REPAIR_COSTS.every((cost) => (numberField(vehicle, cost) ?? 0) <= 0); +} + +/** + * Every block name below a country's tech tree: country -> branch -> column -> vehicle, with + * grouped vehicles one level deeper. Names that are not vehicles (columns, groups) are + * dropped by the caller, which only keeps names that have an economy entry. + */ +function vehiclesInTree(country: BlkBlock): string[] { + const names: string[] = []; + const walk = (block: BlkBlock): void => { + for (const child of block.blocks) { + names.push(child.name); + walk(child); + } + }; + for (const branch of country.blocks) walk(branch); + return names; +} diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index 019685f..889124e 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -9,12 +9,15 @@ import { CharService } from './char/char-service.ts'; import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; +import { reserveVehicles } from './game-data/datasets/reserve-vehicles.ts'; import { shopCountries } from './game-data/datasets/shop-countries.ts'; import { GameFiles } from './game-data/game-files.ts'; import { GameModes } from './game-modes/game-modes.ts'; import { LoginService } from './login/login-service.ts'; import { matchingRequests } from './matching/matching-requests.ts'; import { PlayerProfiles } from './profile/player-profiles.ts'; +import { profileUpgrades } from './profile/profile-upgrades.ts'; +import type { StartingContent } from './profile/starting-content.ts'; import { SaveStore } from './saves/save-store.ts'; import { createPortListener } from './server/port-listener.ts'; import { Router } from './server/router.ts'; @@ -43,9 +46,11 @@ export async function startLocalService(options: LocalServiceOptions): Promise 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); +} diff --git a/packages/local-service/src/profile/new-profile.ts b/packages/local-service/src/profile/new-profile.ts index daa095b..5e9c31b 100644 --- a/packages/local-service/src/profile/new-profile.ts +++ b/packages/local-service/src/profile/new-profile.ts @@ -1,9 +1,12 @@ /** - * A new account's profile. The starting content is Gaijin's own new-account template from - * the player's game files (config/default_user.blk), copied as it is. + * 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). */ import type { BlkBlock } from '@wto/blk'; +import { applyStartingContent, type StartingContent } from './starting-content.ts'; -export function newProfile(template: BlkBlock): BlkBlock { - return structuredClone(template); +export function newProfile(template: BlkBlock, content: StartingContent): BlkBlock { + const profile = structuredClone(template); + applyStartingContent(profile, content); + return profile; } diff --git a/packages/local-service/src/profile/player-profiles.ts b/packages/local-service/src/profile/player-profiles.ts index f48e395..99bff45 100644 --- a/packages/local-service/src/profile/player-profiles.ts +++ b/packages/local-service/src/profile/player-profiles.ts @@ -6,20 +6,23 @@ 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'; export class PlayerProfiles { readonly #saves: SaveStore; readonly #gameFiles: GameFiles; + readonly #startingContent: StartingContent; - constructor(saves: SaveStore, gameFiles: GameFiles) { + constructor(saves: SaveStore, gameFiles: GameFiles, startingContent: StartingContent) { this.#saves = saves; this.#gameFiles = gameFiles; + this.#startingContent = startingContent; } profileOf(userId: string): BlkBlock { const saved = this.#saves.loadProfile(userId); if (saved) return saved; - const created = newProfile(this.#gameFiles.newAccountTemplate()); + const created = newProfile(this.#gameFiles.newAccountTemplate(), this.#startingContent); this.#saves.saveProfile(userId, created); return created; } diff --git a/packages/local-service/src/profile/profile-crews.ts b/packages/local-service/src/profile/profile-crews.ts index 5415509..4cd0668 100644 --- a/packages/local-service/src/profile/profile-crews.ts +++ b/packages/local-service/src/profile/profile-crews.ts @@ -11,7 +11,7 @@ * "trained" lists the vehicles the crew is trained for (repeated), "current" is the vehicle * in its slot. */ -import { ensureBlock, setParam, type BlkBlock } from '@wto/blk'; +import { ensureBlock, type BlkBlock } from '@wto/blk'; const CREWS = 'crews'; const VEHICLES = 'aircrafts'; @@ -22,10 +22,24 @@ export function crewOf(profile: BlkBlock, crewId: number): BlkBlock | undefined return profile.blocks.find((block) => block.name === CREWS)?.blocks.find((crew) => crew.name === `c${crewId}`); } -/** 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 { +/** 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) vehicles.params.push({ name: TRAINED, value: { type: 'string', value: vehicle } }); - setParam(vehicles, CURRENT, { type: 'string', 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 } }); } diff --git a/packages/local-service/src/profile/profile-hangar.ts b/packages/local-service/src/profile/profile-hangar.ts new file mode 100644 index 0000000..083bbf3 --- /dev/null +++ b/packages/local-service/src/profile/profile-hangar.ts @@ -0,0 +1,23 @@ +/** + * 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; +} + +/** 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: [] }); +} diff --git a/packages/local-service/src/profile/profile-mission-progress.ts b/packages/local-service/src/profile/profile-mission-progress.ts new file mode 100644 index 0000000..7590add --- /dev/null +++ b/packages/local-service/src/profile/profile-mission-progress.ts @@ -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, "/", 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 }); + } +} diff --git a/packages/local-service/src/profile/profile-upgrades.ts b/packages/local-service/src/profile/profile-upgrades.ts new file mode 100644 index 0000000..8ca11ee --- /dev/null +++ b/packages/local-service/src/profile/profile-upgrades.ts @@ -0,0 +1,14 @@ +/** + * The save format's upgrade steps (saves/save-upgrades.ts), in version order. A step is + * never changed once released; a later change to saves adds a new step. + */ +import { SaveUpgrades } from '../saves/save-upgrades.ts'; +import { applyStartingContent, type StartingContent } from './starting-content.ts'; + +export function profileUpgrades(content: StartingContent): SaveUpgrades { + return new SaveUpgrades([ + // 1 -> 2: the starting content (reserve vehicles of every branch, completed + // difficulty-gating tutorials) for saves made before new accounts had it. + (profile) => applyStartingContent(profile, content), + ]); +} diff --git a/packages/local-service/src/profile/starting-content.ts b/packages/local-service/src/profile/starting-content.ts new file mode 100644 index 0000000..00f901d --- /dev/null +++ b/packages/local-service/src/profile/starting-content.ts @@ -0,0 +1,36 @@ +/** + * What every account starts with besides Gaijin's new-account template + * (config/default_user.blk), which owns only reserve aircraft. + * + * - 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. + * - The base tutorials that gate a difficulty count as completed on every difficulty, so no + * game mode asks for a tutorial first (user quotes 87, 92; the tutorials stay 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). + */ +import type { BlkBlock } from '@wto/blk'; +import type { ReserveVehicle } from '../game-data/datasets/reserve-vehicles.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; + +export interface StartingContent { + readonly reserveVehicles: readonly ReserveVehicle[]; +} + +export function applyStartingContent(profile: BlkBlock, content: StartingContent): void { + for (const vehicle of content.reserveVehicles) addOwnedVehicle(profile, vehicle.name); + for (const tutorial of DIFFICULTY_GATING_TUTORIALS) recordMissionCompleted(profile, tutorial, HIGHEST_DIFFICULTY); +} diff --git a/packages/local-service/src/saves/save-store.ts b/packages/local-service/src/saves/save-store.ts index c6f6542..78dbe25 100644 --- a/packages/local-service/src/saves/save-store.ts +++ b/packages/local-service/src/saves/save-store.ts @@ -12,7 +12,7 @@ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk'; import { writeFileAtomic } from '../storage/atomic-file.ts'; -import { CURRENT_SAVE_FORMAT, upgradeSave } from './save-upgrades.ts'; +import type { SaveUpgrades } from './save-upgrades.ts'; interface SaveInfo { formatVersion: number; @@ -22,9 +22,11 @@ interface SaveInfo { export class SaveStore { readonly #folder: string; + readonly #upgrades: SaveUpgrades; - constructor(dataFolder: string) { + constructor(dataFolder: string, upgrades: SaveUpgrades) { this.#folder = join(dataFolder, 'saves'); + this.#upgrades = upgrades; } /** The account's profile, or undefined when the account has no save yet. */ @@ -33,8 +35,8 @@ export class SaveStore { if (!existsSync(infoPath)) return undefined; const info = JSON.parse(readFileSync(infoPath, 'utf8')) as SaveInfo; const profile = decodeBlk(readFileSync(this.#profilePath(userId))); - if (info.formatVersion === CURRENT_SAVE_FORMAT) return profile; - const upgraded = upgradeSave(profile, info.formatVersion); + if (info.formatVersion === this.#upgrades.currentFormat) return profile; + const upgraded = this.#upgrades.upgrade(profile, info.formatVersion); this.saveProfile(userId, upgraded); return upgraded; } @@ -43,7 +45,7 @@ export class SaveStore { const now = new Date().toISOString(); const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined; writeFileAtomic(this.#profilePath(userId), encodeBlk(profile)); - const info: SaveInfo = { formatVersion: CURRENT_SAVE_FORMAT, created: previous?.created ?? now, updated: now }; + const info: SaveInfo = { formatVersion: this.#upgrades.currentFormat, created: previous?.created ?? now, updated: now }; writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2)); } diff --git a/packages/local-service/src/saves/save-upgrades.ts b/packages/local-service/src/saves/save-upgrades.ts index 40d8bb0..c0af60e 100644 --- a/packages/local-service/src/saves/save-upgrades.ts +++ b/packages/local-service/src/saves/save-upgrades.ts @@ -1,19 +1,30 @@ /** * Save format versions. Each change to what a save holds adds one upgrade step from the - * previous version, so a save made by any earlier release still opens. + * previous version, so a save made by any earlier release still opens. The steps themselves + * belong to the rules layer (profile/profile-upgrades.ts); this layer only runs them in order. */ import type { BlkBlock } from '@wto/blk'; -export const CURRENT_SAVE_FORMAT = 1; +/** Turns a profile of one format version into the next version, in place. */ +export type SaveUpgrade = (profile: BlkBlock) => void; -/** UPGRADES[n] turns a version n+1 profile into a version n+2 profile. */ -const UPGRADES: ReadonlyArray<(profile: BlkBlock) => BlkBlock> = []; +export class SaveUpgrades { + /** steps[n] turns a version n+1 profile into a version n+2 profile. */ + readonly #steps: readonly SaveUpgrade[]; -export function upgradeSave(profile: BlkBlock, fromVersion: number): BlkBlock { - if (!Number.isInteger(fromVersion) || fromVersion < 1 || fromVersion > CURRENT_SAVE_FORMAT) { - throw new Error(`save format version ${fromVersion} is not supported by this version (current: ${CURRENT_SAVE_FORMAT})`); + constructor(steps: readonly SaveUpgrade[]) { + this.#steps = steps; + } + + get currentFormat(): number { + return this.#steps.length + 1; + } + + upgrade(profile: BlkBlock, fromVersion: number): BlkBlock { + if (!Number.isInteger(fromVersion) || fromVersion < 1 || fromVersion > this.currentFormat) { + throw new Error(`save format version ${fromVersion} is not supported by this version (current: ${this.currentFormat})`); + } + for (let version = fromVersion; version < this.currentFormat; version++) this.#steps[version - 1]!(profile); + return profile; } - let upgraded = profile; - for (let version = fromVersion; version < CURRENT_SAVE_FORMAT; version++) upgraded = UPGRADES[version - 1]!(upgraded); - return upgraded; }