#!/usr/bin/env node /** * Bake the 27 workbench matcaps into raw half-float blobs the browser can bind. * * The source art is 512x512 half-float OpenEXR compressed with DWA. Nothing in * the web app can decode EXR: `createImageBitmap` rejects it, * `web/protocol/render-assets.ts:63-65` refuses the mime type, and the vendored * three has no RGBELoader. Rather than ship a DWA decoder we convert at build * time with `oiiotool` (OpenImageIO 2.4.17 / OpenEXR 3.1.5 on this machine) and * emit plain half-float RGB, which `DataTexture(HalfFloatType)` binds directly. * * Layer split follows the desktop: `studiolight.cc:326-349` takes the layer * literally named `diffuse` as diffuse and `specular` as specular — it is a * name match, not channel arithmetic. * * Output format, little-endian: * bytes 0..7 magic "WBMATCAP" * uint32 width * uint32 height * uint32 flags bit 0 = a specular layer is present * half[3]*w*h diffuse * half[3]*w*h specular (present only when bit 0 is set) */ import { execFileSync } from "node:child_process"; import { mkdir, readFile, readdir, writeFile, unlink } from "node:fs/promises"; import path from "node:path"; import os from "node:os"; const ROOT = "/home/mes123456/workinf_Blender_Wasm"; const SOURCE_DIR = path.join(ROOT, "blender-5.2.0/release/datafiles/studiolights/matcap"); const OUTPUT_DIR = path.join(ROOT, "web/app/public/assets/studiolights/matcap"); const SIZE = 256; const MAGIC = Buffer.from("WBMATCAP", "ascii"); const oiio = (...args) => { try { return execFileSync("oiiotool", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); } catch (error) { throw new Error(`oiiotool ${args.join(" ")} failed: ${error.stderr ?? error.message}`); } }; /** Reads the `channel list:` line so a non-multilayer matcap can be detected. */ function channelNames(file) { const info = oiio("--info", "-v", file); const line = info.split("\n").find((entry) => entry.includes("channel list:")); return line ? line.split("channel list:")[1].split(",").map((name) => name.trim()) : []; } /** * Converts one EXR to an uncompressed half-float scanline EXR and returns the * raw pixels. Uncompressed scanline blocks are fixed-size and in y order, so the * only thing we have to parse is the v2 int64 offset table. */ async function readHalfRgb(source, channels, workDir, tag) { const target = path.join(workDir, `${tag}.exr`); oiio(source, "--ch", channels.join(","), "--resize", `${SIZE}x${SIZE}`, "-d", "half", "--compression", "none", "--noautocc", "-o", target); const buffer = await readFile(target); await unlink(target); if (buffer.readUInt32LE(0) !== 0x01312f76) throw new Error(`${tag}: not an EXR`); const version = buffer.readUInt32LE(4); if (version & 0x200) throw new Error(`${tag}: tiled EXR is not supported`); /* Walk the header attribute list to find the terminator. */ let cursor = 8; let dataWindow = null; let channelCount = 0; for (;;) { if (buffer[cursor] === 0) { cursor += 1; break; } const nameEnd = buffer.indexOf(0, cursor); const name = buffer.toString("ascii", cursor, nameEnd); const typeEnd = buffer.indexOf(0, nameEnd + 1); const type = buffer.toString("ascii", nameEnd + 1, typeEnd); const size = buffer.readInt32LE(typeEnd + 1); const valueAt = typeEnd + 5; if (name === "dataWindow") { dataWindow = [ buffer.readInt32LE(valueAt), buffer.readInt32LE(valueAt + 4), buffer.readInt32LE(valueAt + 8), buffer.readInt32LE(valueAt + 12), ]; } if (name === "channels") { /* chlist entries are null-terminated names; count them by scanning. */ let at = valueAt; channelCount = 0; while (buffer[at] !== 0) { at = buffer.indexOf(0, at) + 1; at += 16; /* pixelType + pLinear + 3 reserved + xSampling + ySampling */ channelCount += 1; } } cursor = valueAt + size; } if (!dataWindow) throw new Error(`${tag}: no dataWindow`); const width = dataWindow[2] - dataWindow[0] + 1; const height = dataWindow[3] - dataWindow[1] + 1; const rowBytes = width * channelCount * 2; const offsets = []; for (let index = 0; index < height; index += 1) { offsets.push(Number(buffer.readBigUInt64LE(cursor + index * 8))); } const out = Buffer.alloc(width * height * 3 * 2); for (let y = 0; y < height; y += 1) { const blockStart = offsets[y]; const blockSize = buffer.readInt32LE(blockStart + 4); if (blockSize !== rowBytes) { throw new Error(`${tag}: row ${y} is ${blockSize} bytes, expected ${rowBytes}`); } buffer.copy(out, y * width * 3 * 2, blockStart + 8, blockStart + 8 + rowBytes); } return { width, height, pixels: out }; } await mkdir(OUTPUT_DIR, { recursive: true }); const workDir = await mkdir(`${os.tmpdir()}/wbmc-${process.pid}`, { recursive: true }); const files = (await readdir(SOURCE_DIR)).filter((name) => name.endsWith(".exr")).sort(); let total = 0; for (const file of files) { const source = path.join(SOURCE_DIR, file); const names = channelNames(source); const hasLayers = names.some((name) => name.startsWith("diffuse.")); const stem = path.basename(file, ".exr"); /* Multilayer matcaps carry `diffuse.*` + `specular.*`. A single-layer file * (check_normal+y.exr) falls back to its plain R/G/B channels and gets no * specular layer, matching studiolight.cc:404-416. */ const diffuseChannels = hasLayers ? ["diffuse.R", "diffuse.G", "diffuse.B"] : ["R", "G", "B"].filter((name) => names.includes(name)); if (diffuseChannels.length !== 3) { throw new Error(`${file}: cannot find three diffuse channels in ${names.join(",")}`); } const specularChannels = hasLayers && names.includes("specular.R") ? ["specular.R", "specular.G", "specular.B"] : null; const diffuse = await readHalfRgb(source, diffuseChannels, workDir, `${stem}-d`); let specular = null; if (specularChannels) { specular = await readHalfRgb(source, specularChannels, workDir, `${stem}-s`); } const header = Buffer.alloc(20); MAGIC.copy(header, 0); header.writeUInt32LE(diffuse.width, 8); header.writeUInt32LE(diffuse.height, 12); header.writeUInt32LE(specular ? 1 : 0, 16); const payload = specular ? Buffer.concat([diffuse.pixels, specular.pixels]) : diffuse.pixels; const target = path.join(OUTPUT_DIR, `${stem}.bin`); await writeFile(target, Buffer.concat([header, payload])); total += 20 + payload.length; console.log(`${stem}.bin ${diffuse.width}x${diffuse.height} ${specular ? "diffuse+specular" : "diffuse only"} ${(payload.length / 1024).toFixed(0)} KB`); } await unlink(workDir).catch(() => {}); console.log(`\n${files.length} matcaps, ${(total / 1048576).toFixed(1)} MB total`);