///
///
var BABYLON;
(function (BABYLON) {
/**
* Mode that determines the coordinate system to use.
*/
var GLTFLoaderCoordinateSystemMode;
(function (GLTFLoaderCoordinateSystemMode) {
/**
* Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
*/
GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
/**
* Sets the useRightHandedSystem flag on the scene.
*/
GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
})(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
/**
* Mode that determines what animations will start.
*/
var GLTFLoaderAnimationStartMode;
(function (GLTFLoaderAnimationStartMode) {
/**
* No animation will start.
*/
GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
/**
* The first animation will start.
*/
GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
/**
* All animations will start.
*/
GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
})(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
/**
* Loader state.
*/
var GLTFLoaderState;
(function (GLTFLoaderState) {
/**
* The asset is loading.
*/
GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
/**
* The asset is ready for rendering.
*/
GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
/**
* The asset is completely loaded.
*/
GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
})(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
/**
* File loader for loading glTF files into a scene.
*/
var GLTFFileLoader = /** @class */ (function () {
function GLTFFileLoader() {
// --------------
// Common options
// --------------
/**
* Raised when the asset has been parsed
*/
this.onParsedObservable = new BABYLON.Observable();
// ----------
// V2 options
// ----------
/**
* The coordinate system mode. Defaults to AUTO.
*/
this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
/**
* The animation start mode. Defaults to FIRST.
*/
this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
/**
* Defines if the loader should compile materials before raising the success callback. Defaults to false.
*/
this.compileMaterials = false;
/**
* Defines if the loader should also compile materials with clip planes. Defaults to false.
*/
this.useClipPlane = false;
/**
* Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
*/
this.compileShadowGenerators = false;
/**
* Defines if the Alpha blended materials are only applied as coverage.
* If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
* If true, no extra effects are applied to transparent pixels.
*/
this.transparencyAsCoverage = false;
/**
* Function called before loading a url referenced by the asset.
*/
this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
/**
* Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
*/
this.onMeshLoadedObservable = new BABYLON.Observable();
/**
* Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
*/
this.onTextureLoadedObservable = new BABYLON.Observable();
/**
* Observable raised when the loader creates a material after parsing the glTF properties of the material.
*/
this.onMaterialLoadedObservable = new BABYLON.Observable();
/**
* Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
*/
this.onCameraLoadedObservable = new BABYLON.Observable();
/**
* Observable raised when the asset is completely loaded, immediately before the loader is disposed.
* For assets with LODs, raised when all of the LODs are complete.
* For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
*/
this.onCompleteObservable = new BABYLON.Observable();
/**
* Observable raised when an error occurs.
*/
this.onErrorObservable = new BABYLON.Observable();
/**
* Observable raised after the loader is disposed.
*/
this.onDisposeObservable = new BABYLON.Observable();
/**
* Observable raised after a loader extension is created.
* Set additional options for a loader extension in this event.
*/
this.onExtensionLoadedObservable = new BABYLON.Observable();
/**
* Defines if the loader should validate the asset.
*/
this.validate = false;
/**
* Observable raised after validation when validate is set to true. The event data is the result of the validation.
*/
this.onValidatedObservable = new BABYLON.Observable();
this._loader = null;
/**
* Name of the loader ("gltf")
*/
this.name = "gltf";
/**
* Supported file extensions of the loader (.gltf, .glb)
*/
this.extensions = {
".gltf": { isBinary: false },
".glb": { isBinary: true }
};
this._logIndentLevel = 0;
this._loggingEnabled = false;
/** @hidden */
this._log = this._logDisabled;
this._capturePerformanceCounters = false;
/** @hidden */
this._startPerformanceCounter = this._startPerformanceCounterDisabled;
/** @hidden */
this._endPerformanceCounter = this._endPerformanceCounterDisabled;
}
Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
/**
* Raised when the asset has been parsed
*/
set: function (callback) {
if (this._onParsedObserver) {
this.onParsedObservable.remove(this._onParsedObserver);
}
this._onParsedObserver = this.onParsedObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
/**
* Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
*/
set: function (callback) {
if (this._onMeshLoadedObserver) {
this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
}
this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
/**
* Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
*/
set: function (callback) {
if (this._onTextureLoadedObserver) {
this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
}
this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
/**
* Callback raised when the loader creates a material after parsing the glTF properties of the material.
*/
set: function (callback) {
if (this._onMaterialLoadedObserver) {
this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
}
this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
/**
* Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
*/
set: function (callback) {
if (this._onCameraLoadedObserver) {
this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
}
this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
/**
* Callback raised when the asset is completely loaded, immediately before the loader is disposed.
* For assets with LODs, raised when all of the LODs are complete.
* For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
*/
set: function (callback) {
if (this._onCompleteObserver) {
this.onCompleteObservable.remove(this._onCompleteObserver);
}
this._onCompleteObserver = this.onCompleteObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onError", {
/**
* Callback raised when an error occurs.
*/
set: function (callback) {
if (this._onErrorObserver) {
this.onErrorObservable.remove(this._onErrorObserver);
}
this._onErrorObserver = this.onErrorObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
/**
* Callback raised after the loader is disposed.
*/
set: function (callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
/**
* Callback raised after a loader extension is created.
*/
set: function (callback) {
if (this._onExtensionLoadedObserver) {
this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
}
this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
/**
* Defines if the loader logging is enabled.
*/
get: function () {
return this._loggingEnabled;
},
set: function (value) {
if (this._loggingEnabled === value) {
return;
}
this._loggingEnabled = value;
if (this._loggingEnabled) {
this._log = this._logEnabled;
}
else {
this._log = this._logDisabled;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
/**
* Defines if the loader should capture performance counters.
*/
get: function () {
return this._capturePerformanceCounters;
},
set: function (value) {
if (this._capturePerformanceCounters === value) {
return;
}
this._capturePerformanceCounters = value;
if (this._capturePerformanceCounters) {
this._startPerformanceCounter = this._startPerformanceCounterEnabled;
this._endPerformanceCounter = this._endPerformanceCounterEnabled;
}
else {
this._startPerformanceCounter = this._startPerformanceCounterDisabled;
this._endPerformanceCounter = this._endPerformanceCounterDisabled;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
/**
* Callback raised after a loader extension is created.
*/
set: function (callback) {
if (this._onValidatedObserver) {
this.onValidatedObservable.remove(this._onValidatedObserver);
}
this._onValidatedObserver = this.onValidatedObservable.add(callback);
},
enumerable: true,
configurable: true
});
/**
* Disposes the loader, releases resources during load, and cancels any outstanding requests.
*/
GLTFFileLoader.prototype.dispose = function () {
if (this._loader) {
this._loader.dispose();
this._loader = null;
}
this._clear();
this.onDisposeObservable.notifyObservers(undefined);
this.onDisposeObservable.clear();
};
/** @hidden */
GLTFFileLoader.prototype._clear = function () {
this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
this.onMeshLoadedObservable.clear();
this.onTextureLoadedObservable.clear();
this.onMaterialLoadedObservable.clear();
this.onCameraLoadedObservable.clear();
this.onCompleteObservable.clear();
this.onExtensionLoadedObservable.clear();
};
/**
* Imports one or more meshes from the loaded glTF data and adds them to the scene
* @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
* @param scene the scene the meshes should be added to
* @param data the glTF data to load
* @param rootUrl root url to load from
* @param onProgress event that fires when loading progress has occured
* @param fileName Defines the name of the file to load
* @returns a promise containg the loaded meshes, particles, skeletons and animations
*/
GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
var _this = this;
return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
_this._log("Loading " + (fileName || ""));
_this._loader = _this._getLoader(loaderData);
return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
});
};
/**
* Imports all objects from the loaded glTF data and adds them to the scene
* @param scene the scene the objects should be added to
* @param data the glTF data to load
* @param rootUrl root url to load from
* @param onProgress event that fires when loading progress has occured
* @param fileName Defines the name of the file to load
* @returns a promise which completes when objects have been loaded to the scene
*/
GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
var _this = this;
return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
_this._log("Loading " + (fileName || ""));
_this._loader = _this._getLoader(loaderData);
return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
});
};
/**
* Load into an asset container.
* @param scene The scene to load into
* @param data The data to import
* @param rootUrl The root url for scene and resources
* @param onProgress The callback when the load progresses
* @param fileName Defines the name of the file to load
* @returns The loaded asset container
*/
GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
var _this = this;
return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
_this._log("Loading " + (fileName || ""));
_this._loader = _this._getLoader(loaderData);
return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
var container = new BABYLON.AssetContainer(scene);
Array.prototype.push.apply(container.meshes, result.meshes);
Array.prototype.push.apply(container.particleSystems, result.particleSystems);
Array.prototype.push.apply(container.skeletons, result.skeletons);
Array.prototype.push.apply(container.animationGroups, result.animationGroups);
container.removeAllFromScene();
return container;
});
});
};
/**
* If the data string can be loaded directly.
* @param data string contianing the file data
* @returns if the data can be loaded directly
*/
GLTFFileLoader.prototype.canDirectLoad = function (data) {
return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
};
/**
* Instantiates a glTF file loader plugin.
* @returns the created plugin
*/
GLTFFileLoader.prototype.createPlugin = function () {
return new GLTFFileLoader();
};
Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
/**
* The loader state or null if the loader is not active.
*/
get: function () {
return this._loader ? this._loader.state : null;
},
enumerable: true,
configurable: true
});
/**
* Returns a promise that resolves when the asset is completely loaded.
* @returns a promise that resolves when the asset is completely loaded.
*/
GLTFFileLoader.prototype.whenCompleteAsync = function () {
var _this = this;
return new Promise(function (resolve, reject) {
_this.onCompleteObservable.addOnce(function () {
resolve();
});
_this.onErrorObservable.addOnce(function (reason) {
reject(reason);
});
});
};
GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
var _this = this;
return Promise.resolve().then(function () {
var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
_this._startPerformanceCounter("Parse JSON");
_this._log("JSON length: " + unpacked.json.length);
var loaderData = {
json: JSON.parse(unpacked.json),
bin: unpacked.bin
};
_this._endPerformanceCounter("Parse JSON");
_this.onParsedObservable.notifyObservers(loaderData);
_this.onParsedObservable.clear();
return loaderData;
});
});
};
GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
var _this = this;
if (!this.validate || typeof GLTFValidator === "undefined") {
return Promise.resolve();
}
this._startPerformanceCounter("Validate JSON");
var options = {
externalResourceFunction: function (uri) {
return _this.preprocessUrlAsync(rootUrl + uri)
.then(function (url) { return scene._loadFileAsync(url, true, true); })
.then(function (data) { return new Uint8Array(data); });
}
};
if (fileName && fileName.substr(0, 5) !== "data:") {
options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
}
return GLTFValidator.validateString(json, options).then(function (result) {
_this._endPerformanceCounter("Validate JSON");
_this.onValidatedObservable.notifyObservers(result);
_this.onValidatedObservable.clear();
}, function (reason) {
_this._endPerformanceCounter("Validate JSON");
BABYLON.Tools.Warn("Failed to validate: " + reason);
_this.onValidatedObservable.clear();
});
};
GLTFFileLoader.prototype._getLoader = function (loaderData) {
var asset = loaderData.json.asset || {};
this._log("Asset version: " + asset.version);
asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
asset.generator && this._log("Asset generator: " + asset.generator);
var version = GLTFFileLoader._parseVersion(asset.version);
if (!version) {
throw new Error("Invalid version: " + asset.version);
}
if (asset.minVersion !== undefined) {
var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
if (!minVersion) {
throw new Error("Invalid minimum version: " + asset.minVersion);
}
if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
throw new Error("Incompatible minimum version: " + asset.minVersion);
}
}
var createLoaders = {
1: GLTFFileLoader._CreateGLTFLoaderV1,
2: GLTFFileLoader._CreateGLTFLoaderV2
};
var createLoader = createLoaders[version.major];
if (!createLoader) {
throw new Error("Unsupported version: " + asset.version);
}
return createLoader(this);
};
GLTFFileLoader.prototype._unpackBinary = function (data) {
this._startPerformanceCounter("Unpack binary");
this._log("Binary length: " + data.byteLength);
var Binary = {
Magic: 0x46546C67
};
var binaryReader = new BinaryReader(data);
var magic = binaryReader.readUint32();
if (magic !== Binary.Magic) {
throw new Error("Unexpected magic: " + magic);
}
var version = binaryReader.readUint32();
if (this.loggingEnabled) {
this._log("Binary version: " + version);
}
var unpacked;
switch (version) {
case 1: {
unpacked = this._unpackBinaryV1(binaryReader);
break;
}
case 2: {
unpacked = this._unpackBinaryV2(binaryReader);
break;
}
default: {
throw new Error("Unsupported version: " + version);
}
}
this._endPerformanceCounter("Unpack binary");
return unpacked;
};
GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
var ContentFormat = {
JSON: 0
};
var length = binaryReader.readUint32();
if (length != binaryReader.getLength()) {
throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
}
var contentLength = binaryReader.readUint32();
var contentFormat = binaryReader.readUint32();
var content;
switch (contentFormat) {
case ContentFormat.JSON: {
content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
break;
}
default: {
throw new Error("Unexpected content format: " + contentFormat);
}
}
var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
var body = binaryReader.readUint8Array(bytesRemaining);
return {
json: content,
bin: body
};
};
GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
var ChunkFormat = {
JSON: 0x4E4F534A,
BIN: 0x004E4942
};
var length = binaryReader.readUint32();
if (length !== binaryReader.getLength()) {
throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
}
// JSON chunk
var chunkLength = binaryReader.readUint32();
var chunkFormat = binaryReader.readUint32();
if (chunkFormat !== ChunkFormat.JSON) {
throw new Error("First chunk format is not JSON");
}
var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
// Look for BIN chunk
var bin = null;
while (binaryReader.getPosition() < binaryReader.getLength()) {
var chunkLength_1 = binaryReader.readUint32();
var chunkFormat_1 = binaryReader.readUint32();
switch (chunkFormat_1) {
case ChunkFormat.JSON: {
throw new Error("Unexpected JSON chunk");
}
case ChunkFormat.BIN: {
bin = binaryReader.readUint8Array(chunkLength_1);
break;
}
default: {
// ignore unrecognized chunkFormat
binaryReader.skipBytes(chunkLength_1);
break;
}
}
}
return {
json: json,
bin: bin
};
};
GLTFFileLoader._parseVersion = function (version) {
if (version === "1.0" || version === "1.0.1") {
return {
major: 1,
minor: 0
};
}
var match = (version + "").match(/^(\d+)\.(\d+)/);
if (!match) {
return null;
}
return {
major: parseInt(match[1]),
minor: parseInt(match[2])
};
};
GLTFFileLoader._compareVersion = function (a, b) {
if (a.major > b.major) {
return 1;
}
if (a.major < b.major) {
return -1;
}
if (a.minor > b.minor) {
return 1;
}
if (a.minor < b.minor) {
return -1;
}
return 0;
};
GLTFFileLoader._decodeBufferToText = function (buffer) {
var result = "";
var length = buffer.byteLength;
for (var i = 0; i < length; i++) {
result += String.fromCharCode(buffer[i]);
}
return result;
};
/** @hidden */
GLTFFileLoader.prototype._logOpen = function (message) {
this._log(message);
this._logIndentLevel++;
};
/** @hidden */
GLTFFileLoader.prototype._logClose = function () {
--this._logIndentLevel;
};
GLTFFileLoader.prototype._logEnabled = function (message) {
var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
BABYLON.Tools.Log("" + spaces + message);
};
GLTFFileLoader.prototype._logDisabled = function (message) {
};
GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
BABYLON.Tools.StartPerformanceCounter(counterName);
};
GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
};
GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
BABYLON.Tools.EndPerformanceCounter(counterName);
};
GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
};
// ----------
// V1 options
// ----------
/**
* Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
* Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
* Defaults to true.
* @hidden
*/
GLTFFileLoader.IncrementalLoading = true;
/**
* Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
* Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
* @hidden
*/
GLTFFileLoader.HomogeneousCoordinates = false;
GLTFFileLoader._logSpaces = " ";
return GLTFFileLoader;
}());
BABYLON.GLTFFileLoader = GLTFFileLoader;
var BinaryReader = /** @class */ (function () {
function BinaryReader(arrayBuffer) {
this._arrayBuffer = arrayBuffer;
this._dataView = new DataView(arrayBuffer);
this._byteOffset = 0;
}
BinaryReader.prototype.getPosition = function () {
return this._byteOffset;
};
BinaryReader.prototype.getLength = function () {
return this._arrayBuffer.byteLength;
};
BinaryReader.prototype.readUint32 = function () {
var value = this._dataView.getUint32(this._byteOffset, true);
this._byteOffset += 4;
return value;
};
BinaryReader.prototype.readUint8Array = function (length) {
var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
this._byteOffset += length;
return value;
};
BinaryReader.prototype.skipBytes = function (length) {
this._byteOffset += length;
};
return BinaryReader;
}());
if (BABYLON.SceneLoader) {
BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
}
})(BABYLON || (BABYLON = {}));
//# sourceMappingURL=babylon.glTFFileLoader.js.map
///
//# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
///
/**
* Defines the module for importing and exporting glTF 2.0 assets
*/
var BABYLON;
(function (BABYLON) {
var GLTF2;
(function (GLTF2) {
/**
* Helper class for working with arrays when loading the glTF asset
*/
var ArrayItem = /** @class */ (function () {
function ArrayItem() {
}
/**
* Gets an item from the given array.
* @param context The context when loading the asset
* @param array The array to get the item from
* @param index The index to the array
* @returns The array item
*/
ArrayItem.Get = function (context, array, index) {
if (!array || index == undefined || !array[index]) {
throw new Error(context + ": Failed to find index (" + index + ")");
}
return array[index];
};
/**
* Assign an `index` field to each item of the given array.
* @param array The array of items
*/
ArrayItem.Assign = function (array) {
if (array) {
for (var index = 0; index < array.length; index++) {
array[index].index = index;
}
}
};
return ArrayItem;
}());
GLTF2.ArrayItem = ArrayItem;
/**
* The glTF 2.0 loader
*/
var GLTFLoader = /** @class */ (function () {
/** @hidden */
function GLTFLoader(parent) {
/** @hidden */
this._completePromises = new Array();
this._disposed = false;
this._state = null;
this._extensions = {};
this._defaultBabylonMaterialData = {};
this._requests = new Array();
this._parent = parent;
}
/**
* Registers a loader extension.
* @param name The name of the loader extension.
* @param factory The factory function that creates the loader extension.
*/
GLTFLoader.RegisterExtension = function (name, factory) {
if (GLTFLoader.UnregisterExtension(name)) {
BABYLON.Tools.Warn("Extension with the name '" + name + "' already exists");
}
GLTFLoader._ExtensionFactories[name] = factory;
// Keep the order of registration so that extensions registered first are called first.
GLTFLoader._ExtensionNames.push(name);
};
/**
* Unregisters a loader extension.
* @param name The name of the loader extenion.
* @returns A boolean indicating whether the extension has been unregistered
*/
GLTFLoader.UnregisterExtension = function (name) {
if (!GLTFLoader._ExtensionFactories[name]) {
return false;
}
delete GLTFLoader._ExtensionFactories[name];
var index = GLTFLoader._ExtensionNames.indexOf(name);
if (index !== -1) {
GLTFLoader._ExtensionNames.splice(index, 1);
}
return true;
};
Object.defineProperty(GLTFLoader.prototype, "state", {
/**
* Gets the loader state.
*/
get: function () {
return this._state;
},
enumerable: true,
configurable: true
});
/** @hidden */
GLTFLoader.prototype.dispose = function () {
if (this._disposed) {
return;
}
this._disposed = true;
for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
var request = _a[_i];
request.abort();
}
this._requests.length = 0;
delete this.gltf;
delete this.babylonScene;
this._completePromises.length = 0;
for (var name_1 in this._extensions) {
var extension = this._extensions[name_1];
if (extension.dispose) {
this._extensions[name_1].dispose();
}
}
this._extensions = {};
delete this._rootBabylonMesh;
delete this._progressCallback;
this._parent._clear();
};
/** @hidden */
GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
var _this = this;
return Promise.resolve().then(function () {
_this.babylonScene = scene;
_this._rootUrl = rootUrl;
_this._fileName = fileName || "scene";
_this._progressCallback = onProgress;
_this._loadData(data);
var nodes = null;
if (meshesNames) {
var nodeMap_1 = {};
if (_this.gltf.nodes) {
for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
var node = _a[_i];
if (node.name) {
nodeMap_1[node.name] = node.index;
}
}
}
var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
nodes = names.map(function (name) {
var node = nodeMap_1[name];
if (node === undefined) {
throw new Error("Failed to find node '" + name + "'");
}
return node;
});
}
return _this._loadAsync(nodes, function () {
return {
meshes: _this._getMeshes(),
particleSystems: [],
skeletons: _this._getSkeletons(),
animationGroups: _this._getAnimationGroups()
};
});
});
};
/** @hidden */
GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
var _this = this;
return Promise.resolve().then(function () {
_this.babylonScene = scene;
_this._rootUrl = rootUrl;
_this._fileName = fileName || "scene";
_this._progressCallback = onProgress;
_this._loadData(data);
return _this._loadAsync(null, function () { return undefined; });
});
};
GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) {
var _this = this;
return Promise.resolve().then(function () {
_this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
_this._loadExtensions();
_this._checkExtensions();
var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];
var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];
_this._parent._startPerformanceCounter(loadingToReadyCounterName);
_this._parent._startPerformanceCounter(loadingToCompleteCounterName);
_this._setState(BABYLON.GLTFLoaderState.LOADING);
_this._extensionsOnLoading();
var promises = new Array();
if (nodes) {
promises.push(_this.loadSceneAsync("/nodes", { nodes: nodes, index: -1 }));
}
else {
var scene = ArrayItem.Get("/scene", _this.gltf.scenes, _this.gltf.scene || 0);
promises.push(_this.loadSceneAsync("/scenes/" + scene.index, scene));
}
if (_this._parent.compileMaterials) {
promises.push(_this._compileMaterialsAsync());
}
if (_this._parent.compileShadowGenerators) {
promises.push(_this._compileShadowGeneratorsAsync());
}
var resultPromise = Promise.all(promises).then(function () {
if (_this._rootBabylonMesh) {
_this._rootBabylonMesh.setEnabled(true);
}
_this._setState(BABYLON.GLTFLoaderState.READY);
_this._extensionsOnReady();
_this._startAnimations();
return resultFunc();
});
resultPromise.then(function () {
_this._parent._endPerformanceCounter(loadingToReadyCounterName);
BABYLON.Tools.SetImmediate(function () {
if (!_this._disposed) {
Promise.all(_this._completePromises).then(function () {
_this._parent._endPerformanceCounter(loadingToCompleteCounterName);
_this._setState(BABYLON.GLTFLoaderState.COMPLETE);
_this._parent.onCompleteObservable.notifyObservers(undefined);
_this._parent.onCompleteObservable.clear();
_this.dispose();
}, function (error) {
_this._parent.onErrorObservable.notifyObservers(error);
_this._parent.onErrorObservable.clear();
_this.dispose();
});
}
});
});
return resultPromise;
}, function (error) {
if (!_this._disposed) {
_this._parent.onErrorObservable.notifyObservers(error);
_this._parent.onErrorObservable.clear();
_this.dispose();
}
throw error;
});
};
GLTFLoader.prototype._loadData = function (data) {
this.gltf = data.json;
this._setupData();
if (data.bin) {
var buffers = this.gltf.buffers;
if (buffers && buffers[0] && !buffers[0].uri) {
var binaryBuffer = buffers[0];
if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
}
binaryBuffer._data = Promise.resolve(data.bin);
}
else {
BABYLON.Tools.Warn("Unexpected BIN chunk");
}
}
};
GLTFLoader.prototype._setupData = function () {
ArrayItem.Assign(this.gltf.accessors);
ArrayItem.Assign(this.gltf.animations);
ArrayItem.Assign(this.gltf.buffers);
ArrayItem.Assign(this.gltf.bufferViews);
ArrayItem.Assign(this.gltf.cameras);
ArrayItem.Assign(this.gltf.images);
ArrayItem.Assign(this.gltf.materials);
ArrayItem.Assign(this.gltf.meshes);
ArrayItem.Assign(this.gltf.nodes);
ArrayItem.Assign(this.gltf.samplers);
ArrayItem.Assign(this.gltf.scenes);
ArrayItem.Assign(this.gltf.skins);
ArrayItem.Assign(this.gltf.textures);
if (this.gltf.nodes) {
var nodeParents = {};
for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
var node = _a[_i];
if (node.children) {
for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
var index = _c[_b];
nodeParents[index] = node.index;
}
}
}
var rootNode = this._createRootNode();
for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
var node = _e[_d];
var parentIndex = nodeParents[node.index];
node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
}
}
};
GLTFLoader.prototype._loadExtensions = function () {
for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
var name_2 = _a[_i];
var extension = GLTFLoader._ExtensionFactories[name_2](this);
this._extensions[name_2] = extension;
this._parent.onExtensionLoadedObservable.notifyObservers(extension);
}
this._parent.onExtensionLoadedObservable.clear();
};
GLTFLoader.prototype._checkExtensions = function () {
if (this.gltf.extensionsRequired) {
for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
var name_3 = _a[_i];
var extension = this._extensions[name_3];
if (!extension || !extension.enabled) {
throw new Error("Require extension " + name_3 + " is not available");
}
}
}
};
GLTFLoader.prototype._setState = function (state) {
this._state = state;
this.log(BABYLON.GLTFLoaderState[this._state]);
};
GLTFLoader.prototype._createRootNode = function () {
this._rootBabylonMesh = new BABYLON.Mesh("__root__", this.babylonScene);
this._rootBabylonMesh.setEnabled(false);
var rootNode = {
_babylonTransformNode: this._rootBabylonMesh,
index: -1
};
switch (this._parent.coordinateSystemMode) {
case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
if (!this.babylonScene.useRightHandedSystem) {
rootNode.rotation = [0, 1, 0, 0];
rootNode.scale = [1, 1, -1];
GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
}
break;
}
case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
this.babylonScene.useRightHandedSystem = true;
break;
}
default: {
throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
}
}
this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
return rootNode;
};
/**
* Loads a glTF scene.
* @param context The context when loading the asset
* @param scene The glTF scene property
* @returns A promise that resolves when the load is complete
*/
GLTFLoader.prototype.loadSceneAsync = function (context, scene) {
var _this = this;
var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
if (extensionPromise) {
return extensionPromise;
}
var promises = new Array();
this.logOpen(context + " " + (scene.name || ""));
if (scene.nodes) {
for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
var index = _a[_i];
var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
promises.push(this.loadNodeAsync("/nodes/" + node.index, node, function (babylonMesh) {
babylonMesh.parent = _this._rootBabylonMesh;
}));
}
}
promises.push(this._loadAnimationsAsync());
this.logClose();
return Promise.all(promises).then(function () { });
};
GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
if (node._primitiveBabylonMeshes) {
for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
var babylonMesh = _a[_i];
callback(babylonMesh);
}
}
else if (node._babylonTransformNode instanceof BABYLON.AbstractMesh) {
callback(node._babylonTransformNode);
}
};
GLTFLoader.prototype._getMeshes = function () {
var meshes = new Array();
// Root mesh is always first.
meshes.push(this._rootBabylonMesh);
var nodes = this.gltf.nodes;
if (nodes) {
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
var node = nodes_1[_i];
this._forEachPrimitive(node, function (babylonMesh) {
meshes.push(babylonMesh);
});
}
}
return meshes;
};
GLTFLoader.prototype._getSkeletons = function () {
var skeletons = new Array();
var skins = this.gltf.skins;
if (skins) {
for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
var skin = skins_1[_i];
if (skin._data) {
skeletons.push(skin._data.babylonSkeleton);
}
}
}
return skeletons;
};
GLTFLoader.prototype._getAnimationGroups = function () {
var animationGroups = new Array();
var animations = this.gltf.animations;
if (animations) {
for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
var animation = animations_1[_i];
if (animation._babylonAnimationGroup) {
animationGroups.push(animation._babylonAnimationGroup);
}
}
}
return animationGroups;
};
GLTFLoader.prototype._startAnimations = function () {
switch (this._parent.animationStartMode) {
case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
// do nothing
break;
}
case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
var babylonAnimationGroups = this._getAnimationGroups();
if (babylonAnimationGroups.length !== 0) {
babylonAnimationGroups[0].start(true);
}
break;
}
case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
var babylonAnimationGroups = this._getAnimationGroups();
for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
var babylonAnimationGroup = babylonAnimationGroups_1[_i];
babylonAnimationGroup.start(true);
}
break;
}
default: {
BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
return;
}
}
};
/**
* Loads a glTF node.
* @param context The context when loading the asset
* @param node The glTF node property
* @param assign A function called synchronously after parsing the glTF properties
* @returns A promise that resolves with the loaded Babylon mesh when the load is complete
*/
GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) {
var _this = this;
if (assign === void 0) { assign = function () { }; }
var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
if (extensionPromise) {
return extensionPromise;
}
if (node._babylonTransformNode) {
throw new Error(context + ": Invalid recursive node hierarchy");
}
var promises = new Array();
this.logOpen(context + " " + (node.name || ""));
var loadNode = function (babylonTransformNode) {
GLTFLoader.AddPointerMetadata(babylonTransformNode, context);
GLTFLoader._LoadTransform(node, babylonTransformNode);
if (node.camera != undefined) {
var camera = ArrayItem.Get(context + "/camera", _this.gltf.cameras, node.camera);
promises.push(_this.loadCameraAsync("/cameras/" + camera.index, camera, function (babylonCamera) {
babylonCamera.parent = babylonTransformNode;
}));
}
if (node.children) {
var _loop_1 = function (index) {
var childNode = ArrayItem.Get(context + "/children/" + index, _this.gltf.nodes, index);
promises.push(_this.loadNodeAsync("/nodes/" + childNode.index, childNode, function (childBabylonMesh) {
// See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
if (childNode.skin != undefined) {
childBabylonMesh.parent = _this._rootBabylonMesh;
return;
}
childBabylonMesh.parent = babylonTransformNode;
}));
};
for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
var index = _a[_i];
_loop_1(index);
}
}
assign(babylonTransformNode);
};
if (node.mesh == undefined) {
var nodeName = node.name || "node" + node.index;
node._babylonTransformNode = new BABYLON.TransformNode(nodeName, this.babylonScene);
loadNode(node._babylonTransformNode);
}
else {
var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
promises.push(this._loadMeshAsync("/meshes/" + mesh.index, node, mesh, loadNode));
}
this.logClose();
return Promise.all(promises).then(function () {
_this._forEachPrimitive(node, function (babylonMesh) {
babylonMesh.refreshBoundingInfo(true);
});
return node._babylonTransformNode;
});
};
GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, assign) {
var primitives = mesh.primitives;
if (!primitives || !primitives.length) {
throw new Error(context + ": Primitives are missing");
}
if (primitives[0].index == undefined) {
ArrayItem.Assign(primitives);
}
var promises = new Array();
this.logOpen(context + " " + (mesh.name || ""));
var name = node.name || "node" + node.index;
if (primitives.length === 1) {
var primitive = mesh.primitives[0];
promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name, node, mesh, primitive, function (babylonMesh) {
node._babylonTransformNode = babylonMesh;
}));
}
else {
var babylonTransformNode_1 = new BABYLON.TransformNode(name, this.babylonScene);
node._babylonTransformNode = babylonTransformNode_1;
for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
var primitive = primitives_1[_i];
promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name + "_primitive" + primitive.index, node, mesh, primitive, function (babylonMesh) {
babylonMesh.parent = babylonTransformNode_1;
node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
node._primitiveBabylonMeshes.push(babylonMesh);
}));
}
}
if (node.skin != undefined) {
var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
promises.push(this._loadSkinAsync("/skins/" + skin.index, node, skin));
}
assign(node._babylonTransformNode);
this.logClose();
return Promise.all(promises).then(function () {
return node._babylonTransformNode;
});
};
GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, name, node, mesh, primitive, assign) {
var _this = this;
this.logOpen("" + context);
var canInstance = (node.skin == undefined && !mesh.primitives[0].targets);
var babylonAbstractMesh;
var promise;
var instanceData = primitive._instanceData;
if (canInstance && instanceData) {
babylonAbstractMesh = instanceData.babylonSourceMesh.createInstance(name);
promise = instanceData.promise;
}
else {
var promises = new Array();
var babylonMesh_1 = new BABYLON.Mesh(name, this.babylonScene);
this._createMorphTargets(context, node, mesh, primitive, babylonMesh_1);
promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh_1).then(function (babylonGeometry) {
return _this._loadMorphTargetsAsync(context, primitive, babylonMesh_1, babylonGeometry).then(function () {
babylonGeometry.applyToMesh(babylonMesh_1);
});
}));
var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
if (primitive.material == undefined) {
var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
if (!babylonMaterial) {
babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
}
babylonMesh_1.material = babylonMaterial;
}
else {
var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
promises.push(this._loadMaterialAsync("/materials/" + material.index, material, babylonMesh_1, babylonDrawMode, function (babylonMaterial) {
babylonMesh_1.material = babylonMaterial;
}));
}
promise = Promise.all(promises);
if (canInstance) {
primitive._instanceData = {
babylonSourceMesh: babylonMesh_1,
promise: promise
};
}
babylonAbstractMesh = babylonMesh_1;
}
GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context);
this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);
assign(babylonAbstractMesh);
this.logClose();
return promise.then(function () {
return babylonAbstractMesh;
});
};
GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
var _this = this;
var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
if (extensionPromise) {
return extensionPromise;
}
var attributes = primitive.attributes;
if (!attributes) {
throw new Error(context + ": Attributes are missing");
}
var promises = new Array();
var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this.babylonScene);
if (primitive.indices == undefined) {
babylonMesh.isUnIndexed = true;
}
else {
var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
promises.push(this._loadIndicesAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) {
babylonGeometry.setIndices(data);
}));
}
var loadAttribute = function (attribute, kind, callback) {
if (attributes[attribute] == undefined) {
return;
}
babylonMesh._delayInfo = babylonMesh._delayInfo || [];
if (babylonMesh._delayInfo.indexOf(kind) === -1) {
babylonMesh._delayInfo.push(kind);
}
var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
promises.push(_this._loadVertexAccessorAsync("/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
}));
if (callback) {
callback(accessor);
}
};
loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
if (accessor.type === "VEC4" /* VEC4 */) {
babylonMesh.hasVertexAlpha = true;
}
});
return Promise.all(promises).then(function () {
return babylonGeometry;
});
};
GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
if (!primitive.targets) {
return;
}
if (node._numMorphTargets == undefined) {
node._numMorphTargets = primitive.targets.length;
}
else if (primitive.targets.length !== node._numMorphTargets) {
throw new Error(context + ": Primitives do not have the same number of targets");
}
babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
for (var index = 0; index < primitive.targets.length; index++) {
var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
// TODO: tell the target whether it has positions, normals, tangents
}
};
GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
if (!primitive.targets) {
return Promise.resolve();
}
var promises = new Array();
var morphTargetManager = babylonMesh.morphTargetManager;
for (var index = 0; index < morphTargetManager.numTargets; index++) {
var babylonMorphTarget = morphTargetManager.getTarget(index);
promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
}
return Promise.all(promises).then(function () { });
};
GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
var _this = this;
var promises = new Array();
var loadAttribute = function (attribute, kind, setData) {
if (attributes[attribute] == undefined) {
return;
}
var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
if (!babylonVertexBuffer) {
return;
}
var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
promises.push(_this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) {
setData(babylonVertexBuffer, data);
}));
};
loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
babylonVertexBuffer.forEach(data.length, function (value, index) {
data[index] += value;
});
babylonMorphTarget.setPositions(data);
});
loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
babylonVertexBuffer.forEach(data.length, function (value, index) {
data[index] += value;
});
babylonMorphTarget.setNormals(data);
});
loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
var dataIndex = 0;
babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
// Tangent data for morph targets is stored as xyz delta.
// The vertexData.tangent is stored as xyzw.
// So we need to skip every fourth vertexData.tangent.
if (((index + 1) % 4) !== 0) {
data[dataIndex++] += value;
}
});
babylonMorphTarget.setTangents(data);
});
return Promise.all(promises).then(function () { });
};
GLTFLoader._LoadTransform = function (node, babylonNode) {
// Ignore the TRS of skinned nodes.
// See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
if (node.skin != undefined) {
return;
}
var position = BABYLON.Vector3.Zero();
var rotation = BABYLON.Quaternion.Identity();
var scaling = BABYLON.Vector3.One();
if (node.matrix) {
var matrix = BABYLON.Matrix.FromArray(node.matrix);
matrix.decompose(scaling, rotation, position);
}
else {
if (node.translation) {
position = BABYLON.Vector3.FromArray(node.translation);
}
if (node.rotation) {
rotation = BABYLON.Quaternion.FromArray(node.rotation);
}
if (node.scale) {
scaling = BABYLON.Vector3.FromArray(node.scale);
}
}
babylonNode.position = position;
babylonNode.rotationQuaternion = rotation;
babylonNode.scaling = scaling;
};
GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) {
var _this = this;
var assignSkeleton = function (skeleton) {
_this._forEachPrimitive(node, function (babylonMesh) {
babylonMesh.skeleton = skeleton;
});
};
if (skin._data) {
var data_1 = skin._data;
return data_1.promise.then(function () {
assignSkeleton(data_1.babylonSkeleton);
});
}
var skeletonId = "skeleton" + skin.index;
var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
this._loadBones(context, skin, babylonSkeleton);
assignSkeleton(babylonSkeleton);
var promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
_this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
});
skin._data = {
babylonSkeleton: babylonSkeleton,
promise: promise
};
return promise;
};
GLTFLoader.prototype._loadBones = function (context, skin, babylonSkeleton) {
var babylonBones = {};
for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
var index = _a[_i];
var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
this._loadBone(node, skin, babylonSkeleton, babylonBones);
}
};
GLTFLoader.prototype._loadBone = function (node, skin, babylonSkeleton, babylonBones) {
var babylonBone = babylonBones[node.index];
if (babylonBone) {
return babylonBone;
}
var babylonParentBone = null;
if (node.parent && node.parent._babylonTransformNode !== this._rootBabylonMesh) {
babylonParentBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);
}
var boneIndex = skin.joints.indexOf(node.index);
babylonBone = new BABYLON.Bone(node.name || "joint" + node.index, babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
babylonBones[node.index] = babylonBone;
node._babylonBones = node._babylonBones || [];
node._babylonBones.push(babylonBone);
return babylonBone;
};
GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
if (skin.inverseBindMatrices == undefined) {
return Promise.resolve(null);
}
var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
return this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor);
};
GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
var babylonBone = _a[_i];
var baseMatrix = BABYLON.Matrix.Identity();
var boneIndex = babylonBone._index;
if (inverseBindMatricesData && boneIndex !== -1) {
BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
baseMatrix.invertToRef(baseMatrix);
}
var babylonParentBone = babylonBone.getParent();
if (babylonParentBone) {
baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
}
babylonBone.updateMatrix(baseMatrix, false, false);
babylonBone._updateDifferenceMatrix(undefined, false);
}
};
GLTFLoader.prototype._getNodeMatrix = function (node) {
return node.matrix ?
BABYLON.Matrix.FromArray(node.matrix) :
BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
};
/**
* Loads a glTF camera.
* @param context The context when loading the asset
* @param camera The glTF camera property
* @param assign A function called synchronously after parsing the glTF properties
* @returns A promise that resolves with the loaded Babylon camera when the load is complete
*/
GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) {
if (assign === void 0) { assign = function () { }; }
var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
if (extensionPromise) {
return extensionPromise;
}
var promises = new Array();
this.logOpen(context + " " + (camera.name || ""));
var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera.index, BABYLON.Vector3.Zero(), this.babylonScene, false);
babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
switch (camera.type) {
case "perspective" /* PERSPECTIVE */: {
var perspective = camera.perspective;
if (!perspective) {
throw new Error(context + ": Camera perspective properties are missing");
}
babylonCamera.fov = perspective.yfov;
babylonCamera.minZ = perspective.znear;
babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
break;
}
case "orthographic" /* ORTHOGRAPHIC */: {
if (!camera.orthographic) {
throw new Error(context + ": Camera orthographic properties are missing");
}
babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
babylonCamera.orthoLeft = -camera.orthographic.xmag;
babylonCamera.orthoRight = camera.orthographic.xmag;
babylonCamera.orthoBottom = -camera.orthographic.ymag;
babylonCamera.orthoTop = camera.orthographic.ymag;
babylonCamera.minZ = camera.orthographic.znear;
babylonCamera.maxZ = camera.orthographic.zfar;
break;
}
default: {
throw new Error(context + ": Invalid camera type (" + camera.type + ")");
}
}
GLTFLoader.AddPointerMetadata(babylonCamera, context);
this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
assign(babylonCamera);
return Promise.all(promises).then(function () {
return babylonCamera;
});
};
GLTFLoader.prototype._loadAnimationsAsync = function () {
var animations = this.gltf.animations;
if (!animations) {
return Promise.resolve();
}
var promises = new Array();
for (var index = 0; index < animations.length; index++) {
var animation = animations[index];
promises.push(this.loadAnimationAsync("/animations/" + animation.index, animation));
}
return Promise.all(promises).then(function () { });
};
/**
* Loads a glTF animation.
* @param context The context when loading the asset
* @param animation The glTF animation property
* @returns A promise that resolves with the loaded Babylon animation group when the load is complete
*/
GLTFLoader.prototype.loadAnimationAsync = function (context, animation) {
var promise = this._extensionsLoadAnimationAsync(context, animation);
if (promise) {
return promise;
}
var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
animation._babylonAnimationGroup = babylonAnimationGroup;
var promises = new Array();
ArrayItem.Assign(animation.channels);
ArrayItem.Assign(animation.samplers);
for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
var channel = _a[_i];
promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
}
return Promise.all(promises).then(function () {
babylonAnimationGroup.normalize(0);
return babylonAnimationGroup;
});
};
GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
var _this = this;
if (channel.target.node == undefined) {
return Promise.resolve();
}
var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
// Ignore animations that have no animation targets.
if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
(channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonTransformNode)) {
return Promise.resolve();
}
// Ignore animations targeting TRS of skinned nodes.
// See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
return Promise.resolve();
}
var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
var targetPath;
var animationType;
switch (channel.target.path) {
case "translation" /* TRANSLATION */: {
targetPath = "position";
animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
break;
}
case "rotation" /* ROTATION */: {
targetPath = "rotationQuaternion";
animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
break;
}
case "scale" /* SCALE */: {
targetPath = "scaling";
animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
break;
}
case "weights" /* WEIGHTS */: {
targetPath = "influence";
animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
break;
}
default: {
throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
}
}
var outputBufferOffset = 0;
var getNextOutputValue;
switch (targetPath) {
case "position": {
getNextOutputValue = function () {
var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
outputBufferOffset += 3;
return value;
};
break;
}
case "rotationQuaternion": {
getNextOutputValue = function () {
var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
outputBufferOffset += 4;
return value;
};
break;
}
case "scaling": {
getNextOutputValue = function () {
var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
outputBufferOffset += 3;
return value;
};
break;
}
case "influence": {
getNextOutputValue = function () {
var value = new Array(targetNode._numMorphTargets);
for (var i = 0; i < targetNode._numMorphTargets; i++) {
value[i] = data.output[outputBufferOffset++];
}
return value;
};
break;
}
}
var getNextKey;
switch (data.interpolation) {
case "STEP" /* STEP */: {
getNextKey = function (frameIndex) { return ({
frame: data.input[frameIndex],
value: getNextOutputValue(),
interpolation: BABYLON.AnimationKeyInterpolation.STEP
}); };
break;
}
case "LINEAR" /* LINEAR */: {
getNextKey = function (frameIndex) { return ({
frame: data.input[frameIndex],
value: getNextOutputValue()
}); };
break;
}
case "CUBICSPLINE" /* CUBICSPLINE */: {
getNextKey = function (frameIndex) { return ({
frame: data.input[frameIndex],
inTangent: getNextOutputValue(),
value: getNextOutputValue(),
outTangent: getNextOutputValue()
}); };
break;
}
}
var keys = new Array(data.input.length);
for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
keys[frameIndex] = getNextKey(frameIndex);
}
if (targetPath === "influence") {
var _loop_2 = function (targetIndex) {
var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
babylonAnimation.setKeys(keys.map(function (key) { return ({
frame: key.frame,
inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
value: key.value[targetIndex],
outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
}); }));
_this._forEachPrimitive(targetNode, function (babylonMesh) {
var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
var babylonAnimationClone = babylonAnimation.clone();
morphTarget.animations.push(babylonAnimationClone);
babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
});
};
for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
_loop_2(targetIndex);
}
}
else {
var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
babylonAnimation.setKeys(keys);
var babylonTransformNode = targetNode._babylonTransformNode;
var babylonBones = targetNode._babylonBones;
if (babylonBones) {
var babylonAnimationTargets = [babylonTransformNode].concat(babylonBones);
for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
var babylonAnimationTarget = babylonAnimationTargets_1[_i];
babylonAnimationTarget.animations.push(babylonAnimation);
}
babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
}
else {
babylonTransformNode.animations.push(babylonAnimation);
babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonTransformNode);
}
}
});
};
GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
if (sampler._data) {
return sampler._data;
}
var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
switch (interpolation) {
case "STEP" /* STEP */:
case "LINEAR" /* LINEAR */:
case "CUBICSPLINE" /* CUBICSPLINE */: {
break;
}
default: {
throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
}
}
var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
sampler._data = Promise.all([
this._loadFloatAccessorAsync("/accessors/" + inputAccessor.index, inputAccessor),
this._loadFloatAccessorAsync("/accessors/" + outputAccessor.index, outputAccessor)
]).then(function (_a) {
var inputData = _a[0], outputData = _a[1];
return {
input: inputData,
interpolation: interpolation,
output: outputData,
};
});
return sampler._data;
};
GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
if (buffer._data) {
return buffer._data;
}
if (!buffer.uri) {
throw new Error(context + "/uri: Value is missing");
}
buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
return buffer._data;
};
/**
* Loads a glTF buffer view.
* @param context The context when loading the asset
* @param bufferView The glTF buffer view property
* @returns A promise that resolves with the loaded data when the load is complete
*/
GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) {
if (bufferView._data) {
return bufferView._data;
}
var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
bufferView._data = this._loadBufferAsync("/buffers/" + buffer.index, buffer).then(function (data) {
try {
return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
}
catch (e) {
throw new Error(context + ": " + e.message);
}
});
return bufferView._data;
};
GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
if (accessor.type !== "SCALAR" /* SCALAR */) {
throw new Error(context + "/type: Invalid value " + accessor.type);
}
if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
accessor.componentType !== 5125 /* UNSIGNED_INT */) {
throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
}
if (accessor._data) {
return accessor._data;
}
var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
accessor._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) {
return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
});
return accessor._data;
};
GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
// TODO: support normalized and stride
var _this = this;
if (accessor.componentType !== 5126 /* FLOAT */) {
throw new Error("Invalid component type " + accessor.componentType);
}
if (accessor._data) {
return accessor._data;
}
var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
var length = numComponents * accessor.count;
if (accessor.bufferView == undefined) {
accessor._data = Promise.resolve(new Float32Array(length));
}
else {
var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
accessor._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) {
return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
});
}
if (accessor.sparse) {
var sparse_1 = accessor.sparse;
accessor._data = accessor._data.then(function (data) {
var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
return Promise.all([
_this.loadBufferViewAsync("/bufferViews/" + indicesBufferView.index, indicesBufferView),
_this.loadBufferViewAsync("/bufferViews/" + valuesBufferView.index, valuesBufferView)
]).then(function (_a) {
var indicesData = _a[0], valuesData = _a[1];
var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
var valuesIndex = 0;
for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
var dataIndex = indices[indicesIndex] * numComponents;
for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
data[dataIndex++] = values[valuesIndex++];
}
}
return data;
});
});
}
return accessor._data;
};
GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
var _this = this;
if (bufferView._babylonBuffer) {
return bufferView._babylonBuffer;
}
bufferView._babylonBuffer = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) {
return new BABYLON.Buffer(_this.babylonScene.getEngine(), data, false);
});
return bufferView._babylonBuffer;
};
GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
var _this = this;
if (accessor._babylonVertexBuffer) {
return accessor._babylonVertexBuffer;
}
if (accessor.sparse) {
accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) {
return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
});
}
// HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
else if (accessor.byteOffset && accessor.byteOffset % BABYLON.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
BABYLON.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) {
return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
});
}
else {
var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
var size = GLTFLoader._GetNumComponents(context, accessor.type);
return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
});
}
return accessor._babylonVertexBuffer;
};
GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
throw new Error(context + ": Material type not supported");
}
var promises = new Array();
if (properties) {
if (properties.baseColorFactor) {
babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
babylonMaterial.alpha = properties.baseColorFactor[3];
}
else {
babylonMaterial.albedoColor = BABYLON.Color3.White();
}
babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
if (properties.baseColorTexture) {
promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
texture.name = babylonMaterial.name + " (Base Color)";
babylonMaterial.albedoTexture = texture;
}));
}
if (properties.metallicRoughnessTexture) {
promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
texture.name = babylonMaterial.name + " (Metallic Roughness)";
babylonMaterial.metallicTexture = texture;
}));
babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
}
}
return Promise.all(promises).then(function () { });
};
/** @hidden */
GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
if (assign === void 0) { assign = function () { }; }
var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
if (extensionPromise) {
return extensionPromise;
}
material._data = material._data || {};
var babylonData = material._data[babylonDrawMode];
if (!babylonData) {
this.logOpen(context + " " + (material.name || ""));
var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
babylonData = {
babylonMaterial: babylonMaterial,
babylonMeshes: [],
promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
};
material._data[babylonDrawMode] = babylonData;
GLTFLoader.AddPointerMetadata(babylonMaterial, context);
this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
this.logClose();
}
babylonData.babylonMeshes.push(babylonMesh);
babylonMesh.onDisposeObservable.addOnce(function () {
var index = babylonData.babylonMeshes.indexOf(babylonMesh);
if (index !== -1) {
babylonData.babylonMeshes.splice(index, 1);
}
});
assign(babylonData.babylonMaterial);
return babylonData.promise.then(function () {
return babylonData.babylonMaterial;
});
};
GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
var babylonMaterial = new BABYLON.PBRMaterial(name, this.babylonScene);
babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
babylonMaterial.fillMode = babylonDrawMode;
babylonMaterial.enableSpecularAntiAliasing = true;
babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
babylonMaterial.metallic = 1;
babylonMaterial.roughness = 1;
return babylonMaterial;
};
/**
* Creates a Babylon material from a glTF material.
* @param context The context when loading the asset
* @param material The glTF material property
* @param babylonDrawMode The draw mode for the Babylon material
* @returns The Babylon material
*/
GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) {
var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
if (extensionPromise) {
return extensionPromise;
}
var name = material.name || "material" + material.index;
var babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode);
return babylonMaterial;
};
/**
* Loads properties from a glTF material into a Babylon material.
* @param context The context when loading the asset
* @param material The glTF material property
* @param babylonMaterial The Babylon material
* @returns A promise that resolves when the load is complete
*/
GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
if (extensionPromise) {
return extensionPromise;
}
var promises = new Array();
promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
if (material.pbrMetallicRoughness) {
promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
}
this.loadMaterialAlphaProperties(context, material, babylonMaterial);
return Promise.all(promises).then(function () { });
};
/**
* Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
* @param context The context when loading the asset
* @param material The glTF material property
* @param babylonMaterial The Babylon material
* @returns A promise that resolves when the load is complete
*/
GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
throw new Error(context + ": Material type not supported");
}
var promises = new Array();
babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
if (material.doubleSided) {
babylonMaterial.backFaceCulling = false;
babylonMaterial.twoSidedLighting = true;
}
if (material.normalTexture) {
promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
texture.name = babylonMaterial.name + " (Normal)";
babylonMaterial.bumpTexture = texture;
}));
babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
if (material.normalTexture.scale != undefined) {
babylonMaterial.bumpTexture.level = material.normalTexture.scale;
}
}
if (material.occlusionTexture) {
promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
texture.name = babylonMaterial.name + " (Occlusion)";
babylonMaterial.ambientTexture = texture;
}));
babylonMaterial.useAmbientInGrayScale = true;
if (material.occlusionTexture.strength != undefined) {
babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
}
}
if (material.emissiveTexture) {
promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
texture.name = babylonMaterial.name + " (Emissive)";
babylonMaterial.emissiveTexture = texture;
}));
}
return Promise.all(promises).then(function () { });
};
/**
* Loads the alpha properties from a glTF material into a Babylon material.
* Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
* @param context The context when loading the asset
* @param material The glTF material property
* @param babylonMaterial The Babylon material
*/
GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
throw new Error(context + ": Material type not supported");
}
var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
switch (alphaMode) {
case "OPAQUE" /* OPAQUE */: {
babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
break;
}
case "MASK" /* MASK */: {
babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
if (babylonMaterial.albedoTexture) {
babylonMaterial.albedoTexture.hasAlpha = true;
}
break;
}
case "BLEND" /* BLEND */: {
babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
if (babylonMaterial.albedoTexture) {
babylonMaterial.albedoTexture.hasAlpha = true;
babylonMaterial.useAlphaFromAlbedoTexture = true;
}
break;
}
default: {
throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
}
}
};
/**
* Loads a glTF texture info.
* @param context The context when loading the asset
* @param textureInfo The glTF texture info property
* @param assign A function called synchronously after parsing the glTF properties
* @returns A promise that resolves with the loaded Babylon texture when the load is complete
*/
GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
var _this = this;
if (assign === void 0) { assign = function () { }; }
var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
if (extensionPromise) {
return extensionPromise;
}
this.logOpen("" + context);
var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
var promise = this._loadTextureAsync("/textures/" + textureInfo.index, texture, function (babylonTexture) {
babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
GLTFLoader.AddPointerMetadata(babylonTexture, context);
_this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
assign(babylonTexture);
});
this.logClose();
return promise;
};
GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
var _this = this;
if (assign === void 0) { assign = function () { }; }
var promises = new Array();
this.logOpen(context + " " + (texture.name || ""));
var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
var samplerData = this._loadSampler("/samplers/" + sampler.index, sampler);
var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
var textureURL = null;
if (image.uri && !BABYLON.Tools.IsBase64(image.uri) && this.babylonScene.getEngine().textureFormatInUse) {
// If an image uri and a texture format is set like (eg. KTX) load from url instead of blob to support texture format and fallback
textureURL = this._uniqueRootUrl + image.uri;
}
var deferred = new BABYLON.Deferred();
var babylonTexture = new BABYLON.Texture(textureURL, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
if (!_this._disposed) {
deferred.resolve();
}
}, function (message, exception) {
if (!_this._disposed) {
deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
}
});
promises.push(deferred.promise);
if (!textureURL) {
promises.push(this.loadImageAsync("/images/" + image.index, image).then(function (data) {
var name = image.uri || _this._fileName + "#image" + image.index;
var dataUrl = "data:" + _this._uniqueRootUrl + name;
babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
}));
}
babylonTexture.wrapU = samplerData.wrapU;
babylonTexture.wrapV = samplerData.wrapV;
assign(babylonTexture);
this.logClose();
return Promise.all(promises).then(function () {
return babylonTexture;
});
};
GLTFLoader.prototype._loadSampler = function (context, sampler) {
if (!sampler._data) {
sampler._data = {
noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
};
}
return sampler._data;
};
/**
* Loads a glTF image.
* @param context The context when loading the asset
* @param image The glTF image property
* @returns A promise that resolves with the loaded data when the load is complete
*/
GLTFLoader.prototype.loadImageAsync = function (context, image) {
if (!image._data) {
this.logOpen(context + " " + (image.name || ""));
if (image.uri) {
image._data = this.loadUriAsync(context + "/uri", image.uri);
}
else {
var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
image._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView);
}
this.logClose();
}
return image._data;
};
/**
* Loads a glTF uri.
* @param context The context when loading the asset
* @param uri The base64 or relative uri
* @returns A promise that resolves with the loaded data when the load is complete
*/
GLTFLoader.prototype.loadUriAsync = function (context, uri) {
var _this = this;
var extensionPromise = this._extensionsLoadUriAsync(context, uri);
if (extensionPromise) {
return extensionPromise;
}
if (!GLTFLoader._ValidateUri(uri)) {
throw new Error(context + ": '" + uri + "' is invalid");
}
if (BABYLON.Tools.IsBase64(uri)) {
var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
return Promise.resolve(data);
}
this.log("Loading " + uri);
return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
return new Promise(function (resolve, reject) {
if (!_this._disposed) {
var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
if (!_this._disposed) {
var data = new Uint8Array(fileData);
_this.log("Loaded " + uri + " (" + data.length + " bytes)");
resolve(data);
}
}, function (event) {
if (!_this._disposed) {
if (request_1) {
request_1._lengthComputable = event.lengthComputable;
request_1._loaded = event.loaded;
request_1._total = event.total;
}
if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
try {
_this._onProgress();
}
catch (e) {
reject(e);
}
}
}
}, _this.babylonScene.offlineProvider, true, function (request, exception) {
if (!_this._disposed) {
reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
}
});
_this._requests.push(request_1);
}
});
});
};
GLTFLoader.prototype._onProgress = function () {
if (!this._progressCallback) {
return;
}
var lengthComputable = true;
var loaded = 0;
var total = 0;
for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
var request = _a[_i];
if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
return;
}
lengthComputable = lengthComputable && request._lengthComputable;
loaded += request._loaded;
total += request._total;
}
this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
};
/**
* Adds a JSON pointer to the metadata of the Babylon object at `