@needle-tools/gltf-build-pipeline 2.15.0-next.adb3357 → 2.15.0-next.ca2fe5b

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.
@@ -0,0 +1,41 @@
1
+ import { Extension, PropertyType, ReaderContext, WriterContext } from '@gltf-transform/core';
2
+ /**
3
+ * NEEDLE_lightmaps gltf-transform extension.
4
+ *
5
+ * Handles both embedded (`/textures/N` pointer) and external (`sunrise.exr` pointer) lightmaps.
6
+ *
7
+ * - **preread(TEXTURE)**: Injects external EXR files into the JSON document so the core reader
8
+ * creates proper Texture objects from them.
9
+ * - **read()**: Resolves `/textures/N` pointers to Texture objects. Sets references so that
10
+ * gltf-transform doesn't prune/dedup referenced textures.
11
+ * - **write()**: Updates pointer strings:
12
+ * - Embedded textures: resolves to the new `/textures/N` index in the output.
13
+ * - External textures: uses the Texture's current URI (e.g. updated by PMREM to `.pmrem.ktx2`).
14
+ */
15
+ export declare class NEEDLE_lightmaps_ext extends Extension {
16
+ static readonly EXTENSION_NAME = "NEEDLE_lightmaps";
17
+ readonly extensionName = "NEEDLE_lightmaps";
18
+ readonly prereadTypes: PropertyType[];
19
+ readonly prewriteTypes: PropertyType[];
20
+ /** Set before io.read() to allow resolving external file paths in preread */
21
+ static inputFile: string;
22
+ /** The raw extension JSON from the input (mutated in-place during write) */
23
+ private extensionData;
24
+ /** Entries with resolved Texture references */
25
+ private resolved;
26
+ /** Image indices injected during preread (for external EXR files) */
27
+ private injectedImageIndices;
28
+ /** The ExtensionProperty that holds references to prevent dedup/prune */
29
+ private lightmapProp;
30
+ preread(context: ReaderContext, _propertyType: PropertyType): this;
31
+ read(context: ReaderContext): this;
32
+ prewrite(context: WriterContext, _propertyType: PropertyType): this;
33
+ write(context: WriterContext): this;
34
+ private pointersResolved;
35
+ private resolvePointers;
36
+ /**
37
+ * Find (or create) a texture def in the output JSON that references the given Texture.
38
+ * This replicates the logic from the opaque system's TextureIndexResolver.
39
+ */
40
+ private findOrCreateTextureIndex;
41
+ }
@@ -0,0 +1,249 @@
1
+ import { Extension, ExtensionProperty, PropertyType } from '@gltf-transform/core';
2
+ import { existsSync, readFileSync } from 'fs';
3
+ import { join, dirname } from 'path';
4
+ import { isLightmap } from '../../utils/texture.js';
5
+ const EXTENSION_NAME = 'NEEDLE_lightmaps';
6
+ /**
7
+ * Opaque-like ExtensionProperty that holds NEEDLE_lightmaps data on the Root.
8
+ * This keeps gltf-transform from garbage-collecting referenced textures.
9
+ */
10
+ class LightmapProperty extends ExtensionProperty {
11
+ static EXTENSION_NAME = EXTENSION_NAME;
12
+ propertyType = 'LightmapProperty';
13
+ parentTypes = [PropertyType.ROOT];
14
+ init() {
15
+ this.extensionName = EXTENSION_NAME;
16
+ }
17
+ getDefaults() {
18
+ return Object.assign(super.getDefaults(), {});
19
+ }
20
+ /** Public wrapper around protected setRef to register references */
21
+ setReference(name, value) {
22
+ this.setRef(name, value);
23
+ }
24
+ }
25
+ /**
26
+ * NEEDLE_lightmaps gltf-transform extension.
27
+ *
28
+ * Handles both embedded (`/textures/N` pointer) and external (`sunrise.exr` pointer) lightmaps.
29
+ *
30
+ * - **preread(TEXTURE)**: Injects external EXR files into the JSON document so the core reader
31
+ * creates proper Texture objects from them.
32
+ * - **read()**: Resolves `/textures/N` pointers to Texture objects. Sets references so that
33
+ * gltf-transform doesn't prune/dedup referenced textures.
34
+ * - **write()**: Updates pointer strings:
35
+ * - Embedded textures: resolves to the new `/textures/N` index in the output.
36
+ * - External textures: uses the Texture's current URI (e.g. updated by PMREM to `.pmrem.ktx2`).
37
+ */
38
+ export class NEEDLE_lightmaps_ext extends Extension {
39
+ static EXTENSION_NAME = EXTENSION_NAME;
40
+ extensionName = EXTENSION_NAME;
41
+ prereadTypes = [PropertyType.TEXTURE];
42
+ prewriteTypes = [PropertyType.MATERIAL];
43
+ /** Set before io.read() to allow resolving external file paths in preread */
44
+ static inputFile = '';
45
+ /** The raw extension JSON from the input (mutated in-place during write) */
46
+ extensionData = null;
47
+ /** Entries with resolved Texture references */
48
+ resolved = [];
49
+ /** Image indices injected during preread (for external EXR files) */
50
+ injectedImageIndices = new Map();
51
+ /** The ExtensionProperty that holds references to prevent dedup/prune */
52
+ lightmapProp = null;
53
+ // ── preread ──────────────────────────────────────────────────
54
+ preread(context, _propertyType) {
55
+ const json = context.jsonDoc.json;
56
+ const ext = json.extensions?.[EXTENSION_NAME];
57
+ if (!ext?.textures)
58
+ return this;
59
+ const inputFile = NEEDLE_lightmaps_ext.inputFile;
60
+ const inputDir = inputFile ? dirname(inputFile) : '';
61
+ for (const entry of ext.textures) {
62
+ // Skip embedded pointers — handled in read()
63
+ if (entry.pointer.startsWith('/') || entry.pointer.startsWith('textures/'))
64
+ continue;
65
+ // External file path (e.g. "sunrise.exr")
66
+ if (!entry.pointer.match(/\.exr$/i))
67
+ continue;
68
+ const exrPath = inputDir ? join(inputDir, entry.pointer) : '';
69
+ if (!exrPath || !existsSync(exrPath)) {
70
+ this.document.getLogger().warn(`NEEDLE_lightmaps: External EXR not found: ${exrPath || entry.pointer}`);
71
+ continue;
72
+ }
73
+ // Read EXR bytes and inject into JSON so the core reader creates a Texture
74
+ const exrBytes = readFileSync(exrPath);
75
+ json.images = json.images || [];
76
+ json.textures = json.textures || [];
77
+ const imageIndex = json.images.length;
78
+ json.images.push({
79
+ uri: entry.pointer,
80
+ mimeType: 'image/exr',
81
+ name: entry.pointer,
82
+ });
83
+ json.textures.push({
84
+ source: imageIndex,
85
+ name: entry.pointer,
86
+ });
87
+ context.jsonDoc.resources[entry.pointer] = new Uint8Array(exrBytes);
88
+ this.injectedImageIndices.set(entry.pointer, imageIndex);
89
+ this.document.getLogger().info(`NEEDLE_lightmaps: Registered external EXR "${entry.pointer}" as image[${imageIndex}]`);
90
+ }
91
+ return this;
92
+ }
93
+ // ── read ─────────────────────────────────────────────────────
94
+ read(context) {
95
+ const json = context.jsonDoc.json;
96
+ const ext = json.extensions?.[EXTENSION_NAME];
97
+ if (!ext?.textures)
98
+ return this;
99
+ // Store the raw extension data — we'll mutate the pointers during write
100
+ this.extensionData = ext;
101
+ // Create the property and attach to root
102
+ const root = this.document.getRoot();
103
+ this.lightmapProp = new LightmapProperty(this.document.getGraph());
104
+ root.setExtension(EXTENSION_NAME, this.lightmapProp);
105
+ const textureDefs = json.textures || [];
106
+ const logger = this.document.getLogger();
107
+ for (const entry of ext.textures) {
108
+ let texture = null;
109
+ let inputTextureDef;
110
+ if (entry.pointer.startsWith('/textures/') || entry.pointer.startsWith('textures/')) {
111
+ // Embedded pointer — resolve to Texture via the JSON texture definition
112
+ const prefix = entry.pointer.startsWith('/') ? '/textures/' : 'textures/';
113
+ const texIndex = parseInt(entry.pointer.substring(prefix.length));
114
+ const texDef = textureDefs[texIndex];
115
+ if (texDef) {
116
+ inputTextureDef = texDef;
117
+ const imageIndex = texDef.source
118
+ ?? texDef.extensions?.['EXT_texture_exr']?.source
119
+ ?? texDef.extensions?.['KHR_texture_basisu']?.source;
120
+ if (imageIndex !== undefined) {
121
+ texture = context.textures[imageIndex] ?? null;
122
+ }
123
+ }
124
+ }
125
+ else if (entry.pointer.match(/\.exr$/i)) {
126
+ // External pointer — find the Texture created from our injected image
127
+ const imageIndex = this.injectedImageIndices.get(entry.pointer);
128
+ if (imageIndex !== undefined) {
129
+ texture = context.textures[imageIndex] ?? null;
130
+ inputTextureDef = textureDefs.find(t => t.source === imageIndex);
131
+ }
132
+ }
133
+ if (texture) {
134
+ this.resolved.push({ entry, texture, inputTextureDef });
135
+ // Set a reference so gltf-transform won't prune/dedup this texture
136
+ const refName = `lightmap_${entry.pointer}`;
137
+ this.lightmapProp.setReference(refName, texture);
138
+ // Also keep a reference to the buffer
139
+ const buffer = this.document.getRoot().listBuffers()[0];
140
+ if (buffer) {
141
+ this.lightmapProp.setReference('buffer', buffer);
142
+ }
143
+ }
144
+ else {
145
+ logger.warn(`NEEDLE_lightmaps: Could not resolve texture for pointer "${entry.pointer}"`);
146
+ }
147
+ }
148
+ // Lightmap workaround: prevent compression on lightmap textures (non-EXR)
149
+ const textures = this.document.getRoot().listTextures();
150
+ for (const tex of textures) {
151
+ if (isLightmap(tex) && tex.getMimeType() !== 'image/exr') {
152
+ const refName = `lightmapTexture_${tex.getName()}`;
153
+ this.lightmapProp.setReference(refName, tex);
154
+ logger.info(`Found lightmap texture "${tex.getName()}" (${tex.getMimeType()}) in ${EXTENSION_NAME}`);
155
+ }
156
+ }
157
+ return this;
158
+ }
159
+ // ── prewrite ─────────────────────────────────────────────────
160
+ prewrite(context, _propertyType) {
161
+ // Resolve pointers early so json.textures is populated for textures
162
+ // not used by any material (same pattern as opaque system)
163
+ this.resolvePointers(context);
164
+ return this;
165
+ }
166
+ // ── write ────────────────────────────────────────────────────
167
+ write(context) {
168
+ if (!this.extensionData)
169
+ return this;
170
+ // Resolve any remaining pointers
171
+ this.resolvePointers(context);
172
+ // Write the extension data to the output JSON
173
+ context.jsonDoc.json.extensions = context.jsonDoc.json.extensions || {};
174
+ context.jsonDoc.json.extensions[EXTENSION_NAME] = this.extensionData;
175
+ return this;
176
+ }
177
+ // ── private ──────────────────────────────────────────────────
178
+ pointersResolved = false;
179
+ resolvePointers(context) {
180
+ if (this.pointersResolved)
181
+ return;
182
+ this.pointersResolved = true;
183
+ for (const { entry, texture, inputTextureDef } of this.resolved) {
184
+ if (entry.pointer.startsWith('/textures/') || entry.pointer.startsWith('textures/')) {
185
+ // Embedded: find the new texture index in the output JSON
186
+ const newIndex = this.findOrCreateTextureIndex(context, texture, inputTextureDef);
187
+ if (newIndex !== undefined) {
188
+ entry.pointer = `/textures/${newIndex}`;
189
+ }
190
+ }
191
+ else {
192
+ // External: use the texture's current URI (may have been updated by PMREM)
193
+ const uri = texture.getURI();
194
+ if (uri) {
195
+ entry.pointer = uri;
196
+ // Ensure the image definition in the output JSON has the URI set.
197
+ // When PMREM clears image data (setImage(null)) for external textures,
198
+ // gltf-transform's core writer won't set a uri or bufferView on the image.
199
+ const imageIndex = context.imageIndexMap.get(texture);
200
+ if (imageIndex !== undefined) {
201
+ const images = context.jsonDoc.json.images;
202
+ if (images && images[imageIndex]) {
203
+ images[imageIndex].uri = uri;
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ }
210
+ /**
211
+ * Find (or create) a texture def in the output JSON that references the given Texture.
212
+ * This replicates the logic from the opaque system's TextureIndexResolver.
213
+ */
214
+ findOrCreateTextureIndex(context, texture, inputTextureDef) {
215
+ const imageIndex = context.imageIndexMap.get(texture);
216
+ if (imageIndex === undefined)
217
+ return undefined;
218
+ const textures = context.jsonDoc.json.textures = context.jsonDoc.json.textures || [];
219
+ // Try to find an existing texture def pointing to the same image
220
+ for (let i = 0; i < textures.length; i++) {
221
+ const texDef = textures[i];
222
+ const source = texDef.source
223
+ ?? texDef.extensions?.['KHR_texture_basisu']?.source
224
+ ?? texDef.extensions?.['NEEDLE_pmrem']?.source;
225
+ if (source === imageIndex) {
226
+ return i;
227
+ }
228
+ }
229
+ // Not found — create a new texture definition
230
+ let extensions = inputTextureDef?.extensions ? { ...inputTextureDef.extensions } : undefined;
231
+ if (extensions) {
232
+ // Remove consumed extensions
233
+ delete extensions['NEEDLE_progressive_texture_settings'];
234
+ // Remove EXT_texture_exr if texture was converted
235
+ if (extensions['EXT_texture_exr'] && texture.getMimeType() !== 'image/exr') {
236
+ delete extensions['EXT_texture_exr'];
237
+ }
238
+ if (Object.keys(extensions).length === 0)
239
+ extensions = undefined;
240
+ }
241
+ const hasExtSource = extensions && Object.values(extensions).some((v) => v?.source !== undefined);
242
+ const texDef = {
243
+ source: hasExtSource ? undefined : imageIndex,
244
+ extensions,
245
+ };
246
+ textures.push(texDef);
247
+ return textures.length - 1;
248
+ }
249
+ }
@@ -10,7 +10,7 @@ export const ALL_EXTENSIONS = [
10
10
  createOpaqueExtension("NEEDLE_gameobject_data", PropertyType.NODE, { ...opaqueOptions }),
11
11
  createOpaqueExtension("NEEDLE_components", PropertyType.NODE, { ...opaqueOptions }),
12
12
  createOpaqueExtension("NEEDLE_persistent_assets", PropertyType.ROOT, { ...opaqueOptions }),
13
- createOpaqueExtension("NEEDLE_lightmaps", PropertyType.ROOT, { ...opaqueOptions }),
13
+ // NEEDLE_lightmaps is now handled by its own dedicated extension (NEEDLE_lightmaps/index.ts)
14
14
  createOpaqueExtension("NEEDLE_lighting_settings", PropertyType.ROOT, { ...opaqueOptions }),
15
15
  createOpaqueExtension("NEEDLE_render_objects", PropertyType.ROOT, { ...opaqueOptions }),
16
16
  createOpaqueExtension("NEEDLE_progressive", [PropertyType.TEXTURE, PropertyType.MATERIAL, PropertyType.MESH], { ...opaqueOptions }),
@@ -1,4 +1,4 @@
1
- import { Extension, Texture, WriterContext } from '@gltf-transform/core';
1
+ import { Extension, PropertyType, ReaderContext, Texture, WriterContext } from '@gltf-transform/core';
2
2
  /**
3
3
  * NEEDLE_pmrem extension for gltf-transform.
4
4
  * Marks textures that have been pre-processed with PMREM (EXR → KTX2 HDR).
@@ -13,7 +13,9 @@ export declare class NEEDLE_pmrem extends Extension {
13
13
  /** Mark a texture as PMREM-converted */
14
14
  addTexture(texture: Texture): void;
15
15
  /** @hidden */
16
- read(): this;
16
+ preread(context: ReaderContext, _propertyType: PropertyType): this;
17
+ /** @hidden */
18
+ read(context: ReaderContext): this;
17
19
  /** @hidden */
18
20
  write(context: WriterContext): this;
19
21
  }
@@ -16,7 +16,44 @@ export class NEEDLE_pmrem extends Extension {
16
16
  this.pmremTextures.add(texture);
17
17
  }
18
18
  /** @hidden */
19
- read() {
19
+ preread(context, _propertyType) {
20
+ const json = context.jsonDoc.json;
21
+ // For each texture with NEEDLE_pmrem, ensure `source` is set so the core reader
22
+ // links the texture to its image (we removed KHR_texture_basisu.source at write time).
23
+ for (const textureDef of json.textures ?? []) {
24
+ const pmrem = textureDef.extensions?.[EXTENSION_NAME];
25
+ if (pmrem?.source !== undefined && textureDef.source === undefined) {
26
+ textureDef.source = pmrem.source;
27
+ }
28
+ }
29
+ // Also ensure the image has the correct mime type
30
+ for (const textureDef of json.textures ?? []) {
31
+ const pmrem = textureDef.extensions?.[EXTENSION_NAME];
32
+ if (pmrem?.source !== undefined) {
33
+ const imageDef = json.images?.[pmrem.source];
34
+ if (imageDef && !imageDef.mimeType) {
35
+ imageDef.mimeType = 'image/ktx2';
36
+ }
37
+ }
38
+ }
39
+ return this;
40
+ }
41
+ /** @hidden */
42
+ read(context) {
43
+ const json = context.jsonDoc.json;
44
+ const textureDefs = json.textures ?? [];
45
+ const textures = this.document.getRoot().listTextures();
46
+ for (let i = 0; i < textureDefs.length; i++) {
47
+ const textureDef = textureDefs[i];
48
+ const pmrem = textureDef.extensions?.[EXTENSION_NAME];
49
+ if (pmrem?.source === undefined)
50
+ continue;
51
+ const texture = textures[i];
52
+ if (!texture)
53
+ continue;
54
+ texture.setMimeType('image/ktx2');
55
+ this.pmremTextures.add(texture);
56
+ }
20
57
  return this;
21
58
  }
22
59
  /** @hidden */
@@ -39,6 +76,20 @@ export class NEEDLE_pmrem extends Extension {
39
76
  }
40
77
  }
41
78
  }
79
+ // If no textures still use KHR_texture_basisu, remove it from extensionsUsed/Required
80
+ // to prevent KHRTextureBasisu.preread() from crashing when re-reading the GLB
81
+ const anyBasisu = (jsonDoc.json.textures ?? []).some((t) => t.extensions?.['KHR_texture_basisu']);
82
+ if (!anyBasisu) {
83
+ const remove = (arr) => {
84
+ if (!arr)
85
+ return;
86
+ const idx = arr.indexOf('KHR_texture_basisu');
87
+ if (idx >= 0)
88
+ arr.splice(idx, 1);
89
+ };
90
+ remove(jsonDoc.json.extensionsUsed);
91
+ remove(jsonDoc.json.extensionsRequired);
92
+ }
42
93
  return this;
43
94
  }
44
95
  }
@@ -5,4 +5,5 @@ export * from "./NEEDLE_progressive/index.js";
5
5
  export * from "./NEEDLE_progressive_texture_settings/index.js";
6
6
  export * from "./NEEDLE_progressive_mesh_settings/index.js";
7
7
  export * from "./NEEDLE_pmrem/index.js";
8
+ export * from "./NEEDLE_lightmaps/index.js";
8
9
  export declare function registerExtensions(node: any): void;
@@ -6,13 +6,18 @@ export * from "./NEEDLE_progressive/index.js";
6
6
  export * from "./NEEDLE_progressive_texture_settings/index.js";
7
7
  export * from "./NEEDLE_progressive_mesh_settings/index.js";
8
8
  export * from "./NEEDLE_pmrem/index.js";
9
+ export * from "./NEEDLE_lightmaps/index.js";
9
10
  import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
10
11
  import { ALL_EXTENSIONS as NEEDLE_EXTENSIONS } from "./NEEDLE_opaque/index.js";
11
12
  import { NEEDLE_progressive } from './NEEDLE_progressive/index.js';
13
+ import { NEEDLE_pmrem } from './NEEDLE_pmrem/index.js';
14
+ import { NEEDLE_lightmaps_ext } from './NEEDLE_lightmaps/index.js';
12
15
  export function registerExtensions(node) {
13
16
  node.registerExtensions(ALL_EXTENSIONS);
14
17
  node.registerExtensions(NEEDLE_EXTENSIONS);
15
18
  node.registerExtensions([
16
- NEEDLE_progressive
19
+ NEEDLE_progressive,
20
+ NEEDLE_pmrem,
21
+ NEEDLE_lightmaps_ext,
17
22
  ]);
18
23
  }
@@ -5,7 +5,7 @@ import draco3d from 'draco3dgltf';
5
5
  import { existsSync, readFileSync, statSync, writeFileSync } from 'fs';
6
6
  import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
7
7
  import { dedup, metalRough, prune, resample } from '@gltf-transform/functions';
8
- import { ALL_EXTENSIONS as NEEDLE_EXTENSIONS, NEEDLE_compression_texture, NEEDLE_mesh_compression, NEEDLE_pmrem, } from '../extensions/index.js';
8
+ import { ALL_EXTENSIONS as NEEDLE_EXTENSIONS, NEEDLE_compression_texture, NEEDLE_mesh_compression, NEEDLE_pmrem, NEEDLE_lightmaps_ext, } from '../extensions/index.js';
9
9
  import { isLOD, isMeshLOD, needle_animation_transform, needle_asset, needle_mesh_transform, needle_texture_transform, } from '../transforms/index.js';
10
10
  import { getOutputPath, getVersion, ioTryReadWithMissingResources, writeNodeIO } from "../utils/index.js";
11
11
  import { addToCache, getHash, tryGetFromCache, } from "../cache/index.js";
@@ -58,6 +58,7 @@ export async function packGLTF(inputFile, outputFile, options) {
58
58
  NEEDLE_compression_texture,
59
59
  NEEDLE_mesh_compression,
60
60
  NEEDLE_pmrem,
61
+ NEEDLE_lightmaps_ext,
61
62
  ])
62
63
  .registerDependencies({
63
64
  'draco3d.decoder': await draco3d.createDecoderModule(),
@@ -65,7 +66,9 @@ export async function packGLTF(inputFile, outputFile, options) {
65
66
  'meshopt.decoder': MeshoptDecoder,
66
67
  'meshopt.encoder': MeshoptEncoder,
67
68
  });
68
- const document = await ioTryReadWithMissingResources(io, inputFile); // await io.read(inputFile);
69
+ // Set input file path so NEEDLE_lightmaps can resolve external EXR files during preread
70
+ NEEDLE_lightmaps_ext.inputFile = inputFile;
71
+ const document = await ioTryReadWithMissingResources(io, inputFile);
69
72
  if (options.logger) {
70
73
  document.setLogger(options.logger);
71
74
  }
@@ -138,7 +141,7 @@ export async function packGLTF(inputFile, outputFile, options) {
138
141
  if (err instanceof TestAssertionError)
139
142
  throw err;
140
143
  const shortedStackTrace = err instanceof Error && err.stack ? err.stack.split('\n').slice(0, 2).join('\n') : '';
141
- logger.error(`Packing of "${path.basename(inputFile)}" using version ${getVersion()} failed with error:\n${err.message}\n${shortedStackTrace}`);
144
+ logger.error(`Packing of "${path.basename(inputFile)}" using version ${getVersion()} failed with error:\n${err instanceof Error ? err.message : String(err)}\n${shortedStackTrace}`);
142
145
  if (debug)
143
146
  throw err;
144
147
  return false;
@@ -11,6 +11,6 @@ export declare class NeedlePmremContext implements INeedleTextureTransformContex
11
11
  private logger;
12
12
  private readonly convertedTextures;
13
13
  prepare(document: Document): Promise<boolean>;
14
- process(index: number, texture: Texture, _settings: NEEDLE_compression_texture_schema | null, _context: NeedleTransformContext): Promise<boolean>;
14
+ process(index: number, texture: Texture, _settings: NEEDLE_compression_texture_schema | null, context: NeedleTransformContext): Promise<boolean>;
15
15
  finalize(document: Document): Promise<void>;
16
16
  }
@@ -81,14 +81,14 @@ export class NeedlePmremContext {
81
81
  this.logger.warn(`pmrem: Failed to load WASM — ${err.message}`);
82
82
  return false;
83
83
  }
84
- // Create temp directory
85
- this.tmpDir = join(tmp.tmpdir, 'needle-pmrem');
84
+ // Create temp directory (per-instance to avoid parallel cleanup races)
85
+ this.tmpDir = join(tmp.tmpdir, 'needle-pmrem', uuid());
86
86
  mkdirSync(this.tmpDir, { recursive: true });
87
87
  this.available = true;
88
- this.logger.info('pmrem: Ready (WASM + basisu loaded)');
88
+ this.logger.debug('pmrem: Ready (WASM + basisu loaded)');
89
89
  return true;
90
90
  }
91
- async process(index, texture, _settings, _context) {
91
+ async process(index, texture, _settings, context) {
92
92
  if (!this.available)
93
93
  return false;
94
94
  if (texture.getMimeType() !== 'image/exr')
@@ -98,6 +98,7 @@ export class NeedlePmremContext {
98
98
  return false;
99
99
  const name = texture.getName() || `texture_${index}`;
100
100
  const id = uuid();
101
+ const wasExternal = !!texture.getURI();
101
102
  // 1. Run PMREM on the EXR bytes
102
103
  this.logger.info(`pmrem:texture[${index}] ${name}: Running PMREM...`);
103
104
  const exrBytes = new Uint8Array(image.buffer, image.byteOffset, image.byteLength);
@@ -107,7 +108,7 @@ export class NeedlePmremContext {
107
108
  const tempKtx2 = join(this.tmpDir, `${id}.ktx2`);
108
109
  writeFileSync(tempExr, Buffer.from(pmremExrBytes));
109
110
  // 3. Encode to KTX2 HDR via basisu
110
- this.logger.info(`pmrem:texture[${index}] ${name}: Encoding KTX2 HDR...`);
111
+ this.logger.debug(`pmrem:texture[${index}] ${name}: Encoding KTX2 HDR...`);
111
112
  const variant = 'hdr4x4'; // 6x6 needs an update in Needle
112
113
  await encodeKTX2WithBasisu(this.basisuExe, tempExr, tempKtx2, variant, true);
113
114
  if (!existsSync(tempKtx2)) {
@@ -115,23 +116,43 @@ export class NeedlePmremContext {
115
116
  }
116
117
  // 4. Read KTX2 and update texture
117
118
  const ktx2Bytes = readFileSync(tempKtx2);
118
- texture.setImage(new Uint8Array(ktx2Bytes));
119
- texture.setMimeType('image/ktx2');
120
119
  // Remove EXT_texture_exr property since the texture is now KTX2
121
120
  const exrProp = texture.getExtension('EXT_texture_exr');
122
121
  if (exrProp) {
123
122
  texture.setExtension('EXT_texture_exr', null);
124
123
  exrProp.dispose();
125
124
  }
126
- // Update URI
127
- const uri = texture.getURI();
128
- if (uri) {
125
+ texture.setMimeType('image/ktx2');
126
+ if (wasExternal) {
127
+ // Keep the texture external: write .pmrem.ktx2 file next to the output GLB
128
+ const uri = texture.getURI();
129
129
  const newUri = uri.replace(/\.exr$/i, '.pmrem.ktx2');
130
- texture.setURI(newUri !== uri ? newUri : uri + '.pmrem.ktx2');
130
+ const ktx2FileName = newUri !== uri ? newUri : uri + '.pmrem.ktx2';
131
+ const outDir = dirname(context.outfile);
132
+ writeFileSync(join(outDir, ktx2FileName), ktx2Bytes);
133
+ // Remove the original EXR file from the output directory
134
+ const originalExrPath = join(outDir, uri);
135
+ if (existsSync(originalExrPath)) {
136
+ rmSync(originalExrPath);
137
+ }
138
+ texture.setURI(ktx2FileName);
139
+ texture.setName(ktx2FileName);
140
+ // Clear image data so gltf-transform doesn't embed it in the GLB
141
+ texture.setImage(null);
142
+ this.logger.info(`pmrem:texture[${index}] ${name}: external → ${ktx2FileName}`);
143
+ }
144
+ else {
145
+ // Bundled: embed the KTX2 in the GLB
146
+ texture.setImage(new Uint8Array(ktx2Bytes));
131
147
  }
132
- const srcKB = (image.byteLength / 1024).toFixed(0);
133
- const dstKB = (ktx2Bytes.byteLength / 1024).toFixed(0);
134
- this.logger.info(`pmrem:texture[${index}] ${name}: ${srcKB} KB EXR → ${dstKB} KB KTX2`);
148
+ // Report size
149
+ const sizeStr = image.byteLength < 100 * 1024
150
+ ? `${(image.byteLength / 1024).toFixed(0)} KB`
151
+ : `${(image.byteLength / (1024 * 1024)).toFixed(2)} MB`;
152
+ const dstSizestr = ktx2Bytes.length < 100 * 1024
153
+ ? `${(ktx2Bytes.length / 1024).toFixed(0)} KB`
154
+ : `${(ktx2Bytes.length / (1024 * 1024)).toFixed(2)} MB`;
155
+ this.logger.info(`pmrem:texture[${index}] ${name}: ${sizeStr} EXR → ${dstSizestr} KTX2`);
135
156
  this.convertedTextures.push(texture);
136
157
  this.processed++;
137
158
  return true;
@@ -139,9 +160,6 @@ export class NeedlePmremContext {
139
160
  async finalize(document) {
140
161
  if (this.processed > 0) {
141
162
  // Register NEEDLE_pmrem extension and mark converted textures
142
- // Note: we do NOT register KHR_texture_basisu here — the NEEDLE_pmrem extension
143
- // writer removes KHR_texture_basisu from texture defs so the runtime NEEDLE_pmrem
144
- // plugin handles loading instead of three.js's built-in handler.
145
163
  const pmremExt = document.createExtension(NEEDLE_pmrem);
146
164
  for (const tex of this.convertedTextures) {
147
165
  pmremExt.addTexture(tex);
@@ -11,7 +11,7 @@ export function validateImageMimeType(mimetype, image) {
11
11
  };
12
12
  }
13
13
  else if (actualMimeType === null) {
14
- console.warn(`WARN: Could not validate image type for \"${mimetype}\"`);
14
+ console.warn(`WARN: Could not validate image type: \"${mimetype}\"`);
15
15
  }
16
16
  return null;
17
17
  }
@@ -1 +1 @@
1
- export declare const version = "2.15.0-next.adb3357";
1
+ export declare const version = "2.15.0-next.ca2fe5b";
@@ -1 +1 @@
1
- export const version = "2.15.0-next.adb3357";
1
+ export const version = "2.15.0-next.ca2fe5b";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/gltf-build-pipeline",
3
- "version": "2.15.0-next.adb3357",
3
+ "version": "2.15.0-next.ca2fe5b",
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