API

Create glTF extensions

Introduction

The glTF format includes the concept of extensions. Usually, glTF loader extensions map 1:1 with corresponding glTF format extensions. However, it is also possible to create custom glTF loader extensions that are unrelated to glTF format extensions and simply perform additional processing on the loaded glTF data.

The glTF loader includes support for many glTF format extensions through built-in glTF loader extensions. It is also possible to create your own glTF loader extensions.

Extensions

Extensions are defined by implementing the IGLTFLoaderExtension interface (from @babylonjs/loaders/glTF/2.0). An abbreviated example would look something like this:

import { IGLTFLoaderExtension } from "@babylonjs/loaders/glTF/2.0";
class MyCustomExtension implements IGLTFLoaderExtension {
public readonly name = "myCustomExtension";
public enabled = true;
public order = 100;
// Implement any of the optional functions, such as:
public loadSceneAsync(): Nullable<Promise<void>> {
// Modify the default behavior when loading scenes.
}
}

Extension Factories

When you register a loader extension, you register an extension factory. The factory is a function that takes the glTF loader and returns an extension instance synchronously or asynchronously. It is invoked each time a glTF is loaded. Using the factory allows you to dynamically import your extension to avoid loading it until it is needed. A simple example might look something like this:

import { registerGLTFExtension } from "@babylonjs/loaders/glTF/2.0";
registerGLTFExtension("myCustomExtension", true, async (loader) => {
const { MyCustomExtension } = await import("./MyCustomExtension");
return new MyCustomExtension(loader);
});

Extension Options

To expose options for your custom glTF loader extension, you should first augment the GLTFLoaderExtensionOptions interface to add options for your extension. For example:

type MyCustomExtensionOptions = { option1?: string, option2?: number };
declare module "@babylonjs/loaders" {
export interface GLTFLoaderExtensionOptions {
myCustomExtension: MyCustomImporterOptions;
}
}

Then, when you register your extension, you can access the options like this:

class MyCustomExtension implements IGLTFLoaderExtension {
constructor (loader: GLTFLoader) {
const options = loader.parent.extensionOptions["myCustomExtension"];
}
}

Finally, these options can be passed into one of the scene loader functions like this:

await LoadAssetContainerAsync("path/to/model", scene, {
pluginOptions: {
glTF: {
extensionOptions: {
myCustomExtension: {
option1: "hello world",
option2: 42,
},
},
},
},
});

Further reading