@needle-tools/gltf-build-pipeline 2.16.0-alpha.bc3af72 → 2.16.0-next.19247c3

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.
@@ -2,6 +2,7 @@
2
2
  /// <reference types="node" resolution-mode="require"/>
3
3
  import { ExtensibleProperty } from "@gltf-transform/core";
4
4
  import { Logger } from "@donmccurdy/caporal";
5
+ export declare function ensureHashReady(): Promise<void>;
5
6
  /**
6
7
  * Clear the cache.
7
8
  * This will remove all files in the cache directory.
@@ -6,9 +6,16 @@ import { getVersion } from "../utils/version.js";
6
6
  // import * as CHECKDISCSPACE from 'check-disk-space'
7
7
  import xxhash from "xxhash-wasm";
8
8
  let xxHashModule = null;
9
- xxhash().then(module => {
10
- xxHashModule = module;
11
- }).catch(() => { });
9
+ // Single shared promise that resolves once the WASM module is loaded (or has failed).
10
+ // Callers should `await ensureHashReady()` once before any synchronous hash call to
11
+ // avoid a race where early calls use the JS fallback and later calls use WASM —
12
+ // producing different cache keys for the same input within one process.
13
+ const xxHashReady = xxhash()
14
+ .then(module => { xxHashModule = module; })
15
+ .catch(() => { });
16
+ export function ensureHashReady() {
17
+ return xxHashReady;
18
+ }
12
19
  /**
13
20
  * Get the available space on the cache directory in bytes.
14
21
  */
@@ -179,6 +186,17 @@ export function getKeyWithHash(property) {
179
186
  const key = `${prefix}-${hash}`;
180
187
  return { key, hash };
181
188
  }
189
+ /**
190
+ * Combine two 32-bit hashes with mixing. Plain `a + b` is commutative and
191
+ * has poor diffusion — swapping two attribute buffers collides. This uses a
192
+ * boost::hash_combine-style mix: xor in the new bits, then bit-shift mix so
193
+ * order matters and unrelated changes don't cancel out.
194
+ */
195
+ function combineHash(seed, value) {
196
+ // 0x9e3779b9 = golden-ratio constant used by boost / fnv variants
197
+ seed = (seed ^ (value + 0x9e3779b9 + ((seed << 6) | 0) + (seed >>> 2))) | 0;
198
+ return seed;
199
+ }
182
200
  /**
183
201
  * Get the hash for a property or an object.
184
202
  * @param property The property to get the hash for.
@@ -186,27 +204,26 @@ export function getKeyWithHash(property) {
186
204
  * @returns The hash as a number.
187
205
  */
188
206
  export function getHash(property, level = 0) {
189
- let hashStr = "";
190
207
  let hash = 0;
191
208
  if (property instanceof ExtensibleProperty) {
192
209
  const extensions = property.listExtensions();
193
210
  const extras = property.getExtras();
194
- hash += hashObject({
211
+ hash = combineHash(hash, hashObject({
195
212
  extensions,
196
213
  extras,
197
- });
214
+ }));
198
215
  if (property instanceof Texture) {
199
216
  const image = property.getImage();
200
217
  const bytes = image?.buffer;
201
218
  if (bytes)
202
- hash += hashBuffer(bytes, image.byteOffset, image.byteLength);
219
+ hash = combineHash(hash, hashBuffer(bytes, image.byteOffset, image.byteLength));
203
220
  }
204
221
  else if (property instanceof Mesh) {
205
222
  const weights = property.getWeights();
206
- hash += hashObject(weights);
223
+ hash = combineHash(hash, hashObject(weights));
207
224
  const primitives = property.listPrimitives();
208
225
  for (const prim of primitives) {
209
- hash += hashString(getHash(prim, level + 1));
226
+ hash = combineHash(hash, hashString(getHash(prim, level + 1)));
210
227
  }
211
228
  }
212
229
  else if (property instanceof Primitive) {
@@ -220,32 +237,35 @@ export function getHash(property, level = 0) {
220
237
  name: s,
221
238
  };
222
239
  });
223
- hash += hashObject({
240
+ hash = combineHash(hash, hashObject({
224
241
  indices,
225
242
  attributes,
226
243
  targets,
227
244
  semantics: semanticsNames
228
- });
245
+ }));
229
246
  if (indices) {
230
247
  const indexBuffer = indices.getArray();
231
248
  if (indexBuffer) {
232
- hash += hashBuffer(indexBuffer.buffer, indexBuffer.byteOffset, indexBuffer.byteLength);
249
+ hash = combineHash(hash, hashBuffer(indexBuffer.buffer, indexBuffer.byteOffset, indexBuffer.byteLength));
233
250
  }
234
251
  }
235
252
  // We can not pass the whole buffer into hashObject since very large meshes will cause errors when trying to stringify
236
253
  // See https://linear.app/needle/issue/NE-6414
254
+ // Mix the semantic name into each attribute hash so swapping two attributes (e.g. POSITION ↔ NORMAL)
255
+ // doesn't collide — without this, the commutative combine would erase attribute identity.
237
256
  for (const sem of semantics) {
238
257
  const arr = property.getAttribute(sem)?.getArray();
239
258
  if (arr) {
240
- hash += hashBuffer(arr.buffer, arr.byteOffset, arr.byteLength);
259
+ hash = combineHash(hash, hashString(sem));
260
+ hash = combineHash(hash, hashBuffer(arr.buffer, arr.byteOffset, arr.byteLength));
241
261
  }
242
262
  }
243
263
  }
244
264
  }
245
265
  else {
246
- hash += hashObject(property);
266
+ hash = combineHash(hash, hashObject(property));
247
267
  }
248
- return hashStr + hash;
268
+ return String(hash);
249
269
  }
250
270
  const cleanBuildPipelineVersion = getVersion(false).replace(/[^a-zA-Z0-9]/g, "_");
251
271
  function getCacheDirectory(root) {
package/dist/cli/index.js CHANGED
@@ -5,7 +5,7 @@ import { printStats, writeFileStatsToFile } from '../utils/stats.js';
5
5
  import { getVersion } from '../utils/version.js';
6
6
  import { UsecaseOptions, createConfig, getConfig } from '../config/index.js';
7
7
  import { isLOD, make_progressive } from '../transforms/needle_progressive.js';
8
- import { cacheSizeLimit, clearCache, limitCacheSize } from '../cache/cache.js';
8
+ import { cacheSizeLimit, clearCache, ensureHashReady, limitCacheSize } from '../cache/cache.js';
9
9
  import { computeJobKey, saveJobResult, tryRestoreJobResult } from '../cache/job-cache.js';
10
10
  import { existsSync, statSync } from 'fs';
11
11
  import { ensureIsDirectory, foreachGLTF, isDirectory } from '../utils/fileutils.js';
@@ -14,6 +14,16 @@ import { ERROR_CODES } from '../constants.js';
14
14
  import { trackPipelineStart, trackPipelineEnd, trackError } from '../utils/analytics.js';
15
15
  // For testing / dev you can run `npm link` in the package directory
16
16
  // For removing the link run `npm rm --global @needle-tools/gltf-build-pipeline`
17
+ // Disable caporal's autoCast for positional arguments.
18
+ //
19
+ // caporal's autoCast uses /^true|false$/ (precedence bug — should be /^(true|false)$/),
20
+ // which matches any string ending with "false" or starting with "true". An <output>
21
+ // path like ".../out-shellfalse" gets coerced to the boolean false, then stringified
22
+ // to "false", and the pipeline writes to "<inputDir>/false" instead of the requested
23
+ // directory. Same shape applies to paths ending with "on" or starting with "yes"/"1".
24
+ // Disabling autoCast at the program level forces positionals through String(...);
25
+ // options with explicit BOOLEAN/STRING validators are unaffected.
26
+ program.cast(false);
17
27
  program
18
28
  .command("version", "Print current version")
19
29
  .action(async ({ logger }) => {
@@ -35,6 +45,9 @@ Caches are limited to ${cacheSizeLimit} MB disc space by default.
35
45
  .option("--verbose", "Enable verbose output", { validator: program.BOOLEAN, default: false })
36
46
  .action(async ({ logger, args, options }) => {
37
47
  logger.level = options.verbose ? "debug" : "info";
48
+ // Wait for the xxHash WASM module so any hashing inside calculateStats sees the
49
+ // same hash function on every call (otherwise the first calls use the JS fallback).
50
+ await ensureHashReady();
38
51
  logger.info("Calculating stats for \"" + args.input + "\"");
39
52
  const input = args.input.toString();
40
53
  const filestats = new Array();
@@ -60,8 +73,14 @@ Caches are limited to ${cacheSizeLimit} MB disc space by default.
60
73
  This will produce multiple versions of the input file, each with a different level of optimization.
61
74
  Each version will be compressed and written to the output directory.
62
75
  `)
63
- .argument('<input>', "The input glTF, GLB or VRM file that should be compressed OR a directory that contains files to be compressed")
64
- .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 })
76
+ // Explicit STRING validators prevent caporal's autoCast() from silently coercing
77
+ // a path that ends with "false" / "on" (or starts with "true" / "yes" / "1") into
78
+ // a boolean — caporal's autoCast regex is missing parentheses and matches as
79
+ // /^true | false$/ rather than /^(true|false)$/. Without these validators, an
80
+ // output path like "out-shellfalse" gets cast to the boolean false → stringified
81
+ // → file written to "<inputDir>/false" instead of the named directory.
82
+ .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 })
83
+ .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 })
65
84
  .option("--compress", `When enabled files will be compressed`, { validator: program.BOOLEAN, default: true })
66
85
  .option("--progressive", `When enabled files will processed to be progressively loaded`, { validator: program.BOOLEAN, default: true })
67
86
  .option("--usecase <usecase>", `The usecase for the compression. This will set the compression settings. Possible options: [${UsecaseOptions.join(", ")}]`, { validator: program.STRING })
@@ -76,6 +95,10 @@ Each version will be compressed and written to the output directory.
76
95
  logger.error(`[Needle Build Pipeline] v${getVersion()} You need to enable at least one of the options: --compress or --progressive`);
77
96
  return;
78
97
  }
98
+ // Wait for the xxHash WASM module before any hashing happens. Without this the
99
+ // first hash calls in a process use the JS fallback while later ones use WASM,
100
+ // producing different cache keys for the same input within a single run.
101
+ await ensureHashReady();
79
102
  logger.info(`[Needle Build Pipeline] v${getVersion()} — Transform '${args.input}'`);
80
103
  const pipelineMode = [options.progressive && 'progressive', options.compress && 'compress'].filter(Boolean).join('+');
81
104
  trackPipelineStart({ mode: pipelineMode, usecase: options.usecase?.toString() });
@@ -164,7 +187,7 @@ Each version will be compressed and written to the output directory.
164
187
  stats.totalFileSizeInMBBefore += inputFileSize;
165
188
  }
166
189
  }
167
- logger.info(`→ [CACHE] Restored ${restored.length} file(s)for job ${jobKey}`);
190
+ logger.info(`→ [CACHE] Restored ${restored.length} file(s) for job ${jobKey}`);
168
191
  return;
169
192
  }
170
193
  }
@@ -1,4 +1,4 @@
1
- import { WriterContext, PropertyType } from '@gltf-transform/core';
1
+ import { Extension, WriterContext, PropertyType } from '@gltf-transform/core';
2
2
  declare interface IExtensibleProperty {
3
3
  }
4
4
  type DebugBreakPoint = boolean | "pointer:read";
@@ -23,5 +23,5 @@ export interface IExtensionWriter {
23
23
  write(context: WriterContext, prop: IExtensibleProperty): void;
24
24
  }
25
25
  export declare let currentGenerator: string;
26
- export declare function createOpaqueExtension(name: string, types: PropertyType | PropertyType[], opts?: Options): IOpaqueExtension;
26
+ export declare function createOpaqueExtension(name: string, types: PropertyType | PropertyType[], opts?: Options): typeof Extension;
27
27
  export {};
@@ -1,3 +1,2 @@
1
- import { Extension } from "@gltf-transform/core";
2
1
  export * from "./NEEDLE_opaque.js";
3
- export declare const ALL_EXTENSIONS: (typeof Extension)[];
2
+ export declare const ALL_EXTENSIONS: typeof import("@gltf-transform/core").Extension[];
@@ -1,4 +1,4 @@
1
- import { ILogger, Texture, Transform, vec2 } from '@gltf-transform/core';
1
+ import { ILogger, Primitive, Texture, Transform, TypedArray, vec2 } from '@gltf-transform/core';
2
2
  import { Config } from '../config/index.js';
3
3
  declare interface ProgressiveOptions {
4
4
  path: string | Array<string>;
@@ -39,6 +39,14 @@ export declare enum TextureResizeFilter {
39
39
  export declare const TEXTURE_RESIZE_DEFAULTS: TextureResizeOptions;
40
40
  export declare function resizeTextureToMax(texture: Texture, maxSize: number, logger: ILogger): Promise<void>;
41
41
  export declare function make_progressive_meshes(filePath: string, _options: any, opts?: ProgressiveOptions): Transform;
42
+ export declare type PrimitiveData = {
43
+ indices: TypedArray;
44
+ attributes: {
45
+ [key: string]: TypedArray;
46
+ };
47
+ };
48
+ export declare function clonePrimitiveData(prim: Primitive, logger: ILogger): PrimitiveData | null;
49
+ export declare function setPrimitiveData(prim: Primitive, data: PrimitiveData): void;
42
50
  export declare function isMeshLOD(filepath: string): boolean;
43
51
  export declare function isImageLOD(filepath: string): boolean;
44
52
  export declare function isLOD(filepath: string): boolean;
@@ -304,10 +304,11 @@ export function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DE
304
304
  // If any texture LOD was generated we can resize the texture here
305
305
  // E.g. for specular/glossiness textures we might not generate any LODs and then we don't want to downsize the texture
306
306
  if (results?.length) {
307
- options.size[0] = settings.maxSize;
308
- options.size[1] = settings.maxSize;
309
- logger.debug(`[${NAME}] Resizing embedded texture[${index}] to ${options.size[0]}x${options.size[1]}`);
310
- await resizeTexture(options, texture, logger, uri || name, slots);
307
+ // Build a per-iteration resize options object — never mutate the shared `options`,
308
+ // otherwise the next texture's size check (line ~238) would see the previous texture's maxSize.
309
+ const resizeOpts = { ...options, size: [settings.maxSize, settings.maxSize] };
310
+ logger.debug(`[${NAME}] Resizing embedded texture[${index}] to ${resizeOpts.size[0]}x${resizeOpts.size[1]}`);
311
+ await resizeTexture(resizeOpts, texture, logger, uri || name, slots);
311
312
  if (opts?.useCache === false) {
312
313
  }
313
314
  else
@@ -453,7 +454,7 @@ async function createTextureLod(args, opts) {
453
454
  mkdirSync(basePath, { recursive: true });
454
455
  }
455
456
  logger.info(`[${NAME}] Write texture LOD ${level} to \"${filename}\"`);
456
- newIo.write(outName, newDoc);
457
+ await newIo.write(outName, newDoc);
457
458
  logger.info(`[${NAME}] Generate hash for texture LOD ${level}`);
458
459
  const hash = getHash(newTexture);
459
460
  return {
@@ -830,24 +831,30 @@ export function make_progressive_meshes(filePath, _options, opts) {
830
831
  function deleteFile(filePath, _context) {
831
832
  rmSync(filePath);
832
833
  }
833
- function clonePrimitiveData(prim, logger) {
834
+ // Clone a TypedArray preserving its concrete type (Uint16Array stays Uint16Array etc.).
835
+ // Coercing to Float32Array breaks integer attributes (JOINTS, FEATURE_ID, indices) and changes
836
+ // the accessor's componentType when written back via setArray.
837
+ function cloneTypedArray(src) {
838
+ return src.slice();
839
+ }
840
+ export function clonePrimitiveData(prim, logger) {
834
841
  const semantics = prim.listSemantics();
835
842
  if (semantics.some(s => s.includes("JOINTS"))) {
836
843
  return null;
837
844
  }
838
- const prevIndices = prim.getIndices();
839
- const indices = !prevIndices ? new Uint32Array() : new Uint32Array(prevIndices.getArray());
845
+ const prevIndicesArray = prim.getIndices()?.getArray();
846
+ const indices = prevIndicesArray ? cloneTypedArray(prevIndicesArray) : new Uint32Array();
840
847
  const attributes = {};
841
848
  for (const attr of semantics) {
842
849
  logger.info(`[${NAME}] Clone attribute ${attr}`);
843
- const accessor = prim.getAttribute(attr);
844
- if (accessor) {
845
- attributes[attr] = new Float32Array(accessor.getArray());
850
+ const src = prim.getAttribute(attr)?.getArray();
851
+ if (src) {
852
+ attributes[attr] = cloneTypedArray(src);
846
853
  }
847
854
  }
848
855
  return { indices, attributes };
849
856
  }
850
- function setPrimitiveData(prim, data) {
857
+ export function setPrimitiveData(prim, data) {
851
858
  const indices = prim.getIndices();
852
859
  if (indices) {
853
860
  indices.setArray(data.indices);
@@ -1090,11 +1097,20 @@ async function simplifyMesh(doc, mesh, prim, index, lodinfo) {
1090
1097
  };
1091
1098
  return compressPrimitive(doc, mesh, prim, index, weldOptions, simplifyOptions);
1092
1099
  }
1100
+ // Match only files this pipeline emits: <basename>_<level>_<uuid>.glb
1101
+ // (uuid is generated via generateGuid → uuid v5, 36 chars with hyphens).
1102
+ // Anchoring against the basename + UUID format prevents false positives from
1103
+ // user assets like "image_hero.glb" or "/path/mesh_lod_test.glb", which the
1104
+ // previous substring check (filepath.includes(...)) misclassified as LODs,
1105
+ // causing the pipeline to silently skip them.
1106
+ const UUID_RE_SRC = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
1107
+ const IMAGE_LOD_RE = new RegExp(`(?:^|[\\\\/])image_\\d+_${UUID_RE_SRC}\\.glb$`, 'i');
1108
+ const MESH_LOD_RE = new RegExp(`(?:^|[\\\\/])mesh_lod_\\d+_${UUID_RE_SRC}\\.glb$`, 'i');
1093
1109
  export function isMeshLOD(filepath) {
1094
- return filepath.includes("mesh_lod_");
1110
+ return MESH_LOD_RE.test(filepath);
1095
1111
  }
1096
1112
  export function isImageLOD(filepath) {
1097
- return filepath.includes("image_");
1113
+ return IMAGE_LOD_RE.test(filepath);
1098
1114
  }
1099
1115
  export function isLOD(filepath) {
1100
1116
  return isMeshLOD(filepath) || isImageLOD(filepath);
@@ -88,6 +88,14 @@ export class FileStats extends Stats {
88
88
  this.isLOD = isLOD(this.filename);
89
89
  }
90
90
  }
91
+ // Union the two arrays, tolerating undefined on either side. `new Set(undefined)`
92
+ // throws, which is what the prior implementation would do whenever `this.errors`
93
+ // was undefined but `other.errors` was non-empty.
94
+ function mergeUnique(a, b) {
95
+ if (!a && !b)
96
+ return undefined;
97
+ return Array.from(new Set([...(a ?? []), ...(b ?? [])]));
98
+ }
91
99
  export class MeshInfo {
92
100
  count = 0;
93
101
  primitives = 0;
@@ -104,8 +112,8 @@ export class MeshInfo {
104
112
  this.triangles += other.triangles;
105
113
  this.memory += other.memory;
106
114
  this.formats = Array.from(new Set(this.formats.concat(other.formats)));
107
- this.errors = Array.from(new Set(this.errors?.concat(other.errors)));
108
- this.warnings = Array.from(new Set(this.warnings?.concat(other.warnings)));
115
+ this.errors = mergeUnique(this.errors, other.errors);
116
+ this.warnings = mergeUnique(this.warnings, other.warnings);
109
117
  }
110
118
  }
111
119
  export class TextureInfo {
@@ -120,8 +128,8 @@ export class TextureInfo {
120
128
  this.memory += other.memory;
121
129
  this.gpu_memory += other.gpu_memory;
122
130
  this.formats = Array.from(new Set(this.formats.concat(other.formats)));
123
- this.errors = Array.from(new Set(this.errors?.concat(other.errors)));
124
- this.warnings = Array.from(new Set(this.warnings?.concat(other.warnings)));
131
+ this.errors = mergeUnique(this.errors, other.errors);
132
+ this.warnings = mergeUnique(this.warnings, other.warnings);
125
133
  }
126
134
  }
127
135
  export class AnimationInfo {
@@ -1 +1 @@
1
- export declare const version = "2.16.0-alpha.bc3af72";
1
+ export declare const version = "2.16.0-next.19247c3";
@@ -1 +1 @@
1
- export const version = "2.16.0-alpha.bc3af72";
1
+ export const version = "2.16.0-next.19247c3";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/gltf-build-pipeline",
3
- "version": "2.16.0-alpha.bc3af72",
3
+ "version": "2.16.0-next.19247c3",
4
4
  "description": "Pipeline and tools for optimizing gltf files using gltf-transform and compression settings within glTF extensions",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
Binary file