@needle-tools/gltf-build-pipeline 3.0.0-next.47d9f08 → 3.0.0-next.73f1606
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +13 -1
- package/dist/cli/index.js +104 -52
- package/package.json +1 -1
- package/tools/pmrem/pkg/pmrem_wasm.d.ts +25 -0
- package/tools/pmrem/pkg/pmrem_wasm.js +110 -0
- package/tools/pmrem/pkg/pmrem_wasm_bg.wasm +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,31 @@ All notable changes to this package will be documented in this file.
|
|
|
4
4
|
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
|
|
5
5
|
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
+
## [3.0.0-alpha] - 2026-05-26
|
|
8
|
+
|
|
9
|
+
### Breaking
|
|
10
|
+
- CLI now requires JWT authentication via `--auth-token`
|
|
11
|
+
- The package ships as a CLI-only right now
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
- **Job cache**: file-level cache that skips an entire transform when the same input + config was already processed
|
|
15
|
+
- **Audio compression**: external audio references are re-encoded to Opus/OGG; supported input formats are WAV, FLAC, and AIFF (lossy formats pass through unchanged)
|
|
16
|
+
- **PMREM standalone CLI command**: `needle-gltf pmrem <input>` converts EXR and Radiance HDR files to PMREM KTX2
|
|
17
|
+
- **Multiple file inputs**: `transform` now accepts comma-separated paths (e.g. `needle-gltf transform a.glb,b.glb out/`)
|
|
18
|
+
- Auth surfaces clean "token expired" message when the JWT `exp` claim is past
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
- Cache restore now also restores external files (KTX2, PMREM) alongside the main GLB
|
|
22
|
+
- PMREM NaN generation that caused artifacts in certain EXR files
|
|
23
|
+
- xxHash WASM init race condition, now resolved with `ensureHashReady` gate
|
|
24
|
+
- LOD file detection no longer matches against directory names
|
|
25
|
+
- toktx: probes `ktx` binary to match what the compression step actually runs
|
|
26
|
+
- `getConfig` now returns a fresh copy instead of a shared mutable reference
|
|
27
|
+
- `stats` tolerates undefined errors/warnings in `addFrom`
|
|
28
|
+
- Material-only GLBs are no longer incorrectly pruned
|
|
29
|
+
- `createOpaqueExtension` return type fixed, downstream casts removed
|
|
30
|
+
- `stats` command exits with code 0
|
|
31
|
+
|
|
7
32
|
## [2.15.0] - 2026-03-20
|
|
8
33
|
- add: EXR environment map compression (PMREM / FASTHDR) for Needle Engine, supporting both Unity and Blender exports
|
|
9
34
|
- fix: cache hashing stability (circular reference handling)
|
package/README.md
CHANGED
|
@@ -26,6 +26,18 @@ To load progressively enhanced glTF files in Needle Engine or another three.js b
|
|
|
26
26
|
### Commands
|
|
27
27
|
- `help` - use help to view options
|
|
28
28
|
|
|
29
|
+
### Platform support
|
|
30
|
+
|
|
31
|
+
The bundled `basisu` encoder (used for HDR / EXR → KTX2 HDR) supports:
|
|
32
|
+
|
|
33
|
+
| OS | Arch | Status |
|
|
34
|
+
|---------|-----------------------|--------|
|
|
35
|
+
| Linux | x64 | Supported |
|
|
36
|
+
| Linux | arm64 | Not supported |
|
|
37
|
+
| macOS | arm64 (Apple Silicon) | Supported |
|
|
38
|
+
| macOS | x64 (Intel) | Not supported |
|
|
39
|
+
| Windows | x64 | Supported |
|
|
40
|
+
|
|
29
41
|
### Configuration
|
|
30
42
|
|
|
31
43
|
The pipeline reads an optional `needle.config.json` from the working directory (or any parent directory). Configure pipeline behaviour under the `gltf` key:
|
|
@@ -49,7 +61,7 @@ The `gltf` value may also be a string shorthand for `usecase` — `"gltf": "prod
|
|
|
49
61
|
| `usecase` | `"default" \| "product" \| "world"` | `"default"` | High-level optimisation profile. |
|
|
50
62
|
| `textures.lods` | `boolean` | `true` | Generate progressive texture LODs. |
|
|
51
63
|
| `meshes.lods` | `boolean` | `true` | Generate progressive mesh LODs. |
|
|
52
|
-
| `audio.enabled` | `boolean` | `true` | Compress externally referenced
|
|
64
|
+
| `audio.enabled` | `boolean` | `true` | Compress externally referenced lossless audio files (`.wav`, `.flac`, `.aiff`/`.aif`) to Opus in an `.ogg` container, rewriting the URIs in the glTF. Lossy formats (`.mp3`, `.ogg`, `.m4a`, `.aac`) pass through unchanged to avoid compounding compression artifacts. Requires `ffmpeg` with `libopus` on `PATH`; when missing the build logs a warning and leaves the audio files untouched. |
|
|
53
65
|
| `audio.bitrate` | `number` (kbps) | `128` | Opus encoding bitrate. 96 is near-transparent for most music; 128 matches YouTube's music tier and is the safe "won't sound bad" default. Drop to 48–64 for known mono/UI-only assets. |
|
|
54
66
|
| `exr.enabled` | `boolean` | `true` | Convert EXR textures to KTX2 HDR via PMREM. When `false`, EXR textures (bundled and externally referenced) are left as-is so a downstream step can handle them. |
|
|
55
67
|
|
package/dist/cli/index.js
CHANGED
|
@@ -138,7 +138,7 @@ function listAudioRefs() {
|
|
|
138
138
|
function clearAudioRegistry() {
|
|
139
139
|
_refs = [];
|
|
140
140
|
}
|
|
141
|
-
var AUDIO_EXTENSIONS = [".wav"], _audioRegex = new RegExp(`(${AUDIO_EXTENSIONS.map((e) => "\\" + e).join("|")})$`, "i");
|
|
141
|
+
var AUDIO_EXTENSIONS = [".wav", ".flac", ".aiff", ".aif"], _audioRegex = new RegExp(`(${AUDIO_EXTENSIONS.map((e) => "\\" + e).join("|")})$`, "i");
|
|
142
142
|
function isAudioUri(value) {
|
|
143
143
|
return _audioRegex.test(value);
|
|
144
144
|
}
|
|
@@ -1190,7 +1190,7 @@ function registerExtensions(node) {
|
|
|
1190
1190
|
import { createTransform } from "@gltf-transform/functions";
|
|
1191
1191
|
|
|
1192
1192
|
// src/utils/version.gen.ts
|
|
1193
|
-
var version = "3.0.0-next.
|
|
1193
|
+
var version = "3.0.0-next.73f1606";
|
|
1194
1194
|
|
|
1195
1195
|
// src/utils/version.ts
|
|
1196
1196
|
function getVersion(_marklocal = !0) {
|
|
@@ -1406,6 +1406,11 @@ function getFileName(filepath) {
|
|
|
1406
1406
|
let parts = filepath.replaceAll("\\", "/").split("/");
|
|
1407
1407
|
return parts[parts.length - 1];
|
|
1408
1408
|
}
|
|
1409
|
+
function parseInputPaths(raw) {
|
|
1410
|
+
if (!raw.includes(",")) return [raw];
|
|
1411
|
+
let segments = raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
1412
|
+
return segments.length < 2 ? [raw] : !segments.some((s) => existsSync3(s)) && existsSync3(raw) ? [raw] : segments;
|
|
1413
|
+
}
|
|
1409
1414
|
async function foreachGLTF(args, callback) {
|
|
1410
1415
|
let initDir = process.env.INIT_CWD, context = {
|
|
1411
1416
|
baseDirectory: initDir,
|
|
@@ -3231,16 +3236,22 @@ async function createPmremRuntime(logger) {
|
|
|
3231
3236
|
async function disposePmremRuntime(runtime) {
|
|
3232
3237
|
runtime?.tmpDir && await safeRmDir(runtime.tmpDir);
|
|
3233
3238
|
}
|
|
3234
|
-
|
|
3235
|
-
|
|
3239
|
+
function convertExrBytesToPmremKtx2(runtime, exrBytes, opts = {}) {
|
|
3240
|
+
return convertBytesToPmremKtx2(runtime, exrBytes, "exr", opts);
|
|
3241
|
+
}
|
|
3242
|
+
function convertHdrBytesToPmremKtx2(runtime, hdrBytes, opts = {}) {
|
|
3243
|
+
return convertBytesToPmremKtx2(runtime, hdrBytes, "hdr", opts);
|
|
3244
|
+
}
|
|
3245
|
+
async function convertBytesToPmremKtx2(runtime, inputBytes, kind, opts = {}) {
|
|
3246
|
+
let useCache = opts.useCache !== !1, label = opts.logLabel ?? "pmrem", logger = runtime.logger, contentHash = createHash("md5").update(inputBytes).digest("hex"), cacheKey = kind === "hdr" ? `pmrem-hdr-${contentHash}` : `pmrem-${contentHash}`;
|
|
3236
3247
|
if (useCache) {
|
|
3237
3248
|
let cached = tryGetFromCache(cacheKey);
|
|
3238
3249
|
if (cached && cached.length > 0)
|
|
3239
3250
|
return logger.debug(`${label}: loaded from cache`), cached;
|
|
3240
3251
|
}
|
|
3241
|
-
let inputSize =
|
|
3242
|
-
logger.debug(`${label}: Running PMREM WASM (${inputSize}
|
|
3243
|
-
let t0 = Date.now(), pmremExrBytes = runtime.wasmModule.pmrem_exr(
|
|
3252
|
+
let inputSize = inputBytes.byteLength < 100 * 1024 ? `${(inputBytes.byteLength / 1024).toFixed(0)} KB` : `${(inputBytes.byteLength / (1024 * 1024)).toFixed(2)} MB`, sourceLabel = kind === "hdr" ? "HDR" : "EXR";
|
|
3253
|
+
logger.debug(`${label}: Running PMREM WASM (${inputSize} ${sourceLabel}) \u2014 this may take a while...`), await new Promise((r) => setTimeout(r, 0));
|
|
3254
|
+
let t0 = Date.now(), pmremExrBytes = (kind === "hdr" ? runtime.wasmModule.pmrem_hdr : runtime.wasmModule.pmrem_exr)(inputBytes), elapsed = ((Date.now() - t0) / 1e3).toFixed(1);
|
|
3244
3255
|
logger.debug(`${label}: PMREM done in ${elapsed}s (${(pmremExrBytes.byteLength / 1024 / 1024).toFixed(1)} MB)`);
|
|
3245
3256
|
let id = uuid3(), tempExr = join5(runtime.tmpDir, `${id}.pmrem.exr`), tempKtx2 = join5(runtime.tmpDir, `${id}.ktx2`);
|
|
3246
3257
|
if (writeFileSync4(tempExr, Buffer.from(pmremExrBytes)), logger.debug(`${label}: Encoding KTX2 HDR...`), await encodeKTX2WithBasisu(runtime.basisuExe, tempExr, tempKtx2, "hdr4x4", !0), !existsSync8(tempKtx2))
|
|
@@ -3890,7 +3901,7 @@ function trackPipelineEnd(info) {
|
|
|
3890
3901
|
}
|
|
3891
3902
|
|
|
3892
3903
|
// src/auth/verify.ts
|
|
3893
|
-
import { jwtVerify, importJWK } from "jose";
|
|
3904
|
+
import { jwtVerify, importJWK, decodeProtectedHeader } from "jose";
|
|
3894
3905
|
|
|
3895
3906
|
// src/auth/keys.ts
|
|
3896
3907
|
var PROD_KEYS = [
|
|
@@ -3915,38 +3926,72 @@ var AuthError = class extends Error {
|
|
|
3915
3926
|
constructor(message) {
|
|
3916
3927
|
super(message), this.name = "AuthError";
|
|
3917
3928
|
}
|
|
3918
|
-
};
|
|
3929
|
+
}, LOCAL_FETCH_TIMEOUT_MS = 2e3;
|
|
3930
|
+
async function tryFetchLocalToken(org) {
|
|
3931
|
+
try {
|
|
3932
|
+
let baseUrl = process.env.NEEDLE_LICENSE_SERVER_URL || "http://localhost:8424/api/license", url = new URL(baseUrl);
|
|
3933
|
+
org && url.searchParams.set("org", org);
|
|
3934
|
+
let res = await fetch(url, {
|
|
3935
|
+
signal: AbortSignal.timeout(LOCAL_FETCH_TIMEOUT_MS)
|
|
3936
|
+
});
|
|
3937
|
+
if (!res.ok) return null;
|
|
3938
|
+
let jwt = (await res.json()).needle_license_jwt;
|
|
3939
|
+
return typeof jwt == "string" && jwt.length > 0 ? jwt : null;
|
|
3940
|
+
} catch {
|
|
3941
|
+
return null;
|
|
3942
|
+
}
|
|
3943
|
+
}
|
|
3944
|
+
async function verifyWithKey(token, key) {
|
|
3945
|
+
if (!key.alg) throw new AuthError(`trusted key '${key.kid ?? "?"}' is missing 'alg'`);
|
|
3946
|
+
let keyObj = await importJWK(key, key.alg);
|
|
3947
|
+
await jwtVerify(token, keyObj);
|
|
3948
|
+
}
|
|
3919
3949
|
async function verifyAuthToken(token) {
|
|
3920
3950
|
if (!token)
|
|
3921
3951
|
throw new AuthError("no token provided");
|
|
3952
|
+
if (token.startsWith("nc_"))
|
|
3953
|
+
throw new AuthError("NEEDLE_CLOUD_TOKEN is a needle-cloud access token (nc_*), not a JWT.");
|
|
3922
3954
|
try {
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
throw new AuthError("token header missing 'kid'");
|
|
3955
|
+
let header = decodeProtectedHeader(token);
|
|
3956
|
+
if (header.kid) {
|
|
3926
3957
|
let match = TRUSTED_KEYS.find((k) => k.kid === header.kid);
|
|
3927
3958
|
if (!match)
|
|
3928
3959
|
throw new AuthError(`token signed by unknown key '${header.kid}'`);
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3960
|
+
await verifyWithKey(token, match);
|
|
3961
|
+
} else {
|
|
3962
|
+
let lastError = null;
|
|
3963
|
+
for (let key of TRUSTED_KEYS)
|
|
3964
|
+
try {
|
|
3965
|
+
await verifyWithKey(token, key);
|
|
3966
|
+
return;
|
|
3967
|
+
} catch (err) {
|
|
3968
|
+
lastError = err;
|
|
3969
|
+
}
|
|
3970
|
+
if (lastError instanceof AuthError) throw lastError;
|
|
3971
|
+
let message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
3972
|
+
throw new AuthError(message || "no trusted key could verify this token");
|
|
3973
|
+
}
|
|
3933
3974
|
} catch (err) {
|
|
3934
3975
|
if (err instanceof AuthError) throw err;
|
|
3976
|
+
if (err && typeof err == "object" && "code" in err && err.code === "ERR_JWT_EXPIRED")
|
|
3977
|
+
throw new AuthError("token expired");
|
|
3935
3978
|
let message = err instanceof Error ? err.message : String(err);
|
|
3936
3979
|
throw new AuthError(message);
|
|
3937
3980
|
}
|
|
3938
3981
|
}
|
|
3939
|
-
async function requireAuth(cliToken) {
|
|
3982
|
+
async function requireAuth(cliToken, org) {
|
|
3940
3983
|
let token = typeof cliToken == "string" && cliToken.length > 0 ? cliToken : process.env.NEEDLE_CLOUD_TOKEN;
|
|
3941
|
-
if (!token)
|
|
3942
|
-
throw new AuthError(
|
|
3984
|
+
if ((!token || typeof token == "string" && token.length === 0) && (token = await tryFetchLocalToken(org ?? process.env.NEEDLE_CLOUD_ORG)), !token)
|
|
3985
|
+
throw new AuthError(
|
|
3986
|
+
"No valid auth token found. Provide one via --auth-token, NEEDLE_CLOUD_TOKEN env, or log in to the needle-cloud CLI (npx needle-cloud@version-1 start --restart). If you are logged in but still see this error, try updating: npx needle-cloud@version-1 start --restart"
|
|
3987
|
+
);
|
|
3943
3988
|
await verifyAuthToken(token);
|
|
3944
3989
|
}
|
|
3945
3990
|
|
|
3946
3991
|
// src/cli/index.ts
|
|
3947
|
-
async function gateAuth(authToken, logger) {
|
|
3992
|
+
async function gateAuth(authToken, org, logger) {
|
|
3948
3993
|
try {
|
|
3949
|
-
await requireAuth(authToken);
|
|
3994
|
+
await requireAuth(authToken, typeof org == "string" ? org : void 0);
|
|
3950
3995
|
} catch (err) {
|
|
3951
3996
|
let message = err instanceof AuthError || err instanceof Error ? err.message : String(err);
|
|
3952
3997
|
logger.error(`[Needle Build Pipeline] Auth failed: ${message}`), process.exit(ERROR_CODES.AUTH_FAILED);
|
|
@@ -3960,8 +4005,8 @@ Caches are limited to ${cacheSizeLimit} MB disc space by default.
|
|
|
3960
4005
|
`).action(async ({ logger }) => {
|
|
3961
4006
|
logger.info("Clearing caches"), clearCache(logger);
|
|
3962
4007
|
}).command("stats", "Calculate glTF stats").help(`
|
|
3963
|
-
`).argument("<input>", "Path to a glTF, GLB or VRM file OR a directory").argument("<output>", "Output path for the stats", { default: null, validator: program.STRING }).option("--verbose", "Enable verbose output", { validator: program.BOOLEAN, default: !1 }).option("--auth-token <
|
|
3964
|
-
await gateAuth(options.authToken, logger), logger.level = options.verbose ? "debug" : "info", await ensureHashReady(), logger.info('Calculating stats for "' + args.input + '"');
|
|
4008
|
+
`).argument("<input>", "Path to a glTF, GLB or VRM file OR a directory").argument("<output>", "Output path for the stats", { default: null, validator: program.STRING }).option("--verbose", "Enable verbose output", { validator: program.BOOLEAN, default: !1 }).option("--auth-token <jwt>", "Required. A JWT minted by needle-cloud (alternatively set NEEDLE_CLOUD_TOKEN). Note: an `nc_*` needle-cloud access token is NOT a JWT and will be rejected.", { validator: program.STRING }).option("--org <org>", "Organization ID for local license-server fallback (or set NEEDLE_CLOUD_ORG).", { validator: program.STRING }).action(async ({ logger, args, options }) => {
|
|
4009
|
+
await gateAuth(options.authToken, options.org, logger), logger.level = options.verbose ? "debug" : "info", await ensureHashReady(), logger.info('Calculating stats for "' + args.input + '"');
|
|
3965
4010
|
let input = args.input.toString(), filestats = new Array();
|
|
3966
4011
|
await foreachGLTF(input, async (file) => {
|
|
3967
4012
|
let stats = await calculateStats(file, { verbose: !!options.verbose });
|
|
@@ -3972,13 +4017,15 @@ Caches are limited to ${cacheSizeLimit} MB disc space by default.
|
|
|
3972
4017
|
}).command("transform", "Transform (progressive loading) and compress glTF, GLB or VRM files").help(`
|
|
3973
4018
|
This will produce multiple versions of the input file, each with a different level of optimization.
|
|
3974
4019
|
Each version will be compressed and written to the output directory.
|
|
3975
|
-
`).argument("<input>", "The input glTF, GLB or VRM file that should be compressed OR a directory that contains files to be compressed", { validator: program.STRING }).argument("<output>", "The output file or directory. It can be an absolute path or a relative path to the input file. If not provided, the input file will be overwritten.", { default: null, validator: program.STRING }).option("--compress", "When enabled files will be compressed", { validator: program.BOOLEAN, default: !0 }).option("--progressive", "When enabled files will processed to be progressively loaded", { validator: program.BOOLEAN, default: !0 }).option("--usecase <usecase>", `The usecase for the compression. This will set the compression settings. Possible options: [${UsecaseOptions.join(", ")}]`, { validator: program.STRING }).option("--config <config>", 'The path to a JSON file containing the compression settings. This can also be a needle.config.json file with a "compression" object or usecase string.', { validator: program.STRING }).option("--cache", `Use "--cache False" to disable caching.
|
|
3976
|
-
When caching is enabled then previously processed files will be detected and loaded from disc cache instead of being processed again if settings or the file contents have not changed.`, { validator: program.BOOLEAN, default: !0 }).option("--debug", 'Enable for more verbose outout with "--debug True"', { validator: program.BOOLEAN, default: !1 }).option("--verbose", 'Enable for more verbose outout with "--verbose True"', { validator: program.BOOLEAN, default: !1 }).option("--auth-token <
|
|
3977
|
-
if (await gateAuth(options.authToken, logger), logger.level = options.debug || options.verbose ? "debug" : "info", options.compress === !1 && options.progressive === !1) {
|
|
4020
|
+
`).argument("<input>", "The input glTF, GLB or VRM file that should be compressed OR a directory that contains files to be compressed. Multiple files can be separated by commas.", { validator: program.STRING }).argument("<output>", "The output file or directory. It can be an absolute path or a relative path to the input file. If not provided, the input file will be overwritten.", { default: null, validator: program.STRING }).option("--compress", "When enabled files will be compressed", { validator: program.BOOLEAN, default: !0 }).option("--progressive", "When enabled files will processed to be progressively loaded", { validator: program.BOOLEAN, default: !0 }).option("--usecase <usecase>", `The usecase for the compression. This will set the compression settings. Possible options: [${UsecaseOptions.join(", ")}]`, { validator: program.STRING }).option("--config <config>", 'The path to a JSON file containing the compression settings. This can also be a needle.config.json file with a "compression" object or usecase string.', { validator: program.STRING }).option("--cache", `Use "--cache False" to disable caching.
|
|
4021
|
+
When caching is enabled then previously processed files will be detected and loaded from disc cache instead of being processed again if settings or the file contents have not changed.`, { validator: program.BOOLEAN, default: !0 }).option("--debug", 'Enable for more verbose outout with "--debug True"', { validator: program.BOOLEAN, default: !1 }).option("--verbose", 'Enable for more verbose outout with "--verbose True"', { validator: program.BOOLEAN, default: !1 }).option("--auth-token <jwt>", "Required. A JWT minted by needle-cloud (alternatively set NEEDLE_CLOUD_TOKEN). Note: an `nc_*` needle-cloud access token is NOT a JWT and will be rejected.", { validator: program.STRING }).option("--org <org>", "Organization ID for local license-server fallback (or set NEEDLE_CLOUD_ORG).", { validator: program.STRING }).action(async ({ logger, args, options }) => {
|
|
4022
|
+
if (await gateAuth(options.authToken, options.org, logger), logger.level = options.debug || options.verbose ? "debug" : "info", options.compress === !1 && options.progressive === !1) {
|
|
3978
4023
|
logger.error(`[Needle Build Pipeline] v${getVersion()} You need to enable at least one of the options: --compress or --progressive`);
|
|
3979
4024
|
return;
|
|
3980
4025
|
}
|
|
3981
|
-
await ensureHashReady()
|
|
4026
|
+
await ensureHashReady();
|
|
4027
|
+
let inputPaths = parseInputPaths(args.input.toString()), input = inputPaths[0], isMultiInput = inputPaths.length > 1;
|
|
4028
|
+
logger.info(`[Needle Build Pipeline] v${getVersion()} \u2014 Transform ${isMultiInput ? `${inputPaths.length} files` : `'${input}'`}`);
|
|
3982
4029
|
let pipelineMode = [options.progressive && "progressive", options.compress && "compress"].filter(Boolean).join("+");
|
|
3983
4030
|
trackPipelineStart({ mode: pipelineMode, usecase: options.usecase?.toString() });
|
|
3984
4031
|
let stats = {
|
|
@@ -3987,19 +4034,19 @@ When caching is enabled then previously processed files will be detected and loa
|
|
|
3987
4034
|
totalFilesProcessed: 0,
|
|
3988
4035
|
totalFileSizeInMB: 0,
|
|
3989
4036
|
totalFileSizeInMBBefore: 0
|
|
3990
|
-
},
|
|
4037
|
+
}, config = getConfig(options.config?.toString(), input, {
|
|
3991
4038
|
logger
|
|
3992
4039
|
});
|
|
3993
4040
|
options.usecase && (logger.info("Using usecase: " + options.usecase), config = { ...createConfig(options.usecase.toString()), ...config }, config.usecase != "default" && config.usecase != options.usecase.toString() ? logger.warn(`Conflicting usecase. Your specific config at "${options.config}" has a different usecase than the one provided by the CLI: "${options.usecase}". Using the usecase from the config file.`) : config.usecase = options.usecase.toString());
|
|
3994
|
-
let inputIsDirectory = isDirectory(input), output = args.output?.toString();
|
|
3995
|
-
!inputIsDirectory && !output && (output = input);
|
|
4041
|
+
let inputIsDirectory = !isMultiInput && isDirectory(input), output = args.output?.toString();
|
|
4042
|
+
isMultiInput && output && !isDirectory(output) && (logger.error("When <input> contains multiple files then <output> must be a directory"), trackError(new Error("Invalid args: multi-input but output is not a directory"), { mode: pipelineMode }), process.exit(ERROR_CODES.INVALID_ARGS)), !inputIsDirectory && !isMultiInput && !output && (output = input);
|
|
3996
4043
|
let outputIsDirectory = output && isDirectory(output);
|
|
3997
4044
|
if (inputIsDirectory && output && !outputIsDirectory && (logger.error("When <input> is a directory then <output> must also be a directory"), trackError(new Error("Invalid args: input is directory but output is not"), { mode: pipelineMode }), process.exit(ERROR_CODES.INVALID_ARGS)), output && path7.isAbsolute(output) === !1) {
|
|
3998
4045
|
let base = ensureIsDirectory(input);
|
|
3999
4046
|
output = resolve3(base, output);
|
|
4000
4047
|
}
|
|
4001
4048
|
let set = /* @__PURE__ */ new Set(), useCache = options.cache !== !1, debug = options.debug === !0, verbose = options.verbose === !0;
|
|
4002
|
-
await foreachGLTF(
|
|
4049
|
+
await foreachGLTF(inputPaths, async (file) => {
|
|
4003
4050
|
if (existsSync13(file)) {
|
|
4004
4051
|
if (file != input && options.progressive === !0 && isLOD(file)) {
|
|
4005
4052
|
logger.debug(`\u2192 Ignore existing LOD file at ${file}`);
|
|
@@ -4085,16 +4132,17 @@ When caching is enabled then previously processed files will be detected and loa
|
|
|
4085
4132
|
gpuMemory_MB: stats.totalGPUMemoryInMB,
|
|
4086
4133
|
duration_ms: Date.now() - stats.startTime
|
|
4087
4134
|
}), useCache && limitCacheSize();
|
|
4088
|
-
}).command("pmrem", "Convert EXR files to PMREM-processed KTX2 HDR (Needle PMREM)").help(`Runs the PMREM WASM + basisu encoder on .exr files,
|
|
4089
|
-
This is the same processing the Needle build pipeline
|
|
4090
|
-
GLB/GLTF files, exposed as a standalone command for
|
|
4091
|
-
|
|
4092
|
-
|
|
4135
|
+
}).command("pmrem", "Convert EXR / HDR files to PMREM-processed KTX2 HDR (Needle PMREM)").help(`Runs the PMREM WASM + basisu encoder on .exr or .hdr (Radiance RGBE) files,
|
|
4136
|
+
producing <name>.pmrem.ktx2. This is the same processing the Needle build pipeline
|
|
4137
|
+
applies to EXR textures inside GLB/GLTF files, exposed as a standalone command for
|
|
4138
|
+
raw .exr / .hdr inputs.
|
|
4139
|
+
`).argument("<input>", "Path to a .exr/.hdr file OR a directory containing .exr/.hdr files (recursive)", { validator: program.STRING }).argument("<output>", "Output file (when input is a single .exr/.hdr) or output directory. Defaults to writing next to the input file.", { default: null, validator: program.STRING }).option("--cache", 'Use "--cache False" to disable caching.', { validator: program.BOOLEAN, default: !0 }).option("--debug", 'Enable verbose output with "--debug True"', { validator: program.BOOLEAN, default: !1 }).option("--verbose", 'Enable verbose output with "--verbose True"', { validator: program.BOOLEAN, default: !1 }).option("--auth-token <jwt>", "Required. A JWT minted by needle-cloud (alternatively set NEEDLE_CLOUD_TOKEN). Note: an `nc_*` needle-cloud access token is NOT a JWT and will be rejected.", { validator: program.STRING }).option("--org <org>", "Organization ID for local license-server fallback (or set NEEDLE_CLOUD_ORG).", { validator: program.STRING }).hide().action(async ({ logger, args, options }) => {
|
|
4140
|
+
await gateAuth(options.authToken, options.org, logger), logger.level = options.debug || options.verbose ? "debug" : "info", await ensureHashReady();
|
|
4093
4141
|
let input = args.input.toString();
|
|
4094
4142
|
existsSync13(input) || (logger.error(`Input does not exist: ${input}`), process.exit(ERROR_CODES.INVALID_ARGS));
|
|
4095
|
-
let
|
|
4096
|
-
if (inputIsDirectory ?
|
|
4097
|
-
logger.warn(`No .exr files found in ${input}`);
|
|
4143
|
+
let inputFiles = [], inputIsDirectory = isDirectory(input);
|
|
4144
|
+
if (inputIsDirectory ? collectPmremInputFiles(input, inputFiles) : isPmremInputFile(input) ? inputFiles.push(input) : (logger.error(`Input is not an .exr/.hdr file or directory: ${input}`), process.exit(ERROR_CODES.INVALID_ARGS)), inputFiles.length === 0) {
|
|
4145
|
+
logger.warn(`No .exr/.hdr files found in ${input}`);
|
|
4098
4146
|
return;
|
|
4099
4147
|
}
|
|
4100
4148
|
let rawOutput = args.output?.toString() || null, outputArg = rawOutput && rawOutput !== "null" ? rawOutput : null;
|
|
@@ -4103,17 +4151,17 @@ GLB/GLTF files, exposed as a standalone command for raw .exr inputs.
|
|
|
4103
4151
|
outputArg = resolve3(base, outputArg);
|
|
4104
4152
|
}
|
|
4105
4153
|
let useCache = options.cache !== !1;
|
|
4106
|
-
logger.info(`[Needle Build Pipeline] v${getVersion()} \u2014 pmrem: ${
|
|
4154
|
+
logger.info(`[Needle Build Pipeline] v${getVersion()} \u2014 pmrem: ${inputFiles.length} file(s)`);
|
|
4107
4155
|
let runtime = await createPmremRuntime(logger);
|
|
4108
4156
|
runtime || (logger.error("pmrem runtime is not available (WASM or basisu binary missing). Run `npm run build:pmrem` in the package directory."), process.exit(ERROR_CODES.PACKING_FAILED));
|
|
4109
4157
|
try {
|
|
4110
|
-
for (let
|
|
4111
|
-
let outPath = resolvePmremOutputPath(
|
|
4112
|
-
logger.info(`\u2192 pmrem ${
|
|
4113
|
-
let
|
|
4158
|
+
for (let inPath of inputFiles) {
|
|
4159
|
+
let outPath = resolvePmremOutputPath(inPath, input, inputIsDirectory, outputArg);
|
|
4160
|
+
logger.info(`\u2192 pmrem ${inPath} \u2192 ${outPath}`);
|
|
4161
|
+
let srcBytes = readFileSync10(inPath), bytes = new Uint8Array(srcBytes.buffer, srcBytes.byteOffset, srcBytes.byteLength), ktx2Bytes = await (inPath.toLowerCase().endsWith(".hdr") ? convertHdrBytesToPmremKtx2 : convertExrBytesToPmremKtx2)(
|
|
4114
4162
|
runtime,
|
|
4115
|
-
|
|
4116
|
-
{ useCache, logLabel: `pmrem ${basename4(
|
|
4163
|
+
bytes,
|
|
4164
|
+
{ useCache, logLabel: `pmrem ${basename4(inPath)}` }
|
|
4117
4165
|
);
|
|
4118
4166
|
writeFileSync7(outPath, ktx2Bytes);
|
|
4119
4167
|
}
|
|
@@ -4122,19 +4170,23 @@ GLB/GLTF files, exposed as a standalone command for raw .exr inputs.
|
|
|
4122
4170
|
}
|
|
4123
4171
|
useCache && limitCacheSize();
|
|
4124
4172
|
});
|
|
4125
|
-
function
|
|
4173
|
+
function isPmremInputFile(name) {
|
|
4174
|
+
let lower = name.toLowerCase();
|
|
4175
|
+
return lower.endsWith(".exr") || lower.endsWith(".hdr");
|
|
4176
|
+
}
|
|
4177
|
+
function collectPmremInputFiles(dir, out) {
|
|
4126
4178
|
for (let entry of readdirSync3(dir)) {
|
|
4127
4179
|
if (entry === "node_modules" || entry.startsWith(".")) continue;
|
|
4128
4180
|
let full = path7.join(dir, entry);
|
|
4129
|
-
statSync7(full).isDirectory() ?
|
|
4181
|
+
statSync7(full).isDirectory() ? collectPmremInputFiles(full, out) : isPmremInputFile(entry) && out.push(full);
|
|
4130
4182
|
}
|
|
4131
4183
|
}
|
|
4132
|
-
function resolvePmremOutputPath(
|
|
4133
|
-
let outName = basename4(
|
|
4184
|
+
function resolvePmremOutputPath(srcPath, input, inputIsDirectory, outputArg) {
|
|
4185
|
+
let outName = basename4(srcPath).replace(/\.(exr|hdr)$/i, ".pmrem.ktx2");
|
|
4134
4186
|
if (!outputArg)
|
|
4135
|
-
return path7.join(dirname8(
|
|
4187
|
+
return path7.join(dirname8(srcPath), outName);
|
|
4136
4188
|
if (inputIsDirectory) {
|
|
4137
|
-
let rel = path7.relative(input,
|
|
4189
|
+
let rel = path7.relative(input, srcPath), relDir = dirname8(rel), outDir = relDir === "." ? outputArg : path7.join(outputArg, relDir);
|
|
4138
4190
|
return ensureIsDirectory(outDir), path7.join(outDir, outName);
|
|
4139
4191
|
}
|
|
4140
4192
|
return existsSync13(outputArg) && isDirectory(outputArg) ? path7.join(outputArg, outName) : outputArg.toLowerCase().endsWith(".ktx2") ? (ensureIsDirectory(dirname8(outputArg)), outputArg) : (ensureIsDirectory(outputArg), path7.join(outputArg, outName));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@needle-tools/gltf-build-pipeline",
|
|
3
|
-
"version": "3.0.0-next.
|
|
3
|
+
"version": "3.0.0-next.73f1606",
|
|
4
4
|
"description": "Pipeline and tools for optimizing gltf files using gltf-transform and compression settings within glTF extensions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
/* tslint:disable */
|
|
2
2
|
/* eslint-disable */
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Decode a Radiance `.hdr` file and re-encode it as an EXR (`SMALL_LOSSLESS`).
|
|
6
|
+
*/
|
|
7
|
+
export function hdr_to_exr(input: Uint8Array): Uint8Array;
|
|
8
|
+
|
|
4
9
|
export function pmrem_exr(input: Uint8Array): Uint8Array;
|
|
5
10
|
|
|
6
11
|
/**
|
|
@@ -14,6 +19,22 @@ export function pmrem_exr_resized(input: Uint8Array, target_width: number): Uint
|
|
|
14
19
|
*/
|
|
15
20
|
export function pmrem_exr_resized_with_filter(input: Uint8Array, target_width: number, filter: string): Uint8Array;
|
|
16
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Decode a Radiance `.hdr` file, run PMREM, and return PMREM EXR bytes.
|
|
24
|
+
* Output is structurally identical to `pmrem_exr`.
|
|
25
|
+
*/
|
|
26
|
+
export function pmrem_hdr(input: Uint8Array): Uint8Array;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* PMREM from HDR with optional downscale to `target_width` (Lanczos3).
|
|
30
|
+
*/
|
|
31
|
+
export function pmrem_hdr_resized(input: Uint8Array, target_width: number): Uint8Array;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* PMREM from HDR with optional downscale and selectable filter.
|
|
35
|
+
*/
|
|
36
|
+
export function pmrem_hdr_resized_with_filter(input: Uint8Array, target_width: number, filter: string): Uint8Array;
|
|
37
|
+
|
|
17
38
|
/**
|
|
18
39
|
* Resize equirectangular EXR to target width (maintain aspect), returning EXR bytes.
|
|
19
40
|
*/
|
|
@@ -33,9 +54,13 @@ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembl
|
|
|
33
54
|
|
|
34
55
|
export interface InitOutput {
|
|
35
56
|
readonly memory: WebAssembly.Memory;
|
|
57
|
+
readonly hdr_to_exr: (a: number, b: number, c: number) => void;
|
|
36
58
|
readonly pmrem_exr: (a: number, b: number, c: number) => void;
|
|
37
59
|
readonly pmrem_exr_resized: (a: number, b: number, c: number, d: number) => void;
|
|
38
60
|
readonly pmrem_exr_resized_with_filter: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
|
|
61
|
+
readonly pmrem_hdr: (a: number, b: number, c: number) => void;
|
|
62
|
+
readonly pmrem_hdr_resized: (a: number, b: number, c: number, d: number) => void;
|
|
63
|
+
readonly pmrem_hdr_resized_with_filter: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
|
|
39
64
|
readonly resize_equirect_exr: (a: number, b: number, c: number, d: number) => void;
|
|
40
65
|
readonly resize_equirect_exr_with_filter: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
|
|
41
66
|
readonly split_pmrem_exr_to_zip: (a: number, b: number, c: number) => void;
|
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
/* @ts-self-types="./pmrem_wasm.d.ts" */
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Decode a Radiance `.hdr` file and re-encode it as an EXR (`SMALL_LOSSLESS`).
|
|
5
|
+
* @param {Uint8Array} input
|
|
6
|
+
* @returns {Uint8Array}
|
|
7
|
+
*/
|
|
8
|
+
export function hdr_to_exr(input) {
|
|
9
|
+
try {
|
|
10
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
11
|
+
const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_export);
|
|
12
|
+
const len0 = WASM_VECTOR_LEN;
|
|
13
|
+
wasm.hdr_to_exr(retptr, ptr0, len0);
|
|
14
|
+
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
|
|
15
|
+
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
|
|
16
|
+
var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
|
|
17
|
+
var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
|
|
18
|
+
if (r3) {
|
|
19
|
+
throw takeObject(r2);
|
|
20
|
+
}
|
|
21
|
+
var v2 = getArrayU8FromWasm0(r0, r1).slice();
|
|
22
|
+
wasm.__wbindgen_export2(r0, r1 * 1, 1);
|
|
23
|
+
return v2;
|
|
24
|
+
} finally {
|
|
25
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
3
29
|
/**
|
|
4
30
|
* @param {Uint8Array} input
|
|
5
31
|
* @returns {Uint8Array}
|
|
@@ -83,6 +109,90 @@ export function pmrem_exr_resized_with_filter(input, target_width, filter) {
|
|
|
83
109
|
}
|
|
84
110
|
}
|
|
85
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Decode a Radiance `.hdr` file, run PMREM, and return PMREM EXR bytes.
|
|
114
|
+
* Output is structurally identical to `pmrem_exr`.
|
|
115
|
+
* @param {Uint8Array} input
|
|
116
|
+
* @returns {Uint8Array}
|
|
117
|
+
*/
|
|
118
|
+
export function pmrem_hdr(input) {
|
|
119
|
+
try {
|
|
120
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
121
|
+
const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_export);
|
|
122
|
+
const len0 = WASM_VECTOR_LEN;
|
|
123
|
+
wasm.pmrem_hdr(retptr, ptr0, len0);
|
|
124
|
+
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
|
|
125
|
+
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
|
|
126
|
+
var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
|
|
127
|
+
var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
|
|
128
|
+
if (r3) {
|
|
129
|
+
throw takeObject(r2);
|
|
130
|
+
}
|
|
131
|
+
var v2 = getArrayU8FromWasm0(r0, r1).slice();
|
|
132
|
+
wasm.__wbindgen_export2(r0, r1 * 1, 1);
|
|
133
|
+
return v2;
|
|
134
|
+
} finally {
|
|
135
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* PMREM from HDR with optional downscale to `target_width` (Lanczos3).
|
|
141
|
+
* @param {Uint8Array} input
|
|
142
|
+
* @param {number} target_width
|
|
143
|
+
* @returns {Uint8Array}
|
|
144
|
+
*/
|
|
145
|
+
export function pmrem_hdr_resized(input, target_width) {
|
|
146
|
+
try {
|
|
147
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
148
|
+
const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_export);
|
|
149
|
+
const len0 = WASM_VECTOR_LEN;
|
|
150
|
+
wasm.pmrem_hdr_resized(retptr, ptr0, len0, target_width);
|
|
151
|
+
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
|
|
152
|
+
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
|
|
153
|
+
var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
|
|
154
|
+
var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
|
|
155
|
+
if (r3) {
|
|
156
|
+
throw takeObject(r2);
|
|
157
|
+
}
|
|
158
|
+
var v2 = getArrayU8FromWasm0(r0, r1).slice();
|
|
159
|
+
wasm.__wbindgen_export2(r0, r1 * 1, 1);
|
|
160
|
+
return v2;
|
|
161
|
+
} finally {
|
|
162
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* PMREM from HDR with optional downscale and selectable filter.
|
|
168
|
+
* @param {Uint8Array} input
|
|
169
|
+
* @param {number} target_width
|
|
170
|
+
* @param {string} filter
|
|
171
|
+
* @returns {Uint8Array}
|
|
172
|
+
*/
|
|
173
|
+
export function pmrem_hdr_resized_with_filter(input, target_width, filter) {
|
|
174
|
+
try {
|
|
175
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
176
|
+
const ptr0 = passArray8ToWasm0(input, wasm.__wbindgen_export);
|
|
177
|
+
const len0 = WASM_VECTOR_LEN;
|
|
178
|
+
const ptr1 = passStringToWasm0(filter, wasm.__wbindgen_export, wasm.__wbindgen_export3);
|
|
179
|
+
const len1 = WASM_VECTOR_LEN;
|
|
180
|
+
wasm.pmrem_hdr_resized_with_filter(retptr, ptr0, len0, target_width, ptr1, len1);
|
|
181
|
+
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
|
|
182
|
+
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
|
|
183
|
+
var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
|
|
184
|
+
var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
|
|
185
|
+
if (r3) {
|
|
186
|
+
throw takeObject(r2);
|
|
187
|
+
}
|
|
188
|
+
var v3 = getArrayU8FromWasm0(r0, r1).slice();
|
|
189
|
+
wasm.__wbindgen_export2(r0, r1 * 1, 1);
|
|
190
|
+
return v3;
|
|
191
|
+
} finally {
|
|
192
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
86
196
|
/**
|
|
87
197
|
* Resize equirectangular EXR to target width (maintain aspect), returning EXR bytes.
|
|
88
198
|
* @param {Uint8Array} input
|
|
Binary file
|