feat(saves)!: add offline crew editing

Add per-country crew slot controls and skill level previews to the launcher. Keep archived crews and their stable IDs in the save, update affected lineups, and back up the save before closing a slot.

Verified with both type checks, the launcher build, 2.61.0.64 patch checks, and temporary save read and write checks.

BREAKING CHANGE: The launcher automatically upgrades existing saves to format 4. Keep a pre-upgrade backup to use a save with an older launcher.
This commit is contained in:
N0VAN0M4LY committed 2026-12-06 15:34:24 +08:00
1 parent 264c5c59b8
commit d58ba9fb9b
31 files changed
+1021 -139

No files matched your search

@@ -11,7 +11,8 @@
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, setParam, type BlkBlock } from '@wto/blk';
import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { intField } from '../profile/blk-fields.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts';
/**
@@ -84,17 +85,21 @@ export class CloudSettingsStore {
}
loadContainer(userId: string, blkType: string): BlkBlock | undefined {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined;
if (blkType === 'GBT_GENERAL_SETTINGS') this.#ensureDefaultGeneralSettings(userId);
const blkPath = this.#blkPath(userId, blkType);
if (!existsSync(blkPath)) return undefined;
if (isValidUserId(userId) && blkType === 'GBT_GENERAL_SETTINGS') this.#ensureDefaultGeneralSettings(userId);
try {
return decodeBlk(readFileSync(blkPath));
return this.loadSavedContainer(userId, blkType);
} catch {
return undefined;
}
}
/** Read persisted settings without creating defaults or ignoring malformed data. */
loadSavedContainer(userId: string, blkType: string): BlkBlock | undefined {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined;
const blkPath = this.#blkPath(userId, blkType);
return existsSync(blkPath) ? decodeBlk(readFileSync(blkPath)) : undefined;
}
saveUpload(userId: string, upload: ParsedGblkUpload): boolean {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(upload.blkType)) return false;
const meta = this.#loadMeta(userId);
@@ -111,6 +116,17 @@ export class CloudSettingsStore {
return true;
}
/** Store a launcher edit at a version newer than the server and client copies. */
replaceContainer(userId: string, blkType: string, container: BlkBlock, cachedVersion: number): void {
const content = findBlock(container, 'content');
if (!content || !isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) throw new Error('Invalid cloud settings container.');
const previous = this.#loadMeta(userId).blocks[blkType]?.version ?? 0;
const version = Math.max(previous, intField(container, 'version'), cachedVersion) + 1;
if (!Number.isInteger(version) || version > 0x7fffffff) throw new Error('Cloud settings version exceeds the supported range.');
const contentHash = createHash('md5').update(encodeBlk({ ...content, name: '' })).digest('hex');
this.saveUpload(userId, { blkType, version, contentHash, container });
}
saveBulkUploads(userId: string, uploads: ReadonlyArray<ParsedGblkUpload>): number {
let savedCount = 0;
for (const upload of uploads) {
+138
View File
@@ -0,0 +1,138 @@
import type { BlkBlock } from '@wto/blk';
import type { CrewSkillData } from '../game-data/datasets/crew-skills.ts';
import { setSkillLevel, skillLevel } from '../profile/profile-crew-skills.ts';
import type { VehicleType } from '../research/vehicle-types.ts';
const CREW_TYPES = ['air', 'tank', 'ship', 'human'] as const;
export type CrewType = (typeof CREW_TYPES)[number];
// Stock baseunittypes.nut assigns the same crew type to aircraft and helicopters, ships and boats.
export const CREW_TYPE_BY_VEHICLE: Readonly<Partial<Record<VehicleType, CrewType>>> = {
Aircraft: 'air', Helicopter: 'air', Tank: 'tank', Ship: 'ship', Boat: 'ship', Human: 'human',
};
// crew.nut getSkillCrewLevel rounds each contribution to 0.01; crewwndhandler.nut displays half levels.
const LEVEL_SCALE = 100;
const DISPLAY_STEP = 0.5;
export interface CrewLevelSkill {
readonly page: string;
readonly skill: string;
readonly types: readonly CrewType[];
readonly min: number;
readonly max: number;
readonly step: number;
readonly contributions: readonly number[];
}
export function crewLevelSkills(data: CrewSkillData): CrewLevelSkill[] {
const { levelRatio, levelSteps } = data;
if (levelRatio === null || !Number.isFinite(levelRatio) || levelRatio <= 0 ||
levelSteps === null || !Number.isSafeInteger(levelSteps) || levelSteps < 1) {
throw new Error('Invalid crew level ratio or step count in config/crew_skills.blk.');
}
return data.pages.flatMap((page) => page.skills.flatMap((skill) => {
const tags = (skill.type || page.type).split(/[; ]+/);
const types = CREW_TYPES.filter((type) => tags.includes(type));
if (!types.length) return [];
const max = skill.levelCosts.length;
const min = skill.minLevel;
if (!max || !Number.isSafeInteger(min) || min < 0 || min > max) {
throw new Error(`Invalid crew skill range for ${page.name}/${skill.name}.`);
}
const step = Math.ceil(max / Math.min(levelSteps, max));
const contributions = Array.from({ length: max + 1 }, (_, value) => Math.round(value / max * levelRatio * LEVEL_SCALE));
return [{ page: page.name, skill: skill.name, types, min, max, step, contributions }];
})).sort((a, b) => a.page.localeCompare(b.page, 'en') || a.skill.localeCompare(b.skill, 'en'));
}
export function crewSkillValue(crew: BlkBlock | undefined, skill: CrewLevelSkill): number {
return crew ? Math.min(skill.max, Math.max(skill.min, skillLevel(crew, skill.page, skill.skill))) : skill.min;
}
export function displayedCrewLevel(contribution: number): number {
return Math.round(contribution / (LEVEL_SCALE * DISPLAY_STEP)) * DISPLAY_STEP;
}
export function crewLevels(crew: BlkBlock | undefined, skills: readonly CrewLevelSkill[], types: readonly CrewType[]) {
return types.map((type) => {
const applicable = skills.filter((skill) => skill.types.includes(type));
const levelAt = (valueOf: (skill: CrewLevelSkill) => number) => displayedCrewLevel(
applicable.reduce((total, skill) => total + skill.contributions[valueOf(skill)]!, 0),
);
return {
type, level: levelAt((skill) => crewSkillValue(crew, skill)),
min: levelAt((skill) => skill.min), max: levelAt((skill) => skill.max),
};
});
}
export interface CrewSkillChange {
readonly page: string;
readonly skill: string;
readonly value: number;
}
interface Allocation {
readonly shared: number;
readonly movement: number;
readonly value: number;
readonly previous?: Allocation;
}
function compareChanges(a: Allocation, b: Allocation): number {
return a.shared - b.shared || a.movement - b.movement;
}
function nextAllocations(sums: ReadonlyMap<number, Allocation>, skill: CrewLevelSkill, current: number, direction: number): Map<number, Allocation> {
// Existing saves may hold an intermediate value from a different version of the game.
const choices = new Set([current, skill.min, skill.max]);
for (let value = skill.step; value < skill.max; value += skill.step) if (value > skill.min) choices.add(value);
const next = new Map<number, Allocation>();
for (const value of choices) {
if ((value - current) * direction < 0) continue;
const contribution = skill.contributions[value]!;
const movement = Math.abs(contribution - skill.contributions[current]!);
const shared = skill.types.length > 1 ? movement : 0;
for (const [sum, previous] of sums) {
const total = sum + contribution;
const change = { value, shared: previous.shared + shared, movement: previous.movement + movement ** 2, previous };
const other = next.get(total);
if (!other || compareChanges(change, other) < 0) next.set(total, change);
}
}
return next;
}
/** Find the closest displayed level, preferring smaller changes to skills shared by crew types. */
export function planCrewLevel(crew: BlkBlock, skills: readonly CrewLevelSkill[], type: CrewType, target: number): CrewSkillChange[] {
const applicable = skills.filter((skill) => skill.types.includes(type));
const current = applicable.map((skill) => crewSkillValue(crew, skill));
const total = applicable.reduce((sum, skill, index) => sum + skill.contributions[current[index]!]!, 0);
const direction = Math.sign(target - displayedCrewLevel(total));
if (!direction) return [];
let sums = new Map<number, Allocation>([[0, { value: 0, shared: 0, movement: 0 }]]);
for (const [index, skill] of applicable.entries()) sums = nextAllocations(sums, skill, current[index]!, direction);
let best: { distance: number; allocation: Allocation } | undefined;
for (const [sum, allocation] of sums) {
const distance = Math.abs(displayedCrewLevel(sum) - target);
if (!best || distance < best.distance || (distance === best.distance && compareChanges(allocation, best.allocation) < 0)) {
best = { distance, allocation };
}
}
const changes: CrewSkillChange[] = [];
let allocation = best?.allocation;
for (let index = applicable.length - 1; index >= 0 && allocation; index -= 1) {
const { page, skill } = applicable[index]!;
if (allocation.value !== current[index]) changes.push({ page, skill, value: allocation.value });
allocation = allocation.previous;
}
return changes;
}
export function applyCrewLevelPlan(crew: BlkBlock, changes: readonly CrewSkillChange[]): void {
for (const { page, skill, value } of changes) setSkillLevel(crew, page, skill, value);
}
@@ -19,6 +19,8 @@ import type { Dataset } from './dataset.ts';
export interface SkillFacts {
readonly name: string;
readonly type: string;
readonly minLevel: number;
/** Cost of each level, index 0 = level 1; the length is the maximum level. */
readonly levelCosts: readonly number[];
}
@@ -49,6 +51,8 @@ export interface CrewTrainingPrices {
}
export interface CrewSkillData {
readonly levelRatio: number | null;
readonly levelSteps: number | null;
readonly pages: readonly SkillPage[];
readonly packs: readonly SkillPointPack[];
readonly aceDiscountStages: readonly AceDiscountStage[];
@@ -57,13 +61,16 @@ export interface CrewSkillData {
export const crewSkillData: Dataset<CrewSkillData> = {
id: 'crew-skills',
version: 2,
version: 3,
extract: (source) => {
const skills = findBlock(source.readBlk('char.vromfs.bin', 'config/crew_skills.blk'), 'crew_skills');
const definitions = source.readBlk('char.vromfs.bin', 'config/crew_skills.blk');
const skills = findBlock(definitions, 'crew_skills');
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
const packs = findBlock(warpoints, 'crewSkillPointsCost');
const aceReduce = findBlock(warpoints, 'expert_to_ace_cost_reduce');
return {
levelRatio: numberField(definitions, 'skill_to_level_ratio') ?? null,
levelSteps: numberField(definitions, 'max_skill_level_steps') ?? null,
pages: (skills?.blocks ?? []).map(pageOf),
packs: (packs?.blocks ?? []).map((pack) => ({ name: pack.name, goldenEagles: numberField(pack, 'costGold') ?? 0, points: numberField(pack, 'crewExp') ?? 0 })),
aceDiscountStages: (aceReduce?.blocks ?? [])
@@ -90,7 +97,12 @@ function pageOf(page: BlkBlock): SkillPage {
const levels = findBlock(skill, 'skill_level_exp');
const levelCosts: number[] = [];
for (let level = 1; levels && numberField(levels, `level${level}`) !== undefined; level++) levelCosts.push(numberField(levels, `level${level}`)!);
return { name: skill.name, levelCosts };
return {
name: skill.name, levelCosts,
type: stringField(skill, 'type') ?? '',
// The native skill constructor defaults min_skill_level to zero (2.61.0.37 0x933d50).
minLevel: numberField(skill, 'min_skill_level') ?? 0,
};
}),
};
}
+1
View File
@@ -7,6 +7,7 @@ export { AccountStore, type RegistrationResult } from './accounts/account-store.
export { REGISTRATION_PATH } from './accounts/registration-service.ts';
export { HEALTH_PATH } from './transport/http-listener.ts';
export { editSaveResearch, readSaveResearch } from './saves/save-research.ts';
export { editSaveCrew, previewSaveCrewEdit, readSaveCrews, syncRestoredCrewPresets } from './saves/save-crews.ts';
export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
+7 -2
View File
@@ -19,6 +19,7 @@ import { setParam, type BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import { currentClanSeason } from '../clans/clan-season.ts';
import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts';
import { CLOSED_CREWS, CREWS, crewsForClient } from './profile-crews.ts';
import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts';
import { clearStoreCart } from './profile-store-cart.ts';
import { clientHangarSpares } from './profile-vehicle-state.ts';
@@ -29,8 +30,12 @@ export function clientProfile(saved: BlkBlock, account: Account, nowMs = Date.no
const profile: BlkBlock = {
name: saved.name,
params: [...saved.params],
blocks: saved.blocks.filter((block) => block.name !== DAILY_SPARES_BLOCK)
.map((block) => block.name === 'hangar' ? clientHangarSpares(block) : block),
blocks: saved.blocks.filter((block) => block.name !== DAILY_SPARES_BLOCK && block.name !== CLOSED_CREWS)
.map((block) => {
if (block.name === 'hangar') return clientHangarSpares(block);
if (block.name === CREWS) return crewsForClient(saved, block);
return block;
}),
};
clearStoreCart(profile);
const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON;
+65 -21
View File
@@ -11,9 +11,11 @@
* "trained" lists the vehicles the crew is trained for (repeated), "current" is the vehicle
* in its slot.
*/
import { ensureBlock, type BlkBlock } from '@wto/blk';
import { emptyBlock, ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
import { stringField } from './blk-fields.ts';
const CREWS = 'crews';
export const CREWS = 'crews';
export const CLOSED_CREWS = 'wtoClosedCrews';
const VEHICLES = 'aircrafts';
const TRAINED = 'trained';
const CURRENT = 'current';
@@ -21,43 +23,54 @@ 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}`);
return findBlock(profile, 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));
return (findBlock(profile, CREWS)?.blocks ?? []).filter((crew) => CREW_NAME.test(crew.name));
}
export function closedCrews(profile: BlkBlock): readonly BlkBlock[] {
return (findBlock(profile, CLOSED_CREWS)?.blocks ?? []).filter((crew) => CREW_NAME.test(crew.name));
}
export function crewIdOf(crew: BlkBlock): number {
return Number(CREW_NAME.exec(crew.name)?.[1] ?? -1);
}
export function crewCountry(crew: BlkBlock): string {
return stringField(crew, 'country');
}
export function crewVehicle(crew: BlkBlock): string {
const vehicles = findBlock(crew, VEHICLES);
return vehicles ? stringField(vehicles, CURRENT) : '';
}
export function crewCountOf(profile: BlkBlock, country: string): number {
return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => crewCountry(crew) === country).length;
return allCrews(profile).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] : [];
});
.map(crewVehicle)
.filter(Boolean);
}
/** 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;
return crew ? (crewVehicle(crew) || undefined) : 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;
});
const slotted = crews.find((entry) => crewVehicle(entry) === vehicle);
if (slotted) return slotted;
return crews.find((entry) =>
(entry.blocks.find((block) => block.name === VEHICLES)?.params ?? []).some(
@@ -65,17 +78,48 @@ export function crewForVehicleInCountry(profile: BlkBlock, country: string, vehi
));
}
/** Add an empty crew for the country, numbered after every existing crew; returns its id. */
/** Add an empty crew with an ID above the active and archived IDs. */
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: [] }] });
const id = Math.max(-1, ...crews.blocks.map(crewIdOf), ...closedCrews(profile).map(crewIdOf)) + 1;
crews.blocks.push({ name: `c${id}`, params: [{ name: 'country', value: { type: 'string', value: country } }], blocks: [emptyBlock(VEHICLES)] });
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;
export function closeCrew(profile: BlkBlock, crew: BlkBlock): void {
const active = ensureBlock(profile, CREWS);
active.blocks = active.blocks.filter((entry) => entry !== crew);
ensureBlock(profile, CLOSED_CREWS).blocks.push(crew);
}
export function reopenCrew(profile: BlkBlock, crew: BlkBlock): number {
const closed = ensureBlock(profile, CLOSED_CREWS);
closed.blocks = closed.blocks.filter((entry) => entry !== crew);
const active = ensureBlock(profile, CREWS);
const id = crewIdOf(crew);
const position = active.blocks.findIndex((entry) => crewIdOf(entry) > id);
if (position < 0) active.blocks.push(crew);
else active.blocks.splice(position, 0, crew);
return id;
}
/** A newly purchased or imported slot can reuse the country's first archived crew. */
export function openNextCrew(profile: BlkBlock, country: string): number {
const closed = closedCrews(profile).filter((crew) => crewCountry(crew) === country).sort((a, b) => crewIdOf(a) - crewIdOf(b))[0];
if (!closed) return addCrew(profile, country);
// Buying a slot leaves it empty. Its trained vehicles and qualifications stay available.
emptyCrewSlot(closed);
return reopenCrew(profile, closed);
}
/** The native crew vector is indexed by the c<N> suffix. Keep vacant IDs out of country lists. */
export function crewsForClient(profile: BlkBlock, active: BlkBlock): BlkBlock {
const closed = closedCrews(profile);
if (!closed.length) return active;
const vacant = closed.map(({ name }): BlkBlock => ({
name, params: [{ name: 'country', value: { type: 'string', value: '' } }], blocks: [emptyBlock(VEHICLES)],
}));
return { ...active, blocks: [...active.blocks, ...vacant].sort((a, b) => crewIdOf(a) - crewIdOf(b)) };
}
/** Leave the crew's slot empty; the vehicles it is trained for stay trained. */
@@ -2,7 +2,9 @@
* 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 { ensureBlock } from '@wto/blk';
import { SaveUpgrades } from '../saves/save-upgrades.ts';
import { CLOSED_CREWS } from './profile-crews.ts';
import { applyStartingContent, type StartingContent } from './starting-content.ts';
export function profileUpgrades(content: StartingContent): SaveUpgrades {
@@ -14,5 +16,7 @@ export function profileUpgrades(content: StartingContent): SaveUpgrades {
addStartingContent,
// 2 -> 3: rank I open in every branch.
addStartingContent,
// 3 -> 4: archive closed crew slots separately from active crews.
(profile) => { ensureBlock(profile, CLOSED_CREWS); },
]);
}
@@ -3,11 +3,10 @@
*
* The price of a country's next slot is config/rank.blk crew_slots slot<N>, N being the
* number of crews the country has, as the client shows it (get_crew_slot_cost, aces.exe
* 2.61.0.37 0x90eaa0). Without a slot<N> there is nothing more to buy. The new crew is empty
* and numbered after every existing crew.
* 2.61.0.37 0x90eaa0). Without a slot<N> there is nothing more to buy. The purchased slot is empty.
*/
import type { BlkBlock } from '@wto/blk';
import { addCrew, crewCountOf } from '../profile/profile-crews.ts';
import { crewCountOf, openNextCrew } from '../profile/profile-crews.ts';
import { canAfford, pay } from '../profile/profile-currency.ts';
import type { ResearchRules } from './research-rules.ts';
import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts';
@@ -18,6 +17,6 @@ export function buyCrewSlot(profile: BlkBlock, rules: ResearchRules, country: st
if (!price) return refused('NOT_AVAILABLE');
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
addCrew(profile, country);
openNextCrew(profile, country);
return ACCEPTED;
}
@@ -0,0 +1,23 @@
import { lstatSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { intField } from '../profile/blk-fields.ts';
import { readBackupBlk } from './import/backup-blk.ts';
// The same local settings files accepted by the launcher's online backup import.
const SETTINGS_FILE_LIMIT = 32 * 1024 * 1024;
export function cachedSettingsVersion(folders: readonly string[], fileName: string): number {
let latest = 0;
for (const folder of folders) {
const path = join(folder, fileName);
try {
const stats = lstatSync(path);
if (!stats.isFile() || stats.size > SETTINGS_FILE_LIMIT) continue;
const version = intField(readBackupBlk(readFileSync(path)), 'version');
if (Number.isInteger(version)) latest = Math.max(latest, version);
} catch {
// A missing or unreadable cache does not have a version to supersede.
}
}
return latest;
}
+21 -92
View File
@@ -1,7 +1,6 @@
import { createHash } from 'node:crypto';
import { existsSync, lstatSync, readFileSync, rmSync } from 'node:fs';
import { basename, join } from 'node:path';
import { encodeBlk, findBlock, type BlkBlock } from '@wto/blk';
import { findBlock, type BlkBlock } from '@wto/blk';
import { AccountStore } from '../../accounts/account-store.ts';
import { ClanStore } from '../../clans/clan-store.ts';
import { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
@@ -10,15 +9,17 @@ import { crewSlotPrices } from '../../game-data/datasets/rank-settings.ts';
import { vehicleCatalogue } from '../../game-data/datasets/vehicle-catalogue.ts';
import { GameFiles } from '../../game-data/game-files.ts';
import { intField } from '../../profile/blk-fields.ts';
import { addCrew, allCrews, crewOf, emptyCrewSlot, putVehicleInCrew, trainCrewFor } from '../../profile/profile-crews.ts';
import { allCrews, crewCountry, crewIdOf, emptyCrewSlot, openNextCrew, putVehicleInCrew, trainCrewFor } from '../../profile/profile-crews.ts';
import { addOwnedVehicle } from '../../profile/profile-hangar.ts';
import { ownsModification, writeModificationRecord } from '../../profile/profile-modifications.ts';
import { addUnlock, earnedUnlocks } from '../../profile/profile-unlocks.ts';
import { weaponRecord, writeWeaponRecord } from '../../profile/profile-weapons.ts';
import { setUpProfiles, type ProfileServices } from '../../profiles-setup.ts';
import { loadTuning } from '../../tuning/tuning.ts';
import { cachedSettingsVersion } from '../client-settings-cache.ts';
import type { SaveLocation } from '../save-editor.ts';
import { loadSaveLabels, localizeVehicleName } from '../save-labels.ts';
import { findSlotbarAccounts, namedBlock, parseSlotbarPreset } from '../slotbar-presets.ts';
import { readBackupBlk } from './backup-blk.ts';
const TYPES = {
@@ -30,7 +31,6 @@ type BackupName = keyof typeof TYPES;
const SURVIVAL = /^(tank_tool_kit|tank_extinguisher|tank_crew_replacement|tank_laser_rangefinder|tank_night_vision|tank_thermal_vision)$/;
const TALISMAN = 'premExpMul';
const CREW_BLOCK_NAME = /^c(\d+)$/;
const FIRST_CHOSEN_UNIT_TYPES = [
'chosen_unit_type_tank',
'chosen_unit_type_air',
@@ -117,19 +117,9 @@ export function importOfficialBackup(
}
const store = new CloudSettingsStore(dataFolder);
const existing = store.buildMetaBlk(userId);
for (const file of files) {
const blkType = TYPES[file.name];
const localCachedVersion = offlineClientCacheFolders.reduce(
(highest, folder) => Math.max(highest, readCachedLocalVersion(folder, file.name)),
0,
);
const version = Math.max(file.version, intField(findBlock(existing, blkType), 'version'), localCachedVersion) + 1;
if (version > 0x7fffffff) throw new Error('Imported settings version exceeds the supported range.');
const contentHash = createHash('md5').update(encodeBlk({ ...file.content, name: '' })).digest('hex');
if (!store.saveUpload(userId, { blkType, version, contentHash, container: file.container })) {
throw new Error('Could not store the imported settings.');
}
store.replaceContainer(userId, blkType, file.container, cachedSettingsVersion(offlineClientCacheFolders, file.name));
for (const folder of offlineClientCacheFolders) {
clearCachedLocalFile(folder, file.name);
}
@@ -181,12 +171,6 @@ function readFile(path: string): OfficialFile {
return { name: name as BackupName, version, container, content };
}
function findAccountsBlock(content: BlkBlock): BlkBlock | undefined {
const settings = findBlock(content, 'settings');
const customSettings = settings ? findBlock(settings, 'customSettings') : undefined;
return (customSettings ? findBlock(customSettings, 'accounts') : undefined) ?? namedBlock(content, 'accounts');
}
function pickSourceAccountBlock(accounts: BlkBlock): BlkBlock | undefined {
const withPresets = accounts.blocks.filter((entry) => findBlock(entry, 'slotbar_presets') !== undefined);
return withPresets.find((entry) => entry.name.endsWith('.production'))
@@ -196,7 +180,7 @@ function pickSourceAccountBlock(accounts: BlkBlock): BlkBlock | undefined {
}
function readPresets(content: BlkBlock): ParsedPreset[] {
const accounts = findAccountsBlock(content);
const accounts = findSlotbarAccounts(content);
const sourceAccount = accounts ? pickSourceAccountBlock(accounts) : undefined;
const root = (sourceAccount ? findBlock(sourceAccount, 'slotbar_presets') : undefined)
?? namedBlock(content, 'slotbar_presets');
@@ -211,59 +195,17 @@ function readPresets(content: BlkBlock): ParsedPreset[] {
}
function parsePresetString(country: string, raw: string, selected: boolean): ParsedPreset | null {
const parts = raw.split('|');
if (parts.length < 3) return null;
const selectedCrewText = parts[0] ?? '';
const crewIdsText = parts[1] ?? '';
const vehiclesText = parts[2] ?? '';
const title = parts[3] ?? '';
const gameModeId = parts[4] ?? '';
const crewInSlotsText = parts[5] ?? '';
const selectedOnlineCrewId = /^\d+$/.test(selectedCrewText) ? Number(selectedCrewText) : -1;
const crewIdTokens = crewIdsText ? crewIdsText.split(',') : [];
const vehicleTokens = vehiclesText ? vehiclesText.split(',') : [];
const slotCrewIds = crewInSlotsText
? crewInSlotsText.split(',').filter((token) => /^\d+$/.test(token)).map(Number)
: [];
const units: PresetUnit[] = [];
const pairCount = Math.min(crewIdTokens.length, vehicleTokens.length);
for (let i = 0; i < pairCount; i += 1) {
const vehicle = vehicleTokens[i]?.trim() ?? '';
const token = crewIdTokens[i]?.trim() ?? '';
if (!vehicle || !/^\d+$/.test(token)) continue;
units.push({ onlineCrewId: Number(token), vehicle });
}
const slotCrewOrder: number[] = [];
const seen = new Set<number>();
for (const id of slotCrewIds) {
if (!seen.has(id)) {
seen.add(id);
slotCrewOrder.push(id);
}
}
return { country, title, gameModeId, selected, selectedOnlineCrewId, slotCrewOrder, units };
}
function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
if (block.name === name) return block;
for (const child of block.blocks) {
const found = namedBlock(child, name);
if (found) return found;
}
}
function crewIdOfBlock(crew: BlkBlock): number {
return Number(CREW_BLOCK_NAME.exec(crew.name)?.[1] ?? -1);
const preset = parseSlotbarPreset(raw);
if (!preset) return null;
return {
country, selected, title: preset.title, gameModeId: preset.gameModeId,
selectedOnlineCrewId: preset.selectedCrewId, slotCrewOrder: preset.slotCrewOrder,
units: preset.units.map(({ crewId, vehicle }) => ({ onlineCrewId: crewId, vehicle })),
};
}
function countryCrewsOf(profile: BlkBlock, country: string): BlkBlock[] {
return allCrews(profile).filter((crew) =>
crew.params.some((param) => param.name === 'country' && param.value.type === 'string' && param.value.value === country),
);
return allCrews(profile).filter((crew) => crewCountry(crew) === country);
}
/**
@@ -328,7 +270,7 @@ function buildExistingCrewMappings(
for (const country of countries) {
if (!research.techTree.hasCountry(country)) continue;
const crews = countryCrewsOf(profile, country);
const offlineCrewIds = crews.map(crewIdOfBlock).filter((id) => id >= 0);
const offlineCrewIds = crews.map(crewIdOf).filter((id) => id >= 0);
const onlineOrder = orderedOnlineCrewIdsForCountry(presets, country);
const onlineToOffline = new Map<number, number>();
for (let slot = 0; slot < Math.min(onlineOrder.length, offlineCrewIds.length); slot += 1) {
@@ -390,20 +332,21 @@ function applyVehicles(
const countries = new Set(presets.map(({ country }) => country));
for (const country of countries) {
if (!research.techTree.hasCountry(country)) continue;
const crews = countryCrewsOf(profile, country);
let crews = countryCrewsOf(profile, country);
const onlineOrder = orderedOnlineCrewIdsForCountry(presets, country);
const targetSlots = Math.min(Math.max(crews.length, onlineOrder.length), Math.max(slotLimit, crews.length));
while (crews.length < targetSlots) {
crews.push(crewOf(profile, addCrew(profile, country))!);
openNextCrew(profile, country);
crews = countryCrewsOf(profile, country);
}
const offlineCrewIds = crews.map(crewIdOfBlock).filter((id) => id >= 0);
const offlineCrewIds = crews.map(crewIdOf).filter((id) => id >= 0);
const onlineToOffline = new Map<number, number>();
const onlineToCrew = new Map<number, BlkBlock>();
for (let slot = 0; slot < Math.min(onlineOrder.length, crews.length); slot += 1) {
const onlineId = onlineOrder[slot]!;
const crew = crews[slot]!;
const offlineId = crewIdOfBlock(crew);
const offlineId = crewIdOf(crew);
if (offlineId >= 0) {
onlineToOffline.set(onlineId, offlineId);
onlineToCrew.set(onlineId, crew);
@@ -445,7 +388,7 @@ function remapGlobalAccountSettings(
mappings: ReadonlyMap<string, CountryCrewMapping>,
known: ReadonlySet<string>,
): void {
const accounts = findAccountsBlock(content);
const accounts = findSlotbarAccounts(content);
if (!accounts) return;
const source = pickSourceAccountBlock(accounts);
if (!source) return;
@@ -508,20 +451,6 @@ function rewritePresetString(
].join('|');
}
function readCachedLocalVersion(cacheFolder: string, fileName: BackupName): number {
const path = join(cacheFolder, fileName);
if (!existsSync(path)) return 0;
try {
const stats = lstatSync(path);
if (!stats.isFile() || stats.size > 32 * 1024 * 1024) return 0;
const block = readBackupBlk(readFileSync(path));
const version = intField(block, 'version', 0);
return Number.isInteger(version) && version > 0 ? version : 0;
} catch {
return 0;
}
}
function clearCachedLocalFile(cacheFolder: string, fileName: BackupName): void {
const path = join(cacheFolder, fileName);
if (!existsSync(path)) return;
+198
View File
@@ -0,0 +1,198 @@
import { createHash } from 'node:crypto';
import { emptyBlock, encodeBlk, type BlkBlock } from '@wto/blk';
import { AccountStore } from '../accounts/account-store.ts';
import { ClanStore } from '../clans/clan-store.ts';
import { CloudSettingsStore } from '../cloud-settings/cloud-settings-store.ts';
import { applyCrewLevelPlan, CREW_TYPE_BY_VEHICLE, crewLevels, crewLevelSkills, planCrewLevel, type CrewType } from '../crew/crew-levels.ts';
import { crewSkillData } from '../game-data/datasets/crew-skills.ts';
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import { crewSlotPrices } from '../game-data/datasets/rank-settings.ts';
import { uiLabels } from '../game-data/datasets/ui-labels.ts';
import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts';
import { GameFiles } from '../game-data/game-files.ts';
import {
addCrew, allCrews, closeCrew, closedCrews, CLOSED_CREWS, CREWS, crewCountOf, crewCountry, crewIdOf, crewVehicle,
crewVehiclesOfCountry, emptyCrewSlot, reopenCrew,
} from '../profile/profile-crews.ts';
import { ownsVehicle } from '../profile/profile-hangar.ts';
import { setUpProfiles } from '../profiles-setup.ts';
import { TechTree } from '../research/tech-tree.ts';
import { loadTuning } from '../tuning/tuning.ts';
import { cachedSettingsVersion } from './client-settings-cache.ts';
import { readSaveSnapshot, type SaveLocation } from './save-editor.ts';
import { loadSaveLabels, localizeVehicleName } from './save-labels.ts';
import { countrySlotbarPresets, removeCrewFromPresets } from './slotbar-presets.ts';
const SETTINGS_TYPE = 'GBT_GENERAL_SETTINGS';
const SETTINGS_FILE = 'global.blk';
export type SaveCrewEdit =
| { readonly action: 'add' }
| { readonly action: 'open' | 'close'; readonly crewId: number }
| { readonly action: 'level'; readonly crewId: number; readonly type: CrewType; readonly target: number };
type CrewEditError = 'not-found' | 'invalid' | 'slot-limit' | 'stale';
function loadEditor(location: SaveLocation, userId: string) {
const accounts = new AccountStore(location.dataFolder);
if (!accounts.byUserId(userId)) return undefined;
const gameFiles = new GameFiles(location.gameFolder);
const datasets = new DatasetCache(location.dataFolder, gameFiles, () => {});
const template = gameFiles.newAccountTemplate();
const vehicles = datasets.load(vehicleCatalogue);
const branchesByCountry = new Map<string, Set<CrewType>>();
const skills = crewLevelSkills(datasets.load(crewSkillData));
for (const { country, type: vehicleType } of new TechTree(vehicles).branches()) {
const types = branchesByCountry.get(country) ?? new Set<CrewType>();
const type = CREW_TYPE_BY_VEHICLE[vehicleType];
if (type && skills.some((skill) => skill.types.includes(type))) types.add(type);
branchesByCountry.set(country, types);
}
return {
accounts, gameFiles, datasets, vehicles, branchesByCountry, skills, template,
snapshot: readSaveSnapshot(location.dataFolder, userId) ?? template,
slotPrices: datasets.load(crewSlotPrices), names: datasets.load(uiLabels),
labels: loadSaveLabels(location.dataFolder, location.gameFolder),
cloud: new CloudSettingsStore(location.dataFolder),
};
}
type Editor = NonNullable<ReturnType<typeof loadEditor>>;
function countryCrews(profile: BlkBlock, country: string) {
const active = allCrews(profile).filter((crew) => crewCountry(crew) === country);
const archived = closedCrews(profile).filter((crew) => crewCountry(crew) === country);
return { active, archived };
}
function slotLimits(editor: Editor, country: string, active: number, archived: number) {
const min = crewCountOf(editor.template, country);
const max = editor.slotPrices.length;
const canOpen = editor.slotPrices[active] != null;
return { min, max, canOpen, canAdd: canOpen && active + archived < max };
}
function viewOf(editor: Editor, profile: BlkBlock, selection?: string) {
const countries = [...editor.branchesByCountry.keys()].map((id) => ({ id, name: editor.names[id] ?? { en: id, zh: id } }));
const selected = countries.find(({ id }) => id === selection)?.id ?? countries[0]?.id ?? null;
const { active, archived } = countryCrews(profile, selected ?? '');
const { min, max, canOpen, canAdd } = slotLimits(editor, selected ?? '', active.length, archived.length);
const types = [...(selected ? editor.branchesByCountry.get(selected) ?? [] : [])];
const crews = [...active, ...archived].sort((a, b) => crewIdOf(a) - crewIdOf(b)).map((crew) => {
const open = active.includes(crew);
return {
id: crewIdOf(crew), open, canToggle: open ? active.length > min : canOpen,
vehicle: localizeVehicleName(crewVehicle(crew), editor.labels),
levels: crewLevels(crew, editor.skills, types),
};
});
return { countries, selected, activeCount: active.length, min, max, canAdd, crews };
}
export function readSaveCrews(location: SaveLocation, userId: string, country?: string) {
const editor = loadEditor(location, userId);
return editor ? viewOf(editor, editor.snapshot, country) : null;
}
function applySlotEdit(editor: Editor, profile: BlkBlock, country: string, edit: Exclude<SaveCrewEdit, { action: 'level' }>):
{ crew: BlkBlock; vehicle: string } | { error: CrewEditError } {
const { active, archived } = countryCrews(profile, country);
const limits = slotLimits(editor, country, active.length, archived.length);
if (edit.action === 'add') {
if (!limits.canAdd) return { error: 'slot-limit' };
const id = addCrew(profile, country);
return { crew: allCrews(profile).find((entry) => crewIdOf(entry) === id)!, vehicle: '' };
}
const crew = (edit.action === 'close' ? active : archived).find((entry) => crewIdOf(entry) === edit.crewId);
if (!crew) return { error: 'invalid' };
const vehicle = crewVehicle(crew);
if (edit.action === 'close') {
if (active.length <= limits.min) return { error: 'slot-limit' };
closeCrew(profile, crew);
} else {
if (!limits.canOpen) return { error: 'slot-limit' };
if (vehicle && (!ownsVehicle(profile, vehicle) || crewVehiclesOfCountry(profile, country).includes(vehicle))) emptyCrewSlot(crew);
reopenCrew(profile, crew);
}
return { crew, vehicle };
}
function applyLevelEdit(editor: Editor, profile: BlkBlock, country: string, edit: Extract<SaveCrewEdit, { action: 'level' }>) {
const { active, archived } = countryCrews(profile, country);
const crew = [...active, ...archived].find((entry) => crewIdOf(entry) === edit.crewId);
const types = [...editor.branchesByCountry.get(country)!];
if (!crew || !types.includes(edit.type) || !Number.isFinite(edit.target)) return { error: 'invalid' } as const;
const before = crewLevels(crew, editor.skills, types);
const range = before.find(({ type }) => type === edit.type)!;
if (edit.target < range.min || edit.target > range.max) return { error: 'invalid' } as const;
const changes = planCrewLevel(crew, editor.skills, edit.type, edit.target);
applyCrewLevelPlan(crew, changes);
const levels = crewLevels(crew, editor.skills, types).map(({ type, level }, index) => ({ type, before: before[index]!.level, after: level }));
return { crew, levels, changed: changes.length > 0 };
}
function isCrewBlock({ name }: BlkBlock): boolean {
return name === CREWS || name === CLOSED_CREWS;
}
function prepareEdit(editor: Editor, userId: string, country: string, edit: SaveCrewEdit) {
if (!editor.branchesByCountry.has(country)) return { error: 'invalid' } as const;
const original = editor.snapshot;
const draft = { ...original, blocks: original.blocks.map((block) => isCrewBlock(block) ? structuredClone(block) : block) };
const result = edit.action === 'level' ? applyLevelEdit(editor, draft, country, edit) : applySlotEdit(editor, draft, country, edit);
if ('error' in result) return { error: result.error };
const cloud = edit.action === 'close' ? editor.cloud.loadSavedContainer(userId, SETTINGS_TYPE) : undefined;
const presets = cloud && countrySlotbarPresets(cloud, userId, country);
const previousPresets = presets && encodeBlk(presets);
const affected = presets && edit.action === 'close' ? removeCrewFromPresets(presets, edit.crewId) : [];
const preview = {
crewId: crewIdOf(result.crew),
vehicle: localizeVehicleName('vehicle' in result ? result.vehicle : '', editor.labels),
restoredVehicle: localizeVehicleName(edit.action === 'open' ? crewVehicle(result.crew) : '', editor.labels),
presets: affected.map((preset) => ({ ...preset, vehicle: localizeVehicleName(preset.vehicle, editor.labels) })),
levels: 'levels' in result ? result.levels : [],
changed: 'changed' in result ? result.changed : true,
};
const hash = createHash('sha256').update(JSON.stringify({ userId, country, edit, preview }));
hash.update(encodeBlk({ ...emptyBlock(), blocks: original.blocks.filter(isCrewBlock) }));
hash.update(encodeBlk({ ...emptyBlock(), blocks: draft.blocks.filter(isCrewBlock) }));
if (previousPresets) hash.update(previousPresets);
return { draft, cloud: affected.length ? cloud : undefined, preview: { ...preview, token: hash.digest('hex') } };
}
export function previewSaveCrewEdit(location: SaveLocation, userId: string, country: string, edit: SaveCrewEdit) {
const editor = loadEditor(location, userId);
if (!editor) return { error: 'not-found' } as const;
const plan = prepareEdit(editor, userId, country, edit);
return 'error' in plan ? { error: plan.error } : { preview: plan.preview };
}
export function editSaveCrew(
location: SaveLocation, userId: string, country: string, edit: SaveCrewEdit, token: string, cacheFolders: readonly string[],
) {
const editor = loadEditor(location, userId);
if (!editor) return { error: 'not-found' } as const;
const plan = prepareEdit(editor, userId, country, edit);
if ('error' in plan) return { error: plan.error };
if (plan.preview.token !== token) return { error: 'stale' } as const;
if (!plan.preview.changed) return { view: viewOf(editor, editor.snapshot, country) };
const tuning = loadTuning(location.dataFolder, () => {});
const clans = new ClanStore(location.dataFolder, tuning.clans);
const { profiles } = setUpProfiles(location.dataFolder, editor.gameFiles, editor.datasets, tuning, { accounts: editor.accounts, clans }, editor.vehicles);
const saved = profiles.update(userId, (profile) => {
profile.blocks = [...profile.blocks.filter((block) => !isCrewBlock(block)), ...plan.draft.blocks.filter(isCrewBlock)];
});
if (plan.cloud) editor.cloud.replaceContainer(userId, SETTINGS_TYPE, plan.cloud, cachedSettingsVersion(cacheFolders, SETTINGS_FILE));
return { view: viewOf(editor, saved, country) };
}
/** Make restored presets take precedence over the offline game's newer cached settings. */
export function syncRestoredCrewPresets(dataFolder: string, userId: string, cacheFolders: readonly string[]): void {
const cloud = new CloudSettingsStore(dataFolder);
const settings = cloud.loadSavedContainer(userId, SETTINGS_TYPE);
if (settings) cloud.replaceContainer(userId, SETTINGS_TYPE, settings, cachedSettingsVersion(cacheFolders, SETTINGS_FILE));
}
+87
View File
@@ -0,0 +1,87 @@
import { findBlock, type BlkBlock } from '@wto/blk';
export interface SlotbarPreset {
readonly selectedCrewId: number;
readonly units: readonly { crewId: number; vehicle: string }[];
readonly slotCrewOrder: readonly number[];
readonly title: string;
readonly gameModeId: string;
readonly extraFields: readonly string[];
}
function parseCrewId(text: string): number | undefined {
const id = Number(text);
return /^\d+$/.test(text) && Number.isSafeInteger(id) ? id : undefined;
}
/** The fields serialized by saveCountryPreset in scripts/slotbar/slotbarpresets.nut. */
export function parseSlotbarPreset(raw: string): SlotbarPreset | undefined {
const fields = raw.split('|');
if (fields.length < 3) return undefined;
const [selected = '', crews = '', vehicles = '', title = '', gameModeId = '', order = '', ...extraFields] = fields;
const crewIds = crews.split(',');
const units = vehicles.split(',').flatMap((name, index) => {
const vehicle = name.trim();
const crewId = parseCrewId(crewIds[index]?.trim() ?? '');
return vehicle && crewId !== undefined ? [{ crewId, vehicle }] : [];
});
const slotIds = order.split(',').map(parseCrewId).filter((id) => id !== undefined);
return { selectedCrewId: parseCrewId(selected) ?? -1, units, slotCrewOrder: [...new Set(slotIds)], title, gameModeId, extraFields };
}
export function formatSlotbarPreset(preset: SlotbarPreset): string {
return [
preset.selectedCrewId,
preset.units.map(({ crewId }) => crewId).join(','),
preset.units.map(({ vehicle }) => vehicle).join(','),
preset.title, preset.gameModeId,
preset.slotCrewOrder.join(','),
...preset.extraFields,
].join('|');
}
export function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
if (block.name === name) return block;
for (const child of block.blocks) {
const found = namedBlock(child, name);
if (found) return found;
}
return undefined;
}
export function findSlotbarAccounts(content: BlkBlock): BlkBlock | undefined {
const settings = findBlock(content, 'settings');
const customSettings = settings && findBlock(settings, 'customSettings');
return (customSettings && findBlock(customSettings, 'accounts')) ?? namedBlock(content, 'accounts');
}
export function countrySlotbarPresets(container: BlkBlock, userId: string, country: string): BlkBlock | undefined {
const content = findBlock(container, 'content');
const accounts = content && findSlotbarAccounts(content);
const account = accounts && findBlock(accounts, `${userId}.production`);
const countries = account && findBlock(account, 'slotbar_presets');
return countries && findBlock(countries, country);
}
/** Remove a closed crew from the paired crew/vehicle arrays and the preset's slot order. */
export function removeCrewFromPresets(country: BlkBlock, crewId: number) {
const removed: { index: number; title: string; vehicle: string; empty: boolean }[] = [];
let index = 0;
for (const parameter of country.params) {
if (parameter.name !== 'preset' || parameter.value.type !== 'string') continue;
const presetIndex = index++;
const preset = parseSlotbarPreset(parameter.value.value);
if (!preset) continue;
const assignment = preset.units.find((unit) => unit.crewId === crewId);
if (!assignment && preset.selectedCrewId !== crewId && !preset.slotCrewOrder.includes(crewId)) continue;
const units = preset.units.filter((unit) => unit.crewId !== crewId);
parameter.value = { type: 'string', value: formatSlotbarPreset({
...preset, units,
selectedCrewId: preset.selectedCrewId === crewId ? (units[0]?.crewId ?? -1) : preset.selectedCrewId,
slotCrewOrder: preset.slotCrewOrder.filter((id) => id !== crewId),
}) };
removed.push({ index: presetIndex, title: preset.title, vehicle: assignment?.vehicle ?? '', empty: Boolean(assignment && units.length === 0) });
}
return removed;
}
+2 -2
View File
@@ -8,7 +8,7 @@ import { vehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts';
import { GameFiles } from '../game-data/game-files.ts';
import { InventoryCatalogue } from '../inventory/itemdef-catalogue.ts';
import { intField, stringField } from '../profile/blk-fields.ts';
import { allCrews } from '../profile/profile-crews.ts';
import { allCrews, closedCrews } from '../profile/profile-crews.ts';
import { ACTIVE_LISTS } from '../profile/profile-items.ts';
import { normalizeModificationBlocks, recordName } from '../profile/profile-modifications.ts';
import { loadTuning } from '../tuning/tuning.ts';
@@ -45,7 +45,7 @@ export function prepareTransferredProfile(location: SaveLocation, bytes: Uint8Ar
}
}
normalizeModificationBlocks(profile);
for (const crew of allCrews(profile)) {
for (const crew of [...allCrews(profile), ...closedCrews(profile)]) {
const aircraft = findBlock(crew, 'aircrafts');
if (aircraft) {
aircraft.params = aircraft.params.filter(({ name, value }) =>