@needle-tools/materialx 1.1.1-next.623fc20 → 1.1.1-next.8e8afe1

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,13 @@
1
+ import { WebGLRenderer, WebGLRenderTarget, Texture } from 'three';
2
+
3
+ /**
4
+ * Renders a PMREM environment map to an equirectangular texture with specified roughness
5
+ */
6
+ export function renderPMREMToEquirect(
7
+ renderer: WebGLRenderer,
8
+ pmremTexture: Texture,
9
+ roughness?: number,
10
+ width?: number,
11
+ height?: number,
12
+ renderTargetHeight?: number
13
+ ): WebGLRenderTarget;
@@ -1,4 +1,4 @@
1
- import { WebGLRenderer, Scene, WebGLRenderTarget, PlaneGeometry, OrthographicCamera, ShaderMaterial, RGBAFormat, FloatType, LinearFilter, Mesh, EquirectangularReflectionMapping, RepeatWrapping, LinearMipMapLinearFilter, Texture, WebGLUtils } from 'three';
1
+ import { WebGLRenderer, Scene, WebGLRenderTarget, PlaneGeometry, OrthographicCamera, ShaderMaterial, RGBAFormat, FloatType, LinearFilter, Mesh, EquirectangularReflectionMapping, RepeatWrapping, LinearMipMapLinearFilter, Texture } from 'three';
2
2
  import { getParam } from './utils.js';
3
3
 
4
4
  const debug = getParam("debugmaterialx");
@@ -7,25 +7,26 @@ const debug = getParam("debugmaterialx");
7
7
  * Renders a PMREM environment map to an equirectangular texture with specified roughness
8
8
  * @param {WebGLRenderer} renderer - Three.js WebGL renderer
9
9
  * @param {Texture} pmremTexture - PMREM texture (2D CubeUV layout) to convert
10
- * @param {number} roughness - Roughness value (0.0 to 1.0)
11
- * @param {number} width - Output texture width (default: 1024)
12
- * @param {number} height - Output texture height (default: 512)
13
- * @param {number} renderTargetHeight - Original render target height (optional, for proper PMREM parameter calculation)
10
+ * @param {number} [roughness=0.0] - Roughness value (0.0 to 1.0)
11
+ * @param {number} [width=1024] - Output texture width
12
+ * @param {number} [height=512] - Output texture height
13
+ * @param {number} [renderTargetHeight] - Original render target height (optional, for proper PMREM parameter calculation)
14
14
  * @returns {WebGLRenderTarget} Render target containing the equirectangular texture
15
- * @example // Creating an equirectangular texture from a PMREM environment map at a certain roughness level:
15
+ * @example
16
+ * // Creating an equirectangular texture from a PMREM environment map at a certain roughness level:
16
17
  * const pmremRenderTarget = pmremGenerator.fromEquirectangular(envMap);
17
18
  * const equirectRenderTarget = await renderPMREMToEquirect(renderer, pmremRenderTarget.texture, 0.5, 2048, 1024, pmremRenderTarget.height);
18
-
19
- // Use the rendered equirectangular texture
20
- const equirectTexture = equirectRenderTarget.texture;
21
-
22
- // Apply to your material or save/export
23
- someMaterial.map = equirectTexture;
24
-
25
- // Don't forget to dispose when done
26
- // equirectRenderTarget.dispose();
19
+ *
20
+ * // Use the rendered equirectangular texture
21
+ * const equirectTexture = equirectRenderTarget.texture;
22
+ *
23
+ * // Apply to your material or save/export
24
+ * someMaterial.map = equirectTexture;
25
+ *
26
+ * // Don't forget to dispose when done
27
+ * // equirectRenderTarget.dispose();
27
28
  */
28
- export function renderPMREMToEquirect(renderer: WebGLRenderer, pmremTexture: Texture, roughness = 0.0, width = 1024, height = 512, renderTargetHeight?: number) {
29
+ export function renderPMREMToEquirect(renderer, pmremTexture, roughness = 0.0, width = 1024, height = 512, renderTargetHeight) {
29
30
  // TODO Validate inputs
30
31
  // console.log(renderer, pmremTexture);
31
32
 
@@ -167,4 +168,4 @@ export function renderPMREMToEquirect(renderer: WebGLRenderer, pmremTexture: Tex
167
168
  });
168
169
 
169
170
  return renderTarget;
170
- }
171
+ }
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- export { ready, type MaterialXContext } from "./materialx.js";
2
- export { MaterialXMaterial } from "./materialx.material.js";
3
- export { MaterialXLoader } from "./loader/loader.three.js";
@@ -1,43 +0,0 @@
1
- import { addCustomExtensionPlugin } from "@needle-tools/engine";
2
- import { Context, GLTF, INeedleGLTFExtensionPlugin } from "@needle-tools/engine";
3
- import type { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
4
- import type { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
5
- import { useNeedleMaterialX as _useNeedleMaterialX, MaterialXLoader } from "./loader.three.js";
6
- import { debug } from "../utils.js";
7
- import { MaterialParameters } from "three";
8
-
9
-
10
- export class MaterialXLoaderPlugin implements INeedleGLTFExtensionPlugin {
11
- readonly name = "MaterialXLoaderPlugin";
12
-
13
- private loader: MaterialXLoader | null = null;
14
-
15
- onImport = (loader: GLTFLoader, url: string, context: Context) => {
16
- if (debug) console.log("MaterialXLoaderPlugin: Registering MaterialX extension for", url);
17
- _useNeedleMaterialX(loader, {
18
- cacheKey: url,
19
- parameters: {
20
- precision: context.renderer.capabilities.getMaxPrecision("highp") as MaterialParameters["precision"],
21
- }
22
- }, {
23
- getTime: () => context.time.time,
24
- getFrame: () => context.time.frame,
25
- });
26
- };
27
-
28
- onLoaded = (url: string, gltf: GLTF, _context: Context) => {
29
- if (debug) console.log("[MaterialX] MaterialXLoaderPlugin: glTF loaded", { url, scene: gltf.scene, materialX_root_data: this.loader?.materialX_root_data });
30
- };
31
-
32
- onExport = (_exporter: GLTFExporter, _context: Context) => {
33
- console.warn("[MaterialX] Export is not supported");
34
- };
35
- }
36
-
37
-
38
- /**
39
- * Add the MaterialXLoaderPlugin to the Needle Engine.
40
- */
41
- export async function useNeedleMaterialX() {
42
- addCustomExtensionPlugin(new MaterialXLoaderPlugin());
43
- }
@@ -1,337 +0,0 @@
1
- import { Material, MeshStandardMaterial, DoubleSide, FrontSide, MaterialParameters } from "three";
2
- import { GLTFLoader, GLTFLoaderPlugin, GLTFParser } from "three/examples/jsm/loaders/GLTFLoader.js";
3
- import { ready, state, MaterialXContext } from "../materialx.js";
4
- import { debug } from "../utils.js";
5
- import { MaterialXMaterial } from "../materialx.material.js";
6
-
7
- // TypeScript interfaces matching the C# data structures
8
- export type MaterialX_root_extension = {
9
- /** e.g. 1.39 */
10
- version: string;
11
- /** e.g. "Material" */
12
- name: string;
13
- /** MaterialX xml content */
14
- mtlx: string;
15
- /** MaterialX texture pointers */
16
- textures: Array<{ name: string, pointer: string }>;
17
- shaders?: Array<{
18
- /** The materialx node name */
19
- name: string,
20
- /** The original name of the shader */
21
- originalName: string,
22
- }>,
23
- }
24
-
25
- export type MaterialX_material_extension = {
26
- /** The MaterialX material name */
27
- name: string;
28
- /** The index of the shader in the shaders array of the root extension. */
29
- shader?: number;
30
- }
31
-
32
- type MaterialDefinition = {
33
- name?: string; // Optional name for the material
34
- doubleSided?: boolean; // Whether the material is double-sided
35
- extensions?: {
36
- [key: string]: any; // Extensions for the material, including MaterialX
37
- },
38
- }
39
-
40
- // init.context.getRenderer().capabilities.getMaxPrecision("highp")
41
- export type MaterialXLoaderOptions = {
42
- /** The URL of the GLTF file being loaded */
43
- cacheKey?: string;
44
- /** Parameters for the MaterialX loader */
45
- parameters?: Pick<MaterialParameters, "precision">;
46
- }
47
-
48
- // MaterialX loader extension for js GLTFLoader
49
- export class MaterialXLoader implements GLTFLoaderPlugin {
50
- readonly name = "NEEDLE_materials_mtlx";
51
-
52
- private readonly _generatedMaterials: MaterialXMaterial[] = [];
53
-
54
- private _documentReadyPromise: Promise<any> | null = null;
55
-
56
- get materialX_root_data() {
57
- return this.parser.json.extensions?.[this.name] as MaterialX_root_extension | null;
58
- }
59
-
60
- /** Generated materialX materials */
61
- get materials() {
62
- return this._generatedMaterials;
63
- }
64
-
65
- /**
66
- * MaterialXLoader constructor
67
- * @param parser The GLTFParser instance
68
- * @param cacheKey The URL of the GLTF file
69
- * @param context The context for the GLTF loading process
70
- */
71
- constructor(
72
- private parser: GLTFParser,
73
- private options: MaterialXLoaderOptions,
74
- private context: MaterialXContext
75
- ) {
76
- if (debug) console.log("MaterialXLoader created for parser");
77
- // Start loading of MaterialX environment if the root extension exists
78
- if (this.materialX_root_data) {
79
- ready();
80
- }
81
- }
82
-
83
-
84
- loadMaterial(materialIndex: number): Promise<Material> | null {
85
- const materialDef = this.parser.json.materials?.[materialIndex];
86
- if (!materialDef?.extensions?.[this.name]) {
87
- return null;
88
- }
89
- // Wrap the async implementation
90
- return this._loadMaterialAsync(materialIndex);
91
- }
92
-
93
- // Parse the MaterialX document once and cache it
94
- private async _materialXDocumentReady(): Promise<any> {
95
- if (this._documentReadyPromise) {
96
- return this._documentReadyPromise;
97
- }
98
- return this._documentReadyPromise = (async () => {
99
- if (debug) console.log("[MaterialX] Parsing MaterialX root document...");
100
-
101
- // Ensure MaterialX is initialized
102
- await ready();
103
-
104
- if (!state.materialXModule) {
105
- throw new Error("[MaterialX] module failed to initialize");
106
- }
107
-
108
- // Create MaterialX document and parse ALL the XML data from root
109
- const doc = state.materialXModule.createDocument();
110
- doc.setDataLibrary(state.materialXStdLib);
111
-
112
- // Parse all MaterialX XML strings from the root data
113
- const root = this.materialX_root_data
114
- if (root) {
115
- if (debug) console.log(`[MaterialX] Parsing XML for: ${root.name}`);
116
- await state.materialXModule.readFromXmlString(doc, root.mtlx, "");
117
- }
118
-
119
- if (debug) console.log("[MaterialX] root document parsed successfully");
120
- return doc;
121
- })();
122
- }
123
-
124
- private async _loadMaterialAsync(materialIndex: number): Promise<Material> {
125
-
126
- const materialDef = this.parser.json.materials?.[materialIndex] as MaterialDefinition;
127
- if (debug) console.log("[MaterialX] extension found in material:", materialDef.extensions?.[this.name]);
128
-
129
- // Handle different types of MaterialX data
130
- const ext = materialDef.extensions?.[this.name] as MaterialX_material_extension;
131
-
132
- if (ext) {
133
- return this._createMaterialXMaterial(materialDef, ext);
134
- }
135
-
136
- // Return fallback material instead of null
137
- const fallbackMaterial = new MeshStandardMaterial();
138
- fallbackMaterial.name = "MaterialX_Fallback";
139
- return fallbackMaterial;
140
- }
141
-
142
- private async _createMaterialXMaterial(material_def: MaterialDefinition, material_extension: MaterialX_material_extension): Promise<Material> {
143
- try {
144
- if (debug) console.log(`Creating MaterialX material: ${material_extension.name}`);
145
-
146
- const doc = await this._materialXDocumentReady();
147
-
148
- if (!state.materialXModule || !state.materialXGenerator || !state.materialXGenContext) {
149
- console.warn("[MaterialX] WASM module not ready, returning fallback material");
150
- const fallbackMaterial = new MeshStandardMaterial();
151
- fallbackMaterial.userData.materialX = material_extension;
152
- fallbackMaterial.name = `MaterialX_Fallback_${material_extension.name}`;
153
- return fallbackMaterial;
154
- }
155
-
156
- // Find the renderable element following MaterialX example pattern exactly
157
- let renderableElement: any = null;
158
- let foundRenderable = false;
159
-
160
- if (debug) console.log("[MaterialX] document", doc);
161
-
162
- // Search for material nodes first (following the reference pattern)
163
- const materialNodes = doc.getMaterialNodes();
164
- if (debug) console.log(`[MaterialX] Found ${materialNodes.length} material nodes in document`, materialNodes);
165
-
166
- // Handle both array and vector-like APIs
167
- const materialNodesLength = materialNodes.length;
168
- for (let i = 0; i < materialNodesLength; ++i) {
169
- const materialNode = materialNodes[i];
170
- if (materialNode) {
171
- const materialName = materialNode.getNamePath();
172
- if (debug) console.log('[MaterialX] Scan material: ', i, materialName);
173
-
174
- // Find the matching material
175
- if (materialName == material_extension.name) {
176
- renderableElement = materialNode;
177
- foundRenderable = true;
178
- if (debug) console.log('[MaterialX] -- add material: ', materialName);
179
- break;
180
- }
181
- }
182
- }
183
-
184
- /*
185
- // If no material nodes found, search nodeGraphs
186
- if (!foundRenderable) {
187
- const nodeGraphs = doc.getNodeGraphs();
188
- console.log(`Found ${nodeGraphs.length} node graphs in document`);
189
- const nodeGraphsLength = nodeGraphs.length;
190
- for (let i = 0; i < nodeGraphsLength; ++i) {
191
- const nodeGraph = nodeGraphs[i];
192
- if (nodeGraph) {
193
- // Skip any nodegraph that has nodedef or sourceUri
194
- if ((nodeGraph as any).hasAttribute('nodedef') || (nodeGraph as any).hasSourceUri()) {
195
- continue;
196
- }
197
- // Skip any nodegraph that is connected to something downstream
198
- if ((nodeGraph as any).getDownstreamPorts().length > 0) {
199
- continue;
200
- }
201
- const outputs = (nodeGraph as any).getOutputs();
202
- for (let j = 0; j < outputs.length; ++j) {
203
- const output = outputs[j];
204
- if (output && !foundRenderable) {
205
- renderableElement = output;
206
- foundRenderable = true;
207
- break;
208
- }
209
- }
210
- if (foundRenderable) break;
211
- }
212
- }
213
- }
214
-
215
- // If still no element found, search document outputs
216
- if (!foundRenderable) {
217
- const outputs = doc.getOutputs();
218
- console.log(`Found ${outputs.length} output nodes in document`);
219
- const outputsLength = outputs.length;
220
- for (let i = 0; i < outputsLength; ++i) {
221
- const output = outputs[i];
222
- if (output && !foundRenderable) {
223
- renderableElement = output;
224
- foundRenderable = true;
225
- break;
226
- }
227
- }
228
- }
229
- */
230
-
231
- if (!renderableElement) {
232
- console.warn(`[MaterialX] No renderable element found in MaterialX document (${material_extension.name})`);
233
- const fallbackMaterial = new MeshStandardMaterial();
234
- fallbackMaterial.color.set(0xff00ff);
235
- fallbackMaterial.userData.materialX = material_extension;
236
- fallbackMaterial.name = `MaterialX_NoRenderable_${material_extension.name}`;
237
- return fallbackMaterial;
238
- }
239
-
240
- if (debug) console.log("[MaterialX] Using renderable element for shader generation");
241
-
242
- // Check transparency and set context options like the reference
243
- const isTransparent = state.materialXModule.isTransparentSurface(renderableElement, state.materialXGenerator.getTarget());
244
- state.materialXGenContext.getOptions().hwTransparency = isTransparent;
245
-
246
- // Generate shaders using the element's name path
247
- if (debug) console.log("[MaterialX] Generating MaterialX shaders...");
248
- const elementName = (renderableElement as any).getNamePath ? (renderableElement as any).getNamePath() : (renderableElement as any).getName();
249
-
250
- const shader = state.materialXGenerator.generate(elementName, renderableElement, state.materialXGenContext);
251
-
252
- const rootExtension = this.materialX_root_data;
253
-
254
- const shaderInfo = rootExtension && material_extension.shader !== undefined && material_extension.shader >= 0
255
- ? rootExtension.shaders?.[material_extension.shader]
256
- : null;
257
-
258
- const shaderMaterial = new MaterialXMaterial({
259
- name: material_extension.name,
260
- shaderName: shaderInfo?.originalName || shaderInfo?.name || null,
261
- shader,
262
- context: this.context,
263
- parameters: {
264
- transparent: isTransparent,
265
- side: material_def.doubleSided ? DoubleSide : FrontSide,
266
- ...this.options.parameters,
267
- },
268
- loaders: {
269
- cacheKey: this.options.cacheKey || "",
270
- getTexture: async url => {
271
- // Find the index of the texture in the parser
272
- const filenameWithoutExt = url.split('/').pop()?.split('.').shift() || '';
273
-
274
- // Resolve the texture from the MaterialX root extension
275
- if (rootExtension) {
276
- const textures = rootExtension.textures || [];
277
- let index = -1;
278
- for (const texture of textures) {
279
- // Find the texture by name and use the pointer string to get the index
280
- if (texture.name === filenameWithoutExt) {
281
- const ptr = texture.pointer;
282
- const indexStr = ptr.substring("/textures/".length);
283
- index = parseInt(indexStr);
284
-
285
- if (isNaN(index) || index < 0) {
286
- console.error("[MaterialX] Invalid texture index in pointer:", ptr);
287
- return;
288
- }
289
- else {
290
- if (debug) console.log("[MaterialX] Texture index found:", index, "for", filenameWithoutExt);
291
- }
292
- }
293
- }
294
-
295
- if (index < 0) {
296
- console.error("[MaterialX] Texture not found in parser:", filenameWithoutExt, this.parser.json);
297
- return;
298
- }
299
- return this.parser.getDependency("texture", index).then(tex => {
300
- if (debug) console.log("[MaterialX] Texture loaded:" + tex.name, tex);
301
- return tex;
302
- });
303
- }
304
- return null;
305
- }
306
- }
307
- });
308
- // Track this material for later lighting updates
309
- this._generatedMaterials.push(shaderMaterial);
310
-
311
- // Add debugging to see if the material compiles correctly
312
- if (debug) console.log("[MaterialX] material created:", shaderMaterial.name);
313
- return shaderMaterial;
314
-
315
- } catch (error) {
316
- // This is a wasm error (an int) that we need to resolve
317
- console.error(`[MaterialX] Error creating MaterialX material (${material_extension.name}):`, error);
318
- // Return a fallback material with stored MaterialX data
319
- const fallbackMaterial = new MeshStandardMaterial();
320
- fallbackMaterial.color.set(0xff00ff);
321
- fallbackMaterial.userData.materialX = material_extension;
322
- fallbackMaterial.name = `MaterialX_Error_${material_extension.name}`;
323
- return fallbackMaterial;
324
- }
325
- }
326
- }
327
-
328
-
329
- /**
330
- * Add the MaterialXLoader to the GLTFLoader instance.
331
- */
332
- export function useNeedleMaterialX(loader: GLTFLoader, options?: MaterialXLoaderOptions, context?: MaterialXContext) {
333
- loader.register(p => {
334
- const loader = new MaterialXLoader(p, options || {}, context || {});
335
- return loader;
336
- });
337
- }