diff --git a/packages/build/src/char-pack.ts b/packages/build/src/char-pack.ts index 092890c..92f06b5 100644 --- a/packages/build/src/char-pack.ts +++ b/packages/build/src/char-pack.ts @@ -1,12 +1,14 @@ /** * Rebuild char.vromfs.bin: config/network.blk pointed at the local service, the offline - * version's features turned on in config/game_settings.blk, and every vehicle shown in the - * tech tree (config/shop.blk). + * version's features turned on in config/game_settings.blk, every vehicle shown in the + * tech tree (config/shop.blk), and, unless the player gave a decal source, placeholder decal + * and skin indexes (decals/offline-decal-index.ts). */ +import { DECALS_CONFIG_PATH, offlineDecalIndex } from './decals/offline-decal-index.ts'; import { enableFeaturesForEveryone, GAME_SETTINGS_PATH, OFFLINE_FEATURES } from './features/offline-features.ts'; import type { LocalEndpoint } from './network/local-endpoint.ts'; import { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts'; -import { editPackBlks } from './pack-edit.ts'; +import { editPackBlks, readPackBlk } from './pack-edit.ts'; import { revealHiddenVehicles, SHOP_PATH } from './tech-tree/reveal-hidden-vehicles.ts'; export const NETWORK_CONFIG_PATH = 'config/network.blk'; @@ -18,16 +20,24 @@ export interface CharPackResult { readonly features: readonly string[]; /** Vehicles that were hidden from players who had not researched or bought them. */ readonly revealedVehicles: number; + /** Decals in the placeholder index; undefined when the index was left out. */ + readonly placeholderDecals: number | undefined; } -export function rebuildCharPack(stockPack: Uint8Array, endpoint: LocalEndpoint): CharPackResult { +export interface CharPackOptions { + /** Store the placeholder decal index (false when the player's own web cache is copied). */ + readonly placeholderDecals: boolean; +} + +export function rebuildCharPack(stockPack: Uint8Array, endpoint: LocalEndpoint, options: CharPackOptions): CharPackResult { let network: NetworkRedirectReport | undefined; let features: string[] = []; let revealedVehicles = 0; + const decals = options.placeholderDecals ? offlineDecalIndex(readPackBlk(stockPack, DECALS_CONFIG_PATH)) : undefined; const pack = editPackBlks(stockPack, [ { path: NETWORK_CONFIG_PATH, edit: (root) => { network = redirectNetworkConfig(root, endpoint); } }, { path: GAME_SETTINGS_PATH, edit: (root) => { features = enableFeaturesForEveryone(root, OFFLINE_FEATURES); } }, { path: SHOP_PATH, edit: (root) => { revealedVehicles = revealHiddenVehicles(root); } }, - ]); - return { pack, network: network!, features, revealedVehicles }; + ], decals?.files ?? []); + return { pack, network: network!, features, revealedVehicles, placeholderDecals: decals?.decals }; } diff --git a/packages/build/src/cli.ts b/packages/build/src/cli.ts index cb44825..b95c6ec 100644 --- a/packages/build/src/cli.ts +++ b/packages/build/src/cli.ts @@ -4,11 +4,14 @@ * * node packages/build/src/cli.ts --game --out --port * [--patches exe-patches] [--gui-patches gui-patches] - * [--native build/native] [--verbose] + * [--native build/native] [--decal-cache ] [--verbose] * * Writes /char.vromfs.bin, /aces.vromfs.bin, /gui.vromfs.bin, /win64/aces.exe * and the network hook library the patched executable loads (/win64/wto_ws.dll from --native, * built by native/wto-net/build.ps1, and its settings wto_ws.cfg). The stock folder is only read. + * --decal-cache names the cache/content folder of the player's online installation; it is copied + * to /cache/content (decals/player-decal-cache.ts), otherwise char.vromfs.bin gets the + * placeholder decal index (decals/offline-decal-index.ts). * The launcher will run the same steps at every launch, with the port the player chose. */ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; @@ -16,6 +19,7 @@ import { dirname, join } from 'node:path'; import { parseArgs } from 'node:util'; import { fileURLToPath } from 'node:url'; import { rebuildCharPack } from './char-pack.ts'; +import { copyPlayerDecalCache, playerDecalCacheProblem } from './decals/player-decal-cache.ts'; import { patchExecutable } from './executable.ts'; import { assertWritableCopy, GAME_FILES } from './game-copy.ts'; import { rebuildGuiPack } from './gui-pack.ts'; @@ -36,15 +40,22 @@ function main(): number { patches: { type: 'string', default: 'exe-patches' }, 'gui-patches': { type: 'string' }, native: { type: 'string', default: join('build', 'native') }, + 'decal-cache': { type: 'string' }, verbose: { type: 'boolean', default: false }, }, }); if (!values.game || !values.out || !values.port) { - console.error('usage: cli.ts --game --out --port [--patches exe-patches] [--gui-patches gui-patches] [--native build/native] [--verbose]'); + console.error('usage: cli.ts --game --out --port [--patches exe-patches] [--gui-patches gui-patches] [--native build/native] [--decal-cache ] [--verbose]'); return 2; } assertWritableCopy(values.game, values.out); const endpoint = localEndpoint(Number(values.port)); + const decalCache = values['decal-cache']; + const decalCacheProblem = decalCache === undefined ? undefined : playerDecalCacheProblem(decalCache); + if (decalCacheProblem) { + console.error(`--decal-cache: ${decalCacheProblem}; nothing was written`); + return 1; + } const hookLibraryPath = join(values.native, NETWORK_HOOK_LIBRARY); if (!existsSync(hookLibraryPath)) { console.error(`${hookLibraryPath} not found (build it with native/wto-net/build.ps1); nothing was written`); @@ -59,7 +70,7 @@ function main(): number { } const stockCharPack = readFileSync(join(values.game, GAME_FILES.charPack)); - const charPack = rebuildCharPack(stockCharPack, endpoint); + const charPack = rebuildCharPack(stockCharPack, endpoint, { placeholderDecals: decalCache === undefined }); console.log(`network.blk: ${charPack.network.addresses.length} address(es) now point to ${endpoint.host}:${endpoint.port}; ` + `environments configured: ${charPack.network.environments.join(', ')}`); if (values.verbose) { @@ -67,6 +78,7 @@ function main(): number { } console.log(`game_settings.blk: features on for every player: ${charPack.features.join(', ') || '(already on)'}`); console.log(`shop.blk: ${charPack.revealedVehicles} hidden vehicles shown in the tech tree`); + if (charPack.placeholderDecals !== undefined) console.log(`dldata: placeholder textures for ${charPack.placeholderDecals} decals`); const packBundles = offlinePackBundleGuids(stockCharPack, STORE_TUNING_PATH); const mainPack = rebuildMainPack(readFileSync(join(values.game, GAME_FILES.mainPack)), endpoint, packBundles); @@ -85,6 +97,10 @@ function main(): number { writeOutput(values.out, join(executableFolder, NETWORK_HOOK_LIBRARY), readFileSync(hookLibraryPath)); const settings = networkHookSettings(endpoint); writeOutput(values.out, join(executableFolder, settings.name), settings.content); + if (decalCache !== undefined) { + const copied = copyPlayerDecalCache(decalCache, values.out); + console.log(`copied the player's web cache to ${copied.copiedTo} (decal indexes: ${copied.decalIndexes.join(', ')})`); + } return 0; } diff --git a/packages/build/src/decals/offline-decal-index.ts b/packages/build/src/decals/offline-decal-index.ts new file mode 100644 index 0000000..bd88c4b --- /dev/null +++ b/packages/build/src/decals/offline-decal-index.ts @@ -0,0 +1,120 @@ +/** + * Decal and skin indexes stored in char.vromfs.bin, for a game copy that has no decal source + * from the player (player-decal-cache.ts): every decal of the stock list shows one of the + * client's built-in decal textures as a placeholder. + * + * How the client gets its decal list (aces.exe 2.61.0.37): + * - webdlcontent init (0xd3bc40) first calls the vromfs index loader (0xd3cc60, also run when + * regional.vromfs.bin is mounted, 0x15fe55b). If the setting debug{ dldataAllowVromIndex:b } + * (default true) allows it and the mounted packs hold both dldata/downloadable_skins.blk and + * dldata/downloadable_decals.blk, it loads them ("vromfs:dldata/downloadable_decals.blk"), + * registers the decals (0xd3da50) and returns true; init then skips the download path + * (jne 0xd3cc0d). No content hash and no signature is checked on this path. + * - Otherwise the client reads dldata_s.info and looks for downloadable_decals..blk in + * its web cache folder (cache/content/, 0xd3e710 -> 0xd3f610). It does not download the + * index there: a missing file leaves the list empty ("dldata: selected existing ...", + * "registering 0 decals"), and a file that fails the signature check over its last 0x100 + * bytes (0xd383e0, "dlData: <%s> signature check failed") is deleted. An index the offline + * version makes can only reach the client through the vromfs path. + * - Each decal is registered as the managed texture "*?" (0xd44fc0). The + * texture manager drops everything from the last '?' before the name lookup (DagorEngine + * prog/engine/baseUtil/texMetaData.cpp TextureMetaData::decode), so lod0 "star" resolves to + * "star*" from content/base/res/decals.dxp.bin. Only if no such texture is registered does + * the client create a downloadable one from the hdr0 header (0xd49e00). + * - config/decals.blk (char.vromfs.bin) is laid over the index afterwards (0xd48380, not + * re-verified) and gives each decal its category, aspect ratio, price, unlock and + * marketplace id; the index only adds textures. + */ +import { emptyBlock, encodeBlk, type BlkBlock } from '@wto/blk'; +import type { AddedFile } from '../pack-edit.ts'; + +export const DECALS_CONFIG_PATH = 'config/decals.blk'; +export const SKINS_INDEX_PATH = 'dldata/downloadable_skins.blk'; +export const DECALS_INDEX_PATH = 'dldata/downloadable_decals.blk'; + +interface PlaceholderTexture { + /** Texture name in content/base/res/decals.dxp.bin (without the trailing '*'). */ + readonly name: string; + readonly width: number; + readonly height: number; +} + +/** Built-in decal textures of the stock client (decals.dxp.bin: lang, panther, star). */ +const SQUARE_PLACEHOLDER: PlaceholderTexture = { name: 'star', width: 512, height: 512 }; +const WIDE_PLACEHOLDER: PlaceholderTexture = { name: 'panther', width: 512, height: 256 }; +/** Offline design: decals at least this much wider than tall use the wide placeholder. */ +const WIDE_ASPECT_RATIO = 1.5; + +/** Dagor ddsx::Header (32 bytes) of an unpacked DXT5 texture, the layout hdr0/hdr1 carry. */ +const DDSX_HEADER_BYTES = 32; +const DDSX_MAGIC = 0x78534444; // "DDSx" +const DDSX_DXT5_FOURCC = 0x35545844; // "DXT5" +const DDSX_UNPACKED_FLAGS = 0x00000044; +const DDSX_QUALITY_WORD = 0x7401; +const DXT5_BLOCK_BYTES = 16; + +export interface OfflineDecalIndex { + readonly files: readonly AddedFile[]; + readonly decals: number; +} + +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: [], + })), + }; + return { + files: [ + { path: SKINS_INDEX_PATH, content: encodeBlk(emptyBlock()) }, + { path: DECALS_INDEX_PATH, content: encodeBlk(index) }, + ], + decals: index.blocks.length, + }; +} + +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; +} + +function textureParams(texture: PlaceholderTexture): BlkBlock['params'] { + const header = ddsxDxt5Header(texture.width, texture.height); + return [ + { name: 'hdr0', value: { type: 'string', value: header } }, + { name: 'lod0', value: { type: 'string', value: texture.name } }, + { name: 'hdr1', value: { type: 'string', value: header } }, + { name: 'lod1', value: { type: 'string', value: texture.name } }, + ]; +} + +/** Base64 of the 32-byte header; read by 0xd49e00 only when the texture is not registered. */ +function ddsxDxt5Header(width: number, height: number): string { + const header = Buffer.alloc(DDSX_HEADER_BYTES); + header.writeUInt32LE(DDSX_MAGIC, 0); + header.writeUInt32LE(DDSX_DXT5_FOURCC, 4); + header.writeUInt32LE(DDSX_UNPACKED_FLAGS, 8); + header.writeUInt16LE(width, 12); + header.writeUInt16LE(height, 14); + let w = width; + let h = height; + let levels = 0; + let memSize = 0; + for (;;) { + levels += 1; + memSize += Math.ceil(w / 4) * Math.ceil(h / 4) * DXT5_BLOCK_BYTES; + if (w === 1 && h === 1) break; + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + header[16] = levels; + header.writeUInt16LE(DDSX_QUALITY_WORD, 22); + header.writeUInt32LE(memSize, 24); + return header.toString('base64'); +} diff --git a/packages/build/src/decals/player-decal-cache.ts b/packages/build/src/decals/player-decal-cache.ts new file mode 100644 index 0000000..e6ad36e --- /dev/null +++ b/packages/build/src/decals/player-decal-cache.ts @@ -0,0 +1,54 @@ +/** + * Decals from the player's own online client: the player names the web cache folder of an + * installation they have played online with (/cache/content), and the build copies it + * into the game copy's cache/content. The offline version never looks for that folder itself. + * + * What the copy gives the client (aces.exe 2.61.0.37): + * - cache/content/ is the web cache root ("ContentProvider::init mount=/cache/content/"). + * - dldata_s.info names the current indexes; when the request for it fails, the client reads + * the cached copy ("failed to get dlContent index hashes from %s, will fallback local copy", + * 0xd3eb40), and the local service answers that request with 404. + * - downloadable_decals..blk is the decal index as the CDN served it, with its signature + * (0xd383e0 checks it and deletes a file that fails). If the file named by dldata_s.info is + * missing, the newest valid downloadable_decals.*.blk in the folder is used (0xd3f610). + * - Each decal's texture is fetched through the web cache by its lod0 name (0xd44fc0); the + * textures the player's client has cached are in the copied folder (assumed, not verified + * against an online cache: the folder layout below httpCache/ was not examined). Textures it + * never cached cannot be fetched offline and stay blank. + * + * With a player source the build leaves the vromfs index (offline-decal-index.ts) out of + * char.vromfs.bin, because the client takes the vromfs index first and then skips the web cache. + */ +import { cpSync, existsSync, readdirSync, statSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; + +export const WEB_CACHE_FOLDER = join('cache', 'content'); +const INDEX_LIST_FILE = 'dldata_s.info'; +const DECALS_INDEX_FILE = /^downloadable_decals\.[a-z2-7]{32}-[a-z2-7]{1,8}\.blk$/; + +export interface PlayerDecalCache { + readonly copiedTo: string; + readonly decalIndexes: readonly string[]; +} + +/** Check that the folder looks like an online client's web cache; returns the problem or undefined. */ +export function playerDecalCacheProblem(source: string): string | undefined { + if (!existsSync(source) || !statSync(source).isDirectory()) return `${source} is not a folder`; + if (!existsSync(join(source, INDEX_LIST_FILE))) return `${source} has no ${INDEX_LIST_FILE} (expected the cache/content folder of an online installation)`; + if (decalIndexes(source).length === 0) return `${source} has no downloadable_decals..blk`; + return undefined; +} + +/** Copy the player's web cache folder into /cache/content; the source is only read. */ +export function copyPlayerDecalCache(source: string, copyFolder: string): PlayerDecalCache { + const target = join(copyFolder, WEB_CACHE_FOLDER); + const from = resolve(source); + const to = resolve(target); + if (from === to || !relative(from, to).startsWith('..')) throw new Error(`the decal source ${source} contains the game copy's web cache`); + cpSync(from, to, { recursive: true, force: true }); + return { copiedTo: target, decalIndexes: decalIndexes(source) }; +} + +function decalIndexes(folder: string): string[] { + return readdirSync(folder).filter((name) => DECALS_INDEX_FILE.test(name)); +} diff --git a/packages/build/src/pack-edit.ts b/packages/build/src/pack-edit.ts index 9fb17d0..47f3240 100644 --- a/packages/build/src/pack-edit.ts +++ b/packages/build/src/pack-edit.ts @@ -1,6 +1,6 @@ /** - * Rebuild a data pack with some of its BLK documents edited. Every other file of the pack is - * kept byte for byte. Edited documents are stored self-contained (they no longer depend on + * Rebuild a data pack with some of its BLK documents edited and, optionally, new files added. + * Every other file of the pack is kept byte for byte. Edited documents are stored self-contained (they no longer depend on * the pack's shared name map), which the game accepts in every loading mode *. */ @@ -24,7 +24,13 @@ export function editPackBlk(stockPack: Uint8Array, blkPath: string, edit: (ro return { pack, report: report as T }; } -export function editPackBlks(stockPack: Uint8Array, edits: readonly BlkEdit[]): Uint8Array { +/** A file the stock pack does not have, stored as is. */ +export interface AddedFile { + readonly path: string; + readonly content: Uint8Array; +} + +export function editPackBlks(stockPack: Uint8Array, edits: readonly BlkEdit[], added: readonly AddedFile[] = []): Uint8Array { const archive = readArchive(stockPack); const dictionary = findDictionary(archive); const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : []; @@ -33,6 +39,10 @@ export function editPackBlks(stockPack: Uint8Array, edits: readonly BlkEdit[]): edit(root); putFile(archive, path, encodeBlk(root)); } + for (const file of added) { + if (archive.files.has(file.path)) throw new Error(`the data pack already has ${file.path}`); + putFile(archive, file.path, file.content); + } return writeArchive(archive); } diff --git a/packages/local-service/src/downloadable-content/content-hash.ts b/packages/local-service/src/downloadable-content/content-hash.ts deleted file mode 100644 index ad2253f..0000000 --- a/packages/local-service/src/downloadable-content/content-hash.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** - * The hash strings that name downloadable-content files: base32 of the file's SHA-1, a dash, - * and base32 of the file's size, e.g. "<32 chars>-<1..8 chars>". - * - * Source: aces.exe 2.61.0.37. The client checks the shape (34..41 characters, '-' at - * position 32, no '.' after it; 0xd3f257 for dldata_s.info, 0xd3741a for a downloaded file), - * decodes the size with the alphabet a-z = 0..25, 2-7 = 26..31, most significant digit first - * (0xd37588), compares it with the file's size, then hashes the file with SHA-1 (0xd37642, - * initial value ends in 0xc3d2e1f0) and compares the base32 of that (0xd37744). The alphabet - * is RFC 4648 base32 in lower case. - */ -import { createHash } from 'node:crypto'; - -const ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567'; - -export function contentHash(content: Uint8Array): string { - const sha1 = createHash('sha1').update(content).digest(); - return `${base32Bytes(sha1)}-${base32Number(content.length)}`; -} - -/** RFC 4648 base32 without padding; 20 bytes of SHA-1 give exactly 32 characters. */ -function base32Bytes(bytes: Uint8Array): string { - let text = ''; - let buffer = 0; - let bits = 0; - for (const byte of bytes) { - buffer = (buffer << 8) | byte; - bits += 8; - while (bits >= 5) { - bits -= 5; - text += ALPHABET[(buffer >> bits) & 31]; - } - buffer &= (1 << bits) - 1; - } - if (bits > 0) text += ALPHABET[(buffer << (5 - bits)) & 31]; - return text; -} - -function base32Number(value: number): string { - let text = ''; - let rest = value; - do { - text = ALPHABET[rest % 32] + text; - rest = Math.floor(rest / 32); - } while (rest > 0); - return text; -} diff --git a/packages/local-service/src/downloadable-content/content-indexes.ts b/packages/local-service/src/downloadable-content/content-indexes.ts deleted file mode 100644 index ff24aef..0000000 --- a/packages/local-service/src/downloadable-content/content-indexes.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Downloadable skin and decal indexes served on the dldata CDN hosts. - * - * Why both indexes are served: - * - Startup waits up to 60 seconds per index before giving up (aces.exe 2.61.0.37 0xd3fa20, - * "webcache: downloadable ... index hasn't arrived yet"). - * - For decals, webdlcontent::getDecalsBlk (0xd41050) merges downloadable_decals..blk - * into sharedDecalsBlk (0xd47e20), overlays char.vromfs.bin config/decals.blk (0xd48380), - * and deletes any block lacking both lod0:t and a "*" managed texture (0xd415d6..0xd4183d). - * Populating downloadable_decals..blk from config/decals.blk + local DXP2 decal textures - * keeps all 1,598 Hangar Customization decals and Marketplace decal coupons active offline: - * 0xd44fc0 resolves "*?" via get_managed_texture_id (0x31aec00) directly to the local DXP - * texture without registering webcache HTTP downloads. - */ -import { emptyBlock, encodeBlk, type BlkBlock } from '@wto/blk'; -import { - makeDdsxDxt5HeaderBase64, - type DecalConfigEntry, - type DxpDecalTexture, -} from '../game-data/datasets/decal-textures.ts'; -import { contentHash } from './content-hash.ts'; - -export type IndexKind = 'skins' | 'decals'; - -export interface ContentIndex { - readonly kind: IndexKind; - readonly bytes: Uint8Array; - /** Names the file: downloadable_..blk (0xd3f43d, 0xd3f491). */ - readonly hash: string; -} - -/** Stock decals.dxp.bin built-in texture names and dimensions when no DXP pack is scanned. */ -const DEFAULT_SQUARE_TEX: DxpDecalTexture = { - name: 'star', - width: 512, - height: 512, - aspectRatio: 1, - ddsxHeaderBase64: makeDdsxDxt5HeaderBase64(512, 512), -}; - -const DEFAULT_WIDE_TEX: DxpDecalTexture = { - name: 'panther', - width: 512, - height: 256, - aspectRatio: 2, - ddsxHeaderBase64: makeDdsxDxt5HeaderBase64(512, 256), -}; - -const WIDE_ASPECT_THRESHOLD = 1.5; - -export function buildContentIndexes( - decals: readonly DecalConfigEntry[] = [], - localDxp: ReadonlyMap = new Map(), -): ReadonlyMap { - const skinsBytes = encodeBlk(emptyBlock()); - const decalsBytes = encodeBlk(decals.length > 0 ? buildDecalsIndexBlk(decals, localDxp) : emptyBlock()); - return new Map([ - ['skins', { kind: 'skins', bytes: skinsBytes, hash: contentHash(skinsBytes) }], - ['decals', { kind: 'decals', bytes: decalsBytes, hash: contentHash(decalsBytes) }], - ]); -} - -export function emptyContentIndexes(): ReadonlyMap { - return buildContentIndexes(); -} - -function buildDecalsIndexBlk( - decals: readonly DecalConfigEntry[], - localDxp: ReadonlyMap, -): BlkBlock { - const squareFallback = localDxp.get('star') ?? firstDxpTexture(localDxp) ?? DEFAULT_SQUARE_TEX; - const wideFallback = localDxp.get('panther') ?? widestDxpTexture(localDxp) ?? DEFAULT_WIDE_TEX; - return { - name: '', - params: [], - blocks: decals.map((entry) => { - const target = localDxp.get(entry.name.toLowerCase()) - ?? (entry.aspectRatio >= WIDE_ASPECT_THRESHOLD ? wideFallback : squareFallback); - return { - name: entry.name, - params: [ - { name: 'category', value: { type: 'string', value: '' } }, - { name: 'aspect_ratio', value: { type: 'real', value: entry.aspectRatio } }, - { name: 'hdr0', value: { type: 'string', value: target.ddsxHeaderBase64 } }, - { name: 'lod0', value: { type: 'string', value: target.name } }, - { name: 'hdr1', value: { type: 'string', value: target.ddsxHeaderBase64 } }, - { name: 'lod1', value: { type: 'string', value: target.name } }, - ], - blocks: [], - }; - }), - }; -} - -function firstDxpTexture(localDxp: ReadonlyMap): DxpDecalTexture | undefined { - return localDxp.values().next().value; -} - -function widestDxpTexture(localDxp: ReadonlyMap): DxpDecalTexture | undefined { - let best: DxpDecalTexture | undefined; - for (const candidate of localDxp.values()) { - if (!best || candidate.aspectRatio > best.aspectRatio) best = candidate; - } - return best; -} diff --git a/packages/local-service/src/downloadable-content/downloadable-content-service.ts b/packages/local-service/src/downloadable-content/downloadable-content-service.ts index 184bb8d..28848f3 100644 --- a/packages/local-service/src/downloadable-content/downloadable-content-service.ts +++ b/packages/local-service/src/downloadable-content/downloadable-content-service.ts @@ -1,61 +1,38 @@ /** - * Downloadable content (dldata): the list of the current skin and decal indexes, and the - * indexes themselves. + * Downloadable content (dldata): there is no CDN offline, so the index list and every file on + * the dldata hosts are answered with 404, each with a note in the traffic log. * - * - dldata_s.info, from the public-configs host (webdlcontent::init, aces.exe 2.61.0.37 - * 0xd3eb40, "%s/dldata_s.info"): a BLK whose strings "skin" and "decal" hold the content - * hashes of the two indexes (0xd3eed3..0xd3f2bd). - * - downloadable_skins..blk and downloadable_decals..blk, from the dldata hosts - * (network.blk skinsDecalsCDN, e.g. dldata-aws.warthunder.com/production/). The client - * checks size and SHA-1 against the hash (content-hash.ts). + * Where the client gets its decals instead (aces.exe 2.61.0.37; packages/build/src/decals/): + * - No player decal source: char.vromfs.bin holds dldata/downloadable_skins.blk and + * dldata/downloadable_decals.blk, the client loads them at init (0xd3bc40 -> 0xd3cc60) and + * never asks for dldata_s.info. + * - Player decal source: the player's web cache folder is copied to /cache/content; the + * client asks for dldata_s.info (webdlcontent::init 0xd3eb40, "%s/dldata_s.info"), and on + * failure reads its cached copy ("will fallback local copy"), whose indexes are then in the + * folder. Decal textures the cache lacks would be fetched from the dldata hosts + * (network.blk skinsDecalsCDN) and are not available. + * The client does not download the indexes themselves (0xd3e710 only looks in the cache + * folder), so serving them here would have no effect. */ -import { emptyBlock, encodeBlk, formatBlkText, setParam } from '@wto/blk'; -import { scanLocalDecalDxp, type DecalConfigEntry } from '../game-data/datasets/decal-textures.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; -import { buildContentIndexes, type ContentIndex, type IndexKind } from './content-indexes.ts'; const INFO_HOST = /^public-configs[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/; const INFO_PATH = /^\/[a-z0-9_-]+\/dldata_s\.info$/; -const INDEX_HOST = /^dldata[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/; -const INDEX_FILE = /\/downloadable_(skins|decals)\.([a-z2-7]{32}-[a-z2-7]{1,8})\.blk$/; - -const BINARY = { 'content-type': 'application/octet-stream' }; +const CONTENT_HOST = /^dldata[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/; export class DownloadableContentService implements Service { readonly name = 'dldata'; - readonly #indexes: ReadonlyMap; - readonly #decalCount: number; - readonly #info: { readonly bytes: Uint8Array; readonly text: string }; - - constructor(decals: readonly DecalConfigEntry[] = [], gameFolder?: string) { - this.#indexes = buildContentIndexes(decals, scanLocalDecalDxp(gameFolder)); - this.#decalCount = decals.length; - this.#info = this.#infoBlk(); - } accepts(request: ServiceRequest): boolean { const host = request.originalHost; if (host === undefined || request.method !== 'GET') return false; - return (INFO_HOST.test(host) && INFO_PATH.test(request.path)) || (INDEX_HOST.test(host) && INDEX_FILE.test(request.path)); + return (INFO_HOST.test(host) && INFO_PATH.test(request.path)) || CONTENT_HOST.test(host); } handle(request: ServiceRequest): ServiceResponse { - if (INFO_PATH.test(request.path)) { - return { status: 200, headers: BINARY, body: this.#info.bytes, logNotes: { summary: 'dldata_s.info', responseText: this.#info.text } }; - } - const match = INDEX_FILE.exec(request.path); - const index = match ? this.#indexes.get(match[1] as ContentIndex['kind']) : undefined; - if (!index || index.hash !== match?.[2]) { - return { status: 404, body: 'unknown index', logNotes: { summary: `index ${request.path}: not one this service listed` } }; - } - const detail = index.kind === 'decals' && this.#decalCount > 0 ? `${this.#decalCount} decals` : 'empty'; - return { status: 200, headers: BINARY, body: index.bytes, logNotes: { summary: `downloadable_${index.kind} (${detail})` } }; - } - - #infoBlk(): { readonly bytes: Uint8Array; readonly text: string } { - const info = emptyBlock(); - setParam(info, 'skin', { type: 'string', value: this.#indexes.get('skins')!.hash }); - setParam(info, 'decal', { type: 'string', value: this.#indexes.get('decals')!.hash }); - return { bytes: encodeBlk(info), text: formatBlkText(info) }; + const summary = INFO_PATH.test(request.path) + ? 'dldata_s.info: no CDN offline, the client falls back to its cached copy' + : `${request.path}: no CDN offline`; + return { status: 404, body: 'not available offline', logNotes: { summary } }; } } diff --git a/packages/local-service/src/game-data/datasets/decal-textures.ts b/packages/local-service/src/game-data/datasets/decal-textures.ts deleted file mode 100644 index f398e4e..0000000 --- a/packages/local-service/src/game-data/datasets/decal-textures.ts +++ /dev/null @@ -1,198 +0,0 @@ -/** - * Dataset and local DXP2 scanner for Hangar and Marketplace decals. - * - * Why this exists: - * - char.vromfs.bin config/decals.blk lists all stock and marketplace decals (1,598 blocks) - * with category, group, costGold, unlock, marketplaceItemdefId, and aspect_ratio, but omits - * lod0 / lod1 texture fields because the online client merges downloadable_decals..blk - * into sharedDecalsBlk first (aces.exe 2.61.0.37 0xd41050 -> 0xd47e20 -> 0xd48380). - * - In webdlcontent::getDecalsBlk (0xd415d6..0xd4183d), any decal block without a lod0 string - * and without a local managed texture "*" (get_managed_texture_id, 0x31aec00) is - * deleted from sharedDecalsBlk ("failed to find texture for decal '%s', skipping it"). - * - Stock client installations only ship built-in decal textures in content/base/res/decals.dxp.bin - * (DxP2 v2 pack: lang, panther, star). Extracting the decal list via DatasetCache and scanning - * any local *decal*.dxp.bin headers lets DownloadableContentService populate every decal block - * with valid lod0/lod1 and 32-byte DDSx headers without outbound CDN requests. - */ -import { closeSync, existsSync, openSync, readdirSync, readSync } from 'node:fs'; -import { join } from 'node:path'; -import { numberField } from './blk-fields.ts'; -import type { Dataset } from './dataset.ts'; - -const DECALS_CONFIG_PATH = 'config/decals.blk'; - -/** DxP2 v2 pack header constants (verified on content/base/res/decals.dxp.bin). */ -const DXP2_MAGIC = 0x32507844; // "DxP2" -const DXP2_VERSION = 2; -const DXP2_PREAMBLE_BYTES = 0x10; -const DXP2_MAX_HEADER_BYTES = 4 * 1024 * 1024; - -/** Dagor ddsx::Header binary layout constants (32 bytes, verified at aces.exe 0xd49e00). */ -const DDSX_HEADER_BYTES = 32; -const DDSX_MAGIC = 0x78534444; // "DDSx" -const DDSX_DXT5_FOURCC = 0x35545844; // "DXT5" -const DDSX_COMPRESSION_MASK = 0x0fffffff; -const DDSX_UNPACKED_DECAL_FLAGS = 0x00000044; -const DDSX_DECAL_QUALITY_WORD = 0x7401; -const DXT5_BLOCK_BYTES = 16; - -export interface DecalConfigEntry { - readonly name: string; - readonly aspectRatio: number; -} - -export interface DxpDecalTexture { - readonly name: string; - readonly width: number; - readonly height: number; - readonly aspectRatio: number; - /** Base64-encoded 32-byte unpacked ddsx::Header expected in hdr0 / hdr1 (0xd49e00). */ - readonly ddsxHeaderBase64: string; -} - -export const decalTextures: Dataset = { - id: 'decal-textures', - version: 1, - extract: (source) => - source.readBlk('char.vromfs.bin', DECALS_CONFIG_PATH).blocks.map((entry) => { - const ratio = numberField(entry, 'aspect_ratio'); - return { - name: entry.name, - aspectRatio: ratio !== undefined && Number.isFinite(ratio) && ratio > 0 ? ratio : 1, - }; - }), -}; - -/** Scan local *decal*.dxp.bin headers inside the game folder, keyed by lowercase texture name. */ -export function scanLocalDecalDxp(gameFolder?: string): ReadonlyMap { - const found = new Map(); - if (!gameFolder || !existsSync(gameFolder)) return found; - for (const dxpPath of candidateDecalDxpPaths(gameFolder)) { - for (const entry of readDxp2DecalHeaders(dxpPath)) { - const key = entry.name.toLowerCase(); - if (!found.has(key)) found.set(key, entry); - } - } - return found; -} - -/** Synthesize a 32-byte Dagor DXT5 ddsx::Header (base64) matching downloadable_decals.blk. */ -export function makeDdsxDxt5HeaderBase64(width: number, height: number): string { - const header = Buffer.alloc(DDSX_HEADER_BYTES); - header.writeUInt32LE(DDSX_MAGIC, 0); - header.writeUInt32LE(DDSX_DXT5_FOURCC, 4); - header.writeUInt32LE(DDSX_UNPACKED_DECAL_FLAGS, 8); - header.writeUInt16LE(width, 12); - header.writeUInt16LE(height, 14); - const { levels, memSize } = dxt5MipChainSize(width, height); - header[16] = levels; - header.writeUInt16LE(DDSX_DECAL_QUALITY_WORD, 22); - header.writeUInt32LE(memSize, 24); - return header.toString('base64'); -} - -function dxt5MipChainSize(width: number, height: number): { readonly levels: number; readonly memSize: number } { - let w = Math.max(1, Math.trunc(width)); - let h = Math.max(1, Math.trunc(height)); - let levels = 0; - let memSize = 0; - for (;;) { - levels += 1; - memSize += Math.max(1, Math.ceil(w / 4)) * Math.max(1, Math.ceil(h / 4)) * DXT5_BLOCK_BYTES; - if (w === 1 && h === 1) break; - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - return { levels, memSize }; -} - -function candidateDecalDxpPaths(gameFolder: string): string[] { - const paths = new Set(); - const addResFolder = (resFolder: string): void => { - if (!existsSync(resFolder)) return; - try { - for (const item of readdirSync(resFolder, { withFileTypes: true })) { - if (item.isFile() && /decal.*\.dxp\.bin$/i.test(item.name)) paths.add(join(resFolder, item.name)); - } - } catch { /* unreadable optional pack folder */ } - }; - addResFolder(join(gameFolder, 'res')); - addResFolder(join(gameFolder, 'content', 'base', 'res')); - const contentRoot = join(gameFolder, 'content'); - if (existsSync(contentRoot)) { - try { - for (const pkg of readdirSync(contentRoot, { withFileTypes: true })) { - if (pkg.isDirectory() && pkg.name !== 'base') addResFolder(join(contentRoot, pkg.name, 'res')); - } - } catch { /* unreadable optional content root */ } - } - return [...paths]; -} - -function readDxp2DecalHeaders(dxpPath: string): DxpDecalTexture[] { - const headerBuf = readDxp2HeaderSlice(dxpPath); - if (!headerBuf) return []; - const count = headerBuf.readUInt32LE(0x08); - const namesTable = DXP2_PREAMBLE_BYTES + headerBuf.readUInt32LE(0x10); - const ddsxTable = DXP2_PREAMBLE_BYTES + headerBuf.readUInt32LE(0x20); - if (namesTable + count * 8 > headerBuf.length || ddsxTable + count * DDSX_HEADER_BYTES > headerBuf.length) { - return []; - } - const textures: DxpDecalTexture[] = []; - for (let i = 0; i < count; i++) { - const nameOffset = DXP2_PREAMBLE_BYTES + Number(headerBuf.readBigUInt64LE(namesTable + i * 8)); - const rawName = readNullTerminatedAscii(headerBuf, nameOffset); - const starIndex = rawName.indexOf('*'); - const cleanName = (starIndex >= 0 ? rawName.slice(0, starIndex) : rawName).trim(); - const ddsxSlice = headerBuf.subarray(ddsxTable + i * DDSX_HEADER_BYTES, ddsxTable + (i + 1) * DDSX_HEADER_BYTES); - if (!cleanName || ddsxSlice.readUInt32LE(0) !== DDSX_MAGIC) continue; - const width = ddsxSlice.readUInt16LE(12); - const height = ddsxSlice.readUInt16LE(14); - if (width === 0 || height === 0) continue; - textures.push({ - name: cleanName, - width, - height, - aspectRatio: width / height, - ddsxHeaderBase64: normalizeDdsxHeader(ddsxSlice), - }); - } - return textures; -} - -function readDxp2HeaderSlice(dxpPath: string): Buffer | undefined { - let fd: number | undefined; - try { - fd = openSync(dxpPath, 'r'); - const preamble = Buffer.alloc(DXP2_PREAMBLE_BYTES); - if (readSync(fd, preamble, 0, DXP2_PREAMBLE_BYTES, 0) < DXP2_PREAMBLE_BYTES) return undefined; - if (preamble.readUInt32LE(0) !== DXP2_MAGIC || preamble.readUInt32LE(4) !== DXP2_VERSION) return undefined; - const hdrSize = preamble.readUInt32LE(0x0c); - if (hdrSize === 0 || hdrSize > DXP2_MAX_HEADER_BYTES) return undefined; - const total = DXP2_PREAMBLE_BYTES + hdrSize; - const full = Buffer.alloc(total); - preamble.copy(full, 0); - if (readSync(fd, full, DXP2_PREAMBLE_BYTES, hdrSize, DXP2_PREAMBLE_BYTES) < hdrSize) return undefined; - return full; - } catch { - return undefined; - } finally { - if (fd !== undefined) { - try { closeSync(fd); } catch { /* ignore close failure */ } - } - } -} - -function normalizeDdsxHeader(rawHeader: Uint8Array): string { - const unpacked = Buffer.from(rawHeader); - unpacked.writeUInt32LE(unpacked.readUInt32LE(8) & DDSX_COMPRESSION_MASK, 8); - unpacked.writeUInt32LE(0, 28); - return unpacked.toString('base64'); -} - -function readNullTerminatedAscii(buffer: Buffer, offset: number): string { - if (offset < 0 || offset >= buffer.length) return ''; - let end = offset; - while (end < buffer.length && buffer[end] !== 0) end += 1; - return buffer.subarray(offset, end).toString('ascii'); -} diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index e7d1a7c..9566633 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -24,7 +24,6 @@ import { BattleLiveLogs } from './battle/battle-live-log.ts'; import { clanEconomy } from './game-data/datasets/clan-economy.ts'; import { crewSkillData } from './game-data/datasets/crew-skills.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; -import { decalTextures } from './game-data/datasets/decal-textures.ts'; import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts'; import { externalItemSources } from './game-data/datasets/external-item-sources.ts'; import { itemCatalogue } from './game-data/datasets/item-catalogue.ts'; @@ -92,7 +91,6 @@ export async function startLocalService(options: LocalServiceOptions): Promise