mtlx-viewer
Shared three.js MaterialX preview viewer, used by the mtlx.ben3d.ca website, the VS Code
extension and mtlx view. Everything here pulls in three.js; the three-free pieces live at
mtlx-viewer/settings, mtlx-viewer/diagnostics and mtlx-viewer/capabilities.
Other
parseEnvironmentFile()
function parseEnvironmentFile(data, source): Promise<Texture<unknown, TextureEventMap>>;
Parse an equirectangular IBL from its file extension (.hdr, .exr, .png, .jpg).
Parameters
| Parameter | Type |
|---|---|
data | ArrayBuffer |
source | string |
Returns
Promise<Texture<unknown, TextureEventMap>>
createEnvironmentSwitcher()
function createEnvironmentSwitcher<Source>(
load,
prepare,
apply
): object;
Owns the active filtered environment and discards superseded asynchronous loads.
Type Parameters
| Type Parameter | Default type |
|---|---|
Source extends object | Texture<unknown, TextureEventMap> |
Parameters
| Parameter | Type |
|---|---|
load | (kind) => Promise<Source> |
prepare | (texture) => object |
apply | (texture) => void |
Returns
object
| Name | Type |
|---|---|
set() | (kind) => Promise<boolean> |
dispose() | () => void |
LoadingProgress
Overall loading progress, including processing and the first render.
Properties
| Property | Type |
|---|---|
totalProgress | number |
reason | "material-load" | "environment-update" | "geometry-update" |
LoadingTracker
Aggregate overlapping activities. Progress never moves backwards within a loading cycle.
Constructors
Constructor
new LoadingTracker(publish): LoadingTracker;
Parameters
| Parameter | Type |
|---|---|
publish | (progress) => void |
Returns
Methods
reset()
reset(): void;
Returns
void
start()
start(reason): (progress) => void;
Parameters
| Parameter | Type |
|---|---|
reason | "material-load" | "environment-update" | "geometry-update" |
Returns
(progress) => void
MaterialProgress
Download progress for the material file, excluding preview assets and rendering setup.
Properties
readMaterialResponse()
function readMaterialResponse(
response,
signal,
onProgress
): Promise<ArrayBuffer>;
Read a material response, reporting immediately, every 250 ms, and on completion.
Parameters
| Parameter | Type |
|---|---|
response | Response |
signal | AbortSignal |
onProgress | (progress) => void |
Returns
Promise<ArrayBuffer>
createViewerRendering()
function createViewerRendering(
renderer,
scene,
camera,
initial?
): object;
Shared HDR pipeline. Initialize the renderer before creating this owner, then dispose it before the renderer.
Parameters
| Parameter | Type | Default value |
|---|---|---|
renderer | WebGPURenderer | undefined |
scene | Scene | undefined |
camera | PerspectiveCamera | undefined |
initial? | RenderingSettings | DEFAULT_RENDERING_SETTINGS |
Returns
| Name | Type | Description |
|---|---|---|
configure() | (next) => void | - |
render() | () => void | Synchronous after renderer.init(); throws on shader compilation failure. |
dispose() | () => void | - |
createViewerRenderer()
function createViewerRenderer(scope, options): Promise<WebGPURenderer>;
Own the renderer before async initialization so replacement/unmount can always clean it up.
Parameters
| Parameter | Type |
|---|---|
scope | CleanupScope |
options | { width: number; height: number; canvas?: HTMLCanvasElement; updateStyle?: boolean; } |
options.width | number |
options.height | number |
options.canvas? | HTMLCanvasElement |
options.updateStyle? | boolean |
Returns
Promise<WebGPURenderer>
observeViewerResize()
function observeViewerResize(
scope,
element,
renderer,
camera,
updateStyle?,
onResize?
): void;
Parameters
| Parameter | Type | Default value |
|---|---|---|
scope | CleanupScope | undefined |
element | HTMLElement | undefined |
renderer | WebGPURenderer | undefined |
camera | PerspectiveCamera | undefined |
updateStyle? | boolean | true |
onResize? | () => void | undefined |
Returns
void
applyViewerRenderingSettings()
function applyViewerRenderingSettings(
renderer,
scene,
rendering,
settings
): void;
Parameters
| Parameter | Type |
|---|---|
renderer | { toneMappingExposure: number; } |
renderer.toneMappingExposure | number |
scene | { environmentIntensity: number; environmentRotation: { y: number; }; backgroundRotation: { y: number; }; } |
scene.environmentIntensity | number |
scene.environmentRotation | { y: number; } |
scene.environmentRotation.y | number |
scene.backgroundRotation | { y: number; } |
scene.backgroundRotation.y | number |
rendering | { configure(settings): void; } |
rendering.configure | (settings) => void |
settings | RenderingSettings & object |
Returns
void
dataUrlToArrayBuffer()
function dataUrlToArrayBuffer(dataUrl): ArrayBuffer;
Decode a base64 data: URL (e.g. a bundler-inlined asset) into bytes; data: URLs are not fetchable under strict CSP.
Parameters
| Parameter | Type |
|---|---|
dataUrl | string |
Returns
ArrayBuffer
ScreenshotOptions
Properties
ViewerOptions
Methods
loadGeometry()?
loadGeometry?(name): Promise<{
data: ArrayBuffer;
manager?: LoadingManager;
}>;
Host-configured geometries beyond totem/sphere/cube/plane; manager resolves glTF sidecar files.
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
Promise<{
data: ArrayBuffer;
manager?: LoadingManager;
}>
onReport()?
onReport?(report): void;
Parameters
| Parameter | Type |
|---|---|
report | PreviewReport |
Returns
void
onCameraChange()?
onCameraChange?(settings): void;
Current camera framing after initialization and each orbit/pan/zoom change.
Parameters
| Parameter | Type |
|---|---|
settings | Required<CameraSettings> |
Returns
void
onError()?
onError?(message): void;
The frame loop failed after startup; the viewer is already disposed.
Parameters
| Parameter | Type |
|---|---|
message | string |
Returns
void
Properties
| Property | Type | Description |
|---|---|---|
signal? | AbortSignal | Cancel an in-progress compilation when an editor supplies a newer document. |
canvas? | HTMLCanvasElement | Render into this canvas; otherwise a canvas is created and appended to container. |
container | HTMLElement | Sized against; a created canvas is appended here. |
data | ArrayBuffer | - |
fileName | string | - |
alt? | string | Accessible description of the material, applied to the focusable canvas. |
shaderBall | ArrayBuffer | - |
settings | ViewerSettings | - |
playing? | boolean | Whether MaterialX <time>/<frame> nodes advance from the first frame; defaults to true. |
loadEnvironment | (kind) => Promise<Texture<unknown, TextureEventMap>> | - |
resolveUrl? | (url) => string | undefined | Rewrite texture URLs the document references (e.g. to blob: URLs of bytes the host already read). |
onLog? | (message) => void | - |
onStatus? | (patch) => void | Transient status text; empty when cleared. |
onProgress? | (progress) => void | Overall progress for setup, resources, settings changes, and rendering. |
onStage? | (stage) => void | Loading milestones for progress UI. |
Viewer
Methods
getCameraSettings()
getCameraSettings(): Required<CameraSettings>;
Capture current framing, including user orbit, pan and zoom, for a share link.
Returns
Required<CameraSettings>
setPlaying()
setPlaying(playing): void;
Parameters
| Parameter | Type |
|---|---|
playing | boolean |
Returns
void
setAlt()
setAlt(alt?): void;
Update the accessible description without reloading; empty/undefined restores the default.
Parameters
| Parameter | Type |
|---|---|
alt? | string |
Returns
void
setSettings()
setSettings(settings): Promise<ViewerSettings>;
Apply a full settings object; only changed fields do work. Resolves to what actually took effect.
Parameters
| Parameter | Type |
|---|---|
settings | ViewerSettings |
Returns
Promise<ViewerSettings>
replaceMaterial()
replaceMaterial(data, fileName): void;
Compile a new document into the running scene, keeping the renderer, environment, camera and
geometry. Reports through onReport; throws (and keeps the previous material) on a parse failure.
Parameters
| Parameter | Type |
|---|---|
data | ArrayBuffer |
fileName | string |
Returns
void
toBlob()
toBlob(options?): Promise<Blob>;
Capture a completed preview frame, including postprocessing, without changing the on-screen view.
Parameters
| Parameter | Type |
|---|---|
options? | ScreenshotOptions |
Returns
Promise<Blob>
dispose()
dispose(): void;
Returns
void
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
disposed | readonly | boolean | - |
scene | readonly | MtlxScene | - |
camera | readonly | PerspectiveCamera | - |
controls | readonly | OrbitControls | - |
playing | readonly | boolean | Whether MaterialX <time>/<frame> nodes run forward; scene.animated says whether the document has any. |
createViewer()
function createViewer(options): Promise<Viewer>;
Builds the viewer and renders the first frame; rejects (already disposed) on any setup failure.
Parameters
| Parameter | Type |
|---|---|
options | ViewerOptions |
Returns
Promise<Viewer>
Viewer
MtlxSceneOptions
Options for createMtlxScene.
Methods
onTranslationMessage()?
onTranslationMessage?(entry): void;
Loader translation log entries (e.g. an unsupported node or an ignored surface input). Errors never throw: parsing continues with a partial material, matching MaterialXView which ignores what it can't render.
Parameters
| Parameter | Type |
|---|---|
entry | { severity: "error" | "warning"; message: string; } |
entry.severity | "error" | "warning" |
entry.message | string |
Returns
void
Properties
| Property | Type | Description |
|---|---|---|
data | ArrayBuffer | Raw .mtlx / .mtlx.zip bytes. |
fileName | string | Passed through to MaterialXLoader for resource-path resolution and archive sniffing. |
materialName? | string | Defaults to the document's last material (matches prior single-material behavior). |
geometry? | string | Defaults to 'totem'. |
autoRotate? | boolean | Defaults to true. |
shaderBall | ArrayBuffer | The shaderball (https://mtlx-static.ben3d.ca/viewer/shaderball.glb) used for the 'totem' geometry. |
manager? | LoadingManager | Supply your own if you need onProgress/onError wiring (e.g. for texture blobs). |
resolveUrl? | (url) => string | undefined | Rewrite texture URLs the document references (e.g. to blob: URLs of bytes the host already read). |
MtlxScene
A live MaterialX preview scene, returned by createMtlxScene.
Methods
dispose()
dispose(): void;
Releases owned geometries, materials and textures; safe to call repeatedly.
Returns
void
setMaterial()
setMaterial(name): void;
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
void
replaceMaterials()
replaceMaterials(data, fileName): void;
Parse a new document and show it on the current geometry, keeping the camera and orientation. The previous materials stay in place when the new document fails to parse.
Parameters
| Parameter | Type |
|---|---|
data | ArrayBuffer |
fileName | string |
Returns
void
hasGeometry()
hasGeometry(name): boolean;
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
boolean
setGeometry()
setGeometry(kind): void;
Parameters
| Parameter | Type |
|---|---|
kind | string |
Returns
void
addGeometry()
addGeometry(
name,
data,
manager?
): Promise<void>;
Load an additional named glTF/GLB geometry; this scene owns its resources.
Parameters
| Parameter | Type |
|---|---|
name | string |
data | ArrayBuffer |
manager? | LoadingManager |
Returns
Promise<void>
resetCamera()
resetCamera(options?): void;
Restore every geometry's orientation and the initial camera framing.
Parameters
| Parameter | Type |
|---|---|
options? | { resetObjects?: boolean; } |
options.resetObjects? | boolean |
Returns
void
reframe()
reframe(): void;
After the viewport aspect changes, re-fit the object while keeping the user's orbit direction and relative zoom.
Returns
void
update()
update(deltaSeconds): void;
Call every frame; advances the auto-rotation.
Parameters
| Parameter | Type |
|---|---|
deltaSeconds | number |
Returns
void
Properties
createMtlxScene()
function createMtlxScene(
camera,
controls,
options
): Promise<MtlxScene>;
Parses a MaterialX document and builds a swappable preview scene for it. Add the returned
scene's .root to your THREE.Scene and call .update(deltaSeconds) each frame.
Parameters
| Parameter | Type |
|---|---|
camera | PerspectiveCamera |
controls | { target: Vector3; update: () => void; enableDamping?: boolean; } |
controls.target | Vector3 |
controls.update | () => void |
controls.enableDamping? | boolean |
options | MtlxSceneOptions |
Returns
Promise<MtlxScene>
Example
const scene = await createMtlxScene(camera, controls, { data, fileName, shaderBall });
threeScene.add(scene.root);