feat(tuning): configure tuning for each game copy

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 16:24:21 +08:00
1 parent 61255f5473
commit 893d60854f
15 files changed
+440 -9

No files matched your search

+4
View File
@@ -2,6 +2,7 @@ import { app, BrowserWindow, dialog, shell } from 'electron';
import { patchFeatures, recordedGameVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts';
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
@@ -127,6 +128,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('tuning:get', ({ copyId }) => getCopyTuning(copyId));
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => {
@@ -0,0 +1,32 @@
import { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from '@wto/server';
import { AppError } from '@shared/errors.ts';
import type { TuningView } from '@shared/schemas/tuning.ts';
import { listCopies } from '../install/install-record.ts';
import { getLaunchState } from '../launch/launch-controller.ts';
async function dataFolder(copyId: string): Promise<string> {
const copy = (await listCopies()).copies.find(({ id }) => id === copyId);
if (!copy) throw new AppError('copy_not_found');
return copy.dataPath;
}
export async function getCopyTuning(copyId: string): Promise<TuningView> {
const folder = await dataFolder(copyId);
try {
return readLauncherTuning(folder);
} catch (error) {
console.error('[tuning] could not read the copy settings:', error);
throw new AppError('tuning_invalid');
}
}
export async function updateCopyTuning(copyId: string, patch: LauncherTuningPatch): Promise<TuningView> {
const folder = await dataFolder(copyId);
if (['checking', 'building', 'starting-server'].includes(getLaunchState().phase)) throw new AppError('launch_busy');
try {
return writeLauncherTuning(folder, patch);
} catch (error) {
console.error('[tuning] could not save the copy settings:', error);
throw new AppError('tuning_invalid');
}
}
+10 -1
View File
@@ -20,6 +20,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts';
import { TuningPage } from './pages/tuning/TuningPage.tsx';
import { SavesPage } from './pages/saves/SavesPage.tsx';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
import { DiagnosticsSettings } from './pages/settings/DiagnosticsSettings.tsx';
@@ -29,7 +30,7 @@ import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx';
import type { BarModel } from './shell/bar-model.ts';
import { Footer } from './shell/Footer.tsx';
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, type Destination, type Route } from './shell/navigation.ts';
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { SubNav } from './shell/SubNav.tsx';
import { TitleBar } from './shell/TitleBar.tsx';
import { useBackgrounds } from './shell/useBackgrounds.ts';
@@ -138,6 +139,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
: <Sheet title={t(`saves.sections.${route.saves}`)}><p className="lead">{t('saves.noCopy')}</p></Sheet>,
bar: home,
};
case 'tuning':
return {
side: <SubNav sections={TUNING_SECTIONS} active={route.tuning} label={(section) => t(`tuning.sections.${section}`)} onSelect={(section) => go({ page: 'tuning', section })} />,
main: record
? <TuningPage key={record.id} copy={record} section={route.tuning} onError={report} />
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
bar: home,
};
case 'copies': {
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
if (route.copies === 'list') {
@@ -6,6 +6,7 @@
"nav": {
"home": "Home",
"saves": "Saves",
"tuning": "Tuning",
"copies": "Copies",
"settings": "Settings",
"about": "About"
@@ -360,6 +361,45 @@
"owned": "Owned vehicles",
"research": "Research progress"
},
"tuning": {
"sections": {
"rewards": "Rewards",
"battle": "Battles",
"newProfile": "New saves",
"research": "Research"
},
"fields": {
"rewardMultiplierSilverLions": "Silver Lions multiplier",
"rewardMultiplierResearchPoints": "Research points multiplier",
"friendlyKillPenaltyMul": "Friendly-fire penalty multiplier",
"maxPlayers": "Player limit per battle",
"smallTeamsMaxPlayers": "Small teams player limit",
"brSpreadMrank": "Matchmaking BR range",
"subModeChance": "Sub-mode probability",
"tankBotRespawns": "AI tank respawns",
"airBotRespawns": "AI aircraft respawns",
"strikeUcavSpawnScore": "Strike UCAV spawn points",
"silverLions": "Starting Silver Lions",
"goldenEagles": "Starting Golden Eagles",
"preferLineSuccessor": "Prefer the next vehicle in the line",
"autoTargetPick": "Automatic research target"
},
"target": {
"lowestRank": "Lowest rank",
"highestRank": "Highest rank",
"treeOrder": "Research tree order"
},
"shared": "These settings apply to all saves in this copy.",
"nextLaunch": "Changes take effect the next time the local server starts.",
"reset": "Restore defaults for this section",
"default": "Default {{value}}",
"on": "Enabled",
"off": "Disabled",
"saved": "Tuning values saved.",
"invalid": "Enter values within the supported range.",
"loading": "Loading tuning values",
"noCopy": "Select a game copy to edit its tuning values."
},
"settings": {
"sections": {
"general": "General",
@@ -482,6 +522,7 @@
"save_login_exists": "An account with this login already exists.",
"save_password_invalid": "Enter a password.",
"save_nick_invalid": "Enter a nickname with up to 16 characters.",
"tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.",
"copy_not_found": "The selected copy is no longer available.",
"copies_write_failed": "The copy registry could not be saved.",
"copy_location_in_use": "The copy or data location overlaps an existing copy.",
@@ -6,6 +6,7 @@
"nav": {
"home": "首页",
"saves": "存档",
"tuning": "数值",
"copies": "副本",
"settings": "设置",
"about": "关于"
@@ -360,6 +361,45 @@
"owned": "已拥有载具",
"research": "研发进度"
},
"tuning": {
"sections": {
"rewards": "收益",
"battle": "对局",
"newProfile": "新存档",
"research": "研发"
},
"fields": {
"rewardMultiplierSilverLions": "银狮倍率",
"rewardMultiplierResearchPoints": "研发点倍率",
"friendlyKillPenaltyMul": "误伤惩罚倍率",
"maxPlayers": "每局人数上限(含 AI)",
"smallTeamsMaxPlayers": "小规模模式人数上限",
"brSpreadMrank": "匹配范围",
"subModeChance": "附加模式概率",
"tankBotRespawns": "AI 坦克重生次数",
"airBotRespawns": "AI 飞机重生次数",
"strikeUcavSpawnScore": "打击无人机所需出生点数",
"silverLions": "初始银狮",
"goldenEagles": "初始金鹰",
"preferLineSuccessor": "优先研发同系载具",
"autoTargetPick": "自动研发目标"
},
"target": {
"lowestRank": "最低等级",
"highestRank": "最高等级",
"treeOrder": "研发树顺序"
},
"shared": "这些数值适用于此副本的全部存档。",
"nextLaunch": "更改将在下次启动本地服务器时生效。",
"reset": "恢复本页默认值",
"default": "默认 {{value}}",
"on": "启用",
"off": "停用",
"saved": "数值已保存。",
"invalid": "请输入受支持范围内的数值。",
"loading": "正在读取数值",
"noCopy": "选择游戏副本后即可编辑数值。"
},
"settings": {
"sections": {
"general": "常规",
@@ -482,6 +522,7 @@
"save_login_exists": "该登录账号已注册。",
"save_password_invalid": "请输入密码。",
"save_nick_invalid": "请输入最多 16 个字符的昵称。",
"tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。",
"copy_not_found": "所选副本已不可用。",
"copies_write_failed": "无法保存副本记录。",
"copy_location_in_use": "副本位置或数据目录与已有副本重叠。",
@@ -0,0 +1,139 @@
import { useEffect, useState, type FormEvent, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { AUTO_TARGET_PICKS, TuningPatchSchema, type TuningValues, type TuningView } from '@shared/schemas/tuning.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { TuningSection } from '../../shell/navigation.ts';
type Field = keyof TuningValues;
type Draft = Partial<Record<Field, string | boolean>>;
const fields = {
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore'],
newProfile: ['silverLions', 'goldenEagles'],
research: ['preferLineSuccessor', 'autoTargetPick'],
} as const satisfies Record<TuningSection, readonly Field[]>;
interface Props {
readonly copy: InstallRecord;
readonly section: TuningSection;
readonly onError: (error: unknown) => void;
}
function inputValue(field: Field, value: TuningValues[Field]): string | boolean {
if (field === 'subModeChance') return String(Number((Number(value) * 100).toPrecision(14)));
return typeof value === 'boolean' ? value : String(value);
}
export function TuningPage({ copy, section, onError }: Props) {
const { t, i18n } = useTranslation();
const [data, setData] = useState<TuningView | null>(null);
const [draft, setDraft] = useState<Draft>({});
const [saving, setSaving] = useState(false);
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
const title = t(`tuning.sections.${section}`);
const sectionFields: readonly Field[] = fields[section];
useEffect(() => {
let mounted = true;
ipcInvoke('tuning:get', { copyId: copy.id }).then((result) => {
if (mounted) setData(result);
}).catch(onError);
return () => { mounted = false; };
}, [copy.id, onError]);
if (!data) return <Sheet title={title} aside={copy.name}><p className="lead">{t('tuning.loading')}</p></Sheet>;
const loaded = data;
const format = new Intl.NumberFormat(i18n.language);
const set = (field: Field, value: string | boolean): void => {
setMessage(null);
setDraft((previous) => ({ ...previous, [field]: value }));
};
const reset = (): void => {
setMessage(null);
setDraft((previous) => {
const next = { ...previous };
for (const field of sectionFields) next[field] = inputValue(field, loaded.defaults[field]);
return next;
});
};
const defaultLabel = (field: Field): string => {
const value = loaded.defaults[field];
if (field === 'brSpreadMrank') return '±' + (Number(value) / 3).toFixed(1);
if (field === 'subModeChance') return format.format(Number(value) * 100) + '%';
if (field === 'autoTargetPick') return t(`tuning.target.${value}`);
if (typeof value === 'boolean') return t(value ? 'tuning.on' : 'tuning.off');
return format.format(Number(value));
};
const editor = (field: Field): ReactNode => {
const active = draft[field] ?? inputValue(field, loaded.effective[field]);
const label = t(`tuning.fields.${field}`);
if (field === 'preferLineSuccessor') {
return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />;
}
if (field === 'autoTargetPick') {
return (
<select className="select" aria-label={label} disabled={saving} value={String(active)} onChange={(event) => set(field, event.target.value)}>
{AUTO_TARGET_PICKS.map((pick) => <option key={pick} value={pick}>{t(`tuning.target.${pick}`)}</option>)}
</select>
);
}
if (field === 'brSpreadMrank') {
return (
<select className="select" aria-label={label} disabled={saving} value={String(active)} onChange={(event) => set(field, event.target.value)}>
{Array.from({ length: 13 }, (_, mrank) => <option key={mrank} value={mrank}>±{(mrank / 3).toFixed(1)}</option>)}
</select>
);
}
const decimal = field === 'subModeChance' || section === 'rewards';
return (
<div className="copy-list-actions">
<input className="input" aria-label={label} type="number" min="0" step={decimal ? 'any' : '1'}
value={String(active)} disabled={saving} onChange={(event) => set(field, event.target.value)} />
{field === 'subModeChance' && <span>%</span>}
</div>
);
};
const submit = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const input = Object.fromEntries((Object.keys(draft) as Field[]).map((field) => {
const value = draft[field];
const parsed = typeof loaded.effective[field] === 'number'
? (value === '' ? NaN : Number(value) / (field === 'subModeChance' ? 100 : 1))
: value;
return [field, parsed];
}));
const result = TuningPatchSchema.safeParse(input);
if (!result.success) {
setMessage('invalid');
return;
}
setSaving(true);
setMessage(null);
ipcInvoke('tuning:update', { copyId: copy.id, patch: result.data }).then((next) => {
setData(next);
setDraft({});
setMessage('saved');
}).catch(onError).finally(() => setSaving(false));
};
return (
<Sheet title={title} aside={copy.name} foot={t('tuning.nextLaunch')}>
<p className="small">{t('tuning.shared')}</p>
<form onSubmit={submit}>
{sectionFields.map((field) => (
<Row key={field} label={t(`tuning.fields.${field}`)} hint={t('tuning.default', { value: defaultLabel(field) })}>
{editor(field)}
</Row>
))}
<div className="copy-list-actions">
<button type="button" className="button" disabled={saving} onClick={reset}>{t('tuning.reset')}</button>
<button type="submit" className="button button-primary" disabled={saving || Object.keys(draft).length === 0}>{t('saves.apply')}</button>
</div>
</form>
{message && <p className="small" role={message === 'invalid' ? 'alert' : 'status'}>{t(`tuning.${message}`)}</p>}
</Sheet>
);
}
@@ -3,12 +3,15 @@
* Pages for later features (saves, tuning) join this list when they are built.
*/
export const PAGES = ['home', 'saves', 'copies', 'settings', 'about'] as const;
export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const;
export type PageId = (typeof PAGES)[number];
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
export type TuningSection = (typeof TUNING_SECTIONS)[number];
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number];
@@ -19,15 +22,17 @@ export interface Route {
readonly page: PageId;
readonly copies: CopySection;
readonly saves: SaveSection;
readonly tuning: TuningSection;
readonly settings: SettingsSection;
}
export const START_ROUTE: Route = { page: 'home', saves: 'list', copies: 'list', settings: 'general' };
export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' };
/** Where a link points: a page, and for pages with sections, which one. */
export type Destination =
| { readonly page: 'home' | 'about' }
| { readonly page: 'saves'; readonly section?: SaveSection }
| { readonly page: 'tuning'; readonly section?: TuningSection }
| { readonly page: 'copies'; readonly section?: CopySection }
| { readonly page: 'settings'; readonly section?: SettingsSection };
@@ -35,6 +40,8 @@ export function navigate(route: Route, to: Destination): Route {
switch (to.page) {
case 'saves':
return { ...route, page: 'saves', saves: to.section ?? route.saves };
case 'tuning':
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
case 'copies':
return { ...route, page: 'copies', copies: to.section ?? route.copies };
case 'settings':
+1
View File
@@ -17,6 +17,7 @@ export const APP_ERROR_CODES = [
'logs_folder_open_failed',
'diagnostics_export_failed',
'copy_not_found',
'tuning_invalid',
'save_not_found',
'save_archive_invalid',
'save_official_invalid',
+2
View File
@@ -14,6 +14,8 @@ export const IPC_CHANNEL_PREFIXES = [
'install:',
/** Listing and managing installed copies. */
'copies:',
/** Settings shared by the saves of a game copy. */
'tuning:',
/** Local account and save management. */
'saves:',
/** Starting and stopping the active copy. */
+9
View File
@@ -16,6 +16,7 @@ import {
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
import { ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
/**
@@ -196,6 +197,14 @@ export const ipcContract = {
input: SaveKeysSchema.extend({ branch: ResearchBranchSchema, action: ResearchOperationSchema }),
output: SaveResearchSchema,
},
'tuning:get': {
input: z.object({ copyId: CopyIdSchema }),
output: TuningViewSchema,
},
'tuning:update': {
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
output: TuningViewSchema,
},
'launch:getState': {
input: z.void(),
output: LaunchStateSchema,
@@ -0,0 +1,24 @@
import { z } from 'zod';
export const AUTO_TARGET_PICKS = ['lowestRank', 'highestRank', 'treeOrder'] as const;
export const TuningValuesSchema = z.object({
rewardMultiplierSilverLions: z.number().min(0).max(100),
rewardMultiplierResearchPoints: z.number().min(0).max(100),
friendlyKillPenaltyMul: z.number().min(0).max(100),
maxPlayers: z.number().int().min(2).max(64),
smallTeamsMaxPlayers: z.number().int().min(2).max(64),
brSpreadMrank: z.number().int().min(0).max(12),
subModeChance: z.number().min(0).max(1),
tankBotRespawns: z.number().int().min(1).max(10),
airBotRespawns: z.number().int().min(1).max(10),
strikeUcavSpawnScore: z.number().int().min(1).max(10000),
silverLions: z.number().int().nonnegative(),
goldenEagles: z.number().int().min(0).max(0x7fffffff),
preferLineSuccessor: z.boolean(),
autoTargetPick: z.enum(AUTO_TARGET_PICKS),
});
export const TuningPatchSchema = TuningValuesSchema.partial();
export const TuningViewSchema = z.object({ defaults: TuningValuesSchema, effective: TuningValuesSchema });
export type TuningValues = z.output<typeof TuningValuesSchema>;
export type TuningPatch = z.output<typeof TuningPatchSchema>;
export type TuningView = z.output<typeof TuningViewSchema>;
+2 -4
View File
@@ -29,10 +29,8 @@ export interface BattleTuning {
export function readBattleTuning(reader: TuningReader): BattleTuning {
const maxPlayers = reader.int('maxPlayers', { min: 2, max: 64 });
const maxBots = reader.int('maxBots', { min: 1, max: 63 });
if (maxBots >= maxPlayers) {
throw new TuningError(`tuning file battle.jsonc: maxBots (${maxBots}) must be less than maxPlayers (${maxPlayers})`);
}
// Keep one slot for the player when the launcher lowers the session capacity.
const maxBots = Math.min(reader.int('maxBots', { min: 1, max: 63 }), maxPlayers - 1);
const smallTeamsMaxPlayers = reader.int('smallTeamsMaxPlayers', { min: 2, max: 64 });
if (smallTeamsMaxPlayers > maxPlayers) {
throw new TuningError(
+1
View File
@@ -10,4 +10,5 @@ export { editSaveResearch, readSaveResearch } from './saves/save-research.ts';
export { editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts';
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
+116
View File
@@ -0,0 +1,116 @@
import { readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { parseJsonc } from '@wto/jsonc';
import { readBattleEconomyTuning } from '../battle/battle-economy-tuning.ts';
import { readBattleTuning } from '../battle/battle-tuning.ts';
import { readNewProfileTuning } from '../profile/new-profile-tuning.ts';
import { readResearchTuning } from '../research/research-tuning.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import { tuningFiles, type TuningFiles } from './tuning-loader.ts';
import { TuningError } from './tuning-reader.ts';
function values(files: TuningFiles) {
const battle = readBattleTuning(files.read('battle'));
const economy = readBattleEconomyTuning(files.read('battle-economy'));
const newProfile = readNewProfileTuning(files.read('new-profile')).startingBalance;
const research = readResearchTuning(files.read('research'));
return {
rewardMultiplierSilverLions: battle.rewardMultiplierSilverLions,
rewardMultiplierResearchPoints: battle.rewardMultiplierResearchPoints,
friendlyKillPenaltyMul: economy.friendlyKillPenaltyMul,
maxPlayers: battle.maxPlayers,
smallTeamsMaxPlayers: battle.smallTeamsMaxPlayers,
brSpreadMrank: battle.brSpreadMrank,
subModeChance: battle.subModeChance,
tankBotRespawns: battle.tankBotRespawns,
airBotRespawns: battle.airBotRespawns,
strikeUcavSpawnScore: battle.strikeUcavSpawnScore,
silverLions: newProfile.silverLions,
goldenEagles: newProfile.goldenEagles,
preferLineSuccessor: research.preferLineSuccessor,
autoTargetPick: research.autoTargetPick,
};
}
type Editable = ReturnType<typeof values>;
export type LauncherTuningPatch = { [K in keyof Editable]?: Editable[K] | undefined };
const fileOf = {
rewardMultiplierSilverLions: 'battle',
rewardMultiplierResearchPoints: 'battle',
friendlyKillPenaltyMul: 'battle-economy',
maxPlayers: 'battle',
smallTeamsMaxPlayers: 'battle',
brSpreadMrank: 'battle',
subModeChance: 'battle',
tankBotRespawns: 'battle',
airBotRespawns: 'battle',
strikeUcavSpawnScore: 'battle',
silverLions: 'new-profile',
goldenEagles: 'new-profile',
preferLineSuccessor: 'research',
autoTargetPick: 'research',
} as const satisfies Record<keyof Editable, string>;
interface OverrideFile {
readonly path: string;
readonly previous: string | undefined;
readonly fields: Record<string, unknown>;
}
export function readLauncherTuning(dataFolder: string): { defaults: Editable; effective: Editable } {
return { defaults: values(tuningFiles(null, () => {})), effective: values(tuningFiles(dataFolder, () => {})) };
}
export function writeLauncherTuning(dataFolder: string, patch: LauncherTuningPatch) {
const { defaults, effective } = readLauncherTuning(dataFolder);
const changes = new Map<string, OverrideFile>();
for (const key of Object.keys(patch) as Array<keyof Editable>) {
if (!Object.hasOwn(fileOf, key)) throw new TuningError(`Unknown launcher tuning field ${key}`);
const value = patch[key];
if (value === undefined || value === effective[key]) continue;
const name = fileOf[key];
const file = changes.get(name) ?? readOverride(join(dataFolder, 'tuning', `${name}.jsonc`));
changes.set(name, file);
if (value === defaults[key]) delete file.fields[key];
else file.fields[key] = value;
}
// Validate the complete proposed configuration before writing any file.
const proposed = new Map([...changes].map(([name, file]) => [name, file.fields]));
const updated = values(tuningFiles(dataFolder, () => {}, proposed));
const written: OverrideFile[] = [];
try {
for (const file of changes.values()) {
if (Object.keys(file.fields).length > 0) writeFileAtomic(file.path, JSON.stringify(file.fields, null, 2) + '\n');
else rmSync(file.path, { force: true });
written.push(file);
}
} catch (error) {
for (const file of written.reverse()) {
try {
if (file.previous === undefined) rmSync(file.path, { force: true });
else writeFileAtomic(file.path, file.previous);
} catch (failure) {
console.error('[tuning] could not restore the previous override:', file.path, failure);
}
}
throw error;
}
return { defaults, effective: updated };
}
function readOverride(path: string): OverrideFile {
let previous: string;
try {
previous = readFileSync(path, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
return { path, previous: undefined, fields: {} };
}
const parsed: unknown = parseJsonc(previous);
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new TuningError(`Expected an object in ${path}`);
}
return { path, previous, fields: { ...parsed } };
}
+9 -2
View File
@@ -17,12 +17,19 @@ export interface TuningFiles {
read(name: string): TuningReader;
}
export function tuningFiles(dataFolder: string, report: (line: string) => void): TuningFiles {
const overridesFolder = join(dataFolder, 'tuning');
export function tuningFiles(
dataFolder: string | null,
report: (line: string) => void,
proposed?: ReadonlyMap<string, Record<string, unknown>>,
): TuningFiles {
const overridesFolder = dataFolder === null ? null : join(dataFolder, 'tuning');
return {
read(name: string): TuningReader {
const fileName = `${name}.jsonc`;
const defaults = parseFile(join(DEFAULTS_FOLDER, fileName));
const candidate = proposed?.get(name);
if (candidate) return new TuningReader(fileName, mergeOverride(defaults, candidate));
if (overridesFolder === null) return new TuningReader(fileName, defaults);
const overridePath = join(overridesFolder, fileName);
if (!existsSync(overridePath)) return new TuningReader(fileName, defaults);
report(`tuning ${fileName}: using overrides from ${overridePath}`);