fix(patcher): filter uncached decal and skin entries with placeholder fallback

Scan locally cached .ddsx files under cache/content (<first2>/<rest>.ddsx) when building char.vromfs.bin from player decal snapshots or regional.vromfs.bin. Repair single-LOD cache hits by falling back missing lodN/hdrN pairs to available LODs, fall back uncached stock decals to built-in placeholders, and drop uncached extra decals and incomplete downloadable skins.
This commit is contained in:
N0VAN0M4LY committed 2026-12-04 19:55:03 +08:00
1 parent 48f01b533e
commit 8f1d175d55
4 files changed
+383 -39

No files matched your search

@@ -58,17 +58,35 @@ export interface OfflineDecalIndex {
readonly decals: number;
}
export interface MergedDecalIndex {
readonly index: BlkBlock;
readonly content: Uint8Array;
/** Total decals backed by locally cached .ddsx textures (stock + extra). */
readonly cachedDecals: number;
/** Stock config/decals.blk entries resolved from cached .ddsx textures. */
readonly cachedStockDecals: number;
/** Extra entries outside config/decals.blk kept because their .ddsx textures are cached. */
readonly cachedExtraDecals: number;
/** Stock config/decals.blk entries that fell back to built-in placeholder textures. */
readonly placeholderDecals: number;
}
const SQUARE_PARAMS = textureParams(SQUARE_PLACEHOLDER);
const WIDE_PARAMS = textureParams(WIDE_PLACEHOLDER);
export function placeholderDecalBlock(decal: BlkBlock): BlkBlock {
return {
name: decal.name,
params: aspectRatio(decal) >= WIDE_ASPECT_RATIO ? WIDE_PARAMS : SQUARE_PARAMS,
blocks: [],
};
}
export function offlineDecalIndex(decalsConfig: BlkBlock): OfflineDecalIndex {
const square = textureParams(SQUARE_PLACEHOLDER);
const wide = textureParams(WIDE_PLACEHOLDER);
const index: BlkBlock = {
name: '',
params: [],
blocks: decalsConfig.blocks.map((decal) => ({
name: decal.name,
params: aspectRatio(decal) >= WIDE_ASPECT_RATIO ? wide : square,
blocks: [],
})),
blocks: decalsConfig.blocks.map(placeholderDecalBlock),
};
return {
files: [
@@ -79,6 +97,64 @@ export function offlineDecalIndex(decalsConfig: BlkBlock): OfflineDecalIndex {
};
}
/**
* Merge a filtered player downloadable_decals.blk (containing only decals with locally cached
* .ddsx textures) with stock config/decals.blk:
* - Every stock decal present in cachedPlayerDecals keeps its real entry.
* - Every stock decal missing from cachedPlayerDecals falls back to a built-in placeholder
* texture (star/panther) so it never fails to load offline.
* - Extra decals outside config/decals.blk that survived cache filtering are appended.
*/
export function mergePlayerDecalIndex(
decalsConfig: BlkBlock,
cachedPlayerDecals: BlkBlock,
): MergedDecalIndex {
const cachedByName = new Map<string, BlkBlock>();
for (const block of cachedPlayerDecals.blocks) {
cachedByName.set(block.name, block);
}
const stockNames = new Set<string>();
const blocks: BlkBlock[] = [];
let cachedStockDecals = 0;
let placeholderDecals = 0;
for (const decal of decalsConfig.blocks) {
stockNames.add(decal.name);
const cached = cachedByName.get(decal.name);
if (cached !== undefined) {
blocks.push(cached);
cachedStockDecals += 1;
} else {
blocks.push(placeholderDecalBlock(decal));
placeholderDecals += 1;
}
}
const emittedExtra = new Set<string>();
let cachedExtraDecals = 0;
for (const block of cachedPlayerDecals.blocks) {
if (stockNames.has(block.name) || emittedExtra.has(block.name)) continue;
emittedExtra.add(block.name);
blocks.push(block);
cachedExtraDecals += 1;
}
const index: BlkBlock = {
name: '',
params: cachedPlayerDecals.params,
blocks,
};
return {
index,
content: encodeBlk(index),
cachedDecals: cachedStockDecals + cachedExtraDecals,
cachedStockDecals,
cachedExtraDecals,
placeholderDecals,
};
}
function aspectRatio(decal: BlkBlock): number {
const value = decal.params.find((param) => param.name === 'aspect_ratio')?.value;
return value?.type === 'real' && Number.isFinite(value.value) && value.value > 0 ? value.value : 1;
+207 -23
View File
@@ -6,20 +6,23 @@
*
* 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
* <first2>/<hash>.ddsx textures, while the decal and skin indexes (dldata/downloadable_decals.blk
* and dldata/downloadable_skins.blk) ship inside sibling cache/binary.<ver>/regional.vromfs.bin
* (mounted by webdlcontent::on_regional_vrom_remounted, 0xd3cf95 -> 0xd3d066). Because the client
* reads the vromfs index first, it never writes downloadable_decals.<hash>.blk into cache/content/.
* We extract both index BLKs into a self-contained snapshot (.wto-index/) on import and embed
* them into char.vromfs.bin during build so webdlcontent::init mounts cache/content/ (0xd3ca11)
* and loads the real hashes from vromfs without signature checks (0xd3cb6b).
* <first2>/<rest>.ddsx textures (where the first 2 characters of each base32 hash form the
* bucket directory and the remaining characters plus ".ddsx" form the filename), while the
* decal and skin indexes (dldata/downloadable_decals.blk and dldata/downloadable_skins.blk)
* ship inside sibling cache/binary.<ver>/regional.vromfs.bin (mounted by
* webdlcontent::on_regional_vrom_remounted, 0xd3cf95 -> 0xd3d066). Because the client reads
* the vromfs index first, it never writes downloadable_decals.<hash>.blk into cache/content/.
* We extract both raw index BLKs into a self-contained snapshot (.wto-index/) on import; when
* building char.vromfs.bin, we filter both indexes against the .ddsx files actually present
* in the cache (backfilling missing single-LOD references from the cached LOD) so uncached
* entries do not fail to load offline.
* 2. Legacy webcache-indexed cache: cache/content/ holds dldata_s.info and signed
* downloadable_decals.<hash>.blk directly; char.vromfs.bin omits dldata/ so the client reads
* the cached index from cache/content/.
*/
import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
import { decodeBlk, emptyBlock, encodeBlk, parseSharedNameMap } from '@wto/blk';
import { decodeBlk, emptyBlock, encodeBlk, parseSharedNameMap, type BlkBlock, type BlkParam } from '@wto/blk';
import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs';
import type { AddedFile } from '../pack-edit.ts';
import { compareVersions } from '../version-record.ts';
@@ -33,6 +36,9 @@ const REGIONAL_PACK_NAME = 'regional.vromfs.bin';
const SNAPSHOT_INDEX_DIR = '.wto-index';
const SNAPSHOT_DECALS_FILE = 'downloadable_decals.blk';
const SNAPSHOT_SKINS_FILE = 'downloadable_skins.blk';
const DDSX_EXTENSION = '.ddsx';
const LOD_PARAM = /^lod(\d+)$/;
const HDR_PARAM = /^hdr(\d+)$/;
export interface PlayerDecalCache {
readonly copiedTo: string;
@@ -60,27 +66,133 @@ export function playerDecalCacheProblem(source: string): string | undefined {
}
/**
* Read real dldata/downloadable_decals.blk and dldata/downloadable_skins.blk for embedding into
* char.vromfs.bin when the cache uses either an imported snapshot index or a sibling
* binary.<ver>/regional.vromfs.bin. Returns undefined for legacy downloadable_decals.<hash>.blk
* caches, which supply their index directly inside cache/content/.
* Map a downloadable texture hash (e.g. "nhy6...cyii") to its cache-relative .ddsx path
* ("nh/y6...cyii.ddsx", lowercased). Returns undefined for non-hash values.
*/
export function readPlayerDecalIndexFiles(source: string): readonly AddedFile[] | undefined {
const folder = resolvePlayerDecalCacheFolder(source);
const snapshot = readSnapshotIndexFiles(folder);
if (snapshot) return snapshot;
if (decalIndexes(folder).length > 0) return undefined;
const regional = findRegionalPack(folder);
if (!regional) return undefined;
return extractRegionalIndexFiles(regional);
export function ddsxPathForHash(hash: string): string | undefined {
const normalized = hash.trim().toLowerCase();
if (normalized.length < 3 || normalized.includes('/') || normalized.includes('\\')) return undefined;
return `${normalized.slice(0, 2)}/${normalized.slice(2)}${DDSX_EXTENSION}`;
}
/**
* Persist extracted vromfs decal/skin indexes into an imported cache snapshot so subsequent
* Scan a player decal cache folder (cache/content, its parent cache folder, or an imported
* snapshot) and collect the normalized relative paths ("<first2>/<rest>.ddsx", lowercased) of
* all cached .ddsx files, skipping .wto-index.
*/
export function scanCachedDdsxFiles(source: string): ReadonlySet<string> {
const folder = resolvePlayerDecalCacheFolder(source);
const cached = new Set<string>();
if (!existsSync(folder) || !statSync(folder).isDirectory()) return cached;
for (const entry of readdirSync(folder, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue;
const bucket = entry.name.toLowerCase();
if (bucket.length !== 2) continue;
const sub = join(folder, entry.name);
for (const child of readdirSync(sub, { withFileTypes: true })) {
if (!child.isFile()) continue;
const name = child.name.toLowerCase();
if (name.endsWith(DDSX_EXTENSION)) cached.add(`${bucket}/${name}`);
}
}
return cached;
}
/**
* Filter a downloadable_decals.blk root block to only decals with at least one cached LOD
* texture in cachedDdsx, backfilling any missing lodN/hdrN from the best cached LOD.
*/
export function filterDownloadableDecalsBlock(
decalsBlk: BlkBlock,
cachedDdsx: ReadonlySet<string>,
): BlkBlock {
const blocks: BlkBlock[] = [];
for (const decal of decalsBlk.blocks) {
const normalized = normalizeTextureBlockLods(decal, cachedDdsx);
if (normalized !== undefined) blocks.push(normalized);
}
return { name: decalsBlk.name, params: decalsBlk.params, blocks };
}
/**
* Filter a downloadable_skins.blk root block to only skins whose texture entries all have at
* least one cached LOD texture in cachedDdsx, backfilling missing lodN (and hdrN if present)
* from the best cached LOD.
*/
export function filterDownloadableSkinsBlock(
skinsBlk: BlkBlock,
cachedDdsx: ReadonlySet<string>,
): BlkBlock {
const blocks: BlkBlock[] = [];
for (const skin of skinsBlk.blocks) {
if (skin.blocks.length > 0) {
const nextChildren: BlkBlock[] = [];
let allCached = true;
let hasTextureChild = false;
for (const child of skin.blocks) {
if (hasLodParams(child)) {
hasTextureChild = true;
const normalized = normalizeTextureBlockLods(child, cachedDdsx);
if (normalized === undefined) {
allCached = false;
break;
}
nextChildren.push(normalized);
} else {
nextChildren.push(child);
}
}
if (allCached && hasTextureChild) {
blocks.push({ name: skin.name, params: skin.params, blocks: nextChildren });
}
} else {
const normalized = normalizeTextureBlockLods(skin, cachedDdsx);
if (normalized !== undefined) blocks.push(normalized);
}
}
return { name: skinsBlk.name, params: skinsBlk.params, blocks };
}
/**
* Filter encoded dldata/downloadable_decals.blk and dldata/downloadable_skins.blk entries
* against the set of locally cached .ddsx relative paths.
*/
export function filterPlayerDecalIndexFiles(
files: readonly AddedFile[],
cachedDdsx: ReadonlySet<string>,
): readonly AddedFile[] {
return files.map((file) => {
if (file.path === DECALS_INDEX_PATH) {
return { path: file.path, content: encodeBlk(filterDownloadableDecalsBlock(decodeBlk(file.content), cachedDdsx)) };
}
if (file.path === SKINS_INDEX_PATH) {
return { path: file.path, content: encodeBlk(filterDownloadableSkinsBlock(decodeBlk(file.content), cachedDdsx)) };
}
return file;
});
}
/**
* Read dldata/downloadable_decals.blk and dldata/downloadable_skins.blk for embedding into
* char.vromfs.bin when the cache uses either an imported snapshot index or a sibling
* binary.<ver>/regional.vromfs.bin, filtered to entries whose .ddsx textures actually exist in
* the cache folder (with single-LOD fallback). Returns undefined for legacy
* downloadable_decals.<hash>.blk caches, which supply their index directly inside cache/content/.
*/
export function readPlayerDecalIndexFiles(source: string): readonly AddedFile[] | undefined {
const folder = resolvePlayerDecalCacheFolder(source);
const raw = readRawPlayerDecalIndexFiles(folder);
if (!raw) return undefined;
return filterPlayerDecalIndexFiles(raw, scanCachedDdsxFiles(folder));
}
/**
* Persist raw extracted vromfs decal/skin indexes into an imported cache snapshot so subsequent
* launches are completely self-contained and never touch the online client directory.
*/
export function writeDecalCacheIndexSnapshot(source: string, target: string): void {
const files = readPlayerDecalIndexFiles(source);
const folder = resolvePlayerDecalCacheFolder(source);
const files = readRawPlayerDecalIndexFiles(folder);
if (!files) return;
const indexDir = join(target, SNAPSHOT_INDEX_DIR);
mkdirSync(indexDir, { recursive: true });
@@ -140,6 +252,78 @@ function directDecalCacheProblem(folder: string): string | undefined {
return `${folder} has no downloadable_decals.<hash>.blk and no sibling binary.*/${REGIONAL_PACK_NAME}`;
}
function readRawPlayerDecalIndexFiles(folder: string): readonly AddedFile[] | undefined {
const snapshot = readSnapshotIndexFiles(folder);
if (snapshot) return snapshot;
if (decalIndexes(folder).length > 0) return undefined;
const regional = findRegionalPack(folder);
if (!regional) return undefined;
return extractRegionalIndexFiles(regional);
}
function hasLodParams(block: BlkBlock): boolean {
return block.params.some((param) => param.value.type === 'string' && LOD_PARAM.test(param.name));
}
function normalizeTextureBlockLods(
block: BlkBlock,
cachedDdsx: ReadonlySet<string>,
): BlkBlock | undefined {
const lods: Array<{ readonly index: number; readonly value: string; readonly cached: boolean }> = [];
const hdrs = new Map<number, string>();
for (const param of block.params) {
if (param.value.type !== 'string') continue;
const lodMatch = LOD_PARAM.exec(param.name);
if (lodMatch) {
const rel = ddsxPathForHash(param.value.value);
lods.push({
index: Number(lodMatch[1]),
value: param.value.value,
cached: rel !== undefined && cachedDdsx.has(rel),
});
continue;
}
const hdrMatch = HDR_PARAM.exec(param.name);
if (hdrMatch) {
hdrs.set(Number(hdrMatch[1]), param.value.value);
}
}
if (lods.length === 0) return undefined;
lods.sort((a, b) => a.index - b.index);
const best = lods.find((entry) => entry.cached);
if (!best) return undefined;
if (lods.every((entry) => entry.cached)) return block;
const missingIndices = new Set(lods.filter((entry) => !entry.cached).map((entry) => entry.index));
const bestHdr = hdrs.get(best.index);
const nextParams: BlkParam[] = [];
for (const param of block.params) {
if (param.value.type === 'string') {
const hdrMatch = HDR_PARAM.exec(param.name);
if (hdrMatch) {
const idx = Number(hdrMatch[1]);
if (missingIndices.has(idx) && bestHdr !== undefined) {
nextParams.push({ name: param.name, value: { type: 'string', value: bestHdr } });
continue;
}
}
const lodMatch = LOD_PARAM.exec(param.name);
if (lodMatch) {
const idx = Number(lodMatch[1]);
if (missingIndices.has(idx)) {
if (bestHdr !== undefined && !hdrs.has(idx)) {
nextParams.push({ name: `hdr${idx}`, value: { type: 'string', value: bestHdr } });
}
nextParams.push({ name: param.name, value: { type: 'string', value: best.value } });
continue;
}
}
}
nextParams.push(param);
}
return { name: block.name, params: nextParams, blocks: block.blocks };
}
function readSnapshotIndexFiles(folder: string): readonly AddedFile[] | undefined {
const decalsPath = join(folder, SNAPSHOT_INDEX_DIR, SNAPSHOT_DECALS_FILE);
if (!statSync(decalsPath, { throwIfNoEntry: false })?.isFile()) return undefined;
@@ -158,7 +342,7 @@ function hasCachedDdsxTextures(folder: string): boolean {
if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue;
const sub = join(folder, entry.name);
for (const child of readdirSync(sub, { withFileTypes: true })) {
if (child.isFile() && child.name.endsWith('.ddsx')) return true;
if (child.isFile() && child.name.toLowerCase().endsWith(DDSX_EXTENSION)) return true;
}
}
return false;