From 893d60854f9f8d7a0bad76b642300a15c76d7a1b Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:24:21 +0800 Subject: [PATCH] feat(tuning): configure tuning for each game copy --- apps/launcher/src/main/ipc/handlers.ts | 4 + .../src/main/services/config/copy-tuning.ts | 32 ++++ apps/launcher/src/renderer/src/App.tsx | 11 +- .../src/renderer/src/i18n/locales/en.json | 41 ++++++ .../src/renderer/src/i18n/locales/zh-CN.json | 41 ++++++ .../renderer/src/pages/tuning/TuningPage.tsx | 139 ++++++++++++++++++ .../src/renderer/src/shell/navigation.ts | 11 +- apps/launcher/src/shared/errors.ts | 1 + apps/launcher/src/shared/ipc/channels.ts | 2 + apps/launcher/src/shared/ipc/contract.ts | 9 ++ apps/launcher/src/shared/schemas/tuning.ts | 24 +++ apps/server/src/battle/battle-tuning.ts | 6 +- apps/server/src/index.ts | 1 + apps/server/src/tuning/launcher-tuning.ts | 116 +++++++++++++++ apps/server/src/tuning/tuning-loader.ts | 11 +- 15 files changed, 440 insertions(+), 9 deletions(-) create mode 100644 apps/launcher/src/main/services/config/copy-tuning.ts create mode 100644 apps/launcher/src/renderer/src/pages/tuning/TuningPage.tsx create mode 100644 apps/launcher/src/shared/schemas/tuning.ts create mode 100644 apps/server/src/tuning/launcher-tuning.ts diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 68d4328..5439b5f 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -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', () => { diff --git a/apps/launcher/src/main/services/config/copy-tuning.ts b/apps/launcher/src/main/services/config/copy-tuning.ts new file mode 100644 index 0000000..ca9ab1f --- /dev/null +++ b/apps/launcher/src/main/services/config/copy-tuning.ts @@ -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 { + 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 { + 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 { + 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'); + } +} diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index 225fff6..1cbdecb 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -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) { :

{t('saves.noCopy')}

, bar: home, }; + case 'tuning': + return { + side: t(`tuning.sections.${section}`)} onSelect={(section) => go({ page: 'tuning', section })} />, + main: record + ? + :

{t('tuning.noCopy')}

, + bar: home, + }; case 'copies': { const side = t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />; if (route.copies === 'list') { diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 46dbb0c..2bdf5b5 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -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.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 7a2b5b4..363fb93 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -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": "副本位置或数据目录与已有副本重叠。", diff --git a/apps/launcher/src/renderer/src/pages/tuning/TuningPage.tsx b/apps/launcher/src/renderer/src/pages/tuning/TuningPage.tsx new file mode 100644 index 0000000..ef8e505 --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/tuning/TuningPage.tsx @@ -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>; +const fields = { + rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'], + battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore'], + newProfile: ['silverLions', 'goldenEagles'], + research: ['preferLineSuccessor', 'autoTargetPick'], +} as const satisfies Record; + +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(null); + const [draft, setDraft] = useState({}); + 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

{t('tuning.loading')}

; + 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 set(field, event.target.checked)} />; + } + if (field === 'autoTargetPick') { + return ( + + ); + } + if (field === 'brSpreadMrank') { + return ( + + ); + } + const decimal = field === 'subModeChance' || section === 'rewards'; + return ( +
+ set(field, event.target.value)} /> + {field === 'subModeChance' && %} +
+ ); + }; + const submit = (event: FormEvent): 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 ( + +

{t('tuning.shared')}

+
+ {sectionFields.map((field) => ( + + {editor(field)} + + ))} +
+ + +
+
+ {message &&

{t(`tuning.${message}`)}

} +
+ ); +} diff --git a/apps/launcher/src/renderer/src/shell/navigation.ts b/apps/launcher/src/renderer/src/shell/navigation.ts index 348d1ba..36a418b 100644 --- a/apps/launcher/src/renderer/src/shell/navigation.ts +++ b/apps/launcher/src/renderer/src/shell/navigation.ts @@ -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': diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index 7764264..6c8063c 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -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', diff --git a/apps/launcher/src/shared/ipc/channels.ts b/apps/launcher/src/shared/ipc/channels.ts index 1b82e4f..1b75424 100644 --- a/apps/launcher/src/shared/ipc/channels.ts +++ b/apps/launcher/src/shared/ipc/channels.ts @@ -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. */ diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index e720748..840014c 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -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, diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts new file mode 100644 index 0000000..50b5b8c --- /dev/null +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -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; +export type TuningPatch = z.output; +export type TuningView = z.output; diff --git a/apps/server/src/battle/battle-tuning.ts b/apps/server/src/battle/battle-tuning.ts index fb9f04a..e4cac27 100644 --- a/apps/server/src/battle/battle-tuning.ts +++ b/apps/server/src/battle/battle-tuning.ts @@ -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( diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 31211e0..5ad96b3 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -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'; diff --git a/apps/server/src/tuning/launcher-tuning.ts b/apps/server/src/tuning/launcher-tuning.ts new file mode 100644 index 0000000..69c0d45 --- /dev/null +++ b/apps/server/src/tuning/launcher-tuning.ts @@ -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; +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; + +interface OverrideFile { + readonly path: string; + readonly previous: string | undefined; + readonly fields: Record; +} + +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(); + for (const key of Object.keys(patch) as Array) { + 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 } }; +} diff --git a/apps/server/src/tuning/tuning-loader.ts b/apps/server/src/tuning/tuning-loader.ts index 49f833a..ed2d795 100644 --- a/apps/server/src/tuning/tuning-loader.ts +++ b/apps/server/src/tuning/tuning-loader.ts @@ -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>, +): 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}`);