@needle-tools/gltf-build-pipeline 2.15.0-next.0c5bc39 → 2.15.0-next.6fb464d
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/dist/extensions/NEEDLE_lightmaps/index.d.ts +41 -0
- package/dist/extensions/NEEDLE_lightmaps/index.js +249 -0
- package/dist/extensions/NEEDLE_opaque/NEEDLE_opaque.js +9 -1
- package/dist/extensions/NEEDLE_opaque/index.js +1 -1
- package/dist/extensions/NEEDLE_pmrem/index.d.ts +19 -0
- package/dist/extensions/NEEDLE_pmrem/index.js +44 -0
- package/dist/extensions/index.d.ts +2 -0
- package/dist/extensions/index.js +2 -0
- package/dist/scripts/pack-gltf.js +7 -3
- package/dist/transforms/needle_pmrem.d.ts +16 -0
- package/dist/transforms/needle_pmrem.js +185 -0
- package/dist/transforms/needle_texture_transform.d.ts +2 -0
- package/dist/transforms/needle_texture_transform.js +12 -2
- package/dist/utils/version.gen.d.ts +1 -1
- package/dist/utils/version.gen.js +1 -1
- package/package.json +4 -2
- package/tools/pmrem/basis/linux/basisu +0 -0
- package/tools/pmrem/basis/osx/basisu +0 -0
- package/tools/pmrem/basis/package.json +3 -0
- package/tools/pmrem/basis/wasm/basis_encoder_threads.js +6693 -0
- package/tools/pmrem/basis/wasm/basis_encoder_threads.wasm +0 -0
- package/tools/pmrem/basis/win/basisu.exe +0 -0
- package/tools/pmrem/basis/win/basisu_help.txt +0 -0
- package/tools/pmrem/basis/win/ocl_kernels.cl +1290 -0
- package/tools/pmrem/pkg/pmrem_wasm.d.ts +68 -0
- package/tools/pmrem/pkg/pmrem_wasm.js +401 -0
- package/tools/pmrem/pkg/pmrem_wasm_bg.wasm +0 -0
|
@@ -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
|
+
}
|
|
@@ -415,6 +415,10 @@ class TextureHandler {
|
|
|
415
415
|
}
|
|
416
416
|
}
|
|
417
417
|
write(ctx) {
|
|
418
|
+
// If the texture was converted (e.g. EXR → KTX2 via PMREM), skip writing the old extension
|
|
419
|
+
if (this.key === "EXT_texture_exr" && this.textureRef.getMimeType() !== "image/exr") {
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
418
422
|
// Resolve the current image index from the gltf-transform graph reference.
|
|
419
423
|
// This is stable even after dedup/prune operations that re-index images.
|
|
420
424
|
const imageIndex = ctx.imageIndexMap.get(this.textureRef);
|
|
@@ -889,10 +893,14 @@ class TextureIndexResolver extends PointerResolver {
|
|
|
889
893
|
// create a new texture def entry
|
|
890
894
|
if (this.debug)
|
|
891
895
|
console.log("Could not find texture, creating a new one: " + this._debugName);
|
|
892
|
-
// Remove
|
|
896
|
+
// Remove extensions that are consumed during processing and should not appear in the output.
|
|
893
897
|
let extensions = this.inputDefinition.extensions ? { ...this.inputDefinition.extensions } : undefined;
|
|
894
898
|
if (extensions) {
|
|
895
899
|
delete extensions[NEEDLE_progressive_texture_settings.EXTENSION_NAME];
|
|
900
|
+
// Remove EXT_texture_exr if the texture was converted (e.g. EXR → KTX2 via PMREM)
|
|
901
|
+
if (extensions["EXT_texture_exr"] && this.inputObject.getMimeType() !== "image/exr") {
|
|
902
|
+
delete extensions["EXT_texture_exr"];
|
|
903
|
+
}
|
|
896
904
|
if (Object.keys(extensions).length === 0)
|
|
897
905
|
extensions = undefined;
|
|
898
906
|
}
|
|
@@ -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
|
-
|
|
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 }),
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Extension, Texture, WriterContext } from '@gltf-transform/core';
|
|
2
|
+
/**
|
|
3
|
+
* NEEDLE_pmrem extension for gltf-transform.
|
|
4
|
+
* Marks textures that have been pre-processed with PMREM (EXR → KTX2 HDR).
|
|
5
|
+
* At write time, adds `NEEDLE_pmrem: { source: imageIndex }` to each marked texture
|
|
6
|
+
* so the Needle Engine runtime can load them correctly with CubeUVReflectionMapping.
|
|
7
|
+
*/
|
|
8
|
+
export declare class NEEDLE_pmrem extends Extension {
|
|
9
|
+
static readonly EXTENSION_NAME = "NEEDLE_pmrem";
|
|
10
|
+
readonly extensionName = "NEEDLE_pmrem";
|
|
11
|
+
/** Textures that were converted from EXR via PMREM */
|
|
12
|
+
private readonly pmremTextures;
|
|
13
|
+
/** Mark a texture as PMREM-converted */
|
|
14
|
+
addTexture(texture: Texture): void;
|
|
15
|
+
/** @hidden */
|
|
16
|
+
read(): this;
|
|
17
|
+
/** @hidden */
|
|
18
|
+
write(context: WriterContext): this;
|
|
19
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Extension } from '@gltf-transform/core';
|
|
2
|
+
const EXTENSION_NAME = 'NEEDLE_pmrem';
|
|
3
|
+
/**
|
|
4
|
+
* NEEDLE_pmrem extension for gltf-transform.
|
|
5
|
+
* Marks textures that have been pre-processed with PMREM (EXR → KTX2 HDR).
|
|
6
|
+
* At write time, adds `NEEDLE_pmrem: { source: imageIndex }` to each marked texture
|
|
7
|
+
* so the Needle Engine runtime can load them correctly with CubeUVReflectionMapping.
|
|
8
|
+
*/
|
|
9
|
+
export class NEEDLE_pmrem extends Extension {
|
|
10
|
+
static EXTENSION_NAME = EXTENSION_NAME;
|
|
11
|
+
extensionName = EXTENSION_NAME;
|
|
12
|
+
/** Textures that were converted from EXR via PMREM */
|
|
13
|
+
pmremTextures = new Set();
|
|
14
|
+
/** Mark a texture as PMREM-converted */
|
|
15
|
+
addTexture(texture) {
|
|
16
|
+
this.pmremTextures.add(texture);
|
|
17
|
+
}
|
|
18
|
+
/** @hidden */
|
|
19
|
+
read() {
|
|
20
|
+
return this;
|
|
21
|
+
}
|
|
22
|
+
/** @hidden */
|
|
23
|
+
write(context) {
|
|
24
|
+
const jsonDoc = context.jsonDoc;
|
|
25
|
+
for (const texture of this.pmremTextures) {
|
|
26
|
+
const imageIndex = context.imageIndexMap.get(texture);
|
|
27
|
+
if (imageIndex === undefined)
|
|
28
|
+
continue;
|
|
29
|
+
// Find texture defs that reference this image
|
|
30
|
+
for (const textureDef of jsonDoc.json.textures ?? []) {
|
|
31
|
+
const source = textureDef.source
|
|
32
|
+
?? textureDef.extensions?.['KHR_texture_basisu']?.source;
|
|
33
|
+
if (source === imageIndex) {
|
|
34
|
+
textureDef.extensions = textureDef.extensions || {};
|
|
35
|
+
textureDef.extensions[EXTENSION_NAME] = { source: imageIndex };
|
|
36
|
+
// Remove KHR_texture_basisu so the runtime NEEDLE_pmrem plugin handles loading
|
|
37
|
+
// (otherwise three.js's built-in KHR_texture_basisu handler intercepts it first)
|
|
38
|
+
delete textureDef.extensions['KHR_texture_basisu'];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return this;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -4,4 +4,6 @@ export * from "./NEEDLE_compression_texture/index.js";
|
|
|
4
4
|
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
|
+
export * from "./NEEDLE_pmrem/index.js";
|
|
8
|
+
export * from "./NEEDLE_lightmaps/index.js";
|
|
7
9
|
export declare function registerExtensions(node: any): void;
|
package/dist/extensions/index.js
CHANGED
|
@@ -5,6 +5,8 @@ export * from "./NEEDLE_compression_texture/index.js";
|
|
|
5
5
|
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
|
+
export * from "./NEEDLE_pmrem/index.js";
|
|
9
|
+
export * from "./NEEDLE_lightmaps/index.js";
|
|
8
10
|
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
|
|
9
11
|
import { ALL_EXTENSIONS as NEEDLE_EXTENSIONS } from "./NEEDLE_opaque/index.js";
|
|
10
12
|
import { NEEDLE_progressive } from './NEEDLE_progressive/index.js';
|
|
@@ -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, } 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";
|
|
@@ -57,6 +57,8 @@ export async function packGLTF(inputFile, outputFile, options) {
|
|
|
57
57
|
.registerExtensions([
|
|
58
58
|
NEEDLE_compression_texture,
|
|
59
59
|
NEEDLE_mesh_compression,
|
|
60
|
+
NEEDLE_pmrem,
|
|
61
|
+
NEEDLE_lightmaps_ext,
|
|
60
62
|
])
|
|
61
63
|
.registerDependencies({
|
|
62
64
|
'draco3d.decoder': await draco3d.createDecoderModule(),
|
|
@@ -64,7 +66,9 @@ export async function packGLTF(inputFile, outputFile, options) {
|
|
|
64
66
|
'meshopt.decoder': MeshoptDecoder,
|
|
65
67
|
'meshopt.encoder': MeshoptEncoder,
|
|
66
68
|
});
|
|
67
|
-
|
|
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);
|
|
68
72
|
if (options.logger) {
|
|
69
73
|
document.setLogger(options.logger);
|
|
70
74
|
}
|
|
@@ -137,7 +141,7 @@ export async function packGLTF(inputFile, outputFile, options) {
|
|
|
137
141
|
if (err instanceof TestAssertionError)
|
|
138
142
|
throw err;
|
|
139
143
|
const shortedStackTrace = err instanceof Error && err.stack ? err.stack.split('\n').slice(0, 2).join('\n') : '';
|
|
140
|
-
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}`);
|
|
141
145
|
if (debug)
|
|
142
146
|
throw err;
|
|
143
147
|
return false;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Document, Texture } from '@gltf-transform/core';
|
|
2
|
+
import { NEEDLE_compression_texture_schema } from '../extensions/index.js';
|
|
3
|
+
import { INeedleTextureTransformContext, NeedleTransformContext } from './needle_common.js';
|
|
4
|
+
export declare class NeedlePmremContext implements INeedleTextureTransformContext {
|
|
5
|
+
private wasmModule;
|
|
6
|
+
private pmremDir;
|
|
7
|
+
private basisuExe;
|
|
8
|
+
private tmpDir;
|
|
9
|
+
private processed;
|
|
10
|
+
private available;
|
|
11
|
+
private logger;
|
|
12
|
+
private readonly convertedTextures;
|
|
13
|
+
prepare(document: Document): Promise<boolean>;
|
|
14
|
+
process(index: number, texture: Texture, _settings: NEEDLE_compression_texture_schema | null, context: NeedleTransformContext): Promise<boolean>;
|
|
15
|
+
finalize(document: Document): Promise<void>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { NEEDLE_pmrem } from '../extensions/index.js';
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, chmodSync } from 'fs';
|
|
3
|
+
import { join, dirname } from 'path';
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from 'url';
|
|
5
|
+
import { execFile } from 'child_process';
|
|
6
|
+
import { v4 as uuid } from 'uuid';
|
|
7
|
+
import tmp from 'tmp';
|
|
8
|
+
/** Resolve the tools/pmrem/ directory relative to this file.
|
|
9
|
+
* At runtime this file is at dist/transforms/needle_pmrem.js,
|
|
10
|
+
* so tools/pmrem/ is at ../../tools/pmrem/ */
|
|
11
|
+
function getPmremDir() {
|
|
12
|
+
const thisDir = dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
return join(thisDir, '..', '..', 'tools', 'pmrem');
|
|
14
|
+
}
|
|
15
|
+
function resolveBasisuExe(pmremDir) {
|
|
16
|
+
const platform = process.platform;
|
|
17
|
+
const base = join(pmremDir, 'basis');
|
|
18
|
+
if (platform === 'win32')
|
|
19
|
+
return join(base, 'win', 'basisu.exe');
|
|
20
|
+
if (platform === 'darwin')
|
|
21
|
+
return join(base, 'osx', 'basisu');
|
|
22
|
+
return join(base, 'linux', 'basisu');
|
|
23
|
+
}
|
|
24
|
+
function encodeKTX2WithBasisu(basisuExe, exrPath, outPath, variant, mipmaps) {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const args = [];
|
|
27
|
+
args.push(variant === 'hdr6x6' ? '-hdr_6x6' : '-hdr_4x4');
|
|
28
|
+
if (mipmaps)
|
|
29
|
+
args.push('-mipmap');
|
|
30
|
+
args.push('-file', exrPath, '-output_file', outPath, '-y_flip');
|
|
31
|
+
execFile(basisuExe, args, { windowsHide: true, encoding: 'utf8' }, (err, _stdout, stderr) => {
|
|
32
|
+
if (err) {
|
|
33
|
+
reject(new Error(`basisu failed: ${stderr || err.message}`));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
resolve();
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export class NeedlePmremContext {
|
|
41
|
+
wasmModule = null;
|
|
42
|
+
pmremDir = '';
|
|
43
|
+
basisuExe = '';
|
|
44
|
+
tmpDir = '';
|
|
45
|
+
processed = 0;
|
|
46
|
+
available = false;
|
|
47
|
+
logger;
|
|
48
|
+
convertedTextures = [];
|
|
49
|
+
async prepare(document) {
|
|
50
|
+
this.logger = document.getLogger();
|
|
51
|
+
this.processed = 0;
|
|
52
|
+
this.pmremDir = getPmremDir();
|
|
53
|
+
// Check WASM exists
|
|
54
|
+
const wasmJsPath = join(this.pmremDir, 'pkg', 'pmrem_wasm.js');
|
|
55
|
+
const wasmBinPath = join(this.pmremDir, 'pkg', 'pmrem_wasm_bg.wasm');
|
|
56
|
+
if (!existsSync(wasmJsPath) || !existsSync(wasmBinPath)) {
|
|
57
|
+
this.logger.warn('pmrem: WASM not found — EXR textures will not be processed');
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
// Check basisu binary
|
|
61
|
+
this.basisuExe = resolveBasisuExe(this.pmremDir);
|
|
62
|
+
if (!existsSync(this.basisuExe)) {
|
|
63
|
+
this.logger.warn(`pmrem: basisu binary not found at ${this.basisuExe} — EXR textures will not be processed`);
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
// Set executable permission
|
|
67
|
+
if (process.platform !== 'win32') {
|
|
68
|
+
try {
|
|
69
|
+
chmodSync(this.basisuExe, 0o755);
|
|
70
|
+
}
|
|
71
|
+
catch { /* ignore */ }
|
|
72
|
+
}
|
|
73
|
+
// Load WASM
|
|
74
|
+
try {
|
|
75
|
+
const mod = await import(pathToFileURL(wasmJsPath).href);
|
|
76
|
+
const wasmBytes = readFileSync(wasmBinPath);
|
|
77
|
+
await mod.default({ module_or_path: wasmBytes });
|
|
78
|
+
this.wasmModule = mod;
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
this.logger.warn(`pmrem: Failed to load WASM — ${err.message}`);
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
// Create temp directory
|
|
85
|
+
this.tmpDir = join(tmp.tmpdir, 'needle-pmrem');
|
|
86
|
+
mkdirSync(this.tmpDir, { recursive: true });
|
|
87
|
+
this.available = true;
|
|
88
|
+
this.logger.debug('pmrem: Ready (WASM + basisu loaded)');
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
async process(index, texture, _settings, context) {
|
|
92
|
+
if (!this.available)
|
|
93
|
+
return false;
|
|
94
|
+
if (texture.getMimeType() !== 'image/exr')
|
|
95
|
+
return false;
|
|
96
|
+
const image = texture.getImage();
|
|
97
|
+
if (!image)
|
|
98
|
+
return false;
|
|
99
|
+
const name = texture.getName() || `texture_${index}`;
|
|
100
|
+
const id = uuid();
|
|
101
|
+
const wasExternal = !!texture.getURI();
|
|
102
|
+
// 1. Run PMREM on the EXR bytes
|
|
103
|
+
this.logger.info(`pmrem:texture[${index}] ${name}: Running PMREM...`);
|
|
104
|
+
const exrBytes = new Uint8Array(image.buffer, image.byteOffset, image.byteLength);
|
|
105
|
+
const pmremExrBytes = this.wasmModule.pmrem_exr(exrBytes);
|
|
106
|
+
// 2. Write PMREM EXR to temp file
|
|
107
|
+
const tempExr = join(this.tmpDir, `${id}.pmrem.exr`);
|
|
108
|
+
const tempKtx2 = join(this.tmpDir, `${id}.ktx2`);
|
|
109
|
+
writeFileSync(tempExr, Buffer.from(pmremExrBytes));
|
|
110
|
+
// 3. Encode to KTX2 HDR via basisu
|
|
111
|
+
this.logger.debug(`pmrem:texture[${index}] ${name}: Encoding KTX2 HDR...`);
|
|
112
|
+
const variant = 'hdr4x4'; // 6x6 needs an update in Needle
|
|
113
|
+
await encodeKTX2WithBasisu(this.basisuExe, tempExr, tempKtx2, variant, true);
|
|
114
|
+
if (!existsSync(tempKtx2)) {
|
|
115
|
+
throw new Error(`pmrem:texture[${index}] ${name}: basisu did not produce output`);
|
|
116
|
+
}
|
|
117
|
+
// 4. Read KTX2 and update texture
|
|
118
|
+
const ktx2Bytes = readFileSync(tempKtx2);
|
|
119
|
+
// Remove EXT_texture_exr property since the texture is now KTX2
|
|
120
|
+
const exrProp = texture.getExtension('EXT_texture_exr');
|
|
121
|
+
if (exrProp) {
|
|
122
|
+
texture.setExtension('EXT_texture_exr', null);
|
|
123
|
+
exrProp.dispose();
|
|
124
|
+
}
|
|
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
|
+
const newUri = uri.replace(/\.exr$/i, '.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));
|
|
147
|
+
}
|
|
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`);
|
|
156
|
+
this.convertedTextures.push(texture);
|
|
157
|
+
this.processed++;
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
160
|
+
async finalize(document) {
|
|
161
|
+
if (this.processed > 0) {
|
|
162
|
+
// Register NEEDLE_pmrem extension and mark converted textures
|
|
163
|
+
const pmremExt = document.createExtension(NEEDLE_pmrem);
|
|
164
|
+
for (const tex of this.convertedTextures) {
|
|
165
|
+
pmremExt.addTexture(tex);
|
|
166
|
+
}
|
|
167
|
+
// If no textures use EXR anymore, remove the EXT_texture_exr extension from the document
|
|
168
|
+
const hasExr = document.getRoot().listTextures().some(t => t.getMimeType() === 'image/exr');
|
|
169
|
+
if (!hasExr) {
|
|
170
|
+
const exrExt = document.getRoot().listExtensionsUsed()
|
|
171
|
+
.find(e => e.extensionName === 'EXT_texture_exr');
|
|
172
|
+
if (exrExt) {
|
|
173
|
+
exrExt.dispose();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
// Clean up temp directory
|
|
178
|
+
if (this.tmpDir && existsSync(this.tmpDir)) {
|
|
179
|
+
try {
|
|
180
|
+
rmSync(this.tmpDir, { recursive: true });
|
|
181
|
+
}
|
|
182
|
+
catch { /* ignore */ }
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|