feat(launcher): auto-detect decal cache from selected or recorded game folder

Extend resolvePlayerDecalCacheFolder to resolve <game>/cache/content when the player picks a game root folder directly. Add read-only decals:detectSource IPC so the install wizard auto-fills a detected decal cache from the chosen source (with one-click reset to placeholders) and the client details view offers one-click import from the recorded online sourcePath.
This commit is contained in:
N0VAN0M4LY committed 2026-12-04 21:09:57 +08:00
1 parent 49264b0326
commit c3cf4e3707
12 files changed
+196 -31

No files matched your search

+2 -1
View File
@@ -11,7 +11,7 @@ import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagn
import { measureFolder } from '../services/game-folder/folder-size.ts'; import { measureFolder } from '../services/game-folder/folder-size.ts';
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts'; import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts'; import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts'; import { changeDecalSource, decalImportInProgress, detectDecalCacheSource } from '../services/install/decals.ts';
import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts'; import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts';
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts'; import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
import { readInstalledLab } from '../services/launch/lab-handoff.ts'; import { readInstalledLab } from '../services/launch/lab-handoff.ts';
@@ -164,6 +164,7 @@ export function registerIpcHandlers(): void {
return updated; return updated;
}); });
handle('copies:cancelMaintenance', () => cancelMaintenance()); handle('copies:cancelMaintenance', () => cancelMaintenance());
handle('decals:detectSource', async ({ path }) => ({ path: await detectDecalCacheSource(path) }));
handle('saves:list', ({ copyId }) => getSaveList(copyId)); handle('saves:list', ({ copyId }) => getSaveList(copyId));
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId)); handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
@@ -22,6 +22,25 @@ export function decalCachePath(dataPath: string, cacheId: string): string {
return join(dataPath, CACHE_FOLDER, cacheId); return join(dataPath, CACHE_FOLDER, cacheId);
} }
/**
* Read-only check whether a player-chosen or registered folder contains a usable decal cache
* (<game>, <game>/cache, or <game>/cache/content). Returns the canonical cache/content path when
* valid, or null when absent, invalid, or unreadable.
*/
export async function detectDecalCacheSource(folderPath: string): Promise<string | null> {
if (!folderPath || !isAbsolute(folderPath)) return null;
try {
const rawSource = await realpath(folderPath).catch(() => null);
if (!rawSource) return null;
const resolved = resolvePlayerDecalCacheFolder(rawSource);
const canonical = await realpath(resolved).catch(() => null);
if (!canonical) return null;
return playerDecalCacheProblem(canonical) === undefined ? canonical : null;
} catch {
return null;
}
}
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> { async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed'); if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
const data = await canonicalCopyPath(dataPath); const data = await canonicalCopyPath(dataPath);
@@ -5,18 +5,21 @@ interface FolderFieldProps {
readonly path: string | null; readonly path: string | null;
/** Title of the folder dialog. */ /** Title of the folder dialog. */
readonly dialogTitle: string; readonly dialogTitle: string;
/** Optional starting directory when no path is chosen yet. */
readonly defaultPath?: string | null | undefined;
readonly disabled?: boolean; readonly disabled?: boolean;
readonly onChosen: (path: string) => void; readonly onChosen: (path: string) => void;
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
} }
/** A chosen folder and the button that opens the folder dialog. */ /** A chosen folder and the button that opens the folder dialog. */
export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) { export function FolderField({ path, dialogTitle, defaultPath, disabled = false, onChosen, onError }: FolderFieldProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const choose = (): void => { const choose = (): void => {
const startPath = path ?? defaultPath;
ipcInvoke('dialog:pickFolder', { ipcInvoke('dialog:pickFolder', {
title: dialogTitle, title: dialogTitle,
...(path ? { defaultPath: path } : {}), ...(startPath ? { defaultPath: startPath } : {}),
}) })
.then(({ path: chosen }) => { .then(({ path: chosen }) => {
if (chosen) onChosen(chosen); if (chosen) onChosen(chosen);
@@ -97,7 +97,9 @@
}, },
"decals": { "decals": {
"source": "Decal source", "source": "Decal source",
"hint": "Import the online game's cache/content (or cache) folder for cached decals and downloadable skins. Placeholder decals are used when no cache is available.", "hint": "Select the online game root folder, cache, or cache/content for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
"autoDetectedNotice": "Online decal cache detected automatically and will be imported during installation. Click the button above if you prefer placeholder decals.",
"importFromSource": "Import from online source",
"choose": "Choose decal cache…", "choose": "Choose decal cache…",
"useDefault": "Use placeholder decals", "useDefault": "Use placeholder decals",
"importing": "Importing decal cache", "importing": "Importing decal cache",
@@ -1058,7 +1060,7 @@
"copy_not_found": "The selected client is no longer available.", "copy_not_found": "The selected client is no longer available.",
"copies_write_failed": "The client registry could not be saved.", "copies_write_failed": "The client registry could not be saved.",
"copy_location_in_use": "The client or data location overlaps an existing client.", "copy_location_in_use": "The client or data location overlaps an existing client.",
"decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose cache/content (or cache).", "decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose the online game root folder, cache, or cache/content.",
"decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.", "decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.",
"maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.", "maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.",
"maintenance_location": "The operation would affect files outside the registered client or data folder.", "maintenance_location": "The operation would affect files outside the registered client or data folder.",
@@ -97,7 +97,9 @@
}, },
"decals": { "decals": {
"source": "贴花来源", "source": "贴花来源",
"hint": "可导入在线版游戏的 cache/content(或 cache),同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。", "hint": "可直接选择在线版游戏根目录、cache 或 cache/content,同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
"autoDetectedNotice": "已自动检测到在线版贴花缓存,安装时将一并导入。如需使用占位贴花,可点击上方按钮取消。",
"importFromSource": "从在线版来源导入",
"choose": "选择贴花缓存…", "choose": "选择贴花缓存…",
"useDefault": "使用占位贴花", "useDefault": "使用占位贴花",
"importing": "正在导入贴花缓存", "importing": "正在导入贴花缓存",
@@ -1058,7 +1060,7 @@
"copy_not_found": "所选客户端已不可用。", "copy_not_found": "所选客户端已不可用。",
"copies_write_failed": "无法保存客户端记录。", "copies_write_failed": "无法保存客户端记录。",
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。", "copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版目录中的 cache/content(或 cache)。", "decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版游戏根目录、cache 或 cache/content。",
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。", "decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。", "maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。", "maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
@@ -20,13 +20,46 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const [name, setName] = useState(record.name); const [name, setName] = useState(record.name);
const [importing, setImporting] = useState(false); const [importing, setImporting] = useState(false);
const [detectedSourceDecals, setDetectedSourceDecals] = useState<string | null>(null);
useEffect(() => setName(record.name), [record.id, record.name]); useEffect(() => setName(record.name), [record.id, record.name]);
// Read-only probe of the copy's registered online source for a usable decal cache.
useEffect(() => {
setDetectedSourceDecals(null);
if (!record.sourcePath) return;
let current = true;
ipcInvoke('decals:detectSource', { path: record.sourcePath })
.then(({ path }) => {
if (current) setDetectedSourceDecals(path);
})
.catch(() => {
if (current) setDetectedSourceDecals(null);
});
return () => {
current = false;
};
}, [record.id, record.sourcePath]);
const missing = missingFeatures(record).length; const missing = missingFeatures(record).length;
const verified = isVerified(record.gameVersion, supportedVersions); const verified = isVerified(record.gameVersion, supportedVersions);
const importFromSource = async (): Promise<void> => {
if (!detectedSourceDecals) return;
setImporting(true);
try {
await ipcInvoke('copies:setDecalSource', { id: record.id, path: detectedSourceDecals });
} catch (error) {
onError(error);
} finally {
setImporting(false);
}
};
const applyDecals = async (chooseFolder: boolean): Promise<void> => { const applyDecals = async (chooseFolder: boolean): Promise<void> => {
setImporting(true); setImporting(true);
try { try {
const path = chooseFolder ? (await ipcInvoke('dialog:pickFolder', { title: t('decals.choose') })).path : null; const path = chooseFolder
? (await ipcInvoke('dialog:pickFolder', {
title: t('decals.choose'),
...(record.sourcePath ? { defaultPath: record.sourcePath } : {}),
})).path
: null;
if (chooseFolder && path === null) return; if (chooseFolder && path === null) return;
await ipcInvoke('copies:setDecalSource', { id: record.id, path }); await ipcInvoke('copies:setDecalSource', { id: record.id, path });
} catch (error) { } catch (error) {
@@ -71,6 +104,11 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row> <Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
<Row label={t('decals.source')} hint={t('decals.hint')}> <Row label={t('decals.source')} hint={t('decals.hint')}>
<span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span> <span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span>
{detectedSourceDecals && (
<button type="button" className="button" disabled={importing} onClick={() => { void importFromSource(); }}>
{t('decals.importFromSource')}
</button>
)}
<button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}> <button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}>
{t('decals.choose')} {t('decals.choose')}
</button> </button>
@@ -8,6 +8,8 @@ interface DataStepProps {
readonly dataPath: string; readonly dataPath: string;
readonly dataProblem: DataFolderProblem | null; readonly dataProblem: DataFolderProblem | null;
readonly decalSource: string | null; readonly decalSource: string | null;
readonly decalAutoDetected: boolean;
readonly defaultDecalPath?: string | null | undefined;
readonly steamDataPath: string | null; readonly steamDataPath: string | null;
readonly steamDataConfirmed: boolean; readonly steamDataConfirmed: boolean;
readonly onSteamDataConfirmed: (confirmed: boolean) => void; readonly onSteamDataConfirmed: (confirmed: boolean) => void;
@@ -17,7 +19,19 @@ interface DataStepProps {
} }
/** Step 3: where saves, caches and logs of the offline version are kept. */ /** Step 3: where saves, caches and logs of the offline version are kept. */
export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) { export function DataStep({
dataPath,
dataProblem,
decalSource,
decalAutoDetected,
defaultDecalPath,
steamDataPath,
steamDataConfirmed,
onSteamDataConfirmed,
onDataPath,
onDecalSource,
onError,
}: DataStepProps) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<> <>
@@ -35,9 +49,16 @@ export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, st
</Notice> </Notice>
)} )}
<Row label={t('decals.source')} hint={t('decals.hint')}> <Row label={t('decals.source')} hint={t('decals.hint')}>
<FolderField path={decalSource} dialogTitle={t('decals.choose')} onChosen={onDecalSource} onError={onError} /> <FolderField
path={decalSource}
defaultPath={defaultDecalPath}
dialogTitle={t('decals.choose')}
onChosen={onDecalSource}
onError={onError}
/>
{decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>} {decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>}
</Row> </Row>
{decalAutoDetected && decalSource && <Notice tone="info">{t('decals.autoDetectedNotice')}</Notice>}
</> </>
); );
} }
@@ -44,6 +44,8 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
steamDataConfirmed={wizard.steamDataConfirmed} steamDataConfirmed={wizard.steamDataConfirmed}
onSteamDataConfirmed={wizard.setSteamDataConfirmed} onSteamDataConfirmed={wizard.setSteamDataConfirmed}
decalSource={wizard.decalSource} decalSource={wizard.decalSource}
decalAutoDetected={wizard.decalAutoDetected}
defaultDecalPath={wizard.decalProbePath}
onDataPath={wizard.setDataPath} onDataPath={wizard.setDataPath}
onDecalSource={wizard.setDecalSource} onDecalSource={wizard.setDecalSource}
onError={wizard.report} onError={wizard.report}
@@ -40,7 +40,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
problem: DataFolderProblem | null; problem: DataFolderProblem | null;
confirmed: boolean; confirmed: boolean;
} | null>(null); } | null>(null);
const [decalSource, setDecalSource] = useState<string | null>(null); const [decalSource, setDecalSourceState] = useState<string | null>(null);
const [decalAutoDetected, setDecalAutoDetected] = useState(false);
const [decalManuallyEdited, setDecalManuallyEdited] = useState(false);
const [check, setCheck] = useState<PatchCheck | null>(null); const [check, setCheck] = useState<PatchCheck | null>(null);
const [missingAccepted, setMissingAccepted] = useState(false); const [missingAccepted, setMissingAccepted] = useState(false);
const [progress, setProgress] = useState<InstallProgress | null>(null); const [progress, setProgress] = useState<InstallProgress | null>(null);
@@ -66,8 +68,34 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
? (source?.path ?? null) ? (source?.path ?? null)
: null; : null;
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null; const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
const decalProbePath = stockSource?.path ?? source?.path ?? null;
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]); const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
// Read-only probe of the player-selected source folder for a usable decal cache.
useEffect(() => {
if (!active || !decalProbePath || decalManuallyEdited) return;
let current = true;
ipcInvoke('decals:detectSource', { path: decalProbePath })
.then(({ path }) => {
if (!current) return;
if (path) {
setDecalSourceState(path);
setDecalAutoDetected(true);
} else {
setDecalSourceState(null);
setDecalAutoDetected(false);
}
})
.catch(() => {
if (!current) return;
setDecalSourceState(null);
setDecalAutoDetected(false);
});
return () => {
current = false;
};
}, [active, decalProbePath, decalManuallyEdited]);
useEffect(() => { useEffect(() => {
if (!active || !dataPath) return; if (!active || !dataPath) return;
let current = true; let current = true;
@@ -119,6 +147,12 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
useEffect(() => ipcOn('event:install-progress', setProgress), []); useEffect(() => ipcOn('event:install-progress', setProgress), []);
const resetDecals = (): void => {
setDecalSourceState(null);
setDecalAutoDetected(false);
setDecalManuallyEdited(false);
};
const start = (): void => { const start = (): void => {
clear(); clear();
setMode('new'); setMode('new');
@@ -130,7 +164,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
setDraftId(null); setDraftId(null);
setDataPath(''); setDataPath('');
setDataInspection(null); setDataInspection(null);
setDecalSource(null); resetDecals();
setActive(true); setActive(true);
ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => { ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => {
setDraftId(id); setDraftId(id);
@@ -145,11 +179,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
setStockSource(null); setStockSource(null);
setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE); setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE);
setName(''); setName('');
resetDecals();
}; };
const chooseSource = (found: GameFolderInspection | null): void => { const chooseSource = (found: GameFolderInspection | null): void => {
setSource(found); setSource(found);
setStockSource(null); setStockSource(null);
resetDecals();
const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource; const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource;
const defaultMethod = isExisting ? 'existing' : 'copy'; const defaultMethod = isExisting ? 'existing' : 'copy';
setChoice({ method: defaultMethod, target: null, steamConfirmed: false }); setChoice({ method: defaultMethod, target: null, steamConfirmed: false });
@@ -166,6 +202,17 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
} }
}; };
const chooseStockSource = (found: GameFolderInspection | null): void => {
setStockSource(found);
resetDecals();
};
const setDecalSource = (path: string | null): void => {
setDecalSourceState(path);
setDecalAutoDetected(false);
setDecalManuallyEdited(true);
};
const install = (): void => { const install = (): void => {
if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return; if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return;
const directFolder = choice.method === 'in-place' || choice.method === 'existing'; const directFolder = choice.method === 'in-place' || choice.method === 'existing';
@@ -230,9 +277,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
}; };
return { return {
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn, active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, decalAutoDetected, decalProbePath, check, missingAccepted, progress, cancelling, message, canGoOn,
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false, steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted, start, back, next, cancel, report, chooseMode, chooseSource, setStockSource: chooseStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
}; };
} }
+2
View File
@@ -14,6 +14,8 @@ export const IPC_CHANNEL_PREFIXES = [
'install:', 'install:',
/** Listing and managing installed copies. */ /** Listing and managing installed copies. */
'copies:', 'copies:',
/** Read-only detection of decal cache folders in player-selected or registered sources. */
'decals:',
/** Settings shared by the saves of a game copy. */ /** Settings shared by the saves of a game copy. */
'tuning:', 'tuning:',
/** Additive mods repository, per-copy ordering/toggles, and presets. */ /** Additive mods repository, per-copy ordering/toggles, and presets. */
+5
View File
@@ -170,6 +170,11 @@ export const ipcContract = {
input: z.void(), input: z.void(),
output: z.void(), output: z.void(),
}, },
'decals:detectSource': {
/** Read-only check for a usable decal cache inside a player-chosen or registered folder. */
input: z.object({ path: z.string().min(1) }),
output: z.object({ path: z.string().nullable() }),
},
'saves:list': { 'saves:list': {
input: z.object({ copyId: CopyIdSchema }), input: z.object({ copyId: CopyIdSchema }),
output: SaveListSchema, output: SaveListSchema,
@@ -1,8 +1,8 @@
/** /**
* Decals and downloadable skins from the player's own online client: the player names the web * Decals and downloadable skins from the player's own online client: the player names the web
* cache folder of an installation they have played online with (<game>/cache/content, or its * cache folder of an installation they have played online with (<game>/cache/content, its parent
* parent <game>/cache), and the build copies the cached textures into the game copy's * <game>/cache, or the game root <game>), and the build copies the cached textures into the game
* cache/content. The offline version never looks for that folder itself. * copy's cache/content. The offline version never looks for that folder itself.
* *
* Two layouts exist across War Thunder builds (verified on 2.61.0.37 and 2.61.0.58): * Two layouts exist across War Thunder builds (verified on 2.61.0.37 and 2.61.0.58):
* 1. Modern vromfs-indexed cache (2.61+): cache/content/ holds dldata_s.info and the downloaded * 1. Modern vromfs-indexed cache (2.61+): cache/content/ holds dldata_s.info and the downloaded
@@ -46,15 +46,16 @@ export interface PlayerDecalCache {
} }
/** /**
* Resolve the actual cache/content folder when the player selects either <game>/cache/content * Resolve the actual cache/content folder when the player selects <game>/cache/content,
* or its parent <game>/cache folder. * its parent <game>/cache folder, or the game root <game>.
*/ */
export function resolvePlayerDecalCacheFolder(source: string): string { export function resolvePlayerDecalCacheFolder(source: string): string {
if (!existsSync(source) || !statSync(source).isDirectory()) return source; if (!existsSync(source) || !statSync(source).isDirectory()) return source;
if (directDecalCacheProblem(source) === undefined) return source; if (directDecalCacheProblem(source) === undefined) return source;
const nested = join(source, 'content'); for (const candidate of [join(source, 'content'), join(source, WEB_CACHE_FOLDER)]) {
if (existsSync(nested) && statSync(nested).isDirectory() && directDecalCacheProblem(nested) === undefined) { if (existsSync(candidate) && statSync(candidate).isDirectory() && directDecalCacheProblem(candidate) === undefined) {
return nested; return candidate;
}
} }
return source; return source;
} }
@@ -76,9 +77,9 @@ export function ddsxPathForHash(hash: string): string | undefined {
} }
/** /**
* Scan a player decal cache folder (cache/content, its parent cache folder, or an imported * Scan a player decal cache folder (cache/content, its parent cache folder, the game root, or an
* snapshot) and collect the normalized relative paths ("<first2>/<rest>.ddsx", lowercased) of * imported snapshot) and collect the normalized relative paths ("<first2>/<rest>.ddsx", lowercased)
* all cached .ddsx files, skipping .wto-index. * of all cached .ddsx files, skipping .wto-index.
*/ */
export function scanCachedDdsxFiles(source: string): ReadonlySet<string> { export function scanCachedDdsxFiles(source: string): ReadonlySet<string> {
const folder = resolvePlayerDecalCacheFolder(source); const folder = resolvePlayerDecalCacheFolder(source);
@@ -338,10 +339,22 @@ function readSnapshotIndexFiles(folder: string): readonly AddedFile[] | undefine
} }
function hasCachedDdsxTextures(folder: string): boolean { function hasCachedDdsxTextures(folder: string): boolean {
for (const entry of readdirSync(folder, { withFileTypes: true })) { let entries;
try {
entries = readdirSync(folder, { withFileTypes: true });
} catch {
return false;
}
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue; if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue;
const sub = join(folder, entry.name); const sub = join(folder, entry.name);
for (const child of readdirSync(sub, { withFileTypes: true })) { let children;
try {
children = readdirSync(sub, { withFileTypes: true });
} catch {
continue;
}
for (const child of children) {
if (child.isFile() && child.name.toLowerCase().endsWith(DDSX_EXTENSION)) return true; if (child.isFile() && child.name.toLowerCase().endsWith(DDSX_EXTENSION)) return true;
} }
} }
@@ -351,8 +364,14 @@ function hasCachedDdsxTextures(folder: string): boolean {
function findRegionalPack(contentFolder: string): string | undefined { function findRegionalPack(contentFolder: string): string | undefined {
const parent = dirname(contentFolder); const parent = dirname(contentFolder);
if (parent === contentFolder || !existsSync(parent)) return undefined; if (parent === contentFolder || !existsSync(parent)) return undefined;
let entries;
try {
entries = readdirSync(parent, { withFileTypes: true });
} catch {
return undefined;
}
const candidates: Array<{ readonly path: string; readonly version: string; readonly mtimeMs: number }> = []; const candidates: Array<{ readonly path: string; readonly version: string; readonly mtimeMs: number }> = [];
for (const entry of readdirSync(parent, { withFileTypes: true })) { for (const entry of entries) {
if (!entry.isDirectory() || entry.isSymbolicLink()) continue; if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
const match = BINARY_CACHE_DIR.exec(entry.name); const match = BINARY_CACHE_DIR.exec(entry.name);
if (!match) continue; if (!match) continue;
@@ -395,7 +414,11 @@ function contains(parent: string, child: string): boolean {
} }
function decalIndexes(folder: string): string[] { function decalIndexes(folder: string): string[] {
return readdirSync(folder, { withFileTypes: true }) try {
.filter((entry) => entry.isFile() && DECALS_INDEX_FILE.test(entry.name)) return readdirSync(folder, { withFileTypes: true })
.map((entry) => entry.name); .filter((entry) => entry.isFile() && DECALS_INDEX_FILE.test(entry.name))
.map((entry) => entry.name);
} catch {
return [];
}
} }