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:
1 parent
264c5c59b8
commit
d58ba9fb9b
31 files changed
+1021
-139
No files matched your search
@@ -31,6 +31,7 @@ import {
|
||||
setModsOrder,
|
||||
} from '../services/mods/mods-service.ts';
|
||||
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
||||
import { changeSaveCrew, getSaveCrews, previewSaveCrew } from '../services/saves/manage-save-crews.ts';
|
||||
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
||||
import { rememberDialogPath, resolveDialogDefaultPath } from '../util/dialog-paths.ts';
|
||||
import { broadcast, handle } from './register.ts';
|
||||
@@ -193,6 +194,9 @@ export function registerIpcHandlers(): void {
|
||||
|
||||
handle('saves:research', ({ copyId, userId, branch }) => getSaveResearch(copyId, userId, branch));
|
||||
handle('saves:editResearch', ({ copyId, userId, branch, action }) => changeSaveResearch(copyId, userId, branch, action));
|
||||
handle('saves:crews', ({ copyId, userId, country }) => getSaveCrews(copyId, userId, country));
|
||||
handle('saves:previewCrew', ({ copyId, userId, country, edit }) => previewSaveCrew(copyId, userId, country, edit));
|
||||
handle('saves:editCrew', ({ copyId, userId, country, edit, token }) => changeSaveCrew(copyId, userId, country, edit, token));
|
||||
|
||||
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
|
||||
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { SaveCrewEdit, SaveCrewPreview, SaveCrewView } from '@shared/schemas/crew-saves.ts';
|
||||
import { offlineClientCacheFolders, requireSaveCopy, runSaveTask, saveLocation, writeSave } from './manage-saves.ts';
|
||||
import { captureSave, restoreDirectory, saveBackup } from './save-archive.ts';
|
||||
|
||||
export async function getSaveCrews(copyId: string, userId: string, country: string | undefined): Promise<SaveCrewView> {
|
||||
const copy = await requireSaveCopy(copyId);
|
||||
return await runSaveTask({ operation: 'readCrews', ...saveLocation(copy), userId, country }) as SaveCrewView;
|
||||
}
|
||||
|
||||
export async function previewSaveCrew(copyId: string, userId: string, country: string, edit: SaveCrewEdit): Promise<SaveCrewPreview> {
|
||||
const copy = await requireSaveCopy(copyId);
|
||||
return await runSaveTask({ operation: 'previewCrew', ...saveLocation(copy), userId, country, edit }) as SaveCrewPreview;
|
||||
}
|
||||
|
||||
export async function changeSaveCrew(copyId: string, userId: string, country: string, edit: SaveCrewEdit, token: string): Promise<SaveCrewView> {
|
||||
return writeSave(async () => {
|
||||
const copy = await requireSaveCopy(copyId);
|
||||
const before = await captureSave(copy, userId);
|
||||
const cacheFolders = edit.action === 'close' ? await offlineClientCacheFolders(userId) : [];
|
||||
if (edit.action === 'close') await saveBackup(copy, userId, 'crew', before);
|
||||
try {
|
||||
return await runSaveTask({ operation: 'editCrew', ...saveLocation(copy), userId, country, edit, token, cacheFolders }) as SaveCrewView;
|
||||
} catch (error) {
|
||||
const refused = error instanceof AppError && ['save_not_found', 'save_crew_invalid', 'save_crew_slot_limit', 'save_crew_stale'].includes(error.code);
|
||||
if (!refused) await restoreDirectory(copy, userId, before);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import { localServerReady } from '../launch/local-server.ts';
|
||||
import { forwardProcessOutput } from '../launch/process-output.ts';
|
||||
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
|
||||
|
||||
export { location as saveLocation, offlineClientCacheFolders, requireCopy as requireSaveCopy, run as runSaveTask, write as writeSave };
|
||||
|
||||
let writing = false;
|
||||
|
||||
export function saveWriteInProgress(): boolean {
|
||||
@@ -191,8 +193,18 @@ export async function restoreSaveBackup(copyId: string, userId: string, name: st
|
||||
await getSaveDetails(copyId, userId);
|
||||
const archive = await archivedBackup(copy, userId, name);
|
||||
await validateProfile(archive, copy);
|
||||
await saveBackup(copy, userId, 'restore');
|
||||
const before = await captureSave(copy, userId);
|
||||
const cacheFolders = name.split('.')[1] === 'crew' ? await offlineClientCacheFolders(userId) : undefined;
|
||||
await saveBackup(copy, userId, 'restore', before);
|
||||
await restoreDirectory(copy, userId, archive);
|
||||
if (cacheFolders) {
|
||||
try {
|
||||
await run({ operation: 'syncRestoredCrewPresets', ...location(copy), userId, cacheFolders });
|
||||
} catch (error) {
|
||||
await restoreDirectory(copy, userId, before);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return getSaveDetails(copyId, userId);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -178,11 +178,11 @@ export async function backupList(copy: InstallRecord, userId: string): Promise<S
|
||||
return backups;
|
||||
}
|
||||
|
||||
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type']): Promise<void> {
|
||||
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type'], archive?: SaveArchive): Promise<void> {
|
||||
const root = await backupFolder(copy, userId);
|
||||
await mkdir(root, { recursive: true });
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), await captureSave(copy, userId));
|
||||
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), archive ?? await captureSave(copy, userId));
|
||||
if (type === 'launch') {
|
||||
const older = (await backupList(copy, userId)).filter((backup) => backup.type === 'launch').slice(10);
|
||||
for (const backup of older) await rm(join(root, backup.name), { force: true });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AppErrorCode } from '@shared/errors.ts';
|
||||
import type { SaveCrewEdit, SaveCrewPreview, SaveCrewView } from '@shared/schemas/crew-saves.ts';
|
||||
import type { AccountEdits, SaveAvatarChoices, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
|
||||
interface Location {
|
||||
@@ -23,9 +24,13 @@ export type SaveTask = Location & (
|
||||
}
|
||||
| { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch }
|
||||
| { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation }
|
||||
| { readonly operation: 'readCrews'; readonly userId: string; readonly country: string | undefined }
|
||||
| { readonly operation: 'previewCrew'; readonly userId: string; readonly country: string; readonly edit: SaveCrewEdit }
|
||||
| { readonly operation: 'editCrew'; readonly userId: string; readonly country: string; readonly edit: SaveCrewEdit; readonly token: string; readonly cacheFolders: readonly string[] }
|
||||
| { readonly operation: 'syncRestoredCrewPresets'; readonly userId: string; readonly cacheFolders: readonly string[] }
|
||||
| { readonly operation: 'remove'; readonly userId: string }
|
||||
| { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean }
|
||||
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
|
||||
);
|
||||
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
|
||||
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | SaveCrewView | SaveCrewPreview | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
|
||||
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
|
||||
@@ -1,7 +1,12 @@
|
||||
import type { MessageEvent } from 'electron';
|
||||
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveAvatars, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveAvatar, readSaveDetails, readSaveResearch } from '@wto/server';
|
||||
import { editSaveCrew, previewSaveCrewEdit, readSaveCrews, syncRestoredCrewPresets } from '@wto/server';
|
||||
import type { SaveTask, SaveReply } from './save-protocol.ts';
|
||||
|
||||
const CREW_ERRORS = {
|
||||
'not-found': 'save_not_found', invalid: 'save_crew_invalid', 'slot-limit': 'save_crew_slot_limit', stale: 'save_crew_stale',
|
||||
} as const;
|
||||
|
||||
function execute(task: SaveTask): SaveReply {
|
||||
switch (task.operation) {
|
||||
case 'list':
|
||||
@@ -37,6 +42,23 @@ function execute(task: SaveTask): SaveReply {
|
||||
const result = editSaveResearch(task, task.userId, task.branch, task.action);
|
||||
return result ? { ok: true, result } : { ok: false, error: 'save_operation_failed' };
|
||||
}
|
||||
case 'readCrews': {
|
||||
const result = readSaveCrews(task, task.userId, task.country);
|
||||
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
|
||||
}
|
||||
case 'previewCrew': {
|
||||
const result = previewSaveCrewEdit(task, task.userId, task.country, task.edit);
|
||||
if ('preview' in result && result.preview) return { ok: true, result: result.preview };
|
||||
return { ok: false, error: CREW_ERRORS[result.error ?? 'invalid'] };
|
||||
}
|
||||
case 'editCrew': {
|
||||
const result = editSaveCrew(task, task.userId, task.country, task.edit, task.token, task.cacheFolders);
|
||||
if ('view' in result && result.view) return { ok: true, result: result.view };
|
||||
return { ok: false, error: CREW_ERRORS[result.error ?? 'invalid'] };
|
||||
}
|
||||
case 'syncRestoredCrewPresets':
|
||||
syncRestoredCrewPresets(task.dataFolder, task.userId, task.cacheFolders);
|
||||
return { ok: true, result: null };
|
||||
case 'remove':
|
||||
return new AccountStore(task.dataFolder).remove(task.userId)
|
||||
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
|
||||
|
||||
@@ -362,6 +362,7 @@
|
||||
"overview": "Overview",
|
||||
"battles": "Battle history",
|
||||
"vehicles": "Vehicles and research",
|
||||
"crews": "Crews",
|
||||
"official": "Import online data",
|
||||
"backup": "Backup and restore"
|
||||
},
|
||||
@@ -396,6 +397,37 @@
|
||||
"Helicopter": "Helicopters"
|
||||
}
|
||||
},
|
||||
"crews": {
|
||||
"noCountries": "This client has no countries available for crew editing.",
|
||||
"loadFailed": "Could not load crews. Check the error message and reopen this page.",
|
||||
"slots": "{{open}} of {{max}} crew slots open",
|
||||
"minimum": "Keep at least {{count}} slots open.",
|
||||
"group": "Crew {{number}}",
|
||||
"noVehicle": "Empty slot",
|
||||
"opened": "Open",
|
||||
"closed": "Closed",
|
||||
"open": "Reopen slot",
|
||||
"close": "Close slot",
|
||||
"add": "Open a new slot",
|
||||
"editLevel": "Set level",
|
||||
"type": "Crew type",
|
||||
"types": { "air": "Air", "tank": "Ground", "ship": "Naval", "human": "Infantry" },
|
||||
"target": "Target crew level",
|
||||
"levelRange": "Available levels {{min}} to {{max}}.",
|
||||
"preview": "Preview changes",
|
||||
"previewLevel": "Target level {{target}}. The game will show these levels after saving.",
|
||||
"levelChange": "{{type}} {{before}} → {{after}}",
|
||||
"noChange": "The current level is the closest available level to the target.",
|
||||
"confirmClose": "Closing this slot backs up the save. Reopen it to restore its skills, training and qualifications.",
|
||||
"removeVehicle": "{{vehicle}} will leave its hangar slot.",
|
||||
"confirmOpen": "Return this crew to the hangar.",
|
||||
"confirmRestoreVehicle": "Return this crew and {{vehicle}} to the hangar.",
|
||||
"confirmAdd": "Open an empty crew slot for this country.",
|
||||
"affectedPresets": "Affected lineup presets",
|
||||
"preset": "Lineup {{number}}",
|
||||
"emptyPreset": "No vehicles after closing",
|
||||
"saved": "Crew changes saved. They will take effect the next time you start the game."
|
||||
},
|
||||
"official": {
|
||||
"auto": "Automatic import",
|
||||
"autoHint": "Locates local online data read-only, copies it into the offline folder, and imports from the copy without modifying the online files.",
|
||||
@@ -441,7 +473,8 @@
|
||||
"manual": "Manual backup",
|
||||
"launch": "Before launch",
|
||||
"restore": "Before restore",
|
||||
"import": "Before import"
|
||||
"import": "Before import",
|
||||
"crew": "Before closing a crew slot"
|
||||
}
|
||||
},
|
||||
"create": "Create save",
|
||||
@@ -1045,6 +1078,9 @@
|
||||
"save_not_found": "The selected save could not be found.",
|
||||
"save_read_only": "Saves are read-only while the game or local server is running.",
|
||||
"save_operation_failed": "The save operation failed. See the launcher log.",
|
||||
"save_crew_invalid": "Invalid crew, crew type or target level. Check the selected save and level range.",
|
||||
"save_crew_slot_limit": "This change exceeds the available crew slot range for the country.",
|
||||
"save_crew_stale": "The save changed after the preview. Preview the change again before saving.",
|
||||
"save_login_invalid": "Enter a login without spaces.",
|
||||
"save_login_exists": "An account with this login already exists.",
|
||||
"save_password_invalid": "Enter a password.",
|
||||
|
||||
@@ -362,6 +362,7 @@
|
||||
"overview": "概览",
|
||||
"battles": "战绩",
|
||||
"vehicles": "载具与研发",
|
||||
"crews": "乘员组",
|
||||
"official": "导入在线版数据",
|
||||
"backup": "备份与还原"
|
||||
},
|
||||
@@ -396,6 +397,37 @@
|
||||
"Helicopter": "直升机"
|
||||
}
|
||||
},
|
||||
"crews": {
|
||||
"noCountries": "当前客户端没有可编辑的国家。",
|
||||
"loadFailed": "无法读取乘员组。请查看错误提示后重新打开此页面。",
|
||||
"slots": "已开放 {{open}} / {{max}} 组",
|
||||
"minimum": "至少保留 {{count}} 个开放槽位。",
|
||||
"group": "第 {{number}} 乘员组",
|
||||
"noVehicle": "空槽",
|
||||
"opened": "已开放",
|
||||
"closed": "已关闭",
|
||||
"open": "重新开放",
|
||||
"close": "关闭槽位",
|
||||
"add": "开放新槽位",
|
||||
"editLevel": "设置等级",
|
||||
"type": "兵种",
|
||||
"types": { "air": "空军", "tank": "陆军", "ship": "海军", "human": "步兵" },
|
||||
"target": "目标乘员等级",
|
||||
"levelRange": "可设置 {{min}} 到 {{max}} 级。",
|
||||
"preview": "预览变更",
|
||||
"previewLevel": "目标 {{target}} 级,保存后游戏会显示以下等级。",
|
||||
"levelChange": "{{type}} {{before}} → {{after}}",
|
||||
"noChange": "当前等级已经是最接近目标的可达等级。",
|
||||
"confirmClose": "关闭前会备份存档。重新开放时可恢复该组的技能、训练和专精。",
|
||||
"removeVehicle": "当前载具「{{vehicle}}」将移出机库槽位。",
|
||||
"confirmOpen": "将这组乘员恢复到机库。",
|
||||
"confirmRestoreVehicle": "将这组乘员和载具「{{vehicle}}」恢复到机库。",
|
||||
"confirmAdd": "为当前国家开放一个空乘员槽位。",
|
||||
"affectedPresets": "受影响的编队预设",
|
||||
"preset": "编队 {{number}}",
|
||||
"emptyPreset": "关闭后没有载具",
|
||||
"saved": "乘员组已保存,下次启动游戏后生效。"
|
||||
},
|
||||
"official": {
|
||||
"auto": "自动导入",
|
||||
"autoHint": "只读查找本机在线版数据并复制到离线目录后再导入,不修改在线版原文件。",
|
||||
@@ -441,7 +473,8 @@
|
||||
"manual": "手动备份",
|
||||
"launch": "启动前自动备份",
|
||||
"restore": "还原前自动备份",
|
||||
"import": "导入前自动备份"
|
||||
"import": "导入前自动备份",
|
||||
"crew": "关闭乘员槽位前"
|
||||
}
|
||||
},
|
||||
"create": "新建存档",
|
||||
@@ -1045,6 +1078,9 @@
|
||||
"save_not_found": "找不到所选存档。",
|
||||
"save_read_only": "游戏或本地服务器运行期间存档为只读。",
|
||||
"save_operation_failed": "存档操作失败。请查看启动器日志。",
|
||||
"save_crew_invalid": "乘员组、兵种或目标等级无效。请核对当前存档和可用范围。",
|
||||
"save_crew_slot_limit": "这项操作超出了该系可开放的槽位范围。",
|
||||
"save_crew_stale": "预览后存档发生了变化。请重新预览再保存。",
|
||||
"save_login_invalid": "登录账号不能包含空格。",
|
||||
"save_login_exists": "该登录账号已注册。",
|
||||
"save_password_invalid": "请输入密码。",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { SaveCrewEdit, SaveCrewPreview } from '@shared/schemas/crew-saves.ts';
|
||||
|
||||
export interface PendingCrewChange {
|
||||
readonly edit: SaveCrewEdit;
|
||||
readonly preview: SaveCrewPreview;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
readonly pending: PendingCrewChange;
|
||||
readonly disabled: boolean;
|
||||
readonly busy: boolean;
|
||||
readonly onApply: () => void;
|
||||
readonly onCancel: () => void;
|
||||
}
|
||||
|
||||
export function SaveCrewChangePreview({ pending, disabled, busy, onApply, onCancel }: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { edit, preview } = pending;
|
||||
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||
const format = new Intl.NumberFormat(i18n.language);
|
||||
const vehicle = preview.vehicle[language];
|
||||
const restored = preview.restoredVehicle[language];
|
||||
const levels = preview.levels.filter(({ type, before, after }) => (edit.action === 'level' && type === edit.type) || before !== after);
|
||||
|
||||
return (
|
||||
<div className="maintenance-confirm" aria-live="polite">
|
||||
{edit.action === 'close' && <p>{t('saves.crews.confirmClose')}</p>}
|
||||
{edit.action === 'close' && vehicle && <p>{t('saves.crews.removeVehicle', { vehicle })}</p>}
|
||||
{edit.action === 'open' && <p>{restored ? t('saves.crews.confirmRestoreVehicle', { vehicle: restored }) : t('saves.crews.confirmOpen')}</p>}
|
||||
{edit.action === 'add' && <p>{t('saves.crews.confirmAdd')}</p>}
|
||||
{edit.action === 'level' && <p>{t('saves.crews.previewLevel', { target: format.format(edit.target) })}</p>}
|
||||
{levels.length > 0 && <ul>{levels.map(({ type, before, after }) => (
|
||||
<li key={type}>{t('saves.crews.levelChange', { type: t(`saves.crews.types.${type}`), before: format.format(before), after: format.format(after) })}</li>
|
||||
))}</ul>}
|
||||
{preview.presets.length > 0 && (
|
||||
<>
|
||||
<p>{t('saves.crews.affectedPresets')}</p>
|
||||
<ul>{preview.presets.map(({ index, title, vehicle: assignment, empty }) => (
|
||||
<li key={index}>
|
||||
{title || t('saves.crews.preset', { number: index + 1 })}
|
||||
{assignment[language] && ` · ${assignment[language]}`}
|
||||
{empty && ` · ${t('saves.crews.emptyPreset')}`}
|
||||
</li>
|
||||
))}</ul>
|
||||
</>
|
||||
)}
|
||||
{!preview.changed && <p>{t('saves.crews.noChange')}</p>}
|
||||
<div className="copy-list-actions">
|
||||
<button type="button" className="button" disabled={busy} onClick={onCancel}>{t('wizard.cancel')}</button>
|
||||
<button type="button" className="button button-primary" disabled={disabled || !preview.changed} onClick={onApply}>{t('saves.apply')}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { SaveCrewEdit, SaveCrewView } from '@shared/schemas/crew-saves.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
|
||||
type Level = SaveCrewView['crews'][number]['levels'][number];
|
||||
|
||||
interface Props {
|
||||
readonly crewId: number;
|
||||
readonly levels: readonly Level[];
|
||||
readonly disabled: boolean;
|
||||
readonly onPreview: (edit: SaveCrewEdit) => void;
|
||||
readonly onChange: () => void;
|
||||
}
|
||||
|
||||
export function SaveCrewLevelEditor({ crewId, levels, disabled, onPreview, onChange }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [type, setType] = useState(levels[0]?.type);
|
||||
const [target, setTarget] = useState<string | null>(null);
|
||||
const range = levels.find((level) => level.type === type);
|
||||
if (!range) return null;
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>): void {
|
||||
event.preventDefault();
|
||||
const value = Number(target);
|
||||
if (!disabled && range && target?.trim() && Number.isFinite(value)) {
|
||||
onPreview({ action: 'level', crewId, type: range.type, target: value });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit}>
|
||||
<Row label={t('saves.crews.target')} hint={t('saves.crews.levelRange', { min: range.min, max: range.max })}>
|
||||
<select className="select" aria-label={t('saves.crews.type')} value={range.type} disabled={disabled} onChange={(event) => {
|
||||
setType(levels.find(({ type: value }) => value === event.target.value)?.type);
|
||||
setTarget(null);
|
||||
onChange();
|
||||
}}>
|
||||
{levels.map(({ type: value }) => <option key={value} value={value}>{t(`saves.crews.types.${value}`)}</option>)}
|
||||
</select>
|
||||
<input className="input" type="number" aria-label={t('saves.crews.target')} disabled={disabled} required step="any"
|
||||
min={range.min} max={range.max} value={target ?? String(range.level)} onChange={(event) => { setTarget(event.target.value); onChange(); }} />
|
||||
<button type="submit" className="button" disabled={disabled || target === null || !target.trim() || Number(target) === range.level}>
|
||||
{t('saves.crews.preview')}
|
||||
</button>
|
||||
</Row>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { SaveCrewEdit, SaveCrewView } from '@shared/schemas/crew-saves.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import { SaveCrewChangePreview, type PendingCrewChange } from './SaveCrewChangePreview.tsx';
|
||||
import { SaveCrewLevelEditor } from './SaveCrewLevelEditor.tsx';
|
||||
|
||||
interface Props {
|
||||
readonly copyId: string;
|
||||
readonly userId: string;
|
||||
readonly readOnly: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
function useCrewPanel({ copyId, userId, readOnly, onError }: Props) {
|
||||
const [view, setView] = useState<SaveCrewView | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [pending, setPending] = useState<PendingCrewChange | null>(null);
|
||||
const keys = { copyId, userId };
|
||||
const disabled = busy || readOnly;
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
ipcInvoke('saves:crews', { copyId, userId }).then((next) => {
|
||||
if (mounted) setView(next);
|
||||
}).catch((error: unknown) => {
|
||||
if (mounted) {
|
||||
setLoadFailed(true);
|
||||
onError(error);
|
||||
}
|
||||
});
|
||||
return () => { mounted = false; };
|
||||
}, [copyId, userId, onError]);
|
||||
|
||||
function run(action: () => Promise<void>): void {
|
||||
setBusy(true);
|
||||
setSaved(false);
|
||||
setPending(null);
|
||||
action().catch(onError).finally(() => setBusy(false));
|
||||
}
|
||||
|
||||
function preview(edit: SaveCrewEdit): void {
|
||||
const country = view?.selected;
|
||||
if (!country || disabled) return;
|
||||
run(async () => setPending({ edit, preview: await ipcInvoke('saves:previewCrew', { ...keys, country, edit }) }));
|
||||
}
|
||||
|
||||
function apply(onApplied: () => void): void {
|
||||
const country = view?.selected;
|
||||
if (!pending || !country || disabled) return;
|
||||
run(async () => {
|
||||
setView(await ipcInvoke('saves:editCrew', { ...keys, country, edit: pending.edit, token: pending.preview.token }));
|
||||
setSaved(true);
|
||||
onApplied();
|
||||
});
|
||||
}
|
||||
return {
|
||||
view, busy, disabled, loadFailed, saved, pending, preview, apply,
|
||||
cancel: () => setPending(null),
|
||||
chooseCountry: (country: string) => run(async () => setView(await ipcInvoke('saves:crews', { ...keys, country }))),
|
||||
};
|
||||
}
|
||||
|
||||
export function SaveCrews(props: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { view, busy, disabled, loadFailed, saved, pending, chooseCountry, preview, apply, cancel } = useCrewPanel(props);
|
||||
const [editing, setEditing] = useState<number | null>(null);
|
||||
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||
const format = new Intl.NumberFormat(i18n.language);
|
||||
|
||||
if (!view) return <p className="lead">{t(loadFailed ? 'saves.crews.loadFailed' : 'saves.loading')}</p>;
|
||||
if (!view.selected) return <p className="lead">{t('saves.crews.noCountries')}</p>;
|
||||
const confirmation = pending && <SaveCrewChangePreview pending={pending} disabled={disabled} busy={busy} onApply={() => apply(() => setEditing(null))} onCancel={cancel} />;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Row label={t('saves.tree.country')}>
|
||||
<select className="select" aria-label={t('saves.tree.country')} value={view.selected} disabled={busy} onChange={(event) => {
|
||||
setEditing(null);
|
||||
chooseCountry(event.target.value);
|
||||
}}>
|
||||
{view.countries.map(({ id, name }) => <option value={id} key={id}>{name[language]}</option>)}
|
||||
</select>
|
||||
</Row>
|
||||
<Row label={t('saves.crews.slots', { open: view.activeCount, max: view.max })} hint={t('saves.crews.minimum', { count: view.min })}>
|
||||
<button type="button" className="button" disabled={disabled || !view.canAdd} onClick={() => preview({ action: 'add' })}>{t('saves.crews.add')}</button>
|
||||
</Row>
|
||||
{props.readOnly && <p className="small">{t('saves.readOnly')}</p>}
|
||||
{saved && <p className="small" role="status">{t('saves.crews.saved')}</p>}
|
||||
{pending?.edit.action === 'add' && confirmation}
|
||||
<div className="save-crews-list">
|
||||
{view.crews.map((crew, index) => (
|
||||
<div key={crew.id}>
|
||||
<Row label={t('saves.crews.group', { number: index + 1 })} hint={crew.vehicle[language] || t('saves.crews.noVehicle')}>
|
||||
<span>{t(crew.open ? 'saves.crews.opened' : 'saves.crews.closed')}</span>
|
||||
<span className="small">{crew.levels.map(({ type, level }) => `${t(`saves.crews.types.${type}`)} ${format.format(level)}`).join(' · ')}</span>
|
||||
<button type="button" className="button" disabled={disabled || !crew.canToggle} onClick={() => preview({ action: crew.open ? 'close' : 'open', crewId: crew.id })}>
|
||||
{t(crew.open ? 'saves.crews.close' : 'saves.crews.open')}
|
||||
</button>
|
||||
{crew.levels.length > 0 && <button type="button" className="button" disabled={disabled} aria-expanded={editing === crew.id} onClick={() => {
|
||||
setEditing(editing === crew.id ? null : crew.id);
|
||||
cancel();
|
||||
}}>{t('saves.crews.editLevel')}</button>}
|
||||
</Row>
|
||||
{editing === crew.id && <SaveCrewLevelEditor crewId={crew.id} levels={crew.levels} disabled={disabled} onPreview={preview} onChange={cancel} />}
|
||||
{pending?.edit.action !== 'add' && pending?.preview.crewId === crew.id && confirmation}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { OfficialSaveImport } from './OfficialSaveImport.tsx';
|
||||
import { SaveAvatarField } from './SaveAvatarField.tsx';
|
||||
import { SaveResearch } from './SaveResearch.tsx';
|
||||
import { SaveBackups } from './SaveBackups.tsx';
|
||||
import { SaveCrews } from './SaveCrews.tsx';
|
||||
|
||||
interface SavesPageProps {
|
||||
readonly copy: InstallRecord;
|
||||
@@ -314,6 +315,7 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
)}
|
||||
{section === 'backup' && <SaveBackups key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onRestored={updateDetails} />}
|
||||
{section === 'vehicles' && <SaveResearch key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
|
||||
{section === 'crews' && <SaveCrews key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const;
|
||||
export type PageId = (typeof PAGES)[number];
|
||||
|
||||
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
|
||||
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'crews', 'official', 'backup'] as const;
|
||||
export type SaveSection = (typeof SAVE_SECTIONS)[number];
|
||||
|
||||
export const TUNING_SECTIONS = ['rewards', 'battle', 'bots', 'newProfile', 'research'] as const;
|
||||
|
||||
@@ -311,6 +311,14 @@
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.save-crews-list > div {
|
||||
border-top: 1px solid var(--line-soft);
|
||||
}
|
||||
|
||||
.save-crews-list .maintenance-confirm {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.save-overview-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -41,6 +41,9 @@ export const APP_ERROR_CODES = [
|
||||
'save_nick_invalid',
|
||||
'save_avatar_invalid',
|
||||
'save_level_invalid',
|
||||
'save_crew_invalid',
|
||||
'save_crew_slot_limit',
|
||||
'save_crew_stale',
|
||||
'copies_write_failed',
|
||||
'maintenance_busy',
|
||||
'maintenance_location',
|
||||
|
||||
@@ -20,6 +20,7 @@ import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSch
|
||||
import { ModsStateViewSchema } from '../schemas/mods.ts';
|
||||
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
|
||||
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||
import { SaveCrewApplyRequest, SaveCrewPreviewRequest, SaveCrewPreviewSchema, SaveCrewViewRequest, SaveCrewViewSchema } from '../schemas/crew-saves.ts';
|
||||
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
|
||||
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
|
||||
|
||||
@@ -263,6 +264,9 @@ export const ipcContract = {
|
||||
input: SaveKeysSchema.extend({ branch: ResearchBranchSchema, action: ResearchOperationSchema }),
|
||||
output: SaveResearchSchema,
|
||||
},
|
||||
'saves:crews': { input: SaveCrewViewRequest, output: SaveCrewViewSchema },
|
||||
'saves:previewCrew': { input: SaveCrewPreviewRequest, output: SaveCrewPreviewSchema },
|
||||
'saves:editCrew': { input: SaveCrewApplyRequest, output: SaveCrewViewSchema },
|
||||
'tuning:get': {
|
||||
input: z.object({ copyId: CopyIdSchema }),
|
||||
output: TuningViewSchema,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { z } from 'zod';
|
||||
import { LocalizedNameSchema, SaveKeysSchema } from './saves.ts';
|
||||
|
||||
const CrewTypeSchema = z.enum(['air', 'tank', 'ship', 'human']);
|
||||
const CrewIdSchema = z.number().int().nonnegative();
|
||||
const CountrySchema = z.string().min(1);
|
||||
const Level = z.number().nonnegative();
|
||||
|
||||
export const SaveCrewEditSchema = z.discriminatedUnion('action', [
|
||||
z.object({ action: z.literal('add') }),
|
||||
z.object({ action: z.literal('open'), crewId: CrewIdSchema }),
|
||||
z.object({ action: z.literal('close'), crewId: CrewIdSchema }),
|
||||
z.object({ action: z.literal('level'), crewId: CrewIdSchema, type: CrewTypeSchema, target: Level }),
|
||||
]);
|
||||
|
||||
export const SaveCrewViewRequest = SaveKeysSchema.extend({ country: CountrySchema.optional() });
|
||||
export const SaveCrewPreviewRequest = SaveKeysSchema.extend({ country: CountrySchema, edit: SaveCrewEditSchema });
|
||||
export const SaveCrewApplyRequest = SaveCrewPreviewRequest.extend({ token: z.string().regex(/^[a-f\d]{64}$/) });
|
||||
|
||||
export const SaveCrewViewSchema = z.object({
|
||||
countries: z.array(z.object({ id: CountrySchema, name: LocalizedNameSchema })),
|
||||
selected: CountrySchema.nullable(),
|
||||
activeCount: z.number().int().nonnegative(),
|
||||
canAdd: z.boolean(),
|
||||
min: z.number().int().nonnegative(),
|
||||
max: z.number().int().nonnegative(),
|
||||
crews: z.array(z.object({
|
||||
id: CrewIdSchema, open: z.boolean(), canToggle: z.boolean(), vehicle: LocalizedNameSchema,
|
||||
levels: z.array(z.object({ type: CrewTypeSchema, level: Level, min: Level, max: Level })),
|
||||
})),
|
||||
});
|
||||
|
||||
export const SaveCrewPreviewSchema = z.object({
|
||||
token: SaveCrewApplyRequest.shape.token,
|
||||
crewId: CrewIdSchema,
|
||||
vehicle: LocalizedNameSchema,
|
||||
restoredVehicle: LocalizedNameSchema,
|
||||
changed: z.boolean(),
|
||||
presets: z.array(z.object({ index: z.number().int().nonnegative(), title: z.string(), vehicle: LocalizedNameSchema, empty: z.boolean() })),
|
||||
levels: z.array(z.object({ type: CrewTypeSchema, before: Level, after: Level })),
|
||||
});
|
||||
|
||||
export type SaveCrewEdit = z.output<typeof SaveCrewEditSchema>;
|
||||
export type SaveCrewView = z.output<typeof SaveCrewViewSchema>;
|
||||
export type SaveCrewPreview = z.output<typeof SaveCrewPreviewSchema>;
|
||||
@@ -67,9 +67,9 @@ export const SaveTransferSchema = SaveRegistrationSchema.extend({
|
||||
z.object({ kind: z.literal('file'), path: z.string().min(1) }),
|
||||
]),
|
||||
});
|
||||
export const SaveBackupNameSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.(manual|launch|restore|import)\.[0-9a-f-]{36}\.zip$/);
|
||||
export const SaveBackupNameSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.(manual|launch|restore|import|crew)\.[0-9a-f-]{36}\.zip$/);
|
||||
export const SaveBackupSchema = z.object({
|
||||
name: SaveBackupNameSchema, createdAt: z.string(), type: z.enum(['manual', 'launch', 'restore', 'import']), size: z.number().int().nonnegative(),
|
||||
name: SaveBackupNameSchema, createdAt: z.string(), type: z.enum(['manual', 'launch', 'restore', 'import', 'crew']), size: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
export const OnlineDataFileNameSchema = z.enum(['global.blk', 'machine.blk', 'storage.blk']);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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';
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 }) =>
|
||||
|
||||
Reference in new issue
Block a user