diff --git a/assets/卷帘大.glb b/assets/卷帘大.glb
index 6f71ecb..9710eb9 100644
Binary files a/assets/卷帘大.glb and b/assets/卷帘大.glb differ
diff --git a/assets/卷帘小.glb b/assets/卷帘小.glb
index b346f2a..12a2012 100644
Binary files a/assets/卷帘小.glb and b/assets/卷帘小.glb differ
diff --git a/assets/小桌.glb b/assets/小桌.glb
index d92e917..e0c3abe 100644
Binary files a/assets/小桌.glb and b/assets/小桌.glb differ
diff --git a/assets/框架.glb b/assets/框架.glb
index a30815e..7aed96e 100644
Binary files a/assets/框架.glb and b/assets/框架.glb differ
diff --git a/assets/百叶窗小.glb b/assets/百叶窗小.glb
index cf43ec3..8efe915 100644
Binary files a/assets/百叶窗小.glb and b/assets/百叶窗小.glb differ
diff --git a/examples/index copy.js b/examples/index copy.js
new file mode 100644
index 0000000..5cce4f6
--- /dev/null
+++ b/examples/index copy.js
@@ -0,0 +1,297813 @@
+const isWeakRefSupported = typeof WeakRef !== "undefined";
+/**
+ * A class serves as a medium between the observable and its observers
+ */
+class EventState {
+ /**
+ * Create a new EventState
+ * @param mask defines the mask associated with this state
+ * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
+ * @param target defines the original target of the state
+ * @param currentTarget defines the current target of the state
+ */
+ constructor(mask, skipNextObservers = false, target, currentTarget) {
+ this.initialize(mask, skipNextObservers, target, currentTarget);
+ }
+ /**
+ * Initialize the current event state
+ * @param mask defines the mask associated with this state
+ * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
+ * @param target defines the original target of the state
+ * @param currentTarget defines the current target of the state
+ * @returns the current event state
+ */
+ initialize(mask, skipNextObservers = false, target, currentTarget) {
+ this.mask = mask;
+ this.skipNextObservers = skipNextObservers;
+ this.target = target;
+ this.currentTarget = currentTarget;
+ return this;
+ }
+}
+/**
+ * Represent an Observer registered to a given Observable object.
+ */
+class Observer {
+ /**
+ * Creates a new observer
+ * @param callback defines the callback to call when the observer is notified
+ * @param mask defines the mask of the observer (used to filter notifications)
+ * @param scope defines the current scope used to restore the JS context
+ */
+ constructor(
+ /**
+ * Defines the callback to call when the observer is notified
+ */
+ callback,
+ /**
+ * Defines the mask of the observer (used to filter notifications)
+ */
+ mask,
+ /**
+ * [null] Defines the current scope used to restore the JS context
+ */
+ scope = null) {
+ this.callback = callback;
+ this.mask = mask;
+ this.scope = scope;
+ /** @internal */
+ this._willBeUnregistered = false;
+ /**
+ * Gets or sets a property defining that the observer as to be unregistered after the next notification
+ */
+ this.unregisterOnNextCall = false;
+ /**
+ * this function can be used to remove the observer from the observable.
+ * It will be set by the observable that the observer belongs to.
+ * @internal
+ */
+ this._remove = null;
+ }
+ /**
+ * Remove the observer from its observable
+ * This can be used instead of using the observable's remove function.
+ */
+ remove() {
+ if (this._remove) {
+ this._remove();
+ }
+ }
+}
+/**
+ * The Observable class is a simple implementation of the Observable pattern.
+ *
+ * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
+ * This enable a more fine grained execution without having to rely on multiple different Observable objects.
+ * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
+ * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
+ */
+class Observable {
+ /**
+ * Create an observable from a Promise.
+ * @param promise a promise to observe for fulfillment.
+ * @param onErrorObservable an observable to notify if a promise was rejected.
+ * @returns the new Observable
+ */
+ static FromPromise(promise, onErrorObservable) {
+ const observable = new Observable();
+ promise
+ .then((ret) => {
+ observable.notifyObservers(ret);
+ })
+ .catch((err) => {
+ if (onErrorObservable) {
+ onErrorObservable.notifyObservers(err);
+ }
+ else {
+ throw err;
+ }
+ });
+ return observable;
+ }
+ /**
+ * Gets the list of observers
+ * Note that observers that were recently deleted may still be present in the list because they are only really deleted on the next javascript tick!
+ */
+ get observers() {
+ return this._observers;
+ }
+ /**
+ * Creates a new observable
+ * @param onObserverAdded defines a callback to call when a new observer is added
+ * @param notifyIfTriggered If set to true the observable will notify when an observer was added if the observable was already triggered.
+ */
+ constructor(onObserverAdded,
+ /**
+ * [false] If set to true the observable will notify when an observer was added if the observable was already triggered.
+ * This is helpful to single-state observables like the scene onReady or the dispose observable.
+ */
+ notifyIfTriggered = false) {
+ this.notifyIfTriggered = notifyIfTriggered;
+ this._observers = new Array();
+ this._numObserversMarkedAsDeleted = 0;
+ this._hasNotified = false;
+ this._eventState = new EventState(0);
+ if (onObserverAdded) {
+ this._onObserverAdded = onObserverAdded;
+ }
+ }
+ add(callback, mask = -1, insertFirst = false, scope = null, unregisterOnFirstCall = false) {
+ if (!callback) {
+ return null;
+ }
+ const observer = new Observer(callback, mask, scope);
+ observer.unregisterOnNextCall = unregisterOnFirstCall;
+ if (insertFirst) {
+ this._observers.unshift(observer);
+ }
+ else {
+ this._observers.push(observer);
+ }
+ if (this._onObserverAdded) {
+ this._onObserverAdded(observer);
+ }
+ // If the observable was already triggered and the observable is set to notify if triggered, notify the new observer
+ if (this._hasNotified && this.notifyIfTriggered) {
+ if (this._lastNotifiedValue !== undefined) {
+ this.notifyObserver(observer, this._lastNotifiedValue);
+ }
+ }
+ // attach the remove function to the observer
+ const observableWeakRef = isWeakRefSupported ? new WeakRef(this) : { deref: () => this };
+ observer._remove = () => {
+ const observable = observableWeakRef.deref();
+ if (observable) {
+ observable._remove(observer);
+ }
+ };
+ return observer;
+ }
+ addOnce(callback) {
+ return this.add(callback, undefined, undefined, undefined, true);
+ }
+ /**
+ * Remove an Observer from the Observable object
+ * @param observer the instance of the Observer to remove
+ * @returns false if it doesn't belong to this Observable
+ */
+ remove(observer) {
+ if (!observer) {
+ return false;
+ }
+ observer._remove = null;
+ const index = this._observers.indexOf(observer);
+ if (index !== -1) {
+ this._deferUnregister(observer);
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Remove a callback from the Observable object
+ * @param callback the callback to remove
+ * @param scope optional scope. If used only the callbacks with this scope will be removed
+ * @returns false if it doesn't belong to this Observable
+ */
+ removeCallback(callback, scope) {
+ for (let index = 0; index < this._observers.length; index++) {
+ const observer = this._observers[index];
+ if (observer._willBeUnregistered) {
+ continue;
+ }
+ if (observer.callback === callback && (!scope || scope === observer.scope)) {
+ this._deferUnregister(observer);
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * @internal
+ */
+ _deferUnregister(observer) {
+ if (observer._willBeUnregistered) {
+ return;
+ }
+ this._numObserversMarkedAsDeleted++;
+ observer.unregisterOnNextCall = false;
+ observer._willBeUnregistered = true;
+ setTimeout(() => {
+ this._remove(observer);
+ }, 0);
+ }
+ // This should only be called when not iterating over _observers to avoid callback skipping.
+ // Removes an observer from the _observer Array.
+ _remove(observer, updateCounter = true) {
+ if (!observer) {
+ return false;
+ }
+ const index = this._observers.indexOf(observer);
+ if (index !== -1) {
+ if (updateCounter) {
+ this._numObserversMarkedAsDeleted--;
+ }
+ this._observers.splice(index, 1);
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Moves the observable to the top of the observer list making it get called first when notified
+ * @param observer the observer to move
+ */
+ makeObserverTopPriority(observer) {
+ this._remove(observer, false);
+ this._observers.unshift(observer);
+ }
+ /**
+ * Moves the observable to the bottom of the observer list making it get called last when notified
+ * @param observer the observer to move
+ */
+ makeObserverBottomPriority(observer) {
+ this._remove(observer, false);
+ this._observers.push(observer);
+ }
+ /**
+ * Notify all Observers by calling their respective callback with the given data
+ * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
+ * @param eventData defines the data to send to all observers
+ * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
+ * @param target defines the original target of the state
+ * @param currentTarget defines the current target of the state
+ * @param userInfo defines any user info to send to observers
+ * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
+ */
+ notifyObservers(eventData, mask = -1, target, currentTarget, userInfo) {
+ // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared.
+ if (this.notifyIfTriggered) {
+ this._hasNotified = true;
+ this._lastNotifiedValue = eventData;
+ }
+ if (!this._observers.length) {
+ return true;
+ }
+ const state = this._eventState;
+ state.mask = mask;
+ state.target = target;
+ state.currentTarget = currentTarget;
+ state.skipNextObservers = false;
+ state.lastReturnValue = eventData;
+ state.userInfo = userInfo;
+ for (const obs of this._observers) {
+ if (obs._willBeUnregistered) {
+ continue;
+ }
+ if (obs.mask & mask) {
+ if (obs.unregisterOnNextCall) {
+ this._deferUnregister(obs);
+ }
+ if (obs.scope) {
+ state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
+ }
+ else {
+ state.lastReturnValue = obs.callback(eventData, state);
+ }
+ }
+ if (state.skipNextObservers) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Notify a specific observer
+ * @param observer defines the observer to notify
+ * @param eventData defines the data to be sent to each callback
+ * @param mask is used to filter observers defaults to -1
+ */
+ notifyObserver(observer, eventData, mask = -1) {
+ // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared.
+ if (this.notifyIfTriggered) {
+ this._hasNotified = true;
+ this._lastNotifiedValue = eventData;
+ }
+ if (observer._willBeUnregistered) {
+ return;
+ }
+ const state = this._eventState;
+ state.mask = mask;
+ state.skipNextObservers = false;
+ if (observer.unregisterOnNextCall) {
+ this._deferUnregister(observer);
+ }
+ observer.callback(eventData, state);
+ }
+ /**
+ * Gets a boolean indicating if the observable has at least one observer
+ * @returns true is the Observable has at least one Observer registered
+ */
+ hasObservers() {
+ return this._observers.length - this._numObserversMarkedAsDeleted > 0;
+ }
+ /**
+ * Clear the list of observers
+ */
+ clear() {
+ while (this._observers.length) {
+ const o = this._observers.pop();
+ if (o) {
+ o._remove = null;
+ }
+ }
+ this._onObserverAdded = null;
+ this._numObserversMarkedAsDeleted = 0;
+ this.cleanLastNotifiedState();
+ }
+ /**
+ * Clean the last notified state - both the internal last value and the has-notified flag
+ */
+ cleanLastNotifiedState() {
+ this._hasNotified = false;
+ this._lastNotifiedValue = undefined;
+ }
+ /**
+ * Clone the current observable
+ * @returns a new observable
+ */
+ clone() {
+ const result = new Observable();
+ result._observers = this._observers.slice(0);
+ return result;
+ }
+ /**
+ * Does this observable handles observer registered with a given mask
+ * @param mask defines the mask to be tested
+ * @returns whether or not one observer registered with the given mask is handled
+ **/
+ hasSpecificMask(mask = -1) {
+ for (const obs of this._observers) {
+ if (obs.mask & mask || obs.mask === mask) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
+
+/**
+ * Class used to store a texture sampler data
+ */
+class TextureSampler {
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ get wrapU() {
+ return this._cachedWrapU;
+ }
+ set wrapU(value) {
+ this._cachedWrapU = value;
+ }
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ get wrapV() {
+ return this._cachedWrapV;
+ }
+ set wrapV(value) {
+ this._cachedWrapV = value;
+ }
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ get wrapR() {
+ return this._cachedWrapR;
+ }
+ set wrapR(value) {
+ this._cachedWrapR = value;
+ }
+ /**
+ * With compliant hardware and browser (supporting anisotropic filtering)
+ * this defines the level of anisotropic filtering in the texture.
+ * The higher the better but the slower.
+ */
+ get anisotropicFilteringLevel() {
+ return this._cachedAnisotropicFilteringLevel;
+ }
+ set anisotropicFilteringLevel(value) {
+ this._cachedAnisotropicFilteringLevel = value;
+ }
+ /**
+ * Gets or sets the comparison function (513, 514, etc). Set 0 to not use a comparison function
+ */
+ get comparisonFunction() {
+ return this._comparisonFunction;
+ }
+ set comparisonFunction(value) {
+ this._comparisonFunction = value;
+ }
+ /**
+ * Indicates to use the mip maps (if available on the texture).
+ * Thanks to this flag, you can instruct the sampler to not sample the mipmaps even if they exist (and if the sampling mode is set to a value that normally samples the mipmaps!)
+ */
+ get useMipMaps() {
+ return this._useMipMaps;
+ }
+ set useMipMaps(value) {
+ this._useMipMaps = value;
+ }
+ /**
+ * Creates a Sampler instance
+ */
+ constructor() {
+ /**
+ * Gets the sampling mode of the texture
+ */
+ this.samplingMode = -1;
+ this._useMipMaps = true;
+ /** @internal */
+ this._cachedWrapU = null;
+ /** @internal */
+ this._cachedWrapV = null;
+ /** @internal */
+ this._cachedWrapR = null;
+ /** @internal */
+ this._cachedAnisotropicFilteringLevel = null;
+ /** @internal */
+ this._comparisonFunction = 0;
+ }
+ /**
+ * Sets all the parameters of the sampler
+ * @param wrapU u address mode (default: TEXTURE_WRAP_ADDRESSMODE)
+ * @param wrapV v address mode (default: TEXTURE_WRAP_ADDRESSMODE)
+ * @param wrapR r address mode (default: TEXTURE_WRAP_ADDRESSMODE)
+ * @param anisotropicFilteringLevel anisotropic level (default: 1)
+ * @param samplingMode sampling mode (default: 2)
+ * @param comparisonFunction comparison function (default: 0 - no comparison function)
+ * @returns the current sampler instance
+ */
+ setParameters(wrapU = 1, wrapV = 1, wrapR = 1, anisotropicFilteringLevel = 1, samplingMode = 2, comparisonFunction = 0) {
+ this._cachedWrapU = wrapU;
+ this._cachedWrapV = wrapV;
+ this._cachedWrapR = wrapR;
+ this._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel;
+ this.samplingMode = samplingMode;
+ this._comparisonFunction = comparisonFunction;
+ return this;
+ }
+ /**
+ * Compares this sampler with another one
+ * @param other sampler to compare with
+ * @returns true if the samplers have the same parametres, else false
+ */
+ compareSampler(other) {
+ return (this._cachedWrapU === other._cachedWrapU &&
+ this._cachedWrapV === other._cachedWrapV &&
+ this._cachedWrapR === other._cachedWrapR &&
+ this._cachedAnisotropicFilteringLevel === other._cachedAnisotropicFilteringLevel &&
+ this.samplingMode === other.samplingMode &&
+ this._comparisonFunction === other._comparisonFunction &&
+ this._useMipMaps === other._useMipMaps);
+ }
+}
+
+/**
+ * Defines the source of the internal texture
+ */
+var InternalTextureSource;
+(function (InternalTextureSource) {
+ /**
+ * The source of the texture data is unknown
+ */
+ InternalTextureSource[InternalTextureSource["Unknown"] = 0] = "Unknown";
+ /**
+ * Texture data comes from an URL
+ */
+ InternalTextureSource[InternalTextureSource["Url"] = 1] = "Url";
+ /**
+ * Texture data is only used for temporary storage
+ */
+ InternalTextureSource[InternalTextureSource["Temp"] = 2] = "Temp";
+ /**
+ * Texture data comes from raw data (ArrayBuffer)
+ */
+ InternalTextureSource[InternalTextureSource["Raw"] = 3] = "Raw";
+ /**
+ * Texture content is dynamic (video or dynamic texture)
+ */
+ InternalTextureSource[InternalTextureSource["Dynamic"] = 4] = "Dynamic";
+ /**
+ * Texture content is generated by rendering to it
+ */
+ InternalTextureSource[InternalTextureSource["RenderTarget"] = 5] = "RenderTarget";
+ /**
+ * Texture content is part of a multi render target process
+ */
+ InternalTextureSource[InternalTextureSource["MultiRenderTarget"] = 6] = "MultiRenderTarget";
+ /**
+ * Texture data comes from a cube data file
+ */
+ InternalTextureSource[InternalTextureSource["Cube"] = 7] = "Cube";
+ /**
+ * Texture data comes from a raw cube data
+ */
+ InternalTextureSource[InternalTextureSource["CubeRaw"] = 8] = "CubeRaw";
+ /**
+ * Texture data come from a prefiltered cube data file
+ */
+ InternalTextureSource[InternalTextureSource["CubePrefiltered"] = 9] = "CubePrefiltered";
+ /**
+ * Texture content is raw 3D data
+ */
+ InternalTextureSource[InternalTextureSource["Raw3D"] = 10] = "Raw3D";
+ /**
+ * Texture content is raw 2D array data
+ */
+ InternalTextureSource[InternalTextureSource["Raw2DArray"] = 11] = "Raw2DArray";
+ /**
+ * Texture content is a depth/stencil texture
+ */
+ InternalTextureSource[InternalTextureSource["DepthStencil"] = 12] = "DepthStencil";
+ /**
+ * Texture data comes from a raw cube data encoded with RGBD
+ */
+ InternalTextureSource[InternalTextureSource["CubeRawRGBD"] = 13] = "CubeRawRGBD";
+ /**
+ * Texture content is a depth texture
+ */
+ InternalTextureSource[InternalTextureSource["Depth"] = 14] = "Depth";
+})(InternalTextureSource || (InternalTextureSource = {}));
+/**
+ * Class used to store data associated with WebGL texture data for the engine
+ * This class should not be used directly
+ */
+class InternalTexture extends TextureSampler {
+ /**
+ * Gets a boolean indicating if the texture uses mipmaps
+ * TODO implements useMipMaps as a separate setting from generateMipMaps
+ */
+ get useMipMaps() {
+ return this.generateMipMaps;
+ }
+ set useMipMaps(value) {
+ this.generateMipMaps = value;
+ }
+ /** Gets the unique id of the internal texture */
+ get uniqueId() {
+ return this._uniqueId;
+ }
+ /** @internal */
+ _setUniqueId(id) {
+ this._uniqueId = id;
+ }
+ /**
+ * Gets the Engine the texture belongs to.
+ * @returns The babylon engine
+ */
+ getEngine() {
+ return this._engine;
+ }
+ /**
+ * Gets the data source type of the texture
+ */
+ get source() {
+ return this._source;
+ }
+ /**
+ * Creates a new InternalTexture
+ * @param engine defines the engine to use
+ * @param source defines the type of data that will be used
+ * @param delayAllocation if the texture allocation should be delayed (default: false)
+ */
+ constructor(engine, source, delayAllocation = false) {
+ super();
+ /**
+ * Defines if the texture is ready
+ */
+ this.isReady = false;
+ /**
+ * Defines if the texture is a cube texture
+ */
+ this.isCube = false;
+ /**
+ * Defines if the texture contains 3D data
+ */
+ this.is3D = false;
+ /**
+ * Defines if the texture contains 2D array data
+ */
+ this.is2DArray = false;
+ /**
+ * Defines if the texture contains multiview data
+ */
+ this.isMultiview = false;
+ /**
+ * Gets the URL used to load this texture
+ */
+ this.url = "";
+ /**
+ * Gets a boolean indicating if the texture needs mipmaps generation
+ */
+ this.generateMipMaps = false;
+ /**
+ * Gets the number of samples used by the texture (WebGL2+ only)
+ */
+ this.samples = 0;
+ /**
+ * Gets the type of the texture (int, float...)
+ */
+ this.type = -1;
+ /**
+ * Gets the format of the texture (RGB, RGBA...)
+ */
+ this.format = -1;
+ /**
+ * Observable called when the texture is loaded
+ */
+ this.onLoadedObservable = new Observable();
+ /**
+ * Observable called when the texture load is raising an error
+ */
+ this.onErrorObservable = new Observable();
+ /**
+ * If this callback is defined it will be called instead of the default _rebuild function
+ */
+ this.onRebuildCallback = null;
+ /**
+ * Gets the width of the texture
+ */
+ this.width = 0;
+ /**
+ * Gets the height of the texture
+ */
+ this.height = 0;
+ /**
+ * Gets the depth of the texture
+ */
+ this.depth = 0;
+ /**
+ * Gets the initial width of the texture (It could be rescaled if the current system does not support non power of two textures)
+ */
+ this.baseWidth = 0;
+ /**
+ * Gets the initial height of the texture (It could be rescaled if the current system does not support non power of two textures)
+ */
+ this.baseHeight = 0;
+ /**
+ * Gets the initial depth of the texture (It could be rescaled if the current system does not support non power of two textures)
+ */
+ this.baseDepth = 0;
+ /**
+ * Gets a boolean indicating if the texture is inverted on Y axis
+ */
+ this.invertY = false;
+ // Private
+ /** @internal */
+ this._invertVScale = false;
+ /** @internal */
+ this._associatedChannel = -1;
+ /** @internal */
+ this._source = 0 /* InternalTextureSource.Unknown */;
+ /** @internal */
+ this._buffer = null;
+ /** @internal */
+ this._bufferView = null;
+ /** @internal */
+ this._bufferViewArray = null;
+ /** @internal */
+ this._bufferViewArrayArray = null;
+ /** @internal */
+ this._size = 0;
+ /** @internal */
+ this._extension = "";
+ /** @internal */
+ this._files = null;
+ /** @internal */
+ this._workingCanvas = null;
+ /** @internal */
+ this._workingContext = null;
+ /** @internal */
+ this._cachedCoordinatesMode = null;
+ /** @internal */
+ this._isDisabled = false;
+ /** @internal */
+ this._compression = null;
+ /** @internal */
+ this._sphericalPolynomial = null;
+ /** @internal */
+ this._sphericalPolynomialPromise = null;
+ /** @internal */
+ this._sphericalPolynomialComputed = false;
+ /** @internal */
+ this._lodGenerationScale = 0;
+ /** @internal */
+ this._lodGenerationOffset = 0;
+ /** @internal */
+ this._useSRGBBuffer = false;
+ /** @internal */
+ this._creationFlags = 0;
+ // The following three fields helps sharing generated fixed LODs for texture filtering
+ // In environment not supporting the textureLOD extension like EDGE. They are for internal use only.
+ // They are at the level of the gl texture to benefit from the cache.
+ /** @internal */
+ this._lodTextureHigh = null;
+ /** @internal */
+ this._lodTextureMid = null;
+ /** @internal */
+ this._lodTextureLow = null;
+ /** @internal */
+ this._isRGBD = false;
+ /** @internal */
+ this._linearSpecularLOD = false;
+ /** @internal */
+ this._irradianceTexture = null;
+ /** @internal */
+ this._hardwareTexture = null;
+ /** @internal */
+ this._maxLodLevel = null;
+ /** @internal */
+ this._references = 1;
+ /** @internal */
+ this._gammaSpace = null;
+ /** @internal */
+ this._premulAlpha = false;
+ /** @internal */
+ this._dynamicTextureSource = null;
+ /** @internal */
+ this._autoMSAAManagement = false;
+ this._engine = engine;
+ this._source = source;
+ this._uniqueId = InternalTexture._Counter++;
+ if (!delayAllocation) {
+ this._hardwareTexture = engine._createHardwareTexture();
+ }
+ }
+ /**
+ * Increments the number of references (ie. the number of Texture that point to it)
+ */
+ incrementReferences() {
+ this._references++;
+ }
+ /**
+ * Change the size of the texture (not the size of the content)
+ * @param width defines the new width
+ * @param height defines the new height
+ * @param depth defines the new depth (1 by default)
+ */
+ updateSize(width, height, depth = 1) {
+ this._engine.updateTextureDimensions(this, width, height, depth);
+ this.width = width;
+ this.height = height;
+ this.depth = depth;
+ this.baseWidth = width;
+ this.baseHeight = height;
+ this.baseDepth = depth;
+ this._size = width * height * depth;
+ }
+ /** @internal */
+ _rebuild() {
+ this.isReady = false;
+ this._cachedCoordinatesMode = null;
+ this._cachedWrapU = null;
+ this._cachedWrapV = null;
+ this._cachedWrapR = null;
+ this._cachedAnisotropicFilteringLevel = null;
+ if (this.onRebuildCallback) {
+ const data = this.onRebuildCallback(this);
+ const swapAndSetIsReady = (proxyInternalTexture) => {
+ proxyInternalTexture._swapAndDie(this, false);
+ this.isReady = data.isReady;
+ };
+ if (data.isAsync) {
+ data.proxy.then(swapAndSetIsReady);
+ }
+ else {
+ swapAndSetIsReady(data.proxy);
+ }
+ return;
+ }
+ let proxy;
+ switch (this.source) {
+ case 2 /* InternalTextureSource.Temp */:
+ break;
+ case 1 /* InternalTextureSource.Url */:
+ proxy = this._engine.createTexture(this._originalUrl ?? this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode,
+ // Do not use Proxy here as it could be fully synchronous
+ // and proxy would be undefined.
+ (temp) => {
+ temp._swapAndDie(this, false);
+ this.isReady = true;
+ }, null, this._buffer, undefined, this.format, this._extension, undefined, undefined, undefined, this._useSRGBBuffer);
+ return;
+ case 3 /* InternalTextureSource.Raw */:
+ proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type, this._creationFlags, this._useSRGBBuffer);
+ proxy._swapAndDie(this, false);
+ this.isReady = true;
+ break;
+ case 10 /* InternalTextureSource.Raw3D */:
+ proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type);
+ proxy._swapAndDie(this, false);
+ this.isReady = true;
+ break;
+ case 11 /* InternalTextureSource.Raw2DArray */:
+ proxy = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type);
+ proxy._swapAndDie(this, false);
+ this.isReady = true;
+ break;
+ case 4 /* InternalTextureSource.Dynamic */:
+ proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
+ proxy._swapAndDie(this, false);
+ if (this._dynamicTextureSource) {
+ this._engine.updateDynamicTexture(this, this._dynamicTextureSource, this.invertY, this._premulAlpha, this.format, true);
+ }
+ // The engine will make sure to update content so no need to flag it as isReady = true
+ break;
+ case 7 /* InternalTextureSource.Cube */:
+ proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, () => {
+ proxy._swapAndDie(this, false);
+ this.isReady = true;
+ }, null, this.format, this._extension, false, 0, 0, null, undefined, this._useSRGBBuffer, ArrayBuffer.isView(this._buffer) ? this._buffer : null);
+ return;
+ case 8 /* InternalTextureSource.CubeRaw */:
+ proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this._originalFormat ?? this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
+ proxy._swapAndDie(this, false);
+ this.isReady = true;
+ break;
+ case 13 /* InternalTextureSource.CubeRawRGBD */:
+ // This case is being handeled by the environment texture tools and is not a part of the rebuild process.
+ // To use CubeRawRGBD use updateRGBDAsync on the cube texture.
+ return;
+ case 9 /* InternalTextureSource.CubePrefiltered */:
+ proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy) => {
+ if (proxy) {
+ proxy._swapAndDie(this, false);
+ }
+ this.isReady = true;
+ }, null, this.format, this._extension);
+ proxy._sphericalPolynomial = this._sphericalPolynomial;
+ return;
+ }
+ }
+ /**
+ * @internal
+ */
+ _swapAndDie(target, swapAll = true) {
+ // TODO what about refcount on target?
+ this._hardwareTexture?.setUsage(target._source, this.generateMipMaps, this.is2DArray, this.isCube, this.is3D, this.width, this.height, this.depth);
+ target._hardwareTexture = this._hardwareTexture;
+ if (swapAll) {
+ target._isRGBD = this._isRGBD;
+ }
+ if (this._lodTextureHigh) {
+ if (target._lodTextureHigh) {
+ target._lodTextureHigh.dispose();
+ }
+ target._lodTextureHigh = this._lodTextureHigh;
+ }
+ if (this._lodTextureMid) {
+ if (target._lodTextureMid) {
+ target._lodTextureMid.dispose();
+ }
+ target._lodTextureMid = this._lodTextureMid;
+ }
+ if (this._lodTextureLow) {
+ if (target._lodTextureLow) {
+ target._lodTextureLow.dispose();
+ }
+ target._lodTextureLow = this._lodTextureLow;
+ }
+ if (this._irradianceTexture) {
+ if (target._irradianceTexture) {
+ target._irradianceTexture.dispose();
+ }
+ target._irradianceTexture = this._irradianceTexture;
+ }
+ const cache = this._engine.getLoadedTexturesCache();
+ let index = cache.indexOf(this);
+ if (index !== -1) {
+ cache.splice(index, 1);
+ }
+ index = cache.indexOf(target);
+ if (index === -1) {
+ cache.push(target);
+ }
+ }
+ /**
+ * Dispose the current allocated resources
+ */
+ dispose() {
+ this._references--;
+ if (this._references === 0) {
+ this.onLoadedObservable.clear();
+ this.onErrorObservable.clear();
+ this._engine._releaseTexture(this);
+ this._hardwareTexture = null;
+ this._dynamicTextureSource = null;
+ }
+ }
+}
+/** @internal */
+InternalTexture._Counter = 0;
+
+/**
+ * The engine store class is responsible to hold all the instances of Engine and Scene created
+ * during the life time of the application.
+ */
+class EngineStore {
+ /**
+ * Gets the latest created engine
+ */
+ static get LastCreatedEngine() {
+ if (this.Instances.length === 0) {
+ return null;
+ }
+ return this.Instances[this.Instances.length - 1];
+ }
+ /**
+ * Gets the latest created scene
+ */
+ static get LastCreatedScene() {
+ return this._LastCreatedScene;
+ }
+}
+/** Gets the list of created engines */
+EngineStore.Instances = [];
+/**
+ * Notifies when an engine was disposed.
+ * Mainly used for static/cache cleanup
+ */
+EngineStore.OnEnginesDisposedObservable = new Observable();
+/** @internal */
+EngineStore._LastCreatedScene = null;
+/**
+ * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
+ * @ignorenaming
+ */
+EngineStore.UseFallbackTexture = true;
+/**
+ * Texture content used if a texture cannot loaded
+ * @ignorenaming
+ */
+EngineStore.FallbackTexture = "";
+
+/** @internal */
+class WebGLPipelineContext {
+ constructor() {
+ this._valueCache = {};
+ this.vertexCompilationError = null;
+ this.fragmentCompilationError = null;
+ this.programLinkError = null;
+ this.programValidationError = null;
+ /** @internal */
+ this._isDisposed = false;
+ }
+ get isAsync() {
+ return this.isParallelCompiled;
+ }
+ get isReady() {
+ if (this.program) {
+ if (this.isParallelCompiled) {
+ return this.engine._isRenderingStateCompiled(this);
+ }
+ return true;
+ }
+ return false;
+ }
+ _handlesSpectorRebuildCallback(onCompiled) {
+ if (onCompiled && this.program) {
+ onCompiled(this.program);
+ }
+ }
+ setEngine(engine) {
+ this.engine = engine;
+ }
+ _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {
+ const engine = this.engine;
+ if (engine.supportsUniformBuffers) {
+ for (const name in uniformBuffersNames) {
+ effect.bindUniformBlock(name, uniformBuffersNames[name]);
+ }
+ }
+ const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames);
+ effectAvailableUniforms.forEach((uniform, index) => {
+ uniforms[uniformsNames[index]] = uniform;
+ });
+ this._uniforms = uniforms;
+ let index;
+ for (index = 0; index < samplerList.length; index++) {
+ const sampler = effect.getUniform(samplerList[index]);
+ if (sampler == null) {
+ samplerList.splice(index, 1);
+ index--;
+ }
+ }
+ samplerList.forEach((name, index) => {
+ samplers[name] = index;
+ });
+ for (const attr of engine.getAttributes(this, attributesNames)) {
+ attributes.push(attr);
+ }
+ }
+ /**
+ * Release all associated resources.
+ **/
+ dispose() {
+ this._uniforms = {};
+ this._isDisposed = true;
+ }
+ /**
+ * @internal
+ */
+ _cacheMatrix(uniformName, matrix) {
+ const cache = this._valueCache[uniformName];
+ const flag = matrix.updateFlag;
+ if (cache !== undefined && cache === flag) {
+ return false;
+ }
+ this._valueCache[uniformName] = flag;
+ return true;
+ }
+ /**
+ * @internal
+ */
+ _cacheFloat2(uniformName, x, y) {
+ let cache = this._valueCache[uniformName];
+ if (!cache || cache.length !== 2) {
+ cache = [x, y];
+ this._valueCache[uniformName] = cache;
+ return true;
+ }
+ let changed = false;
+ if (cache[0] !== x) {
+ cache[0] = x;
+ changed = true;
+ }
+ if (cache[1] !== y) {
+ cache[1] = y;
+ changed = true;
+ }
+ return changed;
+ }
+ /**
+ * @internal
+ */
+ _cacheFloat3(uniformName, x, y, z) {
+ let cache = this._valueCache[uniformName];
+ if (!cache || cache.length !== 3) {
+ cache = [x, y, z];
+ this._valueCache[uniformName] = cache;
+ return true;
+ }
+ let changed = false;
+ if (cache[0] !== x) {
+ cache[0] = x;
+ changed = true;
+ }
+ if (cache[1] !== y) {
+ cache[1] = y;
+ changed = true;
+ }
+ if (cache[2] !== z) {
+ cache[2] = z;
+ changed = true;
+ }
+ return changed;
+ }
+ /**
+ * @internal
+ */
+ _cacheFloat4(uniformName, x, y, z, w) {
+ let cache = this._valueCache[uniformName];
+ if (!cache || cache.length !== 4) {
+ cache = [x, y, z, w];
+ this._valueCache[uniformName] = cache;
+ return true;
+ }
+ let changed = false;
+ if (cache[0] !== x) {
+ cache[0] = x;
+ changed = true;
+ }
+ if (cache[1] !== y) {
+ cache[1] = y;
+ changed = true;
+ }
+ if (cache[2] !== z) {
+ cache[2] = z;
+ changed = true;
+ }
+ if (cache[3] !== w) {
+ cache[3] = w;
+ changed = true;
+ }
+ return changed;
+ }
+ /**
+ * Sets an integer value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param value Value to be set.
+ */
+ setInt(uniformName, value) {
+ const cache = this._valueCache[uniformName];
+ if (cache !== undefined && cache === value) {
+ return;
+ }
+ if (this.engine.setInt(this._uniforms[uniformName], value)) {
+ this._valueCache[uniformName] = value;
+ }
+ }
+ /**
+ * Sets a int2 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First int in int2.
+ * @param y Second int in int2.
+ */
+ setInt2(uniformName, x, y) {
+ if (this._cacheFloat2(uniformName, x, y)) {
+ if (!this.engine.setInt2(this._uniforms[uniformName], x, y)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a int3 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First int in int3.
+ * @param y Second int in int3.
+ * @param z Third int in int3.
+ */
+ setInt3(uniformName, x, y, z) {
+ if (this._cacheFloat3(uniformName, x, y, z)) {
+ if (!this.engine.setInt3(this._uniforms[uniformName], x, y, z)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a int4 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First int in int4.
+ * @param y Second int in int4.
+ * @param z Third int in int4.
+ * @param w Fourth int in int4.
+ */
+ setInt4(uniformName, x, y, z, w) {
+ if (this._cacheFloat4(uniformName, x, y, z, w)) {
+ if (!this.engine.setInt4(this._uniforms[uniformName], x, y, z, w)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets an int array on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setIntArray(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setIntArray(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setIntArray2(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setIntArray2(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setIntArray3(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setIntArray3(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setIntArray4(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setIntArray4(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an unsigned integer value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param value Value to be set.
+ */
+ setUInt(uniformName, value) {
+ const cache = this._valueCache[uniformName];
+ if (cache !== undefined && cache === value) {
+ return;
+ }
+ if (this.engine.setUInt(this._uniforms[uniformName], value)) {
+ this._valueCache[uniformName] = value;
+ }
+ }
+ /**
+ * Sets an unsigned int2 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First unsigned int in uint2.
+ * @param y Second unsigned int in uint2.
+ */
+ setUInt2(uniformName, x, y) {
+ if (this._cacheFloat2(uniformName, x, y)) {
+ if (!this.engine.setUInt2(this._uniforms[uniformName], x, y)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets an unsigned int3 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First unsigned int in uint3.
+ * @param y Second unsigned int in uint3.
+ * @param z Third unsigned int in uint3.
+ */
+ setUInt3(uniformName, x, y, z) {
+ if (this._cacheFloat3(uniformName, x, y, z)) {
+ if (!this.engine.setUInt3(this._uniforms[uniformName], x, y, z)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets an unsigned int4 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First unsigned int in uint4.
+ * @param y Second unsigned int in uint4.
+ * @param z Third unsigned int in uint4.
+ * @param w Fourth unsigned int in uint4.
+ */
+ setUInt4(uniformName, x, y, z, w) {
+ if (this._cacheFloat4(uniformName, x, y, z, w)) {
+ if (!this.engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets an unsigned int array on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setUIntArray(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setUIntArray(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setUIntArray2(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setUIntArray2(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setUIntArray3(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setUIntArray3(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setUIntArray4(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setUIntArray4(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an array on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setArray(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setArray(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setArray2(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setArray2(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setArray3(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setArray3(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ */
+ setArray4(uniformName, array) {
+ this._valueCache[uniformName] = null;
+ this.engine.setArray4(this._uniforms[uniformName], array);
+ }
+ /**
+ * Sets matrices on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param matrices matrices to be set.
+ */
+ setMatrices(uniformName, matrices) {
+ if (!matrices) {
+ return;
+ }
+ this._valueCache[uniformName] = null;
+ this.engine.setMatrices(this._uniforms[uniformName], matrices);
+ }
+ /**
+ * Sets matrix on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param matrix matrix to be set.
+ */
+ setMatrix(uniformName, matrix) {
+ if (this._cacheMatrix(uniformName, matrix)) {
+ if (!this.engine.setMatrices(this._uniforms[uniformName], matrix.asArray())) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
+ * @param uniformName Name of the variable.
+ * @param matrix matrix to be set.
+ */
+ setMatrix3x3(uniformName, matrix) {
+ this._valueCache[uniformName] = null;
+ this.engine.setMatrix3x3(this._uniforms[uniformName], matrix);
+ }
+ /**
+ * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)
+ * @param uniformName Name of the variable.
+ * @param matrix matrix to be set.
+ */
+ setMatrix2x2(uniformName, matrix) {
+ this._valueCache[uniformName] = null;
+ this.engine.setMatrix2x2(this._uniforms[uniformName], matrix);
+ }
+ /**
+ * Sets a float on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param value value to be set.
+ */
+ setFloat(uniformName, value) {
+ const cache = this._valueCache[uniformName];
+ if (cache !== undefined && cache === value) {
+ return;
+ }
+ if (this.engine.setFloat(this._uniforms[uniformName], value)) {
+ this._valueCache[uniformName] = value;
+ }
+ }
+ /**
+ * Sets a Vector2 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param vector2 vector2 to be set.
+ */
+ setVector2(uniformName, vector2) {
+ if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
+ if (!this.engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a float2 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First float in float2.
+ * @param y Second float in float2.
+ */
+ setFloat2(uniformName, x, y) {
+ if (this._cacheFloat2(uniformName, x, y)) {
+ if (!this.engine.setFloat2(this._uniforms[uniformName], x, y)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a Vector3 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param vector3 Value to be set.
+ */
+ setVector3(uniformName, vector3) {
+ if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
+ if (!this.engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a float3 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First float in float3.
+ * @param y Second float in float3.
+ * @param z Third float in float3.
+ */
+ setFloat3(uniformName, x, y, z) {
+ if (this._cacheFloat3(uniformName, x, y, z)) {
+ if (!this.engine.setFloat3(this._uniforms[uniformName], x, y, z)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a Vector4 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param vector4 Value to be set.
+ */
+ setVector4(uniformName, vector4) {
+ if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
+ if (!this.engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a Quaternion on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param quaternion Value to be set.
+ */
+ setQuaternion(uniformName, quaternion) {
+ if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {
+ if (!this.engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a float4 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First float in float4.
+ * @param y Second float in float4.
+ * @param z Third float in float4.
+ * @param w Fourth float in float4.
+ */
+ setFloat4(uniformName, x, y, z, w) {
+ if (this._cacheFloat4(uniformName, x, y, z, w)) {
+ if (!this.engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a Color3 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param color3 Value to be set.
+ */
+ setColor3(uniformName, color3) {
+ if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
+ if (!this.engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a Color4 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param color3 Value to be set.
+ * @param alpha Alpha value to be set.
+ */
+ setColor4(uniformName, color3, alpha) {
+ if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
+ if (!this.engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ /**
+ * Sets a Color4 on a uniform variable
+ * @param uniformName defines the name of the variable
+ * @param color4 defines the value to be set
+ */
+ setDirectColor4(uniformName, color4) {
+ if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
+ if (!this.engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) {
+ this._valueCache[uniformName] = null;
+ }
+ }
+ }
+ _getVertexShaderCode() {
+ return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null;
+ }
+ _getFragmentShaderCode() {
+ return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null;
+ }
+}
+
+const warnedMap = {};
+/**
+ * @internal
+ */
+function _WarnImport(name, warnOnce = false) {
+ if (warnOnce && warnedMap[name]) {
+ return;
+ }
+ warnedMap[name] = true;
+ return `${name} needs to be imported before as it contains a side-effect required by your code.`;
+}
+
+/* eslint-disable @typescript-eslint/naming-convention */
+/**
+ * Checks if the window object exists
+ * @returns true if the window object exists
+ */
+function IsWindowObjectExist() {
+ return typeof window !== "undefined";
+}
+/**
+ * Checks if the navigator object exists
+ * @returns true if the navigator object exists
+ */
+function IsNavigatorAvailable() {
+ return typeof navigator !== "undefined";
+}
+/**
+ * Check if the document object exists
+ * @returns true if the document object exists
+ */
+function IsDocumentAvailable() {
+ return typeof document !== "undefined";
+}
+/**
+ * Extracts text content from a DOM element hierarchy
+ * @param element defines the root element
+ * @returns a string
+ */
+function GetDOMTextContent(element) {
+ let result = "";
+ let child = element.firstChild;
+ while (child) {
+ if (child.nodeType === 3) {
+ result += child.textContent;
+ }
+ child = child.nextSibling;
+ }
+ return result;
+}
+
+const EngineFunctionContext = {};
+/**
+ * @internal
+ */
+function _ConcatenateShader(source, defines, shaderVersion = "") {
+ return shaderVersion + (defines ? defines + "\n" : "") + source;
+}
+/**
+ * @internal
+ */
+function _loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, injectedLoadFile) {
+ const loadFile = injectedLoadFile || EngineFunctionContext.loadFile;
+ if (loadFile) {
+ const request = loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
+ return request;
+ }
+ throw _WarnImport("FileTools");
+}
+/** @internal */
+function _getGlobalDefines(defines, isNDCHalfZRange, useReverseDepthBuffer, useExactSrgbConversions) {
+ if (defines) {
+ if (isNDCHalfZRange) {
+ defines["IS_NDC_HALF_ZRANGE"] = "";
+ }
+ else {
+ delete defines["IS_NDC_HALF_ZRANGE"];
+ }
+ if (useReverseDepthBuffer) {
+ defines["USE_REVERSE_DEPTHBUFFER"] = "";
+ }
+ else {
+ delete defines["USE_REVERSE_DEPTHBUFFER"];
+ }
+ if (useExactSrgbConversions) {
+ defines["USE_EXACT_SRGB_CONVERSIONS"] = "";
+ }
+ else {
+ delete defines["USE_EXACT_SRGB_CONVERSIONS"];
+ }
+ return;
+ }
+ else {
+ let s = "";
+ if (isNDCHalfZRange) {
+ s += "#define IS_NDC_HALF_ZRANGE";
+ }
+ if (useReverseDepthBuffer) {
+ if (s) {
+ s += "\n";
+ }
+ s += "#define USE_REVERSE_DEPTHBUFFER";
+ }
+ if (useExactSrgbConversions) {
+ if (s) {
+ s += "\n";
+ }
+ s += "#define USE_EXACT_SRGB_CONVERSIONS";
+ }
+ return s;
+ }
+}
+/**
+ * Allocate a typed array depending on a texture type. Optionally can copy existing data in the buffer.
+ * @param type type of the texture
+ * @param sizeOrDstBuffer size of the array OR an existing buffer that will be used as the destination of the copy (if copyBuffer is provided)
+ * @param sizeInBytes true if the size of the array is given in bytes, false if it is the number of elements of the array
+ * @param copyBuffer if provided, buffer to copy into the destination buffer (either a newly allocated buffer if sizeOrDstBuffer is a number or use sizeOrDstBuffer as the destination buffer otherwise)
+ * @returns the allocated buffer or sizeOrDstBuffer if the latter is an ArrayBuffer
+ */
+function allocateAndCopyTypedBuffer(type, sizeOrDstBuffer, sizeInBytes = false, copyBuffer) {
+ switch (type) {
+ case 3: {
+ const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int8Array(sizeOrDstBuffer) : new Int8Array(sizeOrDstBuffer);
+ if (copyBuffer) {
+ buffer.set(new Int8Array(copyBuffer));
+ }
+ return buffer;
+ }
+ case 0: {
+ const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);
+ if (copyBuffer) {
+ buffer.set(new Uint8Array(copyBuffer));
+ }
+ return buffer;
+ }
+ case 4: {
+ const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int16Array(sizeOrDstBuffer) : new Int16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);
+ if (copyBuffer) {
+ buffer.set(new Int16Array(copyBuffer));
+ }
+ return buffer;
+ }
+ case 5:
+ case 8:
+ case 9:
+ case 10:
+ case 2: {
+ const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint16Array(sizeOrDstBuffer) : new Uint16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);
+ if (copyBuffer) {
+ buffer.set(new Uint16Array(copyBuffer));
+ }
+ return buffer;
+ }
+ case 6: {
+ const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int32Array(sizeOrDstBuffer) : new Int32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
+ if (copyBuffer) {
+ buffer.set(new Int32Array(copyBuffer));
+ }
+ return buffer;
+ }
+ case 7:
+ case 11:
+ case 12:
+ case 13:
+ case 14:
+ case 15: {
+ const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint32Array(sizeOrDstBuffer) : new Uint32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
+ if (copyBuffer) {
+ buffer.set(new Uint32Array(copyBuffer));
+ }
+ return buffer;
+ }
+ case 1: {
+ const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Float32Array(sizeOrDstBuffer) : new Float32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
+ if (copyBuffer) {
+ buffer.set(new Float32Array(copyBuffer));
+ }
+ return buffer;
+ }
+ }
+ const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);
+ if (copyBuffer) {
+ buffer.set(new Uint8Array(copyBuffer));
+ }
+ return buffer;
+}
+
+/**
+ * @internal
+ */
+const _stateObject = new WeakMap();
+/**
+ * This will be used in cases where the engine doesn't have a context (like the nullengine)
+ */
+const singleStateObject = {
+ _webGLVersion: 2,
+ cachedPipelines: {},
+};
+/**
+ * get or create a state object for the given context
+ * Note - Used in WebGL only at the moment.
+ * @param context The context to get the state object from
+ * @returns the state object
+ * @internal
+ */
+function getStateObject(context) {
+ let state = _stateObject.get(context);
+ if (!state) {
+ if (!context) {
+ return singleStateObject;
+ }
+ state = {
+ // use feature detection. instanceof returns false. This only exists on WebGL2 context
+ _webGLVersion: context.TEXTURE_BINDING_3D ? 2 : 1,
+ _context: context,
+ // when using the function without an engine we need to set it to enable parallel compilation
+ parallelShaderCompile: context.getExtension("KHR_parallel_shader_compile") || undefined,
+ cachedPipelines: {},
+ };
+ _stateObject.set(context, state);
+ }
+ return state;
+}
+/**
+ * Remove the state object that belongs to the specific context
+ * @param context the context that is being
+ */
+function deleteStateObject(context) {
+ _stateObject.delete(context);
+}
+/**
+ * Directly creates a webGL program
+ * @param pipelineContext defines the pipeline context to attach to
+ * @param vertexCode defines the vertex shader code to use
+ * @param fragmentCode defines the fragment shader code to use
+ * @param context defines the webGL context to use (if not set, the current one will be used)
+ * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
+ * @param _createShaderProgramInjection defines an optional injection to use to create the shader program
+ * @returns the new webGL program
+ */
+function createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings, _createShaderProgramInjection) {
+ const stateObject = getStateObject(context);
+ if (!_createShaderProgramInjection) {
+ _createShaderProgramInjection = stateObject._createShaderProgramInjection ?? _createShaderProgram;
+ }
+ const vertexShader = _compileRawShader(vertexCode, "vertex", context, stateObject._contextWasLost);
+ const fragmentShader = _compileRawShader(fragmentCode, "fragment", context, stateObject._contextWasLost);
+ return _createShaderProgramInjection(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings, stateObject.validateShaderPrograms);
+}
+/**
+ * Creates a webGL program
+ * @param pipelineContext defines the pipeline context to attach to
+ * @param vertexCode defines the vertex shader code to use
+ * @param fragmentCode defines the fragment shader code to use
+ * @param defines defines the string containing the defines to use to compile the shaders
+ * @param context defines the webGL context to use (if not set, the current one will be used)
+ * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
+ * @param _createShaderProgramInjection defines an optional injection to use to create the shader program
+ * @returns the new webGL program
+ */
+function createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null, _createShaderProgramInjection) {
+ const stateObject = getStateObject(context);
+ if (!_createShaderProgramInjection) {
+ _createShaderProgramInjection = stateObject._createShaderProgramInjection ?? _createShaderProgram;
+ }
+ const shaderVersion = stateObject._webGLVersion > 1 ? "#version 300 es\n#define WEBGL2 \n" : "";
+ const vertexShader = _compileShader(vertexCode, "vertex", defines, shaderVersion, context, stateObject._contextWasLost);
+ const fragmentShader = _compileShader(fragmentCode, "fragment", defines, shaderVersion, context, stateObject._contextWasLost);
+ return _createShaderProgramInjection(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings, stateObject.validateShaderPrograms);
+}
+/**
+ * Creates a new pipeline context. Note, make sure to attach an engine instance to the created context
+ * @param context defines the webGL context to use (if not set, the current one will be used)
+ * @param _shaderProcessingContext defines the shader processing context used during the processing if available
+ * @returns the new pipeline
+ */
+function createPipelineContext(context, _shaderProcessingContext) {
+ const pipelineContext = new WebGLPipelineContext();
+ const stateObject = getStateObject(context);
+ if (stateObject.parallelShaderCompile && !stateObject.disableParallelShaderCompile) {
+ pipelineContext.isParallelCompiled = true;
+ }
+ pipelineContext.context = stateObject._context;
+ return pipelineContext;
+}
+/**
+ * @internal
+ */
+function _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, _transformFeedbackVaryings = null, validateShaderPrograms) {
+ const shaderProgram = context.createProgram();
+ pipelineContext.program = shaderProgram;
+ if (!shaderProgram) {
+ throw new Error("Unable to create program");
+ }
+ context.attachShader(shaderProgram, vertexShader);
+ context.attachShader(shaderProgram, fragmentShader);
+ context.linkProgram(shaderProgram);
+ pipelineContext.context = context;
+ pipelineContext.vertexShader = vertexShader;
+ pipelineContext.fragmentShader = fragmentShader;
+ if (!pipelineContext.isParallelCompiled) {
+ _finalizePipelineContext(pipelineContext, context, validateShaderPrograms);
+ }
+ return shaderProgram;
+}
+/**
+ * @internal
+ */
+function _isRenderingStateCompiled(pipelineContext, gl, validateShaderPrograms) {
+ const webGLPipelineContext = pipelineContext;
+ if (webGLPipelineContext._isDisposed) {
+ return false;
+ }
+ const stateObject = getStateObject(gl);
+ if (stateObject && stateObject.parallelShaderCompile && stateObject.parallelShaderCompile.COMPLETION_STATUS_KHR && webGLPipelineContext.program) {
+ if (gl.getProgramParameter(webGLPipelineContext.program, stateObject.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
+ _finalizePipelineContext(webGLPipelineContext, gl, validateShaderPrograms);
+ return true;
+ }
+ }
+ return false;
+}
+/**
+ * @internal
+ */
+function _finalizePipelineContext(pipelineContext, gl, validateShaderPrograms) {
+ const context = pipelineContext.context;
+ const vertexShader = pipelineContext.vertexShader;
+ const fragmentShader = pipelineContext.fragmentShader;
+ const program = pipelineContext.program;
+ const linked = context.getProgramParameter(program, context.LINK_STATUS);
+ if (!linked) {
+ // Get more info
+ // Vertex
+ if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
+ const log = gl.getShaderInfoLog(vertexShader);
+ if (log) {
+ pipelineContext.vertexCompilationError = log;
+ throw new Error("VERTEX SHADER " + log);
+ }
+ }
+ // Fragment
+ if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
+ const log = gl.getShaderInfoLog(fragmentShader);
+ if (log) {
+ pipelineContext.fragmentCompilationError = log;
+ throw new Error("FRAGMENT SHADER " + log);
+ }
+ }
+ const error = context.getProgramInfoLog(program);
+ if (error) {
+ pipelineContext.programLinkError = error;
+ throw new Error(error);
+ }
+ }
+ if ( /*this.*/validateShaderPrograms) {
+ context.validateProgram(program);
+ const validated = context.getProgramParameter(program, context.VALIDATE_STATUS);
+ if (!validated) {
+ const error = context.getProgramInfoLog(program);
+ if (error) {
+ pipelineContext.programValidationError = error;
+ throw new Error(error);
+ }
+ }
+ }
+ context.deleteShader(vertexShader);
+ context.deleteShader(fragmentShader);
+ pipelineContext.vertexShader = undefined;
+ pipelineContext.fragmentShader = undefined;
+ if (pipelineContext.onCompiled) {
+ pipelineContext.onCompiled();
+ pipelineContext.onCompiled = undefined;
+ }
+}
+/**
+ * @internal
+ */
+function _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, _key = "", onReady, createRawShaderProgramInjection, createShaderProgramInjection) {
+ const stateObject = getStateObject(pipelineContext.context);
+ if (!createRawShaderProgramInjection) {
+ createRawShaderProgramInjection = stateObject.createRawShaderProgramInjection ?? createRawShaderProgram;
+ }
+ if (!createShaderProgramInjection) {
+ createShaderProgramInjection = stateObject.createShaderProgramInjection ?? createShaderProgram;
+ }
+ const webGLRenderingState = pipelineContext;
+ if (createAsRaw) {
+ webGLRenderingState.program = createRawShaderProgramInjection(webGLRenderingState, vertexSourceCode, fragmentSourceCode, webGLRenderingState.context, transformFeedbackVaryings);
+ }
+ else {
+ webGLRenderingState.program = createShaderProgramInjection(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, webGLRenderingState.context, transformFeedbackVaryings);
+ }
+ webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind;
+ onReady();
+}
+function _compileShader(source, type, defines, shaderVersion, gl, _contextWasLost) {
+ return _compileRawShader(_ConcatenateShader(source, defines, shaderVersion), type, gl, _contextWasLost);
+}
+function _compileRawShader(source, type, gl, _contextWasLost) {
+ const shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
+ if (!shader) {
+ let error = gl.NO_ERROR;
+ let tempError = gl.NO_ERROR;
+ while ((tempError = gl.getError()) !== gl.NO_ERROR) {
+ error = tempError;
+ }
+ throw new Error(`Something went wrong while creating a gl ${type} shader object. gl error=${error}, gl isContextLost=${gl.isContextLost()}, _contextWasLost=${_contextWasLost}`);
+ }
+ gl.shaderSource(shader, source);
+ gl.compileShader(shader);
+ return shader;
+}
+/**
+ * @internal
+ */
+function _setProgram(program, gl) {
+ gl.useProgram(program);
+}
+/**
+ * @internal
+ */
+function _executeWhenRenderingStateIsCompiled(pipelineContext, action) {
+ const webGLPipelineContext = pipelineContext;
+ if (!webGLPipelineContext.isParallelCompiled) {
+ action(pipelineContext);
+ return;
+ }
+ const oldHandler = webGLPipelineContext.onCompiled;
+ webGLPipelineContext.onCompiled = () => {
+ oldHandler?.();
+ action(pipelineContext);
+ };
+}
+
+/**
+ * Detect if the effect is a DrawWrapper
+ * @param effect defines the entity to test
+ * @returns if the entity is a DrawWrapper
+ */
+function IsWrapper(effect) {
+ return effect.getPipelineContext === undefined;
+}
+
+/* eslint-disable no-console */
+/**
+ * Logger used throughout the application to allow configuration of
+ * the log level required for the messages.
+ */
+class Logger {
+ static _CheckLimit(message, limit) {
+ let entry = Logger._LogLimitOutputs[message];
+ if (!entry) {
+ entry = { limit, current: 1 };
+ Logger._LogLimitOutputs[message] = entry;
+ }
+ else {
+ entry.current++;
+ }
+ return entry.current <= entry.limit;
+ }
+ static _GenerateLimitMessage(message, level = 1) {
+ const entry = Logger._LogLimitOutputs[message];
+ if (!entry || !Logger.MessageLimitReached) {
+ return;
+ }
+ const type = this._Levels[level];
+ if (entry.current === entry.limit) {
+ Logger[type.name](Logger.MessageLimitReached.replace(/%LIMIT%/g, "" + entry.limit).replace(/%TYPE%/g, type.name ?? ""));
+ }
+ }
+ static _AddLogEntry(entry) {
+ Logger._LogCache = entry + Logger._LogCache;
+ if (Logger.OnNewCacheEntry) {
+ Logger.OnNewCacheEntry(entry);
+ }
+ }
+ static _FormatMessage(message) {
+ const padStr = (i) => (i < 10 ? "0" + i : "" + i);
+ const date = new Date();
+ return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static _LogDisabled(message, limit) {
+ // nothing to do
+ }
+ static _LogEnabled(level = 1, message, limit) {
+ // take first message if array
+ const msg = Array.isArray(message) ? message[0] : message;
+ if (limit !== undefined && !Logger._CheckLimit(msg, limit)) {
+ return;
+ }
+ const formattedMessage = Logger._FormatMessage(msg);
+ const type = this._Levels[level];
+ const optionals = Array.isArray(message) ? message.slice(1) : [];
+ type.logFunc && type.logFunc("BJS - " + formattedMessage, ...optionals);
+ const entry = `
${formattedMessage}
`;
+ Logger._AddLogEntry(entry);
+ Logger._GenerateLimitMessage(msg, level);
+ }
+ /**
+ * Gets current log cache (list of logs)
+ */
+ static get LogCache() {
+ return Logger._LogCache;
+ }
+ /**
+ * Clears the log cache
+ */
+ static ClearLogCache() {
+ Logger._LogCache = "";
+ Logger._LogLimitOutputs = {};
+ Logger.errorsCount = 0;
+ }
+ /**
+ * Sets the current log level. This property is a bit field, allowing you to combine different levels (MessageLogLevel / WarningLogLevel / ErrorLogLevel).
+ * Use NoneLogLevel to disable logging and AllLogLevel for a quick way to enable all levels.
+ */
+ static set LogLevels(level) {
+ Logger.Log = Logger._LogDisabled;
+ Logger.Warn = Logger._LogDisabled;
+ Logger.Error = Logger._LogDisabled;
+ [Logger.MessageLogLevel, Logger.WarningLogLevel, Logger.ErrorLogLevel].forEach((l) => {
+ if ((level & l) === l) {
+ const type = this._Levels[l];
+ Logger[type.name] = Logger._LogEnabled.bind(Logger, l);
+ }
+ });
+ }
+}
+/**
+ * No log
+ */
+Logger.NoneLogLevel = 0;
+/**
+ * Only message logs
+ */
+Logger.MessageLogLevel = 1;
+/**
+ * Only warning logs
+ */
+Logger.WarningLogLevel = 2;
+/**
+ * Only error logs
+ */
+Logger.ErrorLogLevel = 4;
+/**
+ * All logs
+ */
+Logger.AllLogLevel = 7;
+/**
+ * Message to display when a message has been logged too many times
+ */
+Logger.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";
+Logger._LogCache = "";
+Logger._LogLimitOutputs = {};
+// levels according to the (binary) numbering.
+Logger._Levels = [
+ {},
+ { color: "white", logFunc: console.log, name: "Log" },
+ { color: "orange", logFunc: console.warn, name: "Warn" },
+ {},
+ { color: "red", logFunc: console.error, name: "Error" },
+];
+/**
+ * Gets a value indicating the number of loading errors
+ * @ignorenaming
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+Logger.errorsCount = 0;
+/**
+ * Log a message to the console
+ */
+Logger.Log = Logger._LogEnabled.bind(Logger, Logger.MessageLogLevel);
+/**
+ * Write a warning message to the console
+ */
+Logger.Warn = Logger._LogEnabled.bind(Logger, Logger.WarningLogLevel);
+/**
+ * Write an error message to the console
+ */
+Logger.Error = Logger._LogEnabled.bind(Logger, Logger.ErrorLogLevel);
+
+/** @internal */
+class WebGLShaderProcessor {
+ constructor() {
+ this.shaderLanguage = 0 /* ShaderLanguage.GLSL */;
+ }
+ postProcessor(code, defines, isFragment, processingContext, parameters) {
+ // Remove extensions
+ if (parameters.drawBuffersExtensionDisabled) {
+ // even if enclosed in #if/#endif, IE11 does parse the #extension declaration, so we need to remove it altogether
+ const regex = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g;
+ code = code.replace(regex, "");
+ }
+ return code;
+ }
+}
+
+const varyingRegex$1 = /(flat\s)?\s*varying\s*.*/;
+/** @internal */
+class WebGL2ShaderProcessor {
+ constructor() {
+ this.shaderLanguage = 0 /* ShaderLanguage.GLSL */;
+ }
+ attributeProcessor(attribute) {
+ return attribute.replace("attribute", "in");
+ }
+ varyingCheck(varying, _isFragment) {
+ return varyingRegex$1.test(varying);
+ }
+ varyingProcessor(varying, isFragment) {
+ return varying.replace("varying", isFragment ? "in" : "out");
+ }
+ postProcessor(code, defines, isFragment) {
+ const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
+ // Remove extensions
+ const regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
+ code = code.replace(regex, "");
+ // Replace instructions
+ code = code.replace(/texture2D\s*\(/g, "texture(");
+ if (isFragment) {
+ const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1;
+ code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
+ code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
+ code = code.replace(/textureCube\s*\(/g, "texture(");
+ code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
+ code = code.replace(/gl_FragColor/g, "glFragColor");
+ code = code.replace(/gl_FragData/g, "glFragData");
+ code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension || hasOutput ? "" : "layout(location = 0) out vec4 glFragColor;\n") + "void main(");
+ }
+ else {
+ const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1;
+ if (hasMultiviewExtension) {
+ return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code;
+ }
+ }
+ return code;
+ }
+}
+
+/**
+ * Class used to store gfx data (like WebGLBuffer)
+ */
+class DataBuffer {
+ /**
+ * Gets the underlying buffer
+ */
+ get underlyingResource() {
+ return null;
+ }
+ /**
+ * Constructs the buffer
+ */
+ constructor() {
+ /**
+ * Gets or sets the number of objects referencing this buffer
+ */
+ this.references = 0;
+ /** Gets or sets the size of the underlying buffer */
+ this.capacity = 0;
+ /**
+ * Gets or sets a boolean indicating if the buffer contains 32bits indices
+ */
+ this.is32Bits = false;
+ this.uniqueId = DataBuffer._Counter++;
+ }
+}
+DataBuffer._Counter = 0;
+
+/** @internal */
+class WebGLDataBuffer extends DataBuffer {
+ constructor(resource) {
+ super();
+ this._buffer = resource;
+ }
+ get underlyingResource() {
+ return this._buffer;
+ }
+}
+
+/**
+ * Function indicating if a number is an exponent of 2
+ * @param value defines the value to test
+ * @returns true if the value is an exponent of 2
+ */
+function IsExponentOfTwo(value) {
+ let count = 1;
+ do {
+ count *= 2;
+ } while (count < value);
+ return count === value;
+}
+/**
+ * Interpolates between a and b via alpha
+ * @param a The lower value (returned when alpha = 0)
+ * @param b The upper value (returned when alpha = 1)
+ * @param alpha The interpolation-factor
+ * @returns The mixed value
+ */
+function Mix(a, b, alpha) {
+ return a * (1 - alpha) + b * alpha;
+}
+/**
+ * Find the nearest power of two.
+ * @param x Number to start search from.
+ * @returns Next nearest power of two.
+ */
+function NearestPOT(x) {
+ const c = CeilingPOT(x);
+ const f = FloorPOT(x);
+ return c - x > x - f ? f : c;
+}
+/**
+ * Find the next highest power of two.
+ * @param x Number to start search from.
+ * @returns Next highest power of two.
+ */
+function CeilingPOT(x) {
+ x--;
+ x |= x >> 1;
+ x |= x >> 2;
+ x |= x >> 4;
+ x |= x >> 8;
+ x |= x >> 16;
+ x++;
+ return x;
+}
+/**
+ * Find the next lowest power of two.
+ * @param x Number to start search from.
+ * @returns Next lowest power of two.
+ */
+function FloorPOT(x) {
+ x = x | (x >> 1);
+ x = x | (x >> 2);
+ x = x | (x >> 4);
+ x = x | (x >> 8);
+ x = x | (x >> 16);
+ return x - (x >> 1);
+}
+/**
+ * Get the closest exponent of two
+ * @param value defines the value to approximate
+ * @param max defines the maximum value to return
+ * @param mode defines how to define the closest value
+ * @returns closest exponent of two of the given value
+ */
+function GetExponentOfTwo(value, max, mode = 2) {
+ let pot;
+ switch (mode) {
+ case 1:
+ pot = FloorPOT(value);
+ break;
+ case 2:
+ pot = NearestPOT(value);
+ break;
+ case 3:
+ default:
+ pot = CeilingPOT(value);
+ break;
+ }
+ return Math.min(pot, max);
+}
+
+/**
+ * Defines the shader related stores and directory
+ */
+class ShaderStore {
+ /**
+ * Gets the shaders repository path for a given shader language
+ * @param shaderLanguage the shader language
+ * @returns the path to the shaders repository
+ */
+ static GetShadersRepository(shaderLanguage = 0 /* ShaderLanguage.GLSL */) {
+ return shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? ShaderStore.ShadersRepository : ShaderStore.ShadersRepositoryWGSL;
+ }
+ /**
+ * Gets the shaders store of a given shader language
+ * @param shaderLanguage the shader language
+ * @returns the shaders store
+ */
+ static GetShadersStore(shaderLanguage = 0 /* ShaderLanguage.GLSL */) {
+ return shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? ShaderStore.ShadersStore : ShaderStore.ShadersStoreWGSL;
+ }
+ /**
+ * Gets the include shaders store of a given shader language
+ * @param shaderLanguage the shader language
+ * @returns the include shaders store
+ */
+ static GetIncludesShadersStore(shaderLanguage = 0 /* ShaderLanguage.GLSL */) {
+ return shaderLanguage === 0 /* ShaderLanguage.GLSL */ ? ShaderStore.IncludesShadersStore : ShaderStore.IncludesShadersStoreWGSL;
+ }
+}
+/**
+ * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
+ */
+ShaderStore.ShadersRepository = "src/Shaders/";
+/**
+ * Store of each shader (The can be looked up using effect.key)
+ */
+ShaderStore.ShadersStore = {};
+/**
+ * Store of each included file for a shader (The can be looked up using effect.key)
+ */
+ShaderStore.IncludesShadersStore = {};
+/**
+ * Gets or sets the relative url used to load shaders (WGSL) if using the engine in non-minified mode
+ */
+ShaderStore.ShadersRepositoryWGSL = "src/ShadersWGSL/";
+/**
+ * Store of each shader (WGSL)
+ */
+ShaderStore.ShadersStoreWGSL = {};
+/**
+ * Store of each included file for a shader (WGSL)
+ */
+ShaderStore.IncludesShadersStoreWGSL = {};
+
+const defaultAttributeKeywordName = "attribute";
+const defaultVaryingKeywordName = "varying";
+/** @internal */
+class ShaderCodeNode {
+ constructor() {
+ this.children = [];
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ isValid(preprocessors) {
+ return true;
+ }
+ process(preprocessors, options) {
+ let result = "";
+ if (this.line) {
+ let value = this.line;
+ const processor = options.processor;
+ if (processor) {
+ // This must be done before other replacements to avoid mistakenly changing something that was already changed.
+ if (processor.lineProcessor) {
+ value = processor.lineProcessor(value, options.isFragment, options.processingContext);
+ }
+ const attributeKeyword = options.processor?.attributeKeywordName ?? defaultAttributeKeywordName;
+ const varyingKeyword = options.isFragment && options.processor?.varyingFragmentKeywordName
+ ? options.processor?.varyingFragmentKeywordName
+ : !options.isFragment && options.processor?.varyingVertexKeywordName
+ ? options.processor?.varyingVertexKeywordName
+ : defaultVaryingKeywordName;
+ if (!options.isFragment && processor.attributeProcessor && this.line.startsWith(attributeKeyword)) {
+ value = processor.attributeProcessor(this.line, preprocessors, options.processingContext);
+ }
+ else if (processor.varyingProcessor &&
+ (processor.varyingCheck?.(this.line, options.isFragment) || (!processor.varyingCheck && this.line.startsWith(varyingKeyword)))) {
+ value = processor.varyingProcessor(this.line, options.isFragment, preprocessors, options.processingContext);
+ }
+ else if (processor.uniformProcessor && processor.uniformRegexp && processor.uniformRegexp.test(this.line)) {
+ if (!options.lookForClosingBracketForUniformBuffer) {
+ value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext);
+ }
+ }
+ else if (processor.uniformBufferProcessor && processor.uniformBufferRegexp && processor.uniformBufferRegexp.test(this.line)) {
+ if (!options.lookForClosingBracketForUniformBuffer) {
+ value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext);
+ options.lookForClosingBracketForUniformBuffer = true;
+ }
+ }
+ else if (processor.textureProcessor && processor.textureRegexp && processor.textureRegexp.test(this.line)) {
+ value = processor.textureProcessor(this.line, options.isFragment, preprocessors, options.processingContext);
+ }
+ else if ((processor.uniformProcessor || processor.uniformBufferProcessor) && this.line.startsWith("uniform") && !options.lookForClosingBracketForUniformBuffer) {
+ const regex = /uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/;
+ if (regex.test(this.line)) {
+ // uniform
+ if (processor.uniformProcessor) {
+ value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext);
+ }
+ }
+ else {
+ // Uniform buffer
+ if (processor.uniformBufferProcessor) {
+ value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext);
+ options.lookForClosingBracketForUniformBuffer = true;
+ }
+ }
+ }
+ if (options.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1) {
+ options.lookForClosingBracketForUniformBuffer = false;
+ if (processor.endOfUniformBufferProcessor) {
+ value = processor.endOfUniformBufferProcessor(this.line, options.isFragment, options.processingContext);
+ }
+ }
+ }
+ result += value + "\n";
+ }
+ this.children.forEach((child) => {
+ result += child.process(preprocessors, options);
+ });
+ if (this.additionalDefineKey) {
+ preprocessors[this.additionalDefineKey] = this.additionalDefineValue || "true";
+ }
+ return result;
+ }
+}
+
+/** @internal */
+class ShaderCodeCursor {
+ constructor() {
+ this._lines = [];
+ }
+ get currentLine() {
+ return this._lines[this.lineIndex];
+ }
+ get canRead() {
+ return this.lineIndex < this._lines.length - 1;
+ }
+ set lines(value) {
+ this._lines.length = 0;
+ for (const line of value) {
+ // Skip empty lines
+ if (!line || line === "\r") {
+ continue;
+ }
+ // Prevent removing line break in macros.
+ if (line[0] === "#") {
+ this._lines.push(line);
+ continue;
+ }
+ // Do not split single line comments
+ const trimmedLine = line.trim();
+ if (!trimmedLine) {
+ continue;
+ }
+ if (trimmedLine.startsWith("//")) {
+ this._lines.push(line);
+ continue;
+ }
+ // Work with semicolon in the line
+ const semicolonIndex = trimmedLine.indexOf(";");
+ if (semicolonIndex === -1) {
+ // No semicolon in the line
+ this._lines.push(trimmedLine);
+ }
+ else if (semicolonIndex === trimmedLine.length - 1) {
+ // Single semicolon at the end of the line
+ // If trimmedLine == ";", we must not push, to be backward compatible with the old code!
+ if (trimmedLine.length > 1) {
+ this._lines.push(trimmedLine);
+ }
+ }
+ else {
+ // Semicolon in the middle of the line
+ const split = line.split(";");
+ for (let index = 0; index < split.length; index++) {
+ let subLine = split[index];
+ if (!subLine) {
+ continue;
+ }
+ subLine = subLine.trim();
+ if (!subLine) {
+ continue;
+ }
+ this._lines.push(subLine + (index !== split.length - 1 ? ";" : ""));
+ }
+ }
+ }
+ }
+}
+
+/** @internal */
+class ShaderCodeConditionNode extends ShaderCodeNode {
+ process(preprocessors, options) {
+ for (let index = 0; index < this.children.length; index++) {
+ const node = this.children[index];
+ if (node.isValid(preprocessors)) {
+ return node.process(preprocessors, options);
+ }
+ }
+ return "";
+ }
+}
+
+/** @internal */
+class ShaderCodeTestNode extends ShaderCodeNode {
+ isValid(preprocessors) {
+ return this.testExpression.isTrue(preprocessors);
+ }
+}
+
+/* eslint-disable @typescript-eslint/naming-convention */
+/** @internal */
+class ShaderDefineExpression {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ isTrue(preprocessors) {
+ return true;
+ }
+ static postfixToInfix(postfix) {
+ const stack = [];
+ for (const c of postfix) {
+ if (ShaderDefineExpression._OperatorPriority[c] === undefined) {
+ stack.push(c);
+ }
+ else {
+ const v1 = stack[stack.length - 1], v2 = stack[stack.length - 2];
+ stack.length -= 2;
+ stack.push(`(${v2}${c}${v1})`);
+ }
+ }
+ return stack[stack.length - 1];
+ }
+ /**
+ * Converts an infix expression to a postfix expression.
+ *
+ * This method is used to transform infix expressions, which are more human-readable,
+ * into postfix expressions, also known as Reverse Polish Notation (RPN), that can be
+ * evaluated more efficiently by a computer. The conversion is based on the operator
+ * priority defined in _OperatorPriority.
+ *
+ * The function employs a stack-based algorithm for the conversion and caches the result
+ * to improve performance. The cache keeps track of each converted expression's access time
+ * to manage the cache size and optimize memory usage. When the cache size exceeds a specified
+ * limit, the least recently accessed items in the cache are deleted.
+ *
+ * The cache mechanism is particularly helpful for shader compilation, where the same infix
+ * expressions might be encountered repeatedly, hence the caching can speed up the process.
+ *
+ * @param infix - The infix expression to be converted.
+ * @returns The postfix expression as an array of strings.
+ */
+ static infixToPostfix(infix) {
+ // Is infix already in cache
+ const cacheItem = ShaderDefineExpression._InfixToPostfixCache.get(infix);
+ if (cacheItem) {
+ cacheItem.accessTime = Date.now();
+ return cacheItem.result;
+ }
+ // Is infix contain any operator
+ if (!infix.includes("&&") && !infix.includes("||") && !infix.includes(")") && !infix.includes("(")) {
+ return [infix];
+ }
+ const result = [];
+ let stackIdx = -1;
+ const pushOperand = () => {
+ operand = operand.trim();
+ if (operand !== "") {
+ result.push(operand);
+ operand = "";
+ }
+ };
+ const push = (s) => {
+ if (stackIdx < ShaderDefineExpression._Stack.length - 1) {
+ ShaderDefineExpression._Stack[++stackIdx] = s;
+ }
+ };
+ const peek = () => ShaderDefineExpression._Stack[stackIdx];
+ const pop = () => (stackIdx === -1 ? "!!INVALID EXPRESSION!!" : ShaderDefineExpression._Stack[stackIdx--]);
+ let idx = 0, operand = "";
+ while (idx < infix.length) {
+ const c = infix.charAt(idx), token = idx < infix.length - 1 ? infix.substring(idx, 2 + idx) : "";
+ if (c === "(") {
+ operand = "";
+ push(c);
+ }
+ else if (c === ")") {
+ pushOperand();
+ while (stackIdx !== -1 && peek() !== "(") {
+ result.push(pop());
+ }
+ pop();
+ }
+ else if (ShaderDefineExpression._OperatorPriority[token] > 1) {
+ pushOperand();
+ while (stackIdx !== -1 && ShaderDefineExpression._OperatorPriority[peek()] >= ShaderDefineExpression._OperatorPriority[token]) {
+ result.push(pop());
+ }
+ push(token);
+ idx++;
+ }
+ else {
+ operand += c;
+ }
+ idx++;
+ }
+ pushOperand();
+ while (stackIdx !== -1) {
+ if (peek() === "(") {
+ pop();
+ }
+ else {
+ result.push(pop());
+ }
+ }
+ // If the cache is at capacity, clear it before adding a new item
+ if (ShaderDefineExpression._InfixToPostfixCache.size >= ShaderDefineExpression.InfixToPostfixCacheLimitSize) {
+ ShaderDefineExpression.ClearCache();
+ }
+ // Add the new item to the cache, including the current time as the last access time
+ ShaderDefineExpression._InfixToPostfixCache.set(infix, { result, accessTime: Date.now() });
+ return result;
+ }
+ static ClearCache() {
+ // Convert the cache to an array and sort by last access time
+ const sortedCache = Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((a, b) => a[1].accessTime - b[1].accessTime);
+ // Remove the least recently accessed half of the cache
+ for (let i = 0; i < ShaderDefineExpression.InfixToPostfixCacheCleanupSize; i++) {
+ ShaderDefineExpression._InfixToPostfixCache.delete(sortedCache[i][0]);
+ }
+ }
+}
+/**
+ * Cache items count limit for the InfixToPostfix cache.
+ * It uses to improve the performance of the shader compilation.
+ * For details see PR: https://github.com/BabylonJS/Babylon.js/pull/13936
+ */
+ShaderDefineExpression.InfixToPostfixCacheLimitSize = 50000;
+/**
+ * When the cache size is exceeded, a cache cleanup will be triggered
+ * and the cache will be reduced by the size specified
+ * in the InfixToPostfixCacheCleanupSize variable, removing entries
+ * that have not been accessed the longest.
+ */
+ShaderDefineExpression.InfixToPostfixCacheCleanupSize = 25000;
+ShaderDefineExpression._InfixToPostfixCache = new Map();
+ShaderDefineExpression._OperatorPriority = {
+ ")": 0,
+ "(": 1,
+ "||": 2,
+ "&&": 3,
+};
+ShaderDefineExpression._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""];
+
+/** @internal */
+class ShaderDefineIsDefinedOperator extends ShaderDefineExpression {
+ constructor(define, not = false) {
+ super();
+ this.define = define;
+ this.not = not;
+ }
+ isTrue(preprocessors) {
+ let condition = preprocessors[this.define] !== undefined;
+ if (this.not) {
+ condition = !condition;
+ }
+ return condition;
+ }
+}
+
+/** @internal */
+class ShaderDefineOrOperator extends ShaderDefineExpression {
+ isTrue(preprocessors) {
+ return this.leftOperand.isTrue(preprocessors) || this.rightOperand.isTrue(preprocessors);
+ }
+}
+
+/** @internal */
+class ShaderDefineAndOperator extends ShaderDefineExpression {
+ isTrue(preprocessors) {
+ return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors);
+ }
+}
+
+/** @internal */
+class ShaderDefineArithmeticOperator extends ShaderDefineExpression {
+ constructor(define, operand, testValue) {
+ super();
+ this.define = define;
+ this.operand = operand;
+ this.testValue = testValue;
+ }
+ isTrue(preprocessors) {
+ let value = preprocessors[this.define];
+ if (value === undefined) {
+ value = this.define;
+ }
+ let condition = false;
+ const left = parseInt(value);
+ const right = parseInt(this.testValue);
+ switch (this.operand) {
+ case ">":
+ condition = left > right;
+ break;
+ case "<":
+ condition = left < right;
+ break;
+ case "<=":
+ condition = left <= right;
+ break;
+ case ">=":
+ condition = left >= right;
+ break;
+ case "==":
+ condition = left === right;
+ break;
+ case "!=":
+ condition = left !== right;
+ break;
+ }
+ return condition;
+ }
+}
+
+/* eslint-disable @typescript-eslint/no-unused-vars */
+const regexSE = /defined\s*?\((.+?)\)/g;
+const regexSERevert = /defined\s*?\[(.+?)\]/g;
+const regexShaderInclude = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g;
+const regexShaderDecl = /__decl__/;
+const regexLightX = /light\{X\}.(\w*)/g;
+const regexX = /\{X\}/g;
+const reusableMatches = [];
+const _MoveCursorRegex = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;
+/** @internal */
+function Initialize(options) {
+ if (options.processor && options.processor.initializeShaders) {
+ options.processor.initializeShaders(options.processingContext);
+ }
+}
+/** @internal */
+function Process(sourceCode, options, callback, engine) {
+ if (options.processor?.preProcessShaderCode) {
+ sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment);
+ }
+ _ProcessIncludes(sourceCode, options, (codeWithIncludes) => {
+ if (options.processCodeAfterIncludes) {
+ codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? "fragment" : "vertex", codeWithIncludes, options.defines);
+ }
+ const migratedCode = _ProcessShaderConversion(codeWithIncludes, options, engine);
+ callback(migratedCode, codeWithIncludes);
+ });
+}
+/** @internal */
+function PreProcess(sourceCode, options, callback, engine) {
+ if (options.processor?.preProcessShaderCode) {
+ sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment);
+ }
+ _ProcessIncludes(sourceCode, options, (codeWithIncludes) => {
+ if (options.processCodeAfterIncludes) {
+ codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? "fragment" : "vertex", codeWithIncludes, options.defines);
+ }
+ const migratedCode = _ApplyPreProcessing(codeWithIncludes, options, engine);
+ callback(migratedCode, codeWithIncludes);
+ });
+}
+/** @internal */
+function Finalize(vertexCode, fragmentCode, options) {
+ if (!options.processor || !options.processor.finalizeShaders) {
+ return { vertexCode, fragmentCode };
+ }
+ return options.processor.finalizeShaders(vertexCode, fragmentCode, options.processingContext);
+}
+function _ProcessPrecision(source, options) {
+ if (options.processor?.noPrecision) {
+ return source;
+ }
+ const shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader;
+ if (source.indexOf("precision highp float") === -1) {
+ if (!shouldUseHighPrecisionShader) {
+ source = "precision mediump float;\n" + source;
+ }
+ else {
+ source = "precision highp float;\n" + source;
+ }
+ }
+ else {
+ if (!shouldUseHighPrecisionShader) {
+ // Moving highp to mediump
+ source = source.replace("precision highp float", "precision mediump float");
+ }
+ }
+ return source;
+}
+function _ExtractOperation(expression) {
+ const regex = /defined\((.+)\)/;
+ const match = regex.exec(expression);
+ if (match && match.length) {
+ return new ShaderDefineIsDefinedOperator(match[1].trim(), expression[0] === "!");
+ }
+ const operators = ["==", "!=", ">=", "<=", "<", ">"];
+ let operator = "";
+ let indexOperator = 0;
+ for (operator of operators) {
+ indexOperator = expression.indexOf(operator);
+ if (indexOperator > -1) {
+ break;
+ }
+ }
+ if (indexOperator === -1) {
+ return new ShaderDefineIsDefinedOperator(expression);
+ }
+ const define = expression.substring(0, indexOperator).trim();
+ const value = expression.substring(indexOperator + operator.length).trim();
+ return new ShaderDefineArithmeticOperator(define, operator, value);
+}
+function _BuildSubExpression(expression) {
+ expression = expression.replace(regexSE, "defined[$1]");
+ const postfix = ShaderDefineExpression.infixToPostfix(expression);
+ const stack = [];
+ for (const c of postfix) {
+ if (c !== "||" && c !== "&&") {
+ stack.push(c);
+ }
+ else if (stack.length >= 2) {
+ let v1 = stack[stack.length - 1], v2 = stack[stack.length - 2];
+ stack.length -= 2;
+ const operator = c == "&&" ? new ShaderDefineAndOperator() : new ShaderDefineOrOperator();
+ if (typeof v1 === "string") {
+ v1 = v1.replace(regexSERevert, "defined($1)");
+ }
+ if (typeof v2 === "string") {
+ v2 = v2.replace(regexSERevert, "defined($1)");
+ }
+ operator.leftOperand = typeof v2 === "string" ? _ExtractOperation(v2) : v2;
+ operator.rightOperand = typeof v1 === "string" ? _ExtractOperation(v1) : v1;
+ stack.push(operator);
+ }
+ }
+ let result = stack[stack.length - 1];
+ if (typeof result === "string") {
+ result = result.replace(regexSERevert, "defined($1)");
+ }
+ // note: stack.length !== 1 if there was an error in the parsing
+ return typeof result === "string" ? _ExtractOperation(result) : result;
+}
+function _BuildExpression(line, start) {
+ const node = new ShaderCodeTestNode();
+ const command = line.substring(0, start);
+ let expression = line.substring(start);
+ expression = expression.substring(0, (expression.indexOf("//") + 1 || expression.length + 1) - 1).trim();
+ if (command === "#ifdef") {
+ node.testExpression = new ShaderDefineIsDefinedOperator(expression);
+ }
+ else if (command === "#ifndef") {
+ node.testExpression = new ShaderDefineIsDefinedOperator(expression, true);
+ }
+ else {
+ node.testExpression = _BuildSubExpression(expression);
+ }
+ return node;
+}
+function _MoveCursorWithinIf(cursor, rootNode, ifNode) {
+ let line = cursor.currentLine;
+ while (_MoveCursor(cursor, ifNode)) {
+ line = cursor.currentLine;
+ const first5 = line.substring(0, 5).toLowerCase();
+ if (first5 === "#else") {
+ const elseNode = new ShaderCodeNode();
+ rootNode.children.push(elseNode);
+ _MoveCursor(cursor, elseNode);
+ return;
+ }
+ else if (first5 === "#elif") {
+ const elifNode = _BuildExpression(line, 5);
+ rootNode.children.push(elifNode);
+ ifNode = elifNode;
+ }
+ }
+}
+function _MoveCursor(cursor, rootNode) {
+ while (cursor.canRead) {
+ cursor.lineIndex++;
+ const line = cursor.currentLine;
+ if (line.indexOf("#") >= 0) {
+ const matches = _MoveCursorRegex.exec(line);
+ if (matches && matches.length) {
+ const keyword = matches[0];
+ switch (keyword) {
+ case "#ifdef": {
+ const newRootNode = new ShaderCodeConditionNode();
+ rootNode.children.push(newRootNode);
+ const ifNode = _BuildExpression(line, 6);
+ newRootNode.children.push(ifNode);
+ _MoveCursorWithinIf(cursor, newRootNode, ifNode);
+ break;
+ }
+ case "#else":
+ case "#elif":
+ return true;
+ case "#endif":
+ return false;
+ case "#ifndef": {
+ const newRootNode = new ShaderCodeConditionNode();
+ rootNode.children.push(newRootNode);
+ const ifNode = _BuildExpression(line, 7);
+ newRootNode.children.push(ifNode);
+ _MoveCursorWithinIf(cursor, newRootNode, ifNode);
+ break;
+ }
+ case "#if": {
+ const newRootNode = new ShaderCodeConditionNode();
+ const ifNode = _BuildExpression(line, 3);
+ rootNode.children.push(newRootNode);
+ newRootNode.children.push(ifNode);
+ _MoveCursorWithinIf(cursor, newRootNode, ifNode);
+ break;
+ }
+ }
+ continue;
+ }
+ }
+ const newNode = new ShaderCodeNode();
+ newNode.line = line;
+ rootNode.children.push(newNode);
+ // Detect additional defines
+ if (line[0] === "#" && line[1] === "d") {
+ const split = line.replace(";", "").split(" ");
+ newNode.additionalDefineKey = split[1];
+ if (split.length === 3) {
+ newNode.additionalDefineValue = split[2];
+ }
+ }
+ }
+ return false;
+}
+function _EvaluatePreProcessors(sourceCode, preprocessors, options) {
+ const rootNode = new ShaderCodeNode();
+ const cursor = new ShaderCodeCursor();
+ cursor.lineIndex = -1;
+ cursor.lines = sourceCode.split("\n");
+ // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant)
+ _MoveCursor(cursor, rootNode);
+ // Recompose
+ return rootNode.process(preprocessors, options);
+}
+function _PreparePreProcessors(options, engine) {
+ const defines = options.defines;
+ const preprocessors = {};
+ for (const define of defines) {
+ const keyValue = define.replace("#define", "").replace(";", "").trim();
+ const split = keyValue.split(" ");
+ preprocessors[split[0]] = split.length > 1 ? split[1] : "";
+ }
+ if (options.processor?.shaderLanguage === 0 /* ShaderLanguage.GLSL */) {
+ preprocessors["GL_ES"] = "true";
+ }
+ preprocessors["__VERSION__"] = options.version;
+ preprocessors[options.platformName] = "true";
+ _getGlobalDefines(preprocessors, engine?.isNDCHalfZRange, engine?.useReverseDepthBuffer, engine?.useExactSrgbConversions);
+ return preprocessors;
+}
+function _ProcessShaderConversion(sourceCode, options, engine) {
+ let preparedSourceCode = _ProcessPrecision(sourceCode, options);
+ if (!options.processor) {
+ return preparedSourceCode;
+ }
+ // Already converted
+ if (options.processor.shaderLanguage === 0 /* ShaderLanguage.GLSL */ && preparedSourceCode.indexOf("#version 3") !== -1) {
+ preparedSourceCode = preparedSourceCode.replace("#version 300 es", "");
+ if (!options.processor.parseGLES3) {
+ return preparedSourceCode;
+ }
+ }
+ const defines = options.defines;
+ const preprocessors = _PreparePreProcessors(options, engine);
+ // General pre processing
+ if (options.processor.preProcessor) {
+ preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext);
+ }
+ preparedSourceCode = _EvaluatePreProcessors(preparedSourceCode, preprocessors, options);
+ // Post processing
+ if (options.processor.postProcessor) {
+ preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine
+ ? {
+ drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true,
+ }
+ : {});
+ }
+ // Inline functions tagged with #define inline
+ if (engine?._features.needShaderCodeInlining) {
+ preparedSourceCode = engine.inlineShaderCode(preparedSourceCode);
+ }
+ return preparedSourceCode;
+}
+function _ApplyPreProcessing(sourceCode, options, engine) {
+ let preparedSourceCode = sourceCode;
+ const defines = options.defines;
+ const preprocessors = _PreparePreProcessors(options, engine);
+ // General pre processing
+ if (options.processor?.preProcessor) {
+ preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext);
+ }
+ preparedSourceCode = _EvaluatePreProcessors(preparedSourceCode, preprocessors, options);
+ // Post processing
+ if (options.processor?.postProcessor) {
+ preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine
+ ? {
+ drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true,
+ }
+ : {});
+ }
+ // Inline functions tagged with #define inline
+ if (engine._features.needShaderCodeInlining) {
+ preparedSourceCode = engine.inlineShaderCode(preparedSourceCode);
+ }
+ return preparedSourceCode;
+}
+/** @internal */
+function _ProcessIncludes(sourceCode, options, callback) {
+ reusableMatches.length = 0;
+ let match;
+ // stay back-compat to the old matchAll syntax
+ while ((match = regexShaderInclude.exec(sourceCode)) !== null) {
+ reusableMatches.push(match);
+ }
+ let returnValue = String(sourceCode);
+ let parts = [sourceCode];
+ let keepProcessing = false;
+ for (const match of reusableMatches) {
+ let includeFile = match[1];
+ // Uniform declaration
+ if (includeFile.indexOf("__decl__") !== -1) {
+ includeFile = includeFile.replace(regexShaderDecl, "");
+ if (options.supportsUniformBuffers) {
+ includeFile = includeFile.replace("Vertex", "Ubo").replace("Fragment", "Ubo");
+ }
+ includeFile = includeFile + "Declaration";
+ }
+ if (options.includesShadersStore[includeFile]) {
+ // Substitution
+ let includeContent = options.includesShadersStore[includeFile];
+ if (match[2]) {
+ const splits = match[3].split(",");
+ for (let index = 0; index < splits.length; index += 2) {
+ const source = new RegExp(splits[index], "g");
+ const dest = splits[index + 1];
+ includeContent = includeContent.replace(source, dest);
+ }
+ }
+ if (match[4]) {
+ const indexString = match[5];
+ if (indexString.indexOf("..") !== -1) {
+ const indexSplits = indexString.split("..");
+ const minIndex = parseInt(indexSplits[0]);
+ let maxIndex = parseInt(indexSplits[1]);
+ let sourceIncludeContent = includeContent.slice(0);
+ includeContent = "";
+ if (isNaN(maxIndex)) {
+ maxIndex = options.indexParameters[indexSplits[1]];
+ }
+ for (let i = minIndex; i < maxIndex; i++) {
+ if (!options.supportsUniformBuffers) {
+ // Ubo replacement
+ sourceIncludeContent = sourceIncludeContent.replace(regexLightX, (str, p1) => {
+ return p1 + "{X}";
+ });
+ }
+ includeContent += sourceIncludeContent.replace(regexX, i.toString()) + "\n";
+ }
+ }
+ else {
+ if (!options.supportsUniformBuffers) {
+ // Ubo replacement
+ includeContent = includeContent.replace(regexLightX, (str, p1) => {
+ return p1 + "{X}";
+ });
+ }
+ includeContent = includeContent.replace(regexX, indexString);
+ }
+ }
+ // Replace
+ // Split all parts on match[0] and intersperse the parts with the include content
+ const newParts = [];
+ for (const part of parts) {
+ const splitPart = part.split(match[0]);
+ for (let i = 0; i < splitPart.length - 1; i++) {
+ newParts.push(splitPart[i]);
+ newParts.push(includeContent);
+ }
+ newParts.push(splitPart[splitPart.length - 1]);
+ }
+ parts = newParts;
+ keepProcessing = keepProcessing || includeContent.indexOf("#include<") >= 0 || includeContent.indexOf("#include <") >= 0;
+ }
+ else {
+ const includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx";
+ _functionContainer.loadFile(includeShaderUrl, (fileContent) => {
+ options.includesShadersStore[includeFile] = fileContent;
+ _ProcessIncludes(parts.join(""), options, callback);
+ });
+ return;
+ }
+ }
+ reusableMatches.length = 0;
+ returnValue = parts.join("");
+ if (keepProcessing) {
+ _ProcessIncludes(returnValue.toString(), options, callback);
+ }
+ else {
+ callback(returnValue);
+ }
+}
+/** @internal */
+const _functionContainer = {
+ /**
+ * Loads a file from a url
+ * @param url url to load
+ * @param onSuccess callback called when the file successfully loads
+ * @param onProgress callback called while file is loading (if the server supports this mode)
+ * @param offlineProvider defines the offline provider for caching
+ * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
+ * @param onError callback called when the file fails to load
+ * @returns a file request object
+ * @internal
+ */
+ loadFile: (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) => {
+ throw _WarnImport("FileTools");
+ },
+};
+
+/**
+ * Get a cached pipeline context
+ * @param name the pipeline name
+ * @param context the context to be used when creating the pipeline
+ * @returns the cached pipeline context if it exists
+ * @internal
+ */
+function getCachedPipeline(name, context) {
+ const stateObject = getStateObject(context);
+ return stateObject.cachedPipelines[name];
+}
+/**
+ * @internal
+ */
+function resetCachedPipeline(pipeline) {
+ const name = pipeline._name;
+ const context = pipeline.context;
+ if (name && context) {
+ const stateObject = getStateObject(context);
+ const cachedPipeline = stateObject.cachedPipelines[name];
+ cachedPipeline?.dispose();
+ delete stateObject.cachedPipelines[name];
+ }
+}
+/** @internal */
+function _processShaderCode(processorOptions, baseName, processFinalCode, onFinalCodeReady, shaderLanguage, engine, effectContext) {
+ let vertexSource;
+ let fragmentSource;
+ // const baseName = this.name;
+ const hostDocument = IsWindowObjectExist() ? engine?.getHostDocument() : null;
+ if (typeof baseName === "string") {
+ vertexSource = baseName;
+ }
+ else if (baseName.vertexSource) {
+ vertexSource = "source:" + baseName.vertexSource;
+ }
+ else if (baseName.vertexElement) {
+ vertexSource = hostDocument?.getElementById(baseName.vertexElement) || baseName.vertexElement;
+ }
+ else {
+ vertexSource = baseName.vertex || baseName;
+ }
+ if (typeof baseName === "string") {
+ fragmentSource = baseName;
+ }
+ else if (baseName.fragmentSource) {
+ fragmentSource = "source:" + baseName.fragmentSource;
+ }
+ else if (baseName.fragmentElement) {
+ fragmentSource = hostDocument?.getElementById(baseName.fragmentElement) || baseName.fragmentElement;
+ }
+ else {
+ fragmentSource = baseName.fragment || baseName;
+ }
+ const shaderCodes = [undefined, undefined];
+ const shadersLoaded = () => {
+ if (shaderCodes[0] && shaderCodes[1]) {
+ processorOptions.isFragment = true;
+ const [migratedVertexCode, fragmentCode] = shaderCodes;
+ Process(fragmentCode, processorOptions, (migratedFragmentCode, codeBeforeMigration) => {
+ if (effectContext) {
+ effectContext._fragmentSourceCodeBeforeMigration = codeBeforeMigration;
+ }
+ if (processFinalCode) {
+ migratedFragmentCode = processFinalCode("fragment", migratedFragmentCode);
+ }
+ const finalShaders = Finalize(migratedVertexCode, migratedFragmentCode, processorOptions);
+ processorOptions = null;
+ const finalCode = _useFinalCode(finalShaders.vertexCode, finalShaders.fragmentCode, baseName, shaderLanguage);
+ onFinalCodeReady?.(finalCode.vertexSourceCode, finalCode.fragmentSourceCode);
+ }, engine);
+ }
+ };
+ _loadShader(vertexSource, "Vertex", "", (vertexCode) => {
+ Initialize(processorOptions);
+ Process(vertexCode, processorOptions, (migratedVertexCode, codeBeforeMigration) => {
+ if (effectContext) {
+ effectContext._rawVertexSourceCode = vertexCode;
+ effectContext._vertexSourceCodeBeforeMigration = codeBeforeMigration;
+ }
+ if (processFinalCode) {
+ migratedVertexCode = processFinalCode("vertex", migratedVertexCode);
+ }
+ shaderCodes[0] = migratedVertexCode;
+ shadersLoaded();
+ }, engine);
+ }, shaderLanguage);
+ _loadShader(fragmentSource, "Fragment", "Pixel", (fragmentCode) => {
+ if (effectContext) {
+ effectContext._rawFragmentSourceCode = fragmentCode;
+ }
+ shaderCodes[1] = fragmentCode;
+ shadersLoaded();
+ }, shaderLanguage);
+}
+function _loadShader(shader, key, optionalKey, callback, shaderLanguage, _loadFileInjection) {
+ if (typeof HTMLElement !== "undefined") {
+ // DOM element ?
+ if (shader instanceof HTMLElement) {
+ const shaderCode = GetDOMTextContent(shader);
+ callback(shaderCode);
+ return;
+ }
+ }
+ // Direct source ?
+ if (shader.substring(0, 7) === "source:") {
+ callback(shader.substring(7));
+ return;
+ }
+ // Base64 encoded ?
+ if (shader.substring(0, 7) === "base64:") {
+ const shaderBinary = window.atob(shader.substring(7));
+ callback(shaderBinary);
+ return;
+ }
+ const shaderStore = ShaderStore.GetShadersStore(shaderLanguage);
+ // Is in local store ?
+ if (shaderStore[shader + key + "Shader"]) {
+ callback(shaderStore[shader + key + "Shader"]);
+ return;
+ }
+ if (optionalKey && shaderStore[shader + optionalKey + "Shader"]) {
+ callback(shaderStore[shader + optionalKey + "Shader"]);
+ return;
+ }
+ let shaderUrl;
+ if (shader[0] === "." || shader[0] === "/" || shader.indexOf("http") > -1) {
+ shaderUrl = shader;
+ }
+ else {
+ shaderUrl = ShaderStore.GetShadersRepository(shaderLanguage) + shader;
+ }
+ _loadFileInjection = _loadFileInjection || _loadFile;
+ if (!_loadFileInjection) {
+ // we got to this point and loadFile was not injected - throw an error
+ throw new Error("loadFileInjection is not defined");
+ }
+ // Vertex shader
+ _loadFileInjection(shaderUrl + "." + key.toLowerCase() + ".fx", callback);
+}
+function _useFinalCode(migratedVertexCode, migratedFragmentCode, baseName, shaderLanguage) {
+ if (baseName) {
+ const vertex = baseName.vertexElement || baseName.vertex || baseName.spectorName || baseName;
+ const fragment = baseName.fragmentElement || baseName.fragment || baseName.spectorName || baseName;
+ return {
+ vertexSourceCode: (shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "//" : "") + "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode,
+ fragmentSourceCode: (shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? "//" : "") + "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode,
+ };
+ }
+ else {
+ return {
+ vertexSourceCode: migratedVertexCode,
+ fragmentSourceCode: migratedFragmentCode,
+ };
+ }
+}
+/**
+ * Creates and prepares a pipeline context
+ * @internal
+ */
+const createAndPreparePipelineContext = (options, createPipelineContext, _preparePipelineContext, _executeWhenRenderingStateIsCompiled) => {
+ try {
+ const stateObject = options.context ? getStateObject(options.context) : null;
+ if (stateObject) {
+ // will not remove the reference to parallelShaderPrecompile, but will prevent it from being used in the next shader compilation
+ stateObject.disableParallelShaderCompile = options.disableParallelCompilation;
+ }
+ const pipelineContext = options.existingPipelineContext || createPipelineContext(options.shaderProcessingContext);
+ pipelineContext._name = options.name;
+ if (options.name && stateObject) {
+ stateObject.cachedPipelines[options.name] = pipelineContext;
+ }
+ // Flagged as async as we may need to delay load some processing tools
+ // This does not break anything as the execution is waiting for _executeWhenRenderingStateIsCompiled
+ _preparePipelineContext(pipelineContext, options.vertex, options.fragment, !!options.createAsRaw, "", "", options.rebuildRebind, options.defines, options.transformFeedbackVaryings, "", () => {
+ _executeWhenRenderingStateIsCompiled(pipelineContext, () => {
+ options.onRenderingStateCompiled?.(pipelineContext);
+ });
+ });
+ return pipelineContext;
+ }
+ catch (e) {
+ Logger.Error("Error compiling effect");
+ throw e;
+ }
+};
+
+let _immediateQueue = [];
+/**
+ * Class used to provide helper for timing
+ */
+class TimingTools {
+ /**
+ * Execute a function after the current execution block
+ * @param action defines the action to execute after the current execution block
+ */
+ static SetImmediate(action) {
+ if (_immediateQueue.length === 0) {
+ setTimeout(() => {
+ // Execute all immediate functions
+ const functionsToCall = _immediateQueue;
+ _immediateQueue = [];
+ for (const func of functionsToCall) {
+ func();
+ }
+ }, 1);
+ }
+ _immediateQueue.push(action);
+ }
+}
+function _runWithCondition(condition, onSuccess, onError) {
+ try {
+ if (condition()) {
+ onSuccess();
+ return true;
+ }
+ }
+ catch (e) {
+ onError?.(e);
+ return true;
+ }
+ return false;
+}
+/**
+ * @internal
+ */
+const _retryWithInterval = (condition, onSuccess, onError, step = 16, maxTimeout = 30000, checkConditionOnCall = true, additionalStringOnTimeout) => {
+ // if checkConditionOnCall is true, we check the condition immediately. If it is true, run everything synchronously
+ if (checkConditionOnCall) {
+ // that means that one of the two happened - either the condition is true or an exception was thrown when checking the condition
+ if (_runWithCondition(condition, onSuccess, onError)) {
+ // don't schedule the interval, no reason to check it again.
+ return null;
+ }
+ }
+ const int = setInterval(() => {
+ if (_runWithCondition(condition, onSuccess, onError)) {
+ clearInterval(int);
+ }
+ else {
+ maxTimeout -= step;
+ if (maxTimeout < 0) {
+ clearInterval(int);
+ onError?.(new Error("Operation timed out after maximum retries. " + (additionalStringOnTimeout || "")), true);
+ }
+ }
+ }, step);
+ return () => clearInterval(int);
+};
+
+/**
+ * Effect containing vertex and fragment shader that can be executed on an object.
+ */
+class Effect {
+ /**
+ * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
+ */
+ static get ShadersRepository() {
+ return ShaderStore.ShadersRepository;
+ }
+ static set ShadersRepository(repo) {
+ ShaderStore.ShadersRepository = repo;
+ }
+ /**
+ * Gets a boolean indicating that the effect was already disposed
+ */
+ get isDisposed() {
+ return this._isDisposed;
+ }
+ /**
+ * Observable that will be called when effect is bound.
+ */
+ get onBindObservable() {
+ if (!this._onBindObservable) {
+ this._onBindObservable = new Observable();
+ }
+ return this._onBindObservable;
+ }
+ /**
+ * Gets the shader language type used to write vertex and fragment source code.
+ */
+ get shaderLanguage() {
+ return this._shaderLanguage;
+ }
+ /**
+ * Instantiates an effect.
+ * An effect can be used to create/manage/execute vertex and fragment shaders.
+ * @param baseName Name of the effect.
+ * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
+ * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
+ * @param samplers List of sampler variables that will be passed to the shader.
+ * @param engine Engine to be used to render the effect
+ * @param defines Define statements to be added to the shader.
+ * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
+ * @param onCompiled Callback that will be called when the shader is compiled.
+ * @param onError Callback that will be called if an error occurs during shader compilation.
+ * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. \{lights: 10\})
+ * @param key Effect Key identifying uniquely compiled shader variants
+ * @param shaderLanguage the language the shader is written in (default: GLSL)
+ * @param extraInitializationsAsync additional async code to run before preparing the effect
+ */
+ constructor(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers = null, engine, defines = null, fallbacks = null, onCompiled = null, onError = null, indexParameters, key = "", shaderLanguage = 0 /* ShaderLanguage.GLSL */, extraInitializationsAsync) {
+ /**
+ * String container all the define statements that should be set on the shader.
+ */
+ this.defines = "";
+ /**
+ * Callback that will be called when the shader is compiled.
+ */
+ this.onCompiled = null;
+ /**
+ * Callback that will be called if an error occurs during shader compilation.
+ */
+ this.onError = null;
+ /**
+ * Callback that will be called when effect is bound.
+ */
+ this.onBind = null;
+ /**
+ * Unique ID of the effect.
+ */
+ this.uniqueId = 0;
+ /**
+ * Observable that will be called when the shader is compiled.
+ * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
+ */
+ this.onCompileObservable = new Observable();
+ /**
+ * Observable that will be called if an error occurs during shader compilation.
+ */
+ this.onErrorObservable = new Observable();
+ /** @internal */
+ this._onBindObservable = null;
+ this._isDisposed = false;
+ /** @internal */
+ this._refCount = 1;
+ /** @internal */
+ this._bonesComputationForcedToCPU = false;
+ /** @internal */
+ this._uniformBuffersNames = {};
+ /** @internal */
+ this._multiTarget = false;
+ /** @internal */
+ this._samplers = {};
+ this._isReady = false;
+ this._compilationError = "";
+ this._allFallbacksProcessed = false;
+ /** @internal */
+ this._uniforms = {};
+ /**
+ * Key for the effect.
+ * @internal
+ */
+ this._key = "";
+ this._fallbacks = null;
+ this._vertexSourceCodeOverride = "";
+ this._fragmentSourceCodeOverride = "";
+ this._transformFeedbackVaryings = null;
+ this._disableParallelShaderCompilation = false;
+ /**
+ * Compiled shader to webGL program.
+ * @internal
+ */
+ this._pipelineContext = null;
+ /** @internal */
+ this._vertexSourceCode = "";
+ /** @internal */
+ this._fragmentSourceCode = "";
+ /** @internal */
+ this._vertexSourceCodeBeforeMigration = "";
+ /** @internal */
+ this._fragmentSourceCodeBeforeMigration = "";
+ /** @internal */
+ this._rawVertexSourceCode = "";
+ /** @internal */
+ this._rawFragmentSourceCode = "";
+ this._processCodeAfterIncludes = undefined;
+ this._processFinalCode = null;
+ this.name = baseName;
+ this._key = key;
+ const pipelineName = this._key.replace(/\r/g, "").replace(/\n/g, "|");
+ let cachedPipeline = undefined;
+ if (attributesNamesOrOptions.attributes) {
+ const options = attributesNamesOrOptions;
+ this._engine = uniformsNamesOrEngine;
+ this._attributesNames = options.attributes;
+ this._uniformsNames = options.uniformsNames.concat(options.samplers);
+ this._samplerList = options.samplers.slice();
+ this.defines = options.defines;
+ this.onError = options.onError;
+ this.onCompiled = options.onCompiled;
+ this._fallbacks = options.fallbacks;
+ this._indexParameters = options.indexParameters;
+ this._transformFeedbackVaryings = options.transformFeedbackVaryings || null;
+ this._multiTarget = !!options.multiTarget;
+ this._shaderLanguage = options.shaderLanguage ?? 0 /* ShaderLanguage.GLSL */;
+ this._disableParallelShaderCompilation = !!options.disableParallelShaderCompilation;
+ if (options.uniformBuffersNames) {
+ this._uniformBuffersNamesList = options.uniformBuffersNames.slice();
+ for (let i = 0; i < options.uniformBuffersNames.length; i++) {
+ this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
+ }
+ }
+ this._processFinalCode = options.processFinalCode ?? null;
+ this._processCodeAfterIncludes = options.processCodeAfterIncludes ?? undefined;
+ extraInitializationsAsync = options.extraInitializationsAsync;
+ cachedPipeline = options.existingPipelineContext;
+ }
+ else {
+ this._engine = engine;
+ this.defines = defines == null ? "" : defines;
+ this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
+ this._samplerList = samplers ? samplers.slice() : [];
+ this._attributesNames = attributesNamesOrOptions;
+ this._uniformBuffersNamesList = [];
+ this._shaderLanguage = shaderLanguage;
+ this.onError = onError;
+ this.onCompiled = onCompiled;
+ this._indexParameters = indexParameters;
+ this._fallbacks = fallbacks;
+ }
+ // Use the cache if we can. For now, WebGL2 only.
+ if (this._engine.shaderPlatformName === "WEBGL2") {
+ cachedPipeline = getCachedPipeline(pipelineName, this._engine._gl) ?? cachedPipeline;
+ }
+ this._attributeLocationByName = {};
+ this.uniqueId = Effect._UniqueIdSeed++;
+ if (!cachedPipeline) {
+ this._processShaderCodeAsync(null, false, null, extraInitializationsAsync);
+ }
+ else {
+ this._pipelineContext = cachedPipeline;
+ this._pipelineContext.setEngine(this._engine);
+ this._onRenderingStateCompiled(this._pipelineContext);
+ // rebuildRebind for spector
+ if (this._pipelineContext.program) {
+ this._pipelineContext.program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
+ }
+ }
+ this._engine.onReleaseEffectsObservable.addOnce(() => {
+ if (this.isDisposed) {
+ return;
+ }
+ this.dispose(true);
+ });
+ }
+ /** @internal */
+ async _processShaderCodeAsync(shaderProcessor = null, keepExistingPipelineContext = false, shaderProcessingContext = null, extraInitializationsAsync) {
+ if (extraInitializationsAsync) {
+ await extraInitializationsAsync();
+ }
+ this._processingContext = shaderProcessingContext || this._engine._getShaderProcessingContext(this._shaderLanguage, false);
+ const processorOptions = {
+ defines: this.defines.split("\n"),
+ indexParameters: this._indexParameters,
+ isFragment: false,
+ shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader,
+ processor: shaderProcessor ?? this._engine._getShaderProcessor(this._shaderLanguage),
+ supportsUniformBuffers: this._engine.supportsUniformBuffers,
+ shadersRepository: ShaderStore.GetShadersRepository(this._shaderLanguage),
+ includesShadersStore: ShaderStore.GetIncludesShadersStore(this._shaderLanguage),
+ version: (this._engine.version * 100).toString(),
+ platformName: this._engine.shaderPlatformName,
+ processingContext: this._processingContext,
+ isNDCHalfZRange: this._engine.isNDCHalfZRange,
+ useReverseDepthBuffer: this._engine.useReverseDepthBuffer,
+ processCodeAfterIncludes: this._processCodeAfterIncludes,
+ };
+ _processShaderCode(processorOptions, this.name, this._processFinalCode, (migratedVertexCode, migratedFragmentCode) => {
+ this._vertexSourceCode = migratedVertexCode;
+ this._fragmentSourceCode = migratedFragmentCode;
+ this._prepareEffect(keepExistingPipelineContext);
+ }, this._shaderLanguage, this._engine, this);
+ }
+ /**
+ * Unique key for this effect
+ */
+ get key() {
+ return this._key;
+ }
+ /**
+ * If the effect has been compiled and prepared.
+ * @returns if the effect is compiled and prepared.
+ */
+ isReady() {
+ try {
+ return this._isReadyInternal();
+ }
+ catch {
+ return false;
+ }
+ }
+ _isReadyInternal() {
+ if (this._engine.isDisposed) {
+ // Engine is disposed, we return true to prevent looping over the setTimeout call in _checkIsReady
+ return true;
+ }
+ if (this._isReady) {
+ return true;
+ }
+ if (this._pipelineContext) {
+ return this._pipelineContext.isReady;
+ }
+ return false;
+ }
+ /**
+ * The engine the effect was initialized with.
+ * @returns the engine.
+ */
+ getEngine() {
+ return this._engine;
+ }
+ /**
+ * The pipeline context for this effect
+ * @returns the associated pipeline context
+ */
+ getPipelineContext() {
+ return this._pipelineContext;
+ }
+ /**
+ * The set of names of attribute variables for the shader.
+ * @returns An array of attribute names.
+ */
+ getAttributesNames() {
+ return this._attributesNames;
+ }
+ /**
+ * Returns the attribute at the given index.
+ * @param index The index of the attribute.
+ * @returns The location of the attribute.
+ */
+ getAttributeLocation(index) {
+ return this._attributes[index];
+ }
+ /**
+ * Returns the attribute based on the name of the variable.
+ * @param name of the attribute to look up.
+ * @returns the attribute location.
+ */
+ getAttributeLocationByName(name) {
+ return this._attributeLocationByName[name];
+ }
+ /**
+ * The number of attributes.
+ * @returns the number of attributes.
+ */
+ getAttributesCount() {
+ return this._attributes.length;
+ }
+ /**
+ * Gets the index of a uniform variable.
+ * @param uniformName of the uniform to look up.
+ * @returns the index.
+ */
+ getUniformIndex(uniformName) {
+ return this._uniformsNames.indexOf(uniformName);
+ }
+ /**
+ * Returns the attribute based on the name of the variable.
+ * @param uniformName of the uniform to look up.
+ * @returns the location of the uniform.
+ */
+ getUniform(uniformName) {
+ return this._uniforms[uniformName];
+ }
+ /**
+ * Returns an array of sampler variable names
+ * @returns The array of sampler variable names.
+ */
+ getSamplers() {
+ return this._samplerList;
+ }
+ /**
+ * Returns an array of uniform variable names
+ * @returns The array of uniform variable names.
+ */
+ getUniformNames() {
+ return this._uniformsNames;
+ }
+ /**
+ * Returns an array of uniform buffer variable names
+ * @returns The array of uniform buffer variable names.
+ */
+ getUniformBuffersNames() {
+ return this._uniformBuffersNamesList;
+ }
+ /**
+ * Returns the index parameters used to create the effect
+ * @returns The index parameters object
+ */
+ getIndexParameters() {
+ return this._indexParameters;
+ }
+ /**
+ * The error from the last compilation.
+ * @returns the error string.
+ */
+ getCompilationError() {
+ return this._compilationError;
+ }
+ /**
+ * Gets a boolean indicating that all fallbacks were used during compilation
+ * @returns true if all fallbacks were used
+ */
+ allFallbacksProcessed() {
+ return this._allFallbacksProcessed;
+ }
+ /**
+ * Wait until compilation before fulfilling.
+ * @returns a promise to wait for completion.
+ */
+ whenCompiledAsync() {
+ return new Promise((resolve) => {
+ this.executeWhenCompiled(resolve);
+ });
+ }
+ /**
+ * Adds a callback to the onCompiled observable and call the callback immediately if already ready.
+ * @param func The callback to be used.
+ */
+ executeWhenCompiled(func) {
+ if (this.isReady()) {
+ func(this);
+ return;
+ }
+ this.onCompileObservable.add((effect) => {
+ func(effect);
+ });
+ if (!this._pipelineContext || this._pipelineContext.isAsync) {
+ this._checkIsReady(null);
+ }
+ }
+ _checkIsReady(previousPipelineContext) {
+ _retryWithInterval(() => {
+ return this._isReadyInternal() || this._isDisposed;
+ }, () => {
+ // no-op - done in the _isReadyInternal call
+ }, (e) => {
+ this._processCompilationErrors(e, previousPipelineContext);
+ }, 16, 120000, true, ` - Effect: ${typeof this.name === "string" ? this.name : this.key}`);
+ }
+ /**
+ * Gets the vertex shader source code of this effect
+ * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc)
+ */
+ get vertexSourceCode() {
+ return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride
+ ? this._vertexSourceCodeOverride
+ : (this._pipelineContext?._getVertexShaderCode() ?? this._vertexSourceCode);
+ }
+ /**
+ * Gets the fragment shader source code of this effect
+ * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc)
+ */
+ get fragmentSourceCode() {
+ return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride
+ ? this._fragmentSourceCodeOverride
+ : (this._pipelineContext?._getFragmentShaderCode() ?? this._fragmentSourceCode);
+ }
+ /**
+ * Gets the vertex shader source code before migration.
+ * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed.
+ * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL).
+ */
+ get vertexSourceCodeBeforeMigration() {
+ return this._vertexSourceCodeBeforeMigration;
+ }
+ /**
+ * Gets the fragment shader source code before migration.
+ * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed.
+ * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL).
+ */
+ get fragmentSourceCodeBeforeMigration() {
+ return this._fragmentSourceCodeBeforeMigration;
+ }
+ /**
+ * Gets the vertex shader source code before it has been modified by any processing
+ */
+ get rawVertexSourceCode() {
+ return this._rawVertexSourceCode;
+ }
+ /**
+ * Gets the fragment shader source code before it has been modified by any processing
+ */
+ get rawFragmentSourceCode() {
+ return this._rawFragmentSourceCode;
+ }
+ getPipelineGenerationOptions() {
+ return {
+ platformName: this._engine.shaderPlatformName,
+ shaderLanguage: this._shaderLanguage,
+ shaderNameOrContent: this.name,
+ key: this._key,
+ defines: this.defines.split("\n"),
+ addGlobalDefines: false,
+ extendedProcessingOptions: {
+ indexParameters: this._indexParameters,
+ isNDCHalfZRange: this._engine.isNDCHalfZRange,
+ useReverseDepthBuffer: this._engine.useReverseDepthBuffer,
+ supportsUniformBuffers: this._engine.supportsUniformBuffers,
+ },
+ extendedCreatePipelineOptions: {
+ transformFeedbackVaryings: this._transformFeedbackVaryings,
+ createAsRaw: !!(this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride),
+ },
+ };
+ }
+ /**
+ * Recompiles the webGL program
+ * @param vertexSourceCode The source code for the vertex shader.
+ * @param fragmentSourceCode The source code for the fragment shader.
+ * @param onCompiled Callback called when completed.
+ * @param onError Callback called on error.
+ * @internal
+ */
+ _rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
+ this._isReady = false;
+ this._vertexSourceCodeOverride = vertexSourceCode;
+ this._fragmentSourceCodeOverride = fragmentSourceCode;
+ this.onError = (effect, error) => {
+ if (onError) {
+ onError(error);
+ }
+ };
+ this.onCompiled = () => {
+ const scenes = this.getEngine().scenes;
+ if (scenes) {
+ for (let i = 0; i < scenes.length; i++) {
+ scenes[i].markAllMaterialsAsDirty(127);
+ }
+ }
+ this._pipelineContext._handlesSpectorRebuildCallback?.(onCompiled);
+ };
+ this._fallbacks = null;
+ this._prepareEffect();
+ }
+ _onRenderingStateCompiled(pipelineContext) {
+ this._pipelineContext = pipelineContext;
+ this._pipelineContext.setEngine(this._engine);
+ this._attributes = [];
+ this._pipelineContext._fillEffectInformation(this, this._uniformBuffersNames, this._uniformsNames, this._uniforms, this._samplerList, this._samplers, this._attributesNames, this._attributes);
+ // Caches attribute locations.
+ if (this._attributesNames) {
+ for (let i = 0; i < this._attributesNames.length; i++) {
+ const name = this._attributesNames[i];
+ this._attributeLocationByName[name] = this._attributes[i];
+ }
+ }
+ this._engine.bindSamplers(this);
+ this._compilationError = "";
+ this._isReady = true;
+ if (this.onCompiled) {
+ this.onCompiled(this);
+ }
+ this.onCompileObservable.notifyObservers(this);
+ this.onCompileObservable.clear();
+ // Unbind mesh reference in fallbacks
+ if (this._fallbacks) {
+ this._fallbacks.unBindMesh();
+ }
+ if (Effect.AutomaticallyClearCodeCache) {
+ this.clearCodeCache();
+ }
+ }
+ /**
+ * Prepares the effect
+ * @internal
+ */
+ _prepareEffect(keepExistingPipelineContext = false) {
+ const previousPipelineContext = this._pipelineContext;
+ this._isReady = false;
+ try {
+ const overrides = !!(this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride);
+ const defines = overrides ? null : this.defines;
+ const vertex = overrides ? this._vertexSourceCodeOverride : this._vertexSourceCode;
+ const fragment = overrides ? this._fragmentSourceCodeOverride : this._fragmentSourceCode;
+ const engine = this._engine;
+ this._pipelineContext = createAndPreparePipelineContext({
+ existingPipelineContext: keepExistingPipelineContext ? previousPipelineContext : null,
+ vertex,
+ fragment,
+ context: engine.shaderPlatformName === "WEBGL2" || engine.shaderPlatformName === "WEBGL1" ? engine._gl : undefined,
+ rebuildRebind: (vertexSourceCode, fragmentSourceCode, onCompiled, onError) => this._rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError),
+ defines,
+ transformFeedbackVaryings: this._transformFeedbackVaryings,
+ name: this._key.replace(/\r/g, "").replace(/\n/g, "|"),
+ createAsRaw: overrides,
+ disableParallelCompilation: this._disableParallelShaderCompilation,
+ shaderProcessingContext: this._processingContext,
+ onRenderingStateCompiled: (pipelineContext) => {
+ if (previousPipelineContext && !keepExistingPipelineContext) {
+ this._engine._deletePipelineContext(previousPipelineContext);
+ }
+ if (pipelineContext) {
+ this._onRenderingStateCompiled(pipelineContext);
+ }
+ },
+ }, this._engine.createPipelineContext.bind(this._engine), this._engine._preparePipelineContext.bind(this._engine), this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine));
+ if (this._pipelineContext.isAsync) {
+ this._checkIsReady(previousPipelineContext);
+ }
+ }
+ catch (e) {
+ this._processCompilationErrors(e, previousPipelineContext);
+ }
+ }
+ _getShaderCodeAndErrorLine(code, error, isFragment) {
+ const regexp = isFragment ? /FRAGMENT SHADER ERROR: 0:(\d+?):/ : /VERTEX SHADER ERROR: 0:(\d+?):/;
+ let errorLine = null;
+ if (error && code) {
+ const res = error.match(regexp);
+ if (res && res.length === 2) {
+ const lineNumber = parseInt(res[1]);
+ const lines = code.split("\n", -1);
+ if (lines.length >= lineNumber) {
+ errorLine = `Offending line [${lineNumber}] in ${isFragment ? "fragment" : "vertex"} code: ${lines[lineNumber - 1]}`;
+ }
+ }
+ }
+ return [code, errorLine];
+ }
+ _processCompilationErrors(e, previousPipelineContext = null) {
+ this._compilationError = e.message;
+ const attributesNames = this._attributesNames;
+ const fallbacks = this._fallbacks;
+ // Let's go through fallbacks then
+ Logger.Error("Unable to compile effect:");
+ Logger.Error("Uniforms: " +
+ this._uniformsNames.map(function (uniform) {
+ return " " + uniform;
+ }));
+ Logger.Error("Attributes: " +
+ attributesNames.map(function (attribute) {
+ return " " + attribute;
+ }));
+ Logger.Error("Defines:\n" + this.defines);
+ if (Effect.LogShaderCodeOnCompilationError) {
+ let lineErrorVertex = null, lineErrorFragment = null, code = null;
+ if (this._pipelineContext?._getVertexShaderCode()) {
+ [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, false);
+ if (code) {
+ Logger.Error("Vertex code:");
+ Logger.Error(code);
+ }
+ }
+ if (this._pipelineContext?._getFragmentShaderCode()) {
+ [code, lineErrorFragment] = this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(), this._compilationError, true);
+ if (code) {
+ Logger.Error("Fragment code:");
+ Logger.Error(code);
+ }
+ }
+ if (lineErrorVertex) {
+ Logger.Error(lineErrorVertex);
+ }
+ if (lineErrorFragment) {
+ Logger.Error(lineErrorFragment);
+ }
+ }
+ Logger.Error("Error: " + this._compilationError);
+ const notifyErrors = () => {
+ if (this.onError) {
+ this.onError(this, this._compilationError);
+ }
+ this.onErrorObservable.notifyObservers(this);
+ this._engine.onEffectErrorObservable.notifyObservers({ effect: this, errors: this._compilationError });
+ };
+ // In case a previous compilation was successful, we need to restore the previous pipeline context
+ if (previousPipelineContext) {
+ this._pipelineContext = previousPipelineContext;
+ this._isReady = true;
+ notifyErrors();
+ }
+ // Lets try to compile fallbacks as long as we have some.
+ if (fallbacks) {
+ this._pipelineContext = null;
+ if (fallbacks.hasMoreFallbacks) {
+ this._allFallbacksProcessed = false;
+ Logger.Error("Trying next fallback.");
+ this.defines = fallbacks.reduce(this.defines, this);
+ this._prepareEffect();
+ }
+ else {
+ // Sorry we did everything we can
+ this._allFallbacksProcessed = true;
+ notifyErrors();
+ this.onErrorObservable.clear();
+ // Unbind mesh reference in fallbacks
+ if (this._fallbacks) {
+ this._fallbacks.unBindMesh();
+ }
+ }
+ }
+ else {
+ this._allFallbacksProcessed = true;
+ // In case of error, without any prior successful compilation, let s notify observers
+ if (!previousPipelineContext) {
+ notifyErrors();
+ }
+ }
+ }
+ /**
+ * Checks if the effect is supported. (Must be called after compilation)
+ */
+ get isSupported() {
+ return this._compilationError === "";
+ }
+ /**
+ * Binds a texture to the engine to be used as output of the shader.
+ * @param channel Name of the output variable.
+ * @param texture Texture to bind.
+ * @internal
+ */
+ _bindTexture(channel, texture) {
+ this._engine._bindTexture(this._samplers[channel], texture, channel);
+ }
+ /**
+ * Sets a texture on the engine to be used in the shader.
+ * @param channel Name of the sampler variable.
+ * @param texture Texture to set.
+ */
+ setTexture(channel, texture) {
+ this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture, channel);
+ }
+ /**
+ * Sets an array of textures on the engine to be used in the shader.
+ * @param channel Name of the variable.
+ * @param textures Textures to set.
+ */
+ setTextureArray(channel, textures) {
+ const exName = channel + "Ex";
+ if (this._samplerList.indexOf(exName + "0") === -1) {
+ const initialPos = this._samplerList.indexOf(channel);
+ for (let index = 1; index < textures.length; index++) {
+ const currentExName = exName + (index - 1).toString();
+ this._samplerList.splice(initialPos + index, 0, currentExName);
+ }
+ // Reset every channels
+ let channelIndex = 0;
+ for (const key of this._samplerList) {
+ this._samplers[key] = channelIndex;
+ channelIndex += 1;
+ }
+ }
+ this._engine.setTextureArray(this._samplers[channel], this._uniforms[channel], textures, channel);
+ }
+ /**
+ * Binds a buffer to a uniform.
+ * @param buffer Buffer to bind.
+ * @param name Name of the uniform variable to bind to.
+ */
+ bindUniformBuffer(buffer, name) {
+ const bufferName = this._uniformBuffersNames[name];
+ if (bufferName === undefined || (Effect._BaseCache[bufferName] === buffer && this._engine._features.useUBOBindingCache)) {
+ return;
+ }
+ Effect._BaseCache[bufferName] = buffer;
+ this._engine.bindUniformBufferBase(buffer, bufferName, name);
+ }
+ /**
+ * Binds block to a uniform.
+ * @param blockName Name of the block to bind.
+ * @param index Index to bind.
+ */
+ bindUniformBlock(blockName, index) {
+ this._engine.bindUniformBlock(this._pipelineContext, blockName, index);
+ }
+ /**
+ * Sets an integer value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param value Value to be set.
+ * @returns this effect.
+ */
+ setInt(uniformName, value) {
+ this._pipelineContext.setInt(uniformName, value);
+ return this;
+ }
+ /**
+ * Sets an int2 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First int in int2.
+ * @param y Second int in int2.
+ * @returns this effect.
+ */
+ setInt2(uniformName, x, y) {
+ this._pipelineContext.setInt2(uniformName, x, y);
+ return this;
+ }
+ /**
+ * Sets an int3 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First int in int3.
+ * @param y Second int in int3.
+ * @param z Third int in int3.
+ * @returns this effect.
+ */
+ setInt3(uniformName, x, y, z) {
+ this._pipelineContext.setInt3(uniformName, x, y, z);
+ return this;
+ }
+ /**
+ * Sets an int4 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First int in int4.
+ * @param y Second int in int4.
+ * @param z Third int in int4.
+ * @param w Fourth int in int4.
+ * @returns this effect.
+ */
+ setInt4(uniformName, x, y, z, w) {
+ this._pipelineContext.setInt4(uniformName, x, y, z, w);
+ return this;
+ }
+ /**
+ * Sets an int array on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setIntArray(uniformName, array) {
+ this._pipelineContext.setIntArray(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setIntArray2(uniformName, array) {
+ this._pipelineContext.setIntArray2(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setIntArray3(uniformName, array) {
+ this._pipelineContext.setIntArray3(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setIntArray4(uniformName, array) {
+ this._pipelineContext.setIntArray4(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an unsigned integer value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param value Value to be set.
+ * @returns this effect.
+ */
+ setUInt(uniformName, value) {
+ this._pipelineContext.setUInt(uniformName, value);
+ return this;
+ }
+ /**
+ * Sets an unsigned int2 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First unsigned int in uint2.
+ * @param y Second unsigned int in uint2.
+ * @returns this effect.
+ */
+ setUInt2(uniformName, x, y) {
+ this._pipelineContext.setUInt2(uniformName, x, y);
+ return this;
+ }
+ /**
+ * Sets an unsigned int3 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First unsigned int in uint3.
+ * @param y Second unsigned int in uint3.
+ * @param z Third unsigned int in uint3.
+ * @returns this effect.
+ */
+ setUInt3(uniformName, x, y, z) {
+ this._pipelineContext.setUInt3(uniformName, x, y, z);
+ return this;
+ }
+ /**
+ * Sets an unsigned int4 value on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First unsigned int in uint4.
+ * @param y Second unsigned int in uint4.
+ * @param z Third unsigned int in uint4.
+ * @param w Fourth unsigned int in uint4.
+ * @returns this effect.
+ */
+ setUInt4(uniformName, x, y, z, w) {
+ this._pipelineContext.setUInt4(uniformName, x, y, z, w);
+ return this;
+ }
+ /**
+ * Sets an unsigned int array on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setUIntArray(uniformName, array) {
+ this._pipelineContext.setUIntArray(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setUIntArray2(uniformName, array) {
+ this._pipelineContext.setUIntArray2(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setUIntArray3(uniformName, array) {
+ this._pipelineContext.setUIntArray3(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setUIntArray4(uniformName, array) {
+ this._pipelineContext.setUIntArray4(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an float array on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setFloatArray(uniformName, array) {
+ this._pipelineContext.setArray(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setFloatArray2(uniformName, array) {
+ this._pipelineContext.setArray2(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setFloatArray3(uniformName, array) {
+ this._pipelineContext.setArray3(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setFloatArray4(uniformName, array) {
+ this._pipelineContext.setArray4(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an array on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setArray(uniformName, array) {
+ this._pipelineContext.setArray(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setArray2(uniformName, array) {
+ this._pipelineContext.setArray2(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setArray3(uniformName, array) {
+ this._pipelineContext.setArray3(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
+ * @param uniformName Name of the variable.
+ * @param array array to be set.
+ * @returns this effect.
+ */
+ setArray4(uniformName, array) {
+ this._pipelineContext.setArray4(uniformName, array);
+ return this;
+ }
+ /**
+ * Sets matrices on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param matrices matrices to be set.
+ * @returns this effect.
+ */
+ setMatrices(uniformName, matrices) {
+ this._pipelineContext.setMatrices(uniformName, matrices);
+ return this;
+ }
+ /**
+ * Sets matrix on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param matrix matrix to be set.
+ * @returns this effect.
+ */
+ setMatrix(uniformName, matrix) {
+ this._pipelineContext.setMatrix(uniformName, matrix);
+ return this;
+ }
+ /**
+ * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
+ * @param uniformName Name of the variable.
+ * @param matrix matrix to be set.
+ * @returns this effect.
+ */
+ setMatrix3x3(uniformName, matrix) {
+ // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array
+ this._pipelineContext.setMatrix3x3(uniformName, matrix);
+ return this;
+ }
+ /**
+ * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)
+ * @param uniformName Name of the variable.
+ * @param matrix matrix to be set.
+ * @returns this effect.
+ */
+ setMatrix2x2(uniformName, matrix) {
+ // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array
+ this._pipelineContext.setMatrix2x2(uniformName, matrix);
+ return this;
+ }
+ /**
+ * Sets a float on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param value value to be set.
+ * @returns this effect.
+ */
+ setFloat(uniformName, value) {
+ this._pipelineContext.setFloat(uniformName, value);
+ return this;
+ }
+ /**
+ * Sets a boolean on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param bool value to be set.
+ * @returns this effect.
+ */
+ setBool(uniformName, bool) {
+ this._pipelineContext.setInt(uniformName, bool ? 1 : 0);
+ return this;
+ }
+ /**
+ * Sets a Vector2 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param vector2 vector2 to be set.
+ * @returns this effect.
+ */
+ setVector2(uniformName, vector2) {
+ this._pipelineContext.setVector2(uniformName, vector2);
+ return this;
+ }
+ /**
+ * Sets a float2 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First float in float2.
+ * @param y Second float in float2.
+ * @returns this effect.
+ */
+ setFloat2(uniformName, x, y) {
+ this._pipelineContext.setFloat2(uniformName, x, y);
+ return this;
+ }
+ /**
+ * Sets a Vector3 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param vector3 Value to be set.
+ * @returns this effect.
+ */
+ setVector3(uniformName, vector3) {
+ this._pipelineContext.setVector3(uniformName, vector3);
+ return this;
+ }
+ /**
+ * Sets a float3 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First float in float3.
+ * @param y Second float in float3.
+ * @param z Third float in float3.
+ * @returns this effect.
+ */
+ setFloat3(uniformName, x, y, z) {
+ this._pipelineContext.setFloat3(uniformName, x, y, z);
+ return this;
+ }
+ /**
+ * Sets a Vector4 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param vector4 Value to be set.
+ * @returns this effect.
+ */
+ setVector4(uniformName, vector4) {
+ this._pipelineContext.setVector4(uniformName, vector4);
+ return this;
+ }
+ /**
+ * Sets a Quaternion on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param quaternion Value to be set.
+ * @returns this effect.
+ */
+ setQuaternion(uniformName, quaternion) {
+ this._pipelineContext.setQuaternion(uniformName, quaternion);
+ return this;
+ }
+ /**
+ * Sets a float4 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param x First float in float4.
+ * @param y Second float in float4.
+ * @param z Third float in float4.
+ * @param w Fourth float in float4.
+ * @returns this effect.
+ */
+ setFloat4(uniformName, x, y, z, w) {
+ this._pipelineContext.setFloat4(uniformName, x, y, z, w);
+ return this;
+ }
+ /**
+ * Sets a Color3 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param color3 Value to be set.
+ * @returns this effect.
+ */
+ setColor3(uniformName, color3) {
+ this._pipelineContext.setColor3(uniformName, color3);
+ return this;
+ }
+ /**
+ * Sets a Color4 on a uniform variable.
+ * @param uniformName Name of the variable.
+ * @param color3 Value to be set.
+ * @param alpha Alpha value to be set.
+ * @returns this effect.
+ */
+ setColor4(uniformName, color3, alpha) {
+ this._pipelineContext.setColor4(uniformName, color3, alpha);
+ return this;
+ }
+ /**
+ * Sets a Color4 on a uniform variable
+ * @param uniformName defines the name of the variable
+ * @param color4 defines the value to be set
+ * @returns this effect.
+ */
+ setDirectColor4(uniformName, color4) {
+ this._pipelineContext.setDirectColor4(uniformName, color4);
+ return this;
+ }
+ /**
+ * Use this wisely: It will remove the cached code from this effect
+ * It is probably ok to call it if you are not using ShadowDepthWrapper or if everything is already up and running
+ * DO NOT CALL IT if you want to have support for context lost recovery
+ */
+ clearCodeCache() {
+ this._vertexSourceCode = "";
+ this._fragmentSourceCode = "";
+ this._fragmentSourceCodeBeforeMigration = "";
+ this._vertexSourceCodeBeforeMigration = "";
+ }
+ /**
+ * Release all associated resources.
+ * @param force specifies if the effect must be released no matter what
+ **/
+ dispose(force = false) {
+ if (force) {
+ this._refCount = 0;
+ }
+ else {
+ if (Effect.PersistentMode) {
+ return;
+ }
+ this._refCount--;
+ }
+ if (this._refCount > 0 || this._isDisposed) {
+ // Others are still using the effect or the effect was already disposed
+ return;
+ }
+ if (this._pipelineContext) {
+ resetCachedPipeline(this._pipelineContext);
+ }
+ this._engine._releaseEffect(this);
+ this.clearCodeCache();
+ this._isDisposed = true;
+ }
+ /**
+ * This function will add a new shader to the shader store
+ * @param name the name of the shader
+ * @param pixelShader optional pixel shader content
+ * @param vertexShader optional vertex shader content
+ * @param shaderLanguage the language the shader is written in (default: GLSL)
+ */
+ static RegisterShader(name, pixelShader, vertexShader, shaderLanguage = 0 /* ShaderLanguage.GLSL */) {
+ if (pixelShader) {
+ ShaderStore.GetShadersStore(shaderLanguage)[`${name}PixelShader`] = pixelShader;
+ }
+ if (vertexShader) {
+ ShaderStore.GetShadersStore(shaderLanguage)[`${name}VertexShader`] = vertexShader;
+ }
+ }
+ /**
+ * Resets the cache of effects.
+ */
+ static ResetCache() {
+ Effect._BaseCache = {};
+ }
+}
+/**
+ * Enable logging of the shader code when a compilation error occurs
+ */
+Effect.LogShaderCodeOnCompilationError = true;
+/**
+ * Gets or sets a boolean indicating that effect ref counting is disabled
+ * If true, the effect will persist in memory until engine is disposed
+ */
+Effect.PersistentMode = false;
+/**
+ * Use this with caution
+ * See ClearCodeCache function comments
+ */
+Effect.AutomaticallyClearCodeCache = false;
+Effect._UniqueIdSeed = 0;
+Effect._BaseCache = {};
+/**
+ * Store of each shader (The can be looked up using effect.key)
+ */
+Effect.ShadersStore = ShaderStore.ShadersStore;
+/**
+ * Store of each included file for a shader (The can be looked up using effect.key)
+ */
+Effect.IncludesShadersStore = ShaderStore.IncludesShadersStore;
+
+/** @internal */
+class PerformanceConfigurator {
+ /**
+ * @internal
+ */
+ static SetMatrixPrecision(use64bits) {
+ PerformanceConfigurator.MatrixTrackPrecisionChange = false;
+ if (use64bits && !PerformanceConfigurator.MatrixUse64Bits) {
+ if (PerformanceConfigurator.MatrixTrackedMatrices) {
+ for (let m = 0; m < PerformanceConfigurator.MatrixTrackedMatrices.length; ++m) {
+ const matrix = PerformanceConfigurator.MatrixTrackedMatrices[m];
+ const values = matrix._m;
+ matrix._m = new Array(16);
+ for (let i = 0; i < 16; ++i) {
+ matrix._m[i] = values[i];
+ }
+ }
+ }
+ }
+ PerformanceConfigurator.MatrixUse64Bits = use64bits;
+ PerformanceConfigurator.MatrixCurrentType = PerformanceConfigurator.MatrixUse64Bits ? Array : Float32Array;
+ PerformanceConfigurator.MatrixTrackedMatrices = null; // reclaim some memory, as we don't need _TrackedMatrices anymore
+ }
+}
+/** @internal */
+PerformanceConfigurator.MatrixUse64Bits = false;
+/** @internal */
+PerformanceConfigurator.MatrixTrackPrecisionChange = true;
+/** @internal */
+PerformanceConfigurator.MatrixCurrentType = Float32Array;
+/** @internal */
+PerformanceConfigurator.MatrixTrackedMatrices = [];
+
+/**
+ * Class containing a set of static utilities functions for precision date
+ */
+class PrecisionDate {
+ /**
+ * Gets either window.performance.now() if supported or Date.now() else
+ */
+ static get Now() {
+ if (IsWindowObjectExist() && window.performance && window.performance.now) {
+ return window.performance.now();
+ }
+ return Date.now();
+ }
+}
+
+/**
+ * @internal
+ **/
+class DepthCullingState {
+ /**
+ * Initializes the state.
+ * @param reset
+ */
+ constructor(reset = true) {
+ this._isDepthTestDirty = false;
+ this._isDepthMaskDirty = false;
+ this._isDepthFuncDirty = false;
+ this._isCullFaceDirty = false;
+ this._isCullDirty = false;
+ this._isZOffsetDirty = false;
+ this._isFrontFaceDirty = false;
+ if (reset) {
+ this.reset();
+ }
+ }
+ get isDirty() {
+ return (this._isDepthFuncDirty ||
+ this._isDepthTestDirty ||
+ this._isDepthMaskDirty ||
+ this._isCullFaceDirty ||
+ this._isCullDirty ||
+ this._isZOffsetDirty ||
+ this._isFrontFaceDirty);
+ }
+ get zOffset() {
+ return this._zOffset;
+ }
+ set zOffset(value) {
+ if (this._zOffset === value) {
+ return;
+ }
+ this._zOffset = value;
+ this._isZOffsetDirty = true;
+ }
+ get zOffsetUnits() {
+ return this._zOffsetUnits;
+ }
+ set zOffsetUnits(value) {
+ if (this._zOffsetUnits === value) {
+ return;
+ }
+ this._zOffsetUnits = value;
+ this._isZOffsetDirty = true;
+ }
+ get cullFace() {
+ return this._cullFace;
+ }
+ set cullFace(value) {
+ if (this._cullFace === value) {
+ return;
+ }
+ this._cullFace = value;
+ this._isCullFaceDirty = true;
+ }
+ get cull() {
+ return this._cull;
+ }
+ set cull(value) {
+ if (this._cull === value) {
+ return;
+ }
+ this._cull = value;
+ this._isCullDirty = true;
+ }
+ get depthFunc() {
+ return this._depthFunc;
+ }
+ set depthFunc(value) {
+ if (this._depthFunc === value) {
+ return;
+ }
+ this._depthFunc = value;
+ this._isDepthFuncDirty = true;
+ }
+ get depthMask() {
+ return this._depthMask;
+ }
+ set depthMask(value) {
+ if (this._depthMask === value) {
+ return;
+ }
+ this._depthMask = value;
+ this._isDepthMaskDirty = true;
+ }
+ get depthTest() {
+ return this._depthTest;
+ }
+ set depthTest(value) {
+ if (this._depthTest === value) {
+ return;
+ }
+ this._depthTest = value;
+ this._isDepthTestDirty = true;
+ }
+ get frontFace() {
+ return this._frontFace;
+ }
+ set frontFace(value) {
+ if (this._frontFace === value) {
+ return;
+ }
+ this._frontFace = value;
+ this._isFrontFaceDirty = true;
+ }
+ reset() {
+ this._depthMask = true;
+ this._depthTest = true;
+ this._depthFunc = null;
+ this._cullFace = null;
+ this._cull = null;
+ this._zOffset = 0;
+ this._zOffsetUnits = 0;
+ this._frontFace = null;
+ this._isDepthTestDirty = true;
+ this._isDepthMaskDirty = true;
+ this._isDepthFuncDirty = false;
+ this._isCullFaceDirty = false;
+ this._isCullDirty = false;
+ this._isZOffsetDirty = true;
+ this._isFrontFaceDirty = false;
+ }
+ apply(gl) {
+ if (!this.isDirty) {
+ return;
+ }
+ // Cull
+ if (this._isCullDirty) {
+ if (this.cull) {
+ gl.enable(gl.CULL_FACE);
+ }
+ else {
+ gl.disable(gl.CULL_FACE);
+ }
+ this._isCullDirty = false;
+ }
+ // Cull face
+ if (this._isCullFaceDirty) {
+ gl.cullFace(this.cullFace);
+ this._isCullFaceDirty = false;
+ }
+ // Depth mask
+ if (this._isDepthMaskDirty) {
+ gl.depthMask(this.depthMask);
+ this._isDepthMaskDirty = false;
+ }
+ // Depth test
+ if (this._isDepthTestDirty) {
+ if (this.depthTest) {
+ gl.enable(gl.DEPTH_TEST);
+ }
+ else {
+ gl.disable(gl.DEPTH_TEST);
+ }
+ this._isDepthTestDirty = false;
+ }
+ // Depth func
+ if (this._isDepthFuncDirty) {
+ gl.depthFunc(this.depthFunc);
+ this._isDepthFuncDirty = false;
+ }
+ // zOffset
+ if (this._isZOffsetDirty) {
+ if (this.zOffset || this.zOffsetUnits) {
+ gl.enable(gl.POLYGON_OFFSET_FILL);
+ gl.polygonOffset(this.zOffset, this.zOffsetUnits);
+ }
+ else {
+ gl.disable(gl.POLYGON_OFFSET_FILL);
+ }
+ this._isZOffsetDirty = false;
+ }
+ // Front face
+ if (this._isFrontFaceDirty) {
+ gl.frontFace(this.frontFace);
+ this._isFrontFaceDirty = false;
+ }
+ }
+}
+
+/**
+ * @internal
+ **/
+class StencilStateComposer {
+ get isDirty() {
+ return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
+ }
+ get func() {
+ return this._func;
+ }
+ set func(value) {
+ if (this._func === value) {
+ return;
+ }
+ this._func = value;
+ this._isStencilFuncDirty = true;
+ }
+ get funcRef() {
+ return this._funcRef;
+ }
+ set funcRef(value) {
+ if (this._funcRef === value) {
+ return;
+ }
+ this._funcRef = value;
+ this._isStencilFuncDirty = true;
+ }
+ get funcMask() {
+ return this._funcMask;
+ }
+ set funcMask(value) {
+ if (this._funcMask === value) {
+ return;
+ }
+ this._funcMask = value;
+ this._isStencilFuncDirty = true;
+ }
+ get opStencilFail() {
+ return this._opStencilFail;
+ }
+ set opStencilFail(value) {
+ if (this._opStencilFail === value) {
+ return;
+ }
+ this._opStencilFail = value;
+ this._isStencilOpDirty = true;
+ }
+ get opDepthFail() {
+ return this._opDepthFail;
+ }
+ set opDepthFail(value) {
+ if (this._opDepthFail === value) {
+ return;
+ }
+ this._opDepthFail = value;
+ this._isStencilOpDirty = true;
+ }
+ get opStencilDepthPass() {
+ return this._opStencilDepthPass;
+ }
+ set opStencilDepthPass(value) {
+ if (this._opStencilDepthPass === value) {
+ return;
+ }
+ this._opStencilDepthPass = value;
+ this._isStencilOpDirty = true;
+ }
+ get mask() {
+ return this._mask;
+ }
+ set mask(value) {
+ if (this._mask === value) {
+ return;
+ }
+ this._mask = value;
+ this._isStencilMaskDirty = true;
+ }
+ get enabled() {
+ return this._enabled;
+ }
+ set enabled(value) {
+ if (this._enabled === value) {
+ return;
+ }
+ this._enabled = value;
+ this._isStencilTestDirty = true;
+ }
+ constructor(reset = true) {
+ this._isStencilTestDirty = false;
+ this._isStencilMaskDirty = false;
+ this._isStencilFuncDirty = false;
+ this._isStencilOpDirty = false;
+ this.useStencilGlobalOnly = false;
+ if (reset) {
+ this.reset();
+ }
+ }
+ reset() {
+ this.stencilMaterial = undefined;
+ this.stencilGlobal?.reset();
+ this._isStencilTestDirty = true;
+ this._isStencilMaskDirty = true;
+ this._isStencilFuncDirty = true;
+ this._isStencilOpDirty = true;
+ }
+ apply(gl) {
+ if (!gl) {
+ return;
+ }
+ const stencilMaterialEnabled = !this.useStencilGlobalOnly && !!this.stencilMaterial?.enabled;
+ this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled;
+ this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func;
+ this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef;
+ this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask;
+ this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail;
+ this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail;
+ this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass;
+ this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask;
+ if (!this.isDirty) {
+ return;
+ }
+ // Stencil test
+ if (this._isStencilTestDirty) {
+ if (this.enabled) {
+ gl.enable(gl.STENCIL_TEST);
+ }
+ else {
+ gl.disable(gl.STENCIL_TEST);
+ }
+ this._isStencilTestDirty = false;
+ }
+ // Stencil mask
+ if (this._isStencilMaskDirty) {
+ gl.stencilMask(this.mask);
+ this._isStencilMaskDirty = false;
+ }
+ // Stencil func
+ if (this._isStencilFuncDirty) {
+ gl.stencilFunc(this.func, this.funcRef, this.funcMask);
+ this._isStencilFuncDirty = false;
+ }
+ // Stencil op
+ if (this._isStencilOpDirty) {
+ gl.stencilOp(this.opStencilFail, this.opDepthFail, this.opStencilDepthPass);
+ this._isStencilOpDirty = false;
+ }
+ }
+}
+
+/**
+ * @internal
+ **/
+class StencilState {
+ constructor() {
+ this.reset();
+ }
+ reset() {
+ this.enabled = false;
+ this.mask = 0xff;
+ this.func = StencilState.ALWAYS;
+ this.funcRef = 1;
+ this.funcMask = 0xff;
+ this.opStencilFail = StencilState.KEEP;
+ this.opDepthFail = StencilState.KEEP;
+ this.opStencilDepthPass = StencilState.REPLACE;
+ }
+ get stencilFunc() {
+ return this.func;
+ }
+ set stencilFunc(value) {
+ this.func = value;
+ }
+ get stencilFuncRef() {
+ return this.funcRef;
+ }
+ set stencilFuncRef(value) {
+ this.funcRef = value;
+ }
+ get stencilFuncMask() {
+ return this.funcMask;
+ }
+ set stencilFuncMask(value) {
+ this.funcMask = value;
+ }
+ get stencilOpStencilFail() {
+ return this.opStencilFail;
+ }
+ set stencilOpStencilFail(value) {
+ this.opStencilFail = value;
+ }
+ get stencilOpDepthFail() {
+ return this.opDepthFail;
+ }
+ set stencilOpDepthFail(value) {
+ this.opDepthFail = value;
+ }
+ get stencilOpStencilDepthPass() {
+ return this.opStencilDepthPass;
+ }
+ set stencilOpStencilDepthPass(value) {
+ this.opStencilDepthPass = value;
+ }
+ get stencilMask() {
+ return this.mask;
+ }
+ set stencilMask(value) {
+ this.mask = value;
+ }
+ get stencilTest() {
+ return this.enabled;
+ }
+ set stencilTest(value) {
+ this.enabled = value;
+ }
+}
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
+StencilState.ALWAYS = 519;
+/** Passed to stencilOperation to specify that stencil value must be kept */
+StencilState.KEEP = 7680;
+/** Passed to stencilOperation to specify that stencil value must be replaced */
+StencilState.REPLACE = 7681;
+
+/**
+ * @internal
+ **/
+class AlphaState {
+ /**
+ * Initializes the state.
+ */
+ constructor() {
+ this._blendFunctionParameters = new Array(4);
+ this._blendEquationParameters = new Array(2);
+ this._blendConstants = new Array(4);
+ this._isBlendConstantsDirty = false;
+ this._alphaBlend = false;
+ this._isAlphaBlendDirty = false;
+ this._isBlendFunctionParametersDirty = false;
+ this._isBlendEquationParametersDirty = false;
+ this.reset();
+ }
+ get isDirty() {
+ return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty;
+ }
+ get alphaBlend() {
+ return this._alphaBlend;
+ }
+ set alphaBlend(value) {
+ if (this._alphaBlend === value) {
+ return;
+ }
+ this._alphaBlend = value;
+ this._isAlphaBlendDirty = true;
+ }
+ setAlphaBlendConstants(r, g, b, a) {
+ if (this._blendConstants[0] === r && this._blendConstants[1] === g && this._blendConstants[2] === b && this._blendConstants[3] === a) {
+ return;
+ }
+ this._blendConstants[0] = r;
+ this._blendConstants[1] = g;
+ this._blendConstants[2] = b;
+ this._blendConstants[3] = a;
+ this._isBlendConstantsDirty = true;
+ }
+ setAlphaBlendFunctionParameters(value0, value1, value2, value3) {
+ if (this._blendFunctionParameters[0] === value0 &&
+ this._blendFunctionParameters[1] === value1 &&
+ this._blendFunctionParameters[2] === value2 &&
+ this._blendFunctionParameters[3] === value3) {
+ return;
+ }
+ this._blendFunctionParameters[0] = value0;
+ this._blendFunctionParameters[1] = value1;
+ this._blendFunctionParameters[2] = value2;
+ this._blendFunctionParameters[3] = value3;
+ this._isBlendFunctionParametersDirty = true;
+ }
+ setAlphaEquationParameters(rgb, alpha) {
+ if (this._blendEquationParameters[0] === rgb && this._blendEquationParameters[1] === alpha) {
+ return;
+ }
+ this._blendEquationParameters[0] = rgb;
+ this._blendEquationParameters[1] = alpha;
+ this._isBlendEquationParametersDirty = true;
+ }
+ reset() {
+ this._alphaBlend = false;
+ this._blendFunctionParameters[0] = null;
+ this._blendFunctionParameters[1] = null;
+ this._blendFunctionParameters[2] = null;
+ this._blendFunctionParameters[3] = null;
+ this._blendEquationParameters[0] = null;
+ this._blendEquationParameters[1] = null;
+ this._blendConstants[0] = null;
+ this._blendConstants[1] = null;
+ this._blendConstants[2] = null;
+ this._blendConstants[3] = null;
+ this._isAlphaBlendDirty = true;
+ this._isBlendFunctionParametersDirty = false;
+ this._isBlendEquationParametersDirty = false;
+ this._isBlendConstantsDirty = false;
+ }
+ apply(gl) {
+ if (!this.isDirty) {
+ return;
+ }
+ // Alpha blend
+ if (this._isAlphaBlendDirty) {
+ if (this._alphaBlend) {
+ gl.enable(gl.BLEND);
+ }
+ else {
+ gl.disable(gl.BLEND);
+ }
+ this._isAlphaBlendDirty = false;
+ }
+ // Alpha function
+ if (this._isBlendFunctionParametersDirty) {
+ gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
+ this._isBlendFunctionParametersDirty = false;
+ }
+ // Alpha equation
+ if (this._isBlendEquationParametersDirty) {
+ gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
+ this._isBlendEquationParametersDirty = false;
+ }
+ // Constants
+ if (this._isBlendConstantsDirty) {
+ gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
+ this._isBlendConstantsDirty = false;
+ }
+ }
+}
+
+const _registeredTextureLoaders = new Map();
+/**
+ * Registers a texture loader.
+ * If a loader for the extension exists in the registry, it will be replaced.
+ * @param extension The name of the loader extension.
+ * @param loaderFactory The factory function that creates the loader extension.
+ */
+function registerTextureLoader(extension, loaderFactory) {
+ if (unregisterTextureLoader(extension)) {
+ Logger.Warn(`Extension with the name '${name}' already exists`);
+ }
+ _registeredTextureLoaders.set(extension, loaderFactory);
+}
+/**
+ * Unregisters a texture loader.
+ * @param extension The name of the loader extension.
+ * @returns A boolean indicating whether the extension has been unregistered
+ */
+function unregisterTextureLoader(extension) {
+ return _registeredTextureLoaders.delete(extension);
+}
+/**
+ * Function used to get the correct texture loader for a specific extension.
+ * @param extension defines the file extension of the file being loaded
+ * @param mimeType defines the optional mime type of the file being loaded
+ * @returns the IInternalTextureLoader or null if it wasn't found
+ */
+function _GetCompatibleTextureLoader(extension, mimeType) {
+ if (mimeType === "image/ktx" || mimeType === "image/ktx2") {
+ extension = ".ktx";
+ }
+ if (!_registeredTextureLoaders.has(extension)) {
+ if (extension.endsWith(".ies")) {
+ registerTextureLoader(".ies", () => Promise.resolve().then(() => iesTextureLoader).then((module) => new module._IESTextureLoader()));
+ }
+ if (extension.endsWith(".dds")) {
+ registerTextureLoader(".dds", () => Promise.resolve().then(() => ddsTextureLoader).then((module) => new module._DDSTextureLoader()));
+ }
+ if (extension.endsWith(".basis")) {
+ registerTextureLoader(".basis", () => Promise.resolve().then(() => basisTextureLoader).then((module) => new module._BasisTextureLoader()));
+ }
+ if (extension.endsWith(".env")) {
+ registerTextureLoader(".env", () => Promise.resolve().then(() => envTextureLoader).then((module) => new module._ENVTextureLoader()));
+ }
+ if (extension.endsWith(".hdr")) {
+ registerTextureLoader(".hdr", () => Promise.resolve().then(() => hdrTextureLoader).then((module) => new module._HDRTextureLoader()));
+ }
+ // The ".ktx2" file extension is still up for debate: https://github.com/KhronosGroup/KTX-Specification/issues/18
+ if (extension.endsWith(".ktx") || extension.endsWith(".ktx2")) {
+ registerTextureLoader(".ktx", () => Promise.resolve().then(() => ktxTextureLoader).then((module) => new module._KTXTextureLoader()));
+ registerTextureLoader(".ktx2", () => Promise.resolve().then(() => ktxTextureLoader).then((module) => new module._KTXTextureLoader()));
+ }
+ if (extension.endsWith(".tga")) {
+ registerTextureLoader(".tga", () => Promise.resolve().then(() => tgaTextureLoader).then((module) => new module._TGATextureLoader()));
+ }
+ if (extension.endsWith(".exr")) {
+ registerTextureLoader(".exr", () => Promise.resolve().then(() => exrTextureLoader).then((module) => new module._ExrTextureLoader()));
+ }
+ }
+ const registered = _registeredTextureLoaders.get(extension);
+ return registered ? Promise.resolve(registered(mimeType)) : null;
+}
+
+/**
+ * Queue a new function into the requested animation frame pool (ie. this function will be executed by the browser (or the javascript engine) for the next frame)
+ * @param func - the function to be called
+ * @param requester - the object that will request the next frame. Falls back to window.
+ * @returns frame number
+ */
+function QueueNewFrame(func, requester) {
+ // Note that there is kind of a typing issue here, as `setTimeout` might return something else than a number (NodeJs returns a NodeJS.Timeout object).
+ // Also if the global `requestAnimationFrame`'s returnType is number, `requester.requestPostAnimationFrame` and `requester.requestAnimationFrame` types
+ // are `any`.
+ if (!IsWindowObjectExist()) {
+ if (typeof requestAnimationFrame === "function") {
+ return requestAnimationFrame(func);
+ }
+ }
+ else {
+ const { requestAnimationFrame } = requester || window;
+ if (typeof requestAnimationFrame === "function") {
+ return requestAnimationFrame(func);
+ }
+ }
+ // fallback to the global `setTimeout`.
+ // In most cases (aka in the browser), `window` is the global object, so instead of calling `window.setTimeout` we could call the global `setTimeout`.
+ return setTimeout(func, 16);
+}
+/**
+ * The parent class for specialized engines (WebGL, WebGPU)
+ */
+class AbstractEngine {
+ /**
+ * Gets the current frame id
+ */
+ get frameId() {
+ return this._frameId;
+ }
+ /**
+ * Gets a boolean indicating if the engine runs in WebGPU or not.
+ */
+ get isWebGPU() {
+ return this._isWebGPU;
+ }
+ /**
+ * @internal
+ */
+ _getShaderProcessor(shaderLanguage) {
+ return this._shaderProcessor;
+ }
+ /**
+ * Gets the shader platform name used by the effects.
+ */
+ get shaderPlatformName() {
+ return this._shaderPlatformName;
+ }
+ _clearEmptyResources() {
+ this._emptyTexture = null;
+ this._emptyCubeTexture = null;
+ this._emptyTexture3D = null;
+ this._emptyTexture2DArray = null;
+ }
+ /**
+ * Gets or sets a boolean indicating if depth buffer should be reverse, going from far to near.
+ * This can provide greater z depth for distant objects.
+ */
+ get useReverseDepthBuffer() {
+ return this._useReverseDepthBuffer;
+ }
+ set useReverseDepthBuffer(useReverse) {
+ if (useReverse === this._useReverseDepthBuffer) {
+ return;
+ }
+ this._useReverseDepthBuffer = useReverse;
+ if (useReverse) {
+ this._depthCullingState.depthFunc = 518;
+ }
+ else {
+ this._depthCullingState.depthFunc = 515;
+ }
+ }
+ /**
+ * Enable or disable color writing
+ * @param enable defines the state to set
+ */
+ setColorWrite(enable) {
+ if (enable !== this._colorWrite) {
+ this._colorWriteChanged = true;
+ this._colorWrite = enable;
+ }
+ }
+ /**
+ * Gets a boolean indicating if color writing is enabled
+ * @returns the current color writing state
+ */
+ getColorWrite() {
+ return this._colorWrite;
+ }
+ /**
+ * Gets the depth culling state manager
+ */
+ get depthCullingState() {
+ return this._depthCullingState;
+ }
+ /**
+ * Gets the alpha state manager
+ */
+ get alphaState() {
+ return this._alphaState;
+ }
+ /**
+ * Gets the stencil state manager
+ */
+ get stencilState() {
+ return this._stencilState;
+ }
+ /**
+ * Gets the stencil state composer
+ */
+ get stencilStateComposer() {
+ return this._stencilStateComposer;
+ }
+ /** @internal */
+ _getGlobalDefines(defines) {
+ if (defines) {
+ if (this.isNDCHalfZRange) {
+ defines["IS_NDC_HALF_ZRANGE"] = "";
+ }
+ else {
+ delete defines["IS_NDC_HALF_ZRANGE"];
+ }
+ if (this.useReverseDepthBuffer) {
+ defines["USE_REVERSE_DEPTHBUFFER"] = "";
+ }
+ else {
+ delete defines["USE_REVERSE_DEPTHBUFFER"];
+ }
+ if (this.useExactSrgbConversions) {
+ defines["USE_EXACT_SRGB_CONVERSIONS"] = "";
+ }
+ else {
+ delete defines["USE_EXACT_SRGB_CONVERSIONS"];
+ }
+ return;
+ }
+ else {
+ let s = "";
+ if (this.isNDCHalfZRange) {
+ s += "#define IS_NDC_HALF_ZRANGE";
+ }
+ if (this.useReverseDepthBuffer) {
+ if (s) {
+ s += "\n";
+ }
+ s += "#define USE_REVERSE_DEPTHBUFFER";
+ }
+ if (this.useExactSrgbConversions) {
+ if (s) {
+ s += "\n";
+ }
+ s += "#define USE_EXACT_SRGB_CONVERSIONS";
+ }
+ return s;
+ }
+ }
+ _rebuildInternalTextures() {
+ const currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
+ for (const internalTexture of currentState) {
+ internalTexture._rebuild();
+ }
+ }
+ _rebuildRenderTargetWrappers() {
+ const currentState = this._renderTargetWrapperCache.slice(); // Do a copy because the rebuild will add proxies
+ for (const renderTargetWrapper of currentState) {
+ renderTargetWrapper._rebuild();
+ }
+ }
+ _rebuildEffects() {
+ for (const key in this._compiledEffects) {
+ const effect = this._compiledEffects[key];
+ effect._pipelineContext = null; // because _prepareEffect will try to dispose this pipeline before recreating it and that would lead to webgl errors
+ effect._prepareEffect();
+ }
+ Effect.ResetCache();
+ }
+ _rebuildGraphicsResources() {
+ // Ensure webgl and engine states are matching
+ this.wipeCaches(true);
+ // Rebuild effects
+ this._rebuildEffects();
+ this._rebuildComputeEffects?.();
+ // Note:
+ // The call to _rebuildBuffers must be made before the call to _rebuildInternalTextures because in the process of _rebuildBuffers the buffers used by the post process managers will be rebuilt
+ // and we may need to use the post process manager of the scene during _rebuildInternalTextures (in WebGL1, non-POT textures are rescaled using a post process + post process manager of the scene)
+ // Rebuild buffers
+ this._rebuildBuffers();
+ // Rebuild textures
+ this._rebuildInternalTextures();
+ // Rebuild textures
+ this._rebuildTextures();
+ // Rebuild textures
+ this._rebuildRenderTargetWrappers();
+ // Reset engine states after all the buffer/textures/... have been rebuilt
+ this.wipeCaches(true);
+ }
+ _flagContextRestored() {
+ Logger.Warn(this.name + " context successfully restored.");
+ this.onContextRestoredObservable.notifyObservers(this);
+ this._contextWasLost = false;
+ }
+ _restoreEngineAfterContextLost(initEngine) {
+ // Adding a timeout to avoid race condition at browser level
+ setTimeout(async () => {
+ this._clearEmptyResources();
+ const depthTest = this._depthCullingState.depthTest; // backup those values because the call to initEngine / wipeCaches will reset them
+ const depthFunc = this._depthCullingState.depthFunc;
+ const depthMask = this._depthCullingState.depthMask;
+ const stencilTest = this._stencilState.stencilTest;
+ // Rebuild context
+ await initEngine();
+ this._rebuildGraphicsResources();
+ this._depthCullingState.depthTest = depthTest;
+ this._depthCullingState.depthFunc = depthFunc;
+ this._depthCullingState.depthMask = depthMask;
+ this._stencilState.stencilTest = stencilTest;
+ this._flagContextRestored();
+ }, 0);
+ }
+ /** Gets a boolean indicating if the engine was disposed */
+ get isDisposed() {
+ return this._isDisposed;
+ }
+ /**
+ * Enables or disables the snapshot rendering mode
+ * Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine
+ */
+ get snapshotRendering() {
+ return false;
+ }
+ set snapshotRendering(activate) {
+ // Do nothing
+ }
+ /**
+ * Gets or sets the snapshot rendering mode
+ */
+ get snapshotRenderingMode() {
+ return 0;
+ }
+ set snapshotRenderingMode(mode) { }
+ /**
+ * Returns the string "AbstractEngine"
+ * @returns "AbstractEngine"
+ */
+ getClassName() {
+ return "AbstractEngine";
+ }
+ /**
+ * Gets the default empty texture
+ */
+ get emptyTexture() {
+ if (!this._emptyTexture) {
+ this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, 5, false, false, 1);
+ }
+ return this._emptyTexture;
+ }
+ /**
+ * Gets the default empty 3D texture
+ */
+ get emptyTexture3D() {
+ if (!this._emptyTexture3D) {
+ this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, 5, false, false, 1);
+ }
+ return this._emptyTexture3D;
+ }
+ /**
+ * Gets the default empty 2D array texture
+ */
+ get emptyTexture2DArray() {
+ if (!this._emptyTexture2DArray) {
+ this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, 5, false, false, 1);
+ }
+ return this._emptyTexture2DArray;
+ }
+ /**
+ * Gets the default empty cube texture
+ */
+ get emptyCubeTexture() {
+ if (!this._emptyCubeTexture) {
+ const faceData = new Uint8Array(4);
+ const cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
+ this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, 5, 0, false, false, 1);
+ }
+ return this._emptyCubeTexture;
+ }
+ /**
+ * Gets the list of current active render loop functions
+ * @returns a read only array with the current render loop functions
+ */
+ get activeRenderLoops() {
+ return this._activeRenderLoops;
+ }
+ /**
+ * stop executing a render loop function and remove it from the execution array
+ * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
+ */
+ stopRenderLoop(renderFunction) {
+ if (!renderFunction) {
+ this._activeRenderLoops.length = 0;
+ this._cancelFrame();
+ return;
+ }
+ const index = this._activeRenderLoops.indexOf(renderFunction);
+ if (index >= 0) {
+ this._activeRenderLoops.splice(index, 1);
+ if (this._activeRenderLoops.length == 0) {
+ this._cancelFrame();
+ }
+ }
+ }
+ _cancelFrame() {
+ if (this._frameHandler !== 0) {
+ const handlerToCancel = this._frameHandler;
+ this._frameHandler = 0;
+ if (!IsWindowObjectExist()) {
+ if (typeof cancelAnimationFrame === "function") {
+ return cancelAnimationFrame(handlerToCancel);
+ }
+ }
+ else {
+ const { cancelAnimationFrame } = this.getHostWindow() || window;
+ if (typeof cancelAnimationFrame === "function") {
+ return cancelAnimationFrame(handlerToCancel);
+ }
+ }
+ return clearTimeout(handlerToCancel);
+ }
+ }
+ /**
+ * Begin a new frame
+ */
+ beginFrame() {
+ this.onBeginFrameObservable.notifyObservers(this);
+ }
+ /**
+ * End the current frame
+ */
+ endFrame() {
+ this._frameId++;
+ this.onEndFrameObservable.notifyObservers(this);
+ }
+ /** Gets or sets max frame per second allowed. Will return undefined if not capped */
+ get maxFPS() {
+ return this._maxFPS;
+ }
+ set maxFPS(value) {
+ this._maxFPS = value;
+ if (value === undefined) {
+ return;
+ }
+ if (value <= 0) {
+ this._minFrameTime = Number.MAX_VALUE;
+ return;
+ }
+ this._minFrameTime = 1000 / (value + 1); // We need to provide a bit of leeway to ensure we don't go under because of vbl sync
+ }
+ _isOverFrameTime(timestamp) {
+ if (!timestamp) {
+ return false;
+ }
+ const elapsedTime = timestamp - this._lastFrameTime;
+ if (this._maxFPS === undefined || elapsedTime >= this._minFrameTime) {
+ this._lastFrameTime = timestamp;
+ return false;
+ }
+ return true;
+ }
+ _processFrame(timestamp) {
+ this._frameHandler = 0;
+ if (!this._contextWasLost && !this._isOverFrameTime(timestamp)) {
+ let shouldRender = true;
+ if (this.isDisposed || (!this.renderEvenInBackground && this._windowIsBackground)) {
+ shouldRender = false;
+ }
+ if (shouldRender) {
+ // Start new frame
+ this.beginFrame();
+ // Child canvases
+ if (!this.skipFrameRender && !this._renderViews()) {
+ // Main frame
+ this._renderFrame();
+ }
+ // Present
+ this.endFrame();
+ }
+ }
+ }
+ /** @internal */
+ _renderLoop(timestamp) {
+ this._processFrame(timestamp);
+ // The first condition prevents queuing another frame if we no longer have active render loops (e.g., if
+ // `stopRenderLoop` is called mid frame). The second condition prevents queuing another frame if one has
+ // already been queued (e.g., if `stopRenderLoop` and `runRenderLoop` is called mid frame).
+ if (this._activeRenderLoops.length > 0 && this._frameHandler === 0) {
+ this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
+ }
+ }
+ /** @internal */
+ _renderFrame() {
+ for (let index = 0; index < this._activeRenderLoops.length; index++) {
+ const renderFunction = this._activeRenderLoops[index];
+ renderFunction();
+ }
+ }
+ /** @internal */
+ _renderViews() {
+ return false;
+ }
+ /**
+ * Can be used to override the current requestAnimationFrame requester.
+ * @internal
+ */
+ _queueNewFrame(bindedRenderFunction, requester) {
+ return QueueNewFrame(bindedRenderFunction, requester);
+ }
+ /**
+ * Register and execute a render loop. The engine can have more than one render function
+ * @param renderFunction defines the function to continuously execute
+ */
+ runRenderLoop(renderFunction) {
+ if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
+ return;
+ }
+ this._activeRenderLoops.push(renderFunction);
+ // On the first added function, start the render loop.
+ if (this._activeRenderLoops.length === 1 && this._frameHandler === 0) {
+ this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
+ }
+ }
+ /**
+ * Gets a boolean indicating if depth testing is enabled
+ * @returns the current state
+ */
+ getDepthBuffer() {
+ return this._depthCullingState.depthTest;
+ }
+ /**
+ * Enable or disable depth buffering
+ * @param enable defines the state to set
+ */
+ setDepthBuffer(enable) {
+ this._depthCullingState.depthTest = enable;
+ }
+ /**
+ * Set the z offset Factor to apply to current rendering
+ * @param value defines the offset to apply
+ */
+ setZOffset(value) {
+ this._depthCullingState.zOffset = this.useReverseDepthBuffer ? -value : value;
+ }
+ /**
+ * Gets the current value of the zOffset Factor
+ * @returns the current zOffset Factor state
+ */
+ getZOffset() {
+ const zOffset = this._depthCullingState.zOffset;
+ return this.useReverseDepthBuffer ? -zOffset : zOffset;
+ }
+ /**
+ * Set the z offset Units to apply to current rendering
+ * @param value defines the offset to apply
+ */
+ setZOffsetUnits(value) {
+ this._depthCullingState.zOffsetUnits = this.useReverseDepthBuffer ? -value : value;
+ }
+ /**
+ * Gets the current value of the zOffset Units
+ * @returns the current zOffset Units state
+ */
+ getZOffsetUnits() {
+ const zOffsetUnits = this._depthCullingState.zOffsetUnits;
+ return this.useReverseDepthBuffer ? -zOffsetUnits : zOffsetUnits;
+ }
+ /**
+ * Gets host window
+ * @returns the host window object
+ */
+ getHostWindow() {
+ if (!IsWindowObjectExist()) {
+ return null;
+ }
+ if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) {
+ return this._renderingCanvas.ownerDocument.defaultView;
+ }
+ return window;
+ }
+ /**
+ * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL).
+ * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken.
+ * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details
+ */
+ get compatibilityMode() {
+ return this._compatibilityMode;
+ }
+ set compatibilityMode(mode) {
+ // not supported in WebGL
+ this._compatibilityMode = true;
+ }
+ _rebuildTextures() {
+ for (const scene of this.scenes) {
+ scene._rebuildTextures();
+ }
+ for (const scene of this._virtualScenes) {
+ scene._rebuildTextures();
+ }
+ }
+ /**
+ * @internal
+ */
+ _releaseRenderTargetWrapper(rtWrapper) {
+ const index = this._renderTargetWrapperCache.indexOf(rtWrapper);
+ if (index !== -1) {
+ this._renderTargetWrapperCache.splice(index, 1);
+ }
+ }
+ /**
+ * Gets the current viewport
+ */
+ get currentViewport() {
+ return this._cachedViewport;
+ }
+ /**
+ * Set the WebGL's viewport
+ * @param viewport defines the viewport element to be used
+ * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
+ * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
+ */
+ setViewport(viewport, requiredWidth, requiredHeight) {
+ const width = requiredWidth || this.getRenderWidth();
+ const height = requiredHeight || this.getRenderHeight();
+ const x = viewport.x || 0;
+ const y = viewport.y || 0;
+ this._cachedViewport = viewport;
+ this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
+ }
+ /**
+ * Create an image to use with canvas
+ * @returns IImage interface
+ */
+ createCanvasImage() {
+ return document.createElement("img");
+ }
+ /**
+ * Create a 2D path to use with canvas
+ * @returns IPath2D interface
+ * @param d SVG path string
+ */
+ createCanvasPath2D(d) {
+ return new Path2D(d);
+ }
+ /**
+ * Returns a string describing the current engine
+ */
+ get description() {
+ let description = this.name + this.version;
+ if (this._caps.parallelShaderCompile) {
+ description += " - Parallel shader compilation";
+ }
+ return description;
+ }
+ _createTextureBase(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, prepareTexture, prepareTextureProcess, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, useSRGBBuffer) {
+ url = url || "";
+ const fromData = url.substr(0, 5) === "data:";
+ const fromBlob = url.substr(0, 5) === "blob:";
+ const isBase64 = fromData && url.indexOf(";base64,") !== -1;
+ const texture = fallback ? fallback : new InternalTexture(this, 1 /* InternalTextureSource.Url */);
+ if (texture !== fallback) {
+ texture.label = url.substring(0, 60); // default label, can be overriden by the caller
+ }
+ const originalUrl = url;
+ if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
+ url = this._transformTextureUrl(url);
+ }
+ if (originalUrl !== url) {
+ texture._originalUrl = originalUrl;
+ }
+ // establish the file extension, if possible
+ const lastDot = url.lastIndexOf(".");
+ let extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : "";
+ // Remove query string
+ const queryStringIndex = extension.indexOf("?");
+ if (queryStringIndex > -1) {
+ extension = extension.split("?")[0];
+ }
+ const loaderPromise = _GetCompatibleTextureLoader(extension, mimeType);
+ if (scene) {
+ scene.addPendingData(texture);
+ }
+ texture.url = url;
+ texture.generateMipMaps = !noMipmap;
+ texture.samplingMode = samplingMode;
+ texture.invertY = invertY;
+ texture._useSRGBBuffer = this._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap);
+ if (!this._doNotHandleContextLost) {
+ // Keep a link to the buffer only if we plan to handle context lost
+ texture._buffer = buffer;
+ }
+ let onLoadObserver = null;
+ if (onLoad && !fallback) {
+ onLoadObserver = texture.onLoadedObservable.add(onLoad);
+ }
+ if (!fallback) {
+ this._internalTexturesCache.push(texture);
+ }
+ const onInternalError = (message, exception) => {
+ if (scene) {
+ scene.removePendingData(texture);
+ }
+ if (url === originalUrl) {
+ if (onLoadObserver) {
+ texture.onLoadedObservable.remove(onLoadObserver);
+ }
+ if (EngineStore.UseFallbackTexture && url !== EngineStore.FallbackTexture) {
+ this._createTextureBase(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, prepareTexture, prepareTextureProcess, buffer, texture);
+ }
+ message = (message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : "");
+ texture.onErrorObservable.notifyObservers({ message, exception });
+ if (onError) {
+ onError(message, exception);
+ }
+ }
+ else {
+ // fall back to the original url if the transformed url fails to load
+ Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`);
+ this._createTextureBase(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, prepareTexture, prepareTextureProcess, buffer, texture, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer);
+ }
+ };
+ // processing for non-image formats
+ if (loaderPromise) {
+ const callback = async (data) => {
+ const loader = await loaderPromise;
+ loader.loadData(data, texture, (width, height, loadMipmap, isCompressed, done, loadFailed) => {
+ if (loadFailed) {
+ onInternalError("TextureLoader failed to load data");
+ }
+ else {
+ prepareTexture(texture, extension, scene, { width, height }, texture.invertY, !loadMipmap, isCompressed, () => {
+ done();
+ return false;
+ }, samplingMode);
+ }
+ }, loaderOptions);
+ };
+ if (!buffer) {
+ this._loadFile(url, (data) => callback(new Uint8Array(data)), undefined, scene ? scene.offlineProvider : undefined, true, (request, exception) => {
+ onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
+ });
+ }
+ else {
+ if (buffer instanceof ArrayBuffer) {
+ callback(new Uint8Array(buffer));
+ }
+ else if (ArrayBuffer.isView(buffer)) {
+ callback(buffer);
+ }
+ else {
+ if (onError) {
+ onError("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null);
+ }
+ }
+ }
+ }
+ else {
+ const onload = (img) => {
+ if (fromBlob && !this._doNotHandleContextLost) {
+ // We need to store the image if we need to rebuild the texture
+ // in case of a webgl context lost
+ texture._buffer = img;
+ }
+ prepareTexture(texture, extension, scene, img, texture.invertY, noMipmap, false, prepareTextureProcess, samplingMode);
+ };
+ // According to the WebGL spec section 6.10, ImageBitmaps must be inverted on creation.
+ // So, we pass imageOrientation to _FileToolsLoadImage() as it may create an ImageBitmap.
+ if (!fromData || isBase64) {
+ if (buffer && (typeof buffer.decoding === "string" || buffer.close)) {
+ onload(buffer);
+ }
+ else {
+ AbstractEngine._FileToolsLoadImage(url || "", onload, onInternalError, scene ? scene.offlineProvider : null, mimeType, texture.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : undefined, this);
+ }
+ }
+ else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) {
+ AbstractEngine._FileToolsLoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType, texture.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : undefined, this);
+ }
+ else if (buffer) {
+ onload(buffer);
+ }
+ }
+ return texture;
+ }
+ _rebuildBuffers() {
+ // Uniforms
+ for (const uniformBuffer of this._uniformBuffers) {
+ uniformBuffer._rebuildAfterContextLost();
+ }
+ }
+ /** @internal */
+ get _shouldUseHighPrecisionShader() {
+ return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed);
+ }
+ /**
+ * Gets host document
+ * @returns the host document object
+ */
+ getHostDocument() {
+ if (this._renderingCanvas && this._renderingCanvas.ownerDocument) {
+ return this._renderingCanvas.ownerDocument;
+ }
+ return IsDocumentAvailable() ? document : null;
+ }
+ /**
+ * Gets the list of loaded textures
+ * @returns an array containing all loaded textures
+ */
+ getLoadedTexturesCache() {
+ return this._internalTexturesCache;
+ }
+ /**
+ * Clears the list of texture accessible through engine.
+ * This can help preventing texture load conflict due to name collision.
+ */
+ clearInternalTexturesCache() {
+ this._internalTexturesCache.length = 0;
+ }
+ /**
+ * Gets the object containing all engine capabilities
+ * @returns the EngineCapabilities object
+ */
+ getCaps() {
+ return this._caps;
+ }
+ /**
+ * Reset the texture cache to empty state
+ */
+ resetTextureCache() {
+ for (const key in this._boundTexturesCache) {
+ if (!Object.prototype.hasOwnProperty.call(this._boundTexturesCache, key)) {
+ continue;
+ }
+ this._boundTexturesCache[key] = null;
+ }
+ this._currentTextureChannel = -1;
+ }
+ /**
+ * Gets or sets the name of the engine
+ */
+ get name() {
+ return this._name;
+ }
+ set name(value) {
+ this._name = value;
+ }
+ /**
+ * Returns the current npm package of the sdk
+ */
+ // Not mixed with Version for tooling purpose.
+ static get NpmPackage() {
+ return "babylonjs@7.54.3";
+ }
+ /**
+ * Returns the current version of the framework
+ */
+ static get Version() {
+ return "7.54.3";
+ }
+ /**
+ * Gets the HTML canvas attached with the current webGL context
+ * @returns a HTML canvas
+ */
+ getRenderingCanvas() {
+ return this._renderingCanvas;
+ }
+ /**
+ * Gets the audio context specified in engine initialization options
+ * @deprecated please use AudioEngineV2 instead
+ * @returns an Audio Context
+ */
+ getAudioContext() {
+ return this._audioContext;
+ }
+ /**
+ * Gets the audio destination specified in engine initialization options
+ * @deprecated please use AudioEngineV2 instead
+ * @returns an audio destination node
+ */
+ getAudioDestination() {
+ return this._audioDestination;
+ }
+ /**
+ * Defines the hardware scaling level.
+ * By default the hardware scaling level is computed from the window device ratio.
+ * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
+ * @param level defines the level to use
+ */
+ setHardwareScalingLevel(level) {
+ this._hardwareScalingLevel = level;
+ this.resize();
+ }
+ /**
+ * Gets the current hardware scaling level.
+ * By default the hardware scaling level is computed from the window device ratio.
+ * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
+ * @returns a number indicating the current hardware scaling level
+ */
+ getHardwareScalingLevel() {
+ return this._hardwareScalingLevel;
+ }
+ /**
+ * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#handling-webgl-context-lost
+ */
+ get doNotHandleContextLost() {
+ return this._doNotHandleContextLost;
+ }
+ set doNotHandleContextLost(value) {
+ this._doNotHandleContextLost = value;
+ }
+ /**
+ * Returns true if the stencil buffer has been enabled through the creation option of the context.
+ */
+ get isStencilEnable() {
+ return this._isStencilEnable;
+ }
+ /**
+ * Gets the options used for engine creation
+ * @returns EngineOptions object
+ */
+ getCreationOptions() {
+ return this._creationOptions;
+ }
+ /**
+ * Creates a new engine
+ * @param antialias defines whether anti-aliasing should be enabled. If undefined, it means that the underlying engine is free to enable it or not
+ * @param options defines further options to be sent to the creation context
+ * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
+ */
+ constructor(antialias, options, adaptToDeviceRatio) {
+ // States
+ /** @internal */
+ this._colorWrite = true;
+ /** @internal */
+ this._colorWriteChanged = true;
+ /** @internal */
+ this._depthCullingState = new DepthCullingState();
+ /** @internal */
+ this._stencilStateComposer = new StencilStateComposer();
+ /** @internal */
+ this._stencilState = new StencilState();
+ /** @internal */
+ this._alphaState = new AlphaState();
+ /** @internal */
+ this._alphaMode = 1;
+ /** @internal */
+ this._alphaEquation = 0;
+ this._activeRequests = [];
+ /** @internal */
+ this._badOS = false;
+ /** @internal */
+ this._badDesktopOS = false;
+ this._compatibilityMode = true;
+ /** @internal */
+ this._internalTexturesCache = new Array();
+ /** @internal */
+ this._currentRenderTarget = null;
+ /** @internal */
+ this._boundTexturesCache = {};
+ /** @internal */
+ this._activeChannel = 0;
+ /** @internal */
+ this._currentTextureChannel = -1;
+ /** @internal */
+ this._viewportCached = { x: 0, y: 0, z: 0, w: 0 };
+ /** @internal */
+ this._isWebGPU = false;
+ /**
+ * Observable event triggered each time the canvas loses focus
+ */
+ this.onCanvasBlurObservable = new Observable();
+ /**
+ * Observable event triggered each time the canvas gains focus
+ */
+ this.onCanvasFocusObservable = new Observable();
+ /**
+ * Event raised when a new scene is created
+ */
+ this.onNewSceneAddedObservable = new Observable();
+ /**
+ * Observable event triggered each time the rendering canvas is resized
+ */
+ this.onResizeObservable = new Observable();
+ /**
+ * Observable event triggered each time the canvas receives pointerout event
+ */
+ this.onCanvasPointerOutObservable = new Observable();
+ /**
+ * Observable event triggered each time an effect compilation fails
+ */
+ this.onEffectErrorObservable = new Observable();
+ /**
+ * Turn this value on if you want to pause FPS computation when in background
+ */
+ this.disablePerformanceMonitorInBackground = false;
+ /**
+ * Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported
+ */
+ this.disableVertexArrayObjects = false;
+ /** @internal */
+ this._frameId = 0;
+ /**
+ * Gets information about the current host
+ */
+ this.hostInformation = {
+ isMobile: false,
+ };
+ /**
+ * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
+ */
+ this.isFullscreen = false;
+ /**
+ * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
+ **/
+ this.enableOfflineSupport = false;
+ /**
+ * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (js will always consider the database is up to date)
+ **/
+ this.disableManifestCheck = false;
+ /**
+ * Gets or sets a boolean to enable/disable the context menu (right-click) from appearing on the main canvas
+ */
+ this.disableContextMenu = true;
+ /**
+ * Gets or sets the current render pass id
+ */
+ this.currentRenderPassId = 0;
+ /**
+ * Gets a boolean indicating if the pointer is currently locked
+ */
+ this.isPointerLock = false;
+ /**
+ * Gets the list of created postprocesses
+ */
+ this.postProcesses = [];
+ /** Gets or sets the tab index to set to the rendering canvas. 1 is the minimum value to set to be able to capture keyboard events */
+ this.canvasTabIndex = 1;
+ /** @internal */
+ this._contextWasLost = false;
+ this._useReverseDepthBuffer = false;
+ /**
+ * Indicates if the z range in NDC space is 0..1 (value: true) or -1..1 (value: false)
+ */
+ this.isNDCHalfZRange = false;
+ /**
+ * Indicates that the origin of the texture/framebuffer space is the bottom left corner. If false, the origin is top left
+ */
+ this.hasOriginBottomLeft = true;
+ /** @internal */
+ this._renderTargetWrapperCache = new Array();
+ /** @internal */
+ this._compiledEffects = {};
+ /** @internal */
+ this._isDisposed = false;
+ /**
+ * Gets the list of created scenes
+ */
+ this.scenes = [];
+ /** @internal */
+ this._virtualScenes = new Array();
+ /**
+ * Observable event triggered before each texture is initialized
+ */
+ this.onBeforeTextureInitObservable = new Observable();
+ /**
+ * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foreground
+ */
+ this.renderEvenInBackground = true;
+ /**
+ * Gets or sets a boolean indicating that cache can be kept between frames
+ */
+ this.preventCacheWipeBetweenFrames = false;
+ /** @internal */
+ this._frameHandler = 0;
+ /** @internal */
+ this._activeRenderLoops = new Array();
+ /** @internal */
+ this._windowIsBackground = false;
+ /** @internal */
+ this._boundRenderFunction = (timestamp) => this._renderLoop(timestamp);
+ this._lastFrameTime = 0;
+ /**
+ * Skip frame rendering but keep the frame heartbeat (begin/end frame).
+ * This is useful if you need all the plumbing but not the rendering work.
+ * (for instance when capturing a screenshot where you do not want to mix rendering to the screen and to the screenshot)
+ */
+ this.skipFrameRender = false;
+ /**
+ * Observable raised when the engine is about to compile a shader
+ */
+ this.onBeforeShaderCompilationObservable = new Observable();
+ /**
+ * Observable raised when the engine has just compiled a shader
+ */
+ this.onAfterShaderCompilationObservable = new Observable();
+ /**
+ * Observable raised when the engine begins a new frame
+ */
+ this.onBeginFrameObservable = new Observable();
+ /**
+ * Observable raised when the engine ends the current frame
+ */
+ this.onEndFrameObservable = new Observable();
+ /** @internal */
+ this._transformTextureUrl = null;
+ /** @internal */
+ this._uniformBuffers = new Array();
+ /** @internal */
+ this._storageBuffers = new Array();
+ this._highPrecisionShadersAllowed = true;
+ // Lost context
+ /**
+ * Observable signaled when a context lost event is raised
+ */
+ this.onContextLostObservable = new Observable();
+ /**
+ * Observable signaled when a context restored event is raised
+ */
+ this.onContextRestoredObservable = new Observable();
+ /** @internal */
+ this._name = "";
+ /**
+ * Defines whether the engine has been created with the premultipliedAlpha option on or not.
+ */
+ this.premultipliedAlpha = true;
+ /**
+ * If set to true zooming in and out in the browser will rescale the hardware-scaling correctly.
+ */
+ this.adaptToDeviceRatio = false;
+ /** @internal */
+ this._lastDevicePixelRatio = 1.0;
+ /** @internal */
+ this._doNotHandleContextLost = false;
+ /**
+ * Gets or sets a boolean indicating if back faces must be culled. If false, front faces are culled instead (true by default)
+ * If non null, this takes precedence over the value from the material
+ */
+ this.cullBackFaces = null;
+ /** @internal */
+ this._renderPassNames = ["main"];
+ // FPS
+ this._fps = 60;
+ this._deltaTime = 0;
+ // Deterministic lockstepMaxSteps
+ /** @internal */
+ this._deterministicLockstep = false;
+ /** @internal */
+ this._lockstepMaxSteps = 4;
+ /** @internal */
+ this._timeStep = 1 / 60;
+ /**
+ * An event triggered when the engine is disposed.
+ */
+ this.onDisposeObservable = new Observable();
+ /**
+ * An event triggered when a global cleanup of all effects is required
+ */
+ this.onReleaseEffectsObservable = new Observable();
+ EngineStore.Instances.push(this);
+ this.startTime = PrecisionDate.Now;
+ this._stencilStateComposer.stencilGlobal = this._stencilState;
+ PerformanceConfigurator.SetMatrixPrecision(!!options.useHighPrecisionMatrix);
+ if (IsNavigatorAvailable() && navigator.userAgent) {
+ // Detect if we are running on a faulty buggy OS.
+ this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
+ // Detect if we are running on a faulty buggy desktop OS.
+ this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
+ }
+ // Save this off for use in resize().
+ this.adaptToDeviceRatio = adaptToDeviceRatio ?? false;
+ options.antialias = antialias ?? options.antialias;
+ options.deterministicLockstep = options.deterministicLockstep ?? false;
+ options.lockstepMaxSteps = options.lockstepMaxSteps ?? 4;
+ options.timeStep = options.timeStep ?? 1 / 60;
+ options.stencil = options.stencil ?? true;
+ this._audioContext = options.audioEngineOptions?.audioContext ?? null;
+ this._audioDestination = options.audioEngineOptions?.audioDestination ?? null;
+ this.premultipliedAlpha = options.premultipliedAlpha ?? true;
+ this._doNotHandleContextLost = !!options.doNotHandleContextLost;
+ this._isStencilEnable = options.stencil ? true : false;
+ this.useExactSrgbConversions = options.useExactSrgbConversions ?? false;
+ const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1.0 : 1.0;
+ const limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
+ // Viewport
+ adaptToDeviceRatio = adaptToDeviceRatio || options.adaptToDeviceRatio || false;
+ this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
+ this._lastDevicePixelRatio = devicePixelRatio;
+ this._creationOptions = options;
+ }
+ /**
+ * Resize the view according to the canvas' size
+ * @param forceSetSize true to force setting the sizes of the underlying canvas
+ */
+ resize(forceSetSize = false) {
+ let width;
+ let height;
+ // Re-query hardware scaling level to handle zoomed-in resizing.
+ if (this.adaptToDeviceRatio) {
+ const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1.0 : 1.0;
+ const changeRatio = this._lastDevicePixelRatio / devicePixelRatio;
+ this._lastDevicePixelRatio = devicePixelRatio;
+ this._hardwareScalingLevel *= changeRatio;
+ }
+ if (IsWindowObjectExist() && IsDocumentAvailable()) {
+ // make sure it is a Node object, and is a part of the document.
+ if (this._renderingCanvas) {
+ const boundingRect = this._renderingCanvas.getBoundingClientRect?.();
+ width = this._renderingCanvas.clientWidth || boundingRect?.width || this._renderingCanvas.width * this._hardwareScalingLevel || 100;
+ height = this._renderingCanvas.clientHeight || boundingRect?.height || this._renderingCanvas.height * this._hardwareScalingLevel || 100;
+ }
+ else {
+ width = window.innerWidth;
+ height = window.innerHeight;
+ }
+ }
+ else {
+ width = this._renderingCanvas ? this._renderingCanvas.width : 100;
+ height = this._renderingCanvas ? this._renderingCanvas.height : 100;
+ }
+ this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel, forceSetSize);
+ }
+ /**
+ * Force a specific size of the canvas
+ * @param width defines the new canvas' width
+ * @param height defines the new canvas' height
+ * @param forceSetSize true to force setting the sizes of the underlying canvas
+ * @returns true if the size was changed
+ */
+ setSize(width, height, forceSetSize = false) {
+ if (!this._renderingCanvas) {
+ return false;
+ }
+ width = width | 0;
+ height = height | 0;
+ if (!forceSetSize && this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
+ return false;
+ }
+ this._renderingCanvas.width = width;
+ this._renderingCanvas.height = height;
+ if (this.scenes) {
+ for (let index = 0; index < this.scenes.length; index++) {
+ const scene = this.scenes[index];
+ for (let camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
+ const cam = scene.cameras[camIndex];
+ cam._currentRenderId = 0;
+ }
+ }
+ if (this.onResizeObservable.hasObservers()) {
+ this.onResizeObservable.notifyObservers(this);
+ }
+ }
+ return true;
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Creates a raw texture
+ * @param data defines the data to store in the texture
+ * @param width defines the width of the texture
+ * @param height defines the height of the texture
+ * @param format defines the format of the data
+ * @param generateMipMaps defines if the engine should generate the mip levels
+ * @param invertY defines if data must be stored with Y axis inverted
+ * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
+ * @param compression defines the compression used (null by default)
+ * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_BYTE by default)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).
+ * @returns the raw texture inside an InternalTexture
+ */
+ createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type, creationFlags, useSRGBBuffer) {
+ throw _WarnImport("engine.rawTexture");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Creates a new raw cube texture
+ * @param data defines the array of data to use to create each face
+ * @param size defines the size of the textures
+ * @param format defines the format of the data
+ * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_BYTE)
+ * @param generateMipMaps defines if the engine should generate the mip levels
+ * @param invertY defines if data must be stored with Y axis inverted
+ * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
+ * @param compression defines the compression used (null by default)
+ * @returns the cube texture as an InternalTexture
+ */
+ createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
+ throw _WarnImport("engine.rawTexture");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Creates a new raw 3D texture
+ * @param data defines the data used to create the texture
+ * @param width defines the width of the texture
+ * @param height defines the height of the texture
+ * @param depth defines the depth of the texture
+ * @param format defines the format of the texture
+ * @param generateMipMaps defines if the engine must generate mip levels
+ * @param invertY defines if data must be stored with Y axis inverted
+ * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
+ * @param compression defines the compressed used (can be null)
+ * @param textureType defines the compressed used (can be null)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @returns a new raw 3D texture (stored in an InternalTexture)
+ */
+ createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType, creationFlags) {
+ throw _WarnImport("engine.rawTexture");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Creates a new raw 2D array texture
+ * @param data defines the data used to create the texture
+ * @param width defines the width of the texture
+ * @param height defines the height of the texture
+ * @param depth defines the number of layers of the texture
+ * @param format defines the format of the texture
+ * @param generateMipMaps defines if the engine must generate mip levels
+ * @param invertY defines if data must be stored with Y axis inverted
+ * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
+ * @param compression defines the compressed used (can be null)
+ * @param textureType defines the compressed used (can be null)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @returns a new raw 2D array texture (stored in an InternalTexture)
+ */
+ createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType, creationFlags) {
+ throw _WarnImport("engine.rawTexture");
+ }
+ /**
+ * Shared initialization across engines types.
+ * @param canvas The canvas associated with this instance of the engine.
+ */
+ _sharedInit(canvas) {
+ this._renderingCanvas = canvas;
+ }
+ _setupMobileChecks() {
+ if (!(navigator && navigator.userAgent)) {
+ return;
+ }
+ // Function to check if running on mobile device
+ this._checkForMobile = () => {
+ const currentUA = navigator.userAgent;
+ this.hostInformation.isMobile =
+ currentUA.indexOf("Mobile") !== -1 ||
+ // Needed for iOS 13+ detection on iPad (inspired by solution from https://stackoverflow.com/questions/9038625/detect-if-device-is-ios)
+ (currentUA.indexOf("Mac") !== -1 && IsDocumentAvailable() && "ontouchend" in document);
+ };
+ // Set initial isMobile value
+ this._checkForMobile();
+ // Set up event listener to check when window is resized (used to get emulator activation to work properly)
+ if (IsWindowObjectExist()) {
+ window.addEventListener("resize", this._checkForMobile);
+ }
+ }
+ /**
+ * creates and returns a new video element
+ * @param constraints video constraints
+ * @returns video element
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ createVideoElement(constraints) {
+ return document.createElement("video");
+ }
+ /**
+ * @internal
+ */
+ _reportDrawCall(numDrawCalls = 1) {
+ this._drawCalls?.addCount(numDrawCalls, false);
+ }
+ /**
+ * Gets the current framerate
+ * @returns a number representing the framerate
+ */
+ getFps() {
+ return this._fps;
+ }
+ /**
+ * Gets the time spent between current and previous frame
+ * @returns a number representing the delta time in ms
+ */
+ getDeltaTime() {
+ return this._deltaTime;
+ }
+ /**
+ * Gets a boolean indicating that the engine is running in deterministic lock step mode
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep
+ * @returns true if engine is in deterministic lock step mode
+ */
+ isDeterministicLockStep() {
+ return this._deterministicLockstep;
+ }
+ /**
+ * Gets the max steps when engine is running in deterministic lock step
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep
+ * @returns the max steps
+ */
+ getLockstepMaxSteps() {
+ return this._lockstepMaxSteps;
+ }
+ /**
+ * Returns the time in ms between steps when using deterministic lock step.
+ * @returns time step in (ms)
+ */
+ getTimeStep() {
+ return this._timeStep * 1000;
+ }
+ /**
+ * Engine abstraction for loading and creating an image bitmap from a given source string.
+ * @param imageSource source to load the image from.
+ * @param options An object that sets options for the image's extraction.
+ */
+ _createImageBitmapFromSource(imageSource, options) {
+ throw new Error("createImageBitmapFromSource is not implemented");
+ }
+ /**
+ * Engine abstraction for createImageBitmap
+ * @param image source for image
+ * @param options An object that sets options for the image's extraction.
+ * @returns ImageBitmap
+ */
+ createImageBitmap(image, options) {
+ return createImageBitmap(image, options);
+ }
+ /**
+ * Resize an image and returns the image data as an uint8array
+ * @param image image to resize
+ * @param bufferWidth destination buffer width
+ * @param bufferHeight destination buffer height
+ */
+ resizeImageBitmap(image, bufferWidth, bufferHeight) {
+ throw new Error("resizeImageBitmap is not implemented");
+ }
+ /**
+ * Get Font size information
+ * @param font font name
+ */
+ getFontOffset(font) {
+ throw new Error("getFontOffset is not implemented");
+ }
+ static _CreateCanvas(width, height) {
+ if (typeof document === "undefined") {
+ return new OffscreenCanvas(width, height);
+ }
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ return canvas;
+ }
+ /**
+ * Create a canvas. This method is overridden by other engines
+ * @param width width
+ * @param height height
+ * @returns ICanvas interface
+ */
+ createCanvas(width, height) {
+ return AbstractEngine._CreateCanvas(width, height);
+ }
+ /**
+ * Loads an image as an HTMLImageElement.
+ * @param input url string, ArrayBuffer, or Blob to load
+ * @param onLoad callback called when the image successfully loads
+ * @param onError callback called when the image fails to load
+ * @param offlineProvider offline provider for caching
+ * @param mimeType optional mime type
+ * @param imageBitmapOptions optional the options to use when creating an ImageBitmap
+ * @param engine the engine instance to use
+ * @returns the HTMLImageElement of the loaded image
+ * @internal
+ */
+ static _FileToolsLoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions, engine) {
+ throw _WarnImport("FileTools");
+ }
+ /**
+ * @internal
+ */
+ _loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
+ const request = _loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
+ this._activeRequests.push(request);
+ request.onCompleteObservable.add(() => {
+ const index = this._activeRequests.indexOf(request);
+ if (index !== -1) {
+ this._activeRequests.splice(index, 1);
+ }
+ });
+ return request;
+ }
+ /**
+ * Loads a file from a url
+ * @param url url to load
+ * @param onSuccess callback called when the file successfully loads
+ * @param onProgress callback called while file is loading (if the server supports this mode)
+ * @param offlineProvider defines the offline provider for caching
+ * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
+ * @param onError callback called when the file fails to load
+ * @returns a file request object
+ * @internal
+ */
+ static _FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
+ if (EngineFunctionContext.loadFile) {
+ return EngineFunctionContext.loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
+ }
+ throw _WarnImport("FileTools");
+ }
+ /**
+ * Dispose and release all associated resources
+ */
+ dispose() {
+ this.releaseEffects();
+ this._isDisposed = true;
+ this.stopRenderLoop();
+ // Empty texture
+ if (this._emptyTexture) {
+ this._releaseTexture(this._emptyTexture);
+ this._emptyTexture = null;
+ }
+ if (this._emptyCubeTexture) {
+ this._releaseTexture(this._emptyCubeTexture);
+ this._emptyCubeTexture = null;
+ }
+ this._renderingCanvas = null;
+ // Clear observables
+ if (this.onBeforeTextureInitObservable) {
+ this.onBeforeTextureInitObservable.clear();
+ }
+ // Release postProcesses
+ while (this.postProcesses.length) {
+ this.postProcesses[0].dispose();
+ }
+ // Release scenes
+ while (this.scenes.length) {
+ this.scenes[0].dispose();
+ }
+ while (this._virtualScenes.length) {
+ this._virtualScenes[0].dispose();
+ }
+ // Release effects
+ this.releaseComputeEffects?.();
+ Effect.ResetCache();
+ // Abort active requests
+ for (const request of this._activeRequests) {
+ request.abort();
+ }
+ this._boundRenderFunction = null;
+ this.onDisposeObservable.notifyObservers(this);
+ this.onDisposeObservable.clear();
+ this.onResizeObservable.clear();
+ this.onCanvasBlurObservable.clear();
+ this.onCanvasFocusObservable.clear();
+ this.onCanvasPointerOutObservable.clear();
+ this.onNewSceneAddedObservable.clear();
+ this.onEffectErrorObservable.clear();
+ if (IsWindowObjectExist()) {
+ window.removeEventListener("resize", this._checkForMobile);
+ }
+ // Remove from Instances
+ const index = EngineStore.Instances.indexOf(this);
+ if (index >= 0) {
+ EngineStore.Instances.splice(index, 1);
+ }
+ // no more engines left in the engine store? Notify!
+ if (!EngineStore.Instances.length) {
+ EngineStore.OnEnginesDisposedObservable.notifyObservers(this);
+ EngineStore.OnEnginesDisposedObservable.clear();
+ }
+ // Observables
+ this.onBeginFrameObservable.clear();
+ this.onEndFrameObservable.clear();
+ }
+ /**
+ * Method called to create the default loading screen.
+ * This can be overridden in your own app.
+ * @param canvas The rendering canvas element
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static DefaultLoadingScreenFactory(canvas) {
+ throw _WarnImport("LoadingScreen");
+ }
+ /**
+ * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
+ * @param flag defines which part of the materials must be marked as dirty
+ * @param predicate defines a predicate used to filter which materials should be affected
+ */
+ static MarkAllMaterialsAsDirty(flag, predicate) {
+ for (let engineIndex = 0; engineIndex < EngineStore.Instances.length; engineIndex++) {
+ const engine = EngineStore.Instances[engineIndex];
+ for (let sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
+ engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
+ }
+ }
+ }
+}
+// eslint-disable-next-line @typescript-eslint/naming-convention
+/** @internal */
+AbstractEngine._RenderPassIdCounter = 0;
+/**
+ * Method called to create the default rescale post process on each engine.
+ */
+AbstractEngine._RescalePostProcessFactory = null;
+// Updatable statics so stick with vars here
+/**
+ * Gets or sets the epsilon value used by collision engine
+ */
+AbstractEngine.CollisionsEpsilon = 0.001;
+/**
+ * Queue a new function into the requested animation frame pool (ie. this function will be executed by the browser (or the javascript engine) for the next frame)
+ * @param func - the function to be called
+ * @param requester - the object that will request the next frame. Falls back to window.
+ * @returns frame number
+ */
+AbstractEngine.QueueNewFrame = QueueNewFrame;
+
+/** @internal */
+class WebGLHardwareTexture {
+ get underlyingResource() {
+ return this._webGLTexture;
+ }
+ constructor(existingTexture = null, context) {
+ // There can be multiple buffers for a single WebGL texture because different layers of a 2DArrayTexture / 3DTexture
+ // or different faces of a cube texture can be bound to different render targets at the same time.
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ this._MSAARenderBuffers = null;
+ this._context = context;
+ if (!existingTexture) {
+ existingTexture = context.createTexture();
+ if (!existingTexture) {
+ throw new Error("Unable to create webGL texture");
+ }
+ }
+ this.set(existingTexture);
+ }
+ setUsage() { }
+ set(hardwareTexture) {
+ this._webGLTexture = hardwareTexture;
+ }
+ reset() {
+ this._webGLTexture = null;
+ this._MSAARenderBuffers = null;
+ }
+ addMSAARenderBuffer(buffer) {
+ if (!this._MSAARenderBuffers) {
+ this._MSAARenderBuffers = [];
+ }
+ this._MSAARenderBuffers.push(buffer);
+ }
+ releaseMSAARenderBuffers() {
+ if (this._MSAARenderBuffers) {
+ for (const buffer of this._MSAARenderBuffers) {
+ this._context.deleteRenderbuffer(buffer);
+ }
+ this._MSAARenderBuffers = null;
+ }
+ }
+ getMSAARenderBuffer(index = 0) {
+ return this._MSAARenderBuffers?.[index] ?? null;
+ }
+ release() {
+ this.releaseMSAARenderBuffers();
+ if (this._webGLTexture) {
+ this._context.deleteTexture(this._webGLTexture);
+ }
+ this.reset();
+ }
+}
+
+/**
+ * Checks if a given format is a depth texture format
+ * @param format Format to check
+ * @returns True if the format is a depth texture format
+ */
+function IsDepthTexture(format) {
+ return (format === 13 ||
+ format === 14 ||
+ format === 15 ||
+ format === 16 ||
+ format === 17 ||
+ format === 18 ||
+ format === 19);
+}
+/**
+ * Gets the type of a depth texture for a given format
+ * @param format Format of the texture
+ * @returns The type of the depth texture
+ */
+function GetTypeForDepthTexture(format) {
+ switch (format) {
+ case 13:
+ case 17:
+ case 18:
+ case 14:
+ case 16:
+ return 1;
+ case 15:
+ return 5;
+ case 19:
+ return 0;
+ }
+ return 0;
+}
+/**
+ * Checks if a given format has a stencil aspect
+ * @param format Format to check
+ * @returns True if the format has a stencil aspect
+ */
+function HasStencilAspect(format) {
+ return (format === 13 ||
+ format === 17 ||
+ format === 18 ||
+ format === 19);
+}
+
+/**
+ * Keeps track of all the buffer info used in engine.
+ */
+class BufferPointer {
+}
+/**
+ * The base engine class (root of all engines)
+ */
+class ThinEngine extends AbstractEngine {
+ /**
+ * Gets or sets the name of the engine
+ */
+ get name() {
+ return this._name;
+ }
+ set name(value) {
+ this._name = value;
+ }
+ /**
+ * Returns the version of the engine
+ */
+ get version() {
+ return this._webGLVersion;
+ }
+ /**
+ * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
+ */
+ static get ShadersRepository() {
+ return Effect.ShadersRepository;
+ }
+ static set ShadersRepository(value) {
+ Effect.ShadersRepository = value;
+ }
+ /**
+ * Gets a boolean indicating that the engine supports uniform buffers
+ * @see https://doc.babylonjs.com/setup/support/webGL2#uniform-buffer-objets
+ */
+ get supportsUniformBuffers() {
+ return this.webGLVersion > 1 && !this.disableUniformBuffers;
+ }
+ /**
+ * Gets a boolean indicating that only power of 2 textures are supported
+ * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
+ */
+ get needPOTTextures() {
+ return this._webGLVersion < 2 || this.forcePOTTextures;
+ }
+ get _supportsHardwareTextureRescaling() {
+ return false;
+ }
+ /**
+ * sets the object from which width and height will be taken from when getting render width and height
+ * Will fallback to the gl object
+ * @param dimensions the framebuffer width and height that will be used.
+ */
+ set framebufferDimensionsObject(dimensions) {
+ this._framebufferDimensionsObject = dimensions;
+ }
+ /**
+ * Creates a new snapshot at the next frame using the current snapshotRenderingMode
+ */
+ snapshotRenderingReset() {
+ this.snapshotRendering = false;
+ }
+ /**
+ * Creates a new engine
+ * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which already used the WebGL context
+ * @param antialias defines whether anti-aliasing should be enabled (default value is "undefined", meaning that the browser may or may not enable it)
+ * @param options defines further options to be sent to the getContext() function
+ * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
+ */
+ constructor(canvasOrContext, antialias, options, adaptToDeviceRatio) {
+ options = options || {};
+ super(antialias ?? options.antialias, options, adaptToDeviceRatio);
+ /** @internal */
+ this._name = "WebGL";
+ /**
+ * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
+ */
+ this.forcePOTTextures = false;
+ /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
+ this.validateShaderPrograms = false;
+ /**
+ * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
+ */
+ this.disableUniformBuffers = false;
+ /** @internal */
+ this._webGLVersion = 1.0;
+ this._vertexAttribArraysEnabled = [];
+ this._uintIndicesCurrentlySet = false;
+ this._currentBoundBuffer = new Array();
+ /** @internal */
+ this._currentFramebuffer = null;
+ /** @internal */
+ this._dummyFramebuffer = null;
+ this._currentBufferPointers = new Array();
+ this._currentInstanceLocations = new Array();
+ this._currentInstanceBuffers = new Array();
+ this._vaoRecordInProgress = false;
+ this._mustWipeVertexAttributes = false;
+ this._nextFreeTextureSlots = new Array();
+ this._maxSimultaneousTextures = 0;
+ this._maxMSAASamplesOverride = null;
+ this._unpackFlipYCached = null;
+ /**
+ * In case you are sharing the context with other applications, it might
+ * be interested to not cache the unpack flip y state to ensure a consistent
+ * value would be set.
+ */
+ this.enableUnpackFlipYCached = true;
+ /**
+ * @internal
+ */
+ this._boundUniforms = {};
+ if (!canvasOrContext) {
+ return;
+ }
+ let canvas = null;
+ if (canvasOrContext.getContext) {
+ canvas = canvasOrContext;
+ if (options.preserveDrawingBuffer === undefined) {
+ options.preserveDrawingBuffer = false;
+ }
+ if (options.xrCompatible === undefined) {
+ options.xrCompatible = false;
+ }
+ // Exceptions
+ if (navigator && navigator.userAgent) {
+ this._setupMobileChecks();
+ const ua = navigator.userAgent;
+ for (const exception of ThinEngine.ExceptionList) {
+ const key = exception.key;
+ const targets = exception.targets;
+ const check = new RegExp(key);
+ if (check.test(ua)) {
+ if (exception.capture && exception.captureConstraint) {
+ const capture = exception.capture;
+ const constraint = exception.captureConstraint;
+ const regex = new RegExp(capture);
+ const matches = regex.exec(ua);
+ if (matches && matches.length > 0) {
+ const capturedValue = parseInt(matches[matches.length - 1]);
+ if (capturedValue >= constraint) {
+ continue;
+ }
+ }
+ }
+ for (const target of targets) {
+ switch (target) {
+ case "uniformBuffer":
+ this.disableUniformBuffers = true;
+ break;
+ case "vao":
+ this.disableVertexArrayObjects = true;
+ break;
+ case "antialias":
+ options.antialias = false;
+ break;
+ case "maxMSAASamples":
+ this._maxMSAASamplesOverride = 1;
+ break;
+ }
+ }
+ }
+ }
+ }
+ // Context lost
+ if (!this._doNotHandleContextLost) {
+ this._onContextLost = (evt) => {
+ evt.preventDefault();
+ this._contextWasLost = true;
+ deleteStateObject(this._gl);
+ Logger.Warn("WebGL context lost.");
+ this.onContextLostObservable.notifyObservers(this);
+ };
+ this._onContextRestored = () => {
+ this._restoreEngineAfterContextLost(() => this._initGLContext());
+ };
+ canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
+ options.powerPreference = options.powerPreference || "high-performance";
+ }
+ else {
+ this._onContextLost = () => {
+ deleteStateObject(this._gl);
+ };
+ }
+ canvas.addEventListener("webglcontextlost", this._onContextLost, false);
+ if (this._badDesktopOS) {
+ options.xrCompatible = false;
+ }
+ // GL
+ if (!options.disableWebGL2Support) {
+ try {
+ this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
+ if (this._gl) {
+ this._webGLVersion = 2.0;
+ this._shaderPlatformName = "WEBGL2";
+ // Prevent weird browsers to lie (yeah that happens!)
+ if (!this._gl.deleteQuery) {
+ this._webGLVersion = 1.0;
+ this._shaderPlatformName = "WEBGL1";
+ }
+ }
+ }
+ catch (e) {
+ // Do nothing
+ }
+ }
+ if (!this._gl) {
+ if (!canvas) {
+ throw new Error("The provided canvas is null or undefined.");
+ }
+ try {
+ this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
+ }
+ catch (e) {
+ throw new Error("WebGL not supported");
+ }
+ }
+ if (!this._gl) {
+ throw new Error("WebGL not supported");
+ }
+ }
+ else {
+ this._gl = canvasOrContext;
+ canvas = this._gl.canvas;
+ if (this._gl.renderbufferStorageMultisample) {
+ this._webGLVersion = 2.0;
+ this._shaderPlatformName = "WEBGL2";
+ }
+ else {
+ this._shaderPlatformName = "WEBGL1";
+ }
+ const attributes = this._gl.getContextAttributes();
+ if (attributes) {
+ options.stencil = attributes.stencil;
+ }
+ }
+ this._sharedInit(canvas);
+ // Ensures a consistent color space unpacking of textures cross browser.
+ this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
+ if (options.useHighPrecisionFloats !== undefined) {
+ this._highPrecisionShadersAllowed = options.useHighPrecisionFloats;
+ }
+ this.resize();
+ this._initGLContext();
+ this._initFeatures();
+ // Prepare buffer pointers
+ for (let i = 0; i < this._caps.maxVertexAttribs; i++) {
+ this._currentBufferPointers[i] = new BufferPointer();
+ }
+ // Shader processor
+ this._shaderProcessor = this.webGLVersion > 1 ? new WebGL2ShaderProcessor() : new WebGLShaderProcessor();
+ // Starting with iOS 14, we can trust the browser
+ // let matches = navigator.userAgent.match(/Version\/(\d+)/);
+ // if (matches && matches.length === 2) {
+ // if (parseInt(matches[1]) >= 14) {
+ // this._badOS = false;
+ // }
+ // }
+ const versionToLog = `Babylon.js v${ThinEngine.Version}`;
+ Logger.Log(versionToLog + ` - ${this.description}`);
+ // Check setAttribute in case of workers
+ if (this._renderingCanvas && this._renderingCanvas.setAttribute) {
+ this._renderingCanvas.setAttribute("data-engine", versionToLog);
+ }
+ const stateObject = getStateObject(this._gl);
+ // update state object with the current engine state
+ stateObject.validateShaderPrograms = this.validateShaderPrograms;
+ stateObject.parallelShaderCompile = this._caps.parallelShaderCompile;
+ }
+ _clearEmptyResources() {
+ this._dummyFramebuffer = null;
+ super._clearEmptyResources();
+ }
+ /**
+ * @internal
+ */
+ _getShaderProcessingContext(shaderLanguage) {
+ return null;
+ }
+ /**
+ * Gets a boolean indicating if all created effects are ready
+ * @returns true if all effects are ready
+ */
+ areAllEffectsReady() {
+ for (const key in this._compiledEffects) {
+ const effect = this._compiledEffects[key];
+ if (!effect.isReady()) {
+ return false;
+ }
+ }
+ return true;
+ }
+ _initGLContext() {
+ // Caps
+ this._caps = {
+ maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),
+ maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),
+ maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
+ maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),
+ maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1,
+ maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),
+ maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),
+ maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),
+ maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),
+ maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),
+ maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),
+ parallelShaderCompile: this._gl.getExtension("KHR_parallel_shader_compile") || undefined,
+ standardDerivatives: this._webGLVersion > 1 || this._gl.getExtension("OES_standard_derivatives") !== null,
+ maxAnisotropy: 1,
+ astc: this._gl.getExtension("WEBGL_compressed_texture_astc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),
+ bptc: this._gl.getExtension("EXT_texture_compression_bptc") || this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),
+ s3tc: this._gl.getExtension("WEBGL_compressed_texture_s3tc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ s3tc_srgb: this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),
+ pvrtc: this._gl.getExtension("WEBGL_compressed_texture_pvrtc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),
+ etc1: this._gl.getExtension("WEBGL_compressed_texture_etc1") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),
+ etc2: this._gl.getExtension("WEBGL_compressed_texture_etc") ||
+ this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc") ||
+ this._gl.getExtension("WEBGL_compressed_texture_es3_0"), // also a requirement of OpenGL ES 3
+ textureAnisotropicFilterExtension: this._gl.getExtension("EXT_texture_filter_anisotropic") ||
+ this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") ||
+ this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),
+ uintIndices: this._webGLVersion > 1 || this._gl.getExtension("OES_element_index_uint") !== null,
+ fragmentDepthSupported: this._webGLVersion > 1 || this._gl.getExtension("EXT_frag_depth") !== null,
+ highPrecisionShaderSupported: false,
+ timerQuery: this._gl.getExtension("EXT_disjoint_timer_query_webgl2") || this._gl.getExtension("EXT_disjoint_timer_query"),
+ supportOcclusionQuery: this._webGLVersion > 1,
+ canUseTimestampForTimerQuery: false,
+ drawBuffersExtension: false,
+ maxMSAASamples: 1,
+ colorBufferFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_float")),
+ supportFloatTexturesResolve: false,
+ rg11b10ufColorRenderable: false,
+ colorBufferHalfFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_half_float")),
+ textureFloat: this._webGLVersion > 1 || this._gl.getExtension("OES_texture_float") ? true : false,
+ textureHalfFloat: this._webGLVersion > 1 || this._gl.getExtension("OES_texture_half_float") ? true : false,
+ textureHalfFloatRender: false,
+ textureFloatLinearFiltering: false,
+ textureFloatRender: false,
+ textureHalfFloatLinearFiltering: false,
+ vertexArrayObject: false,
+ instancedArrays: false,
+ textureLOD: this._webGLVersion > 1 || this._gl.getExtension("EXT_shader_texture_lod") ? true : false,
+ texelFetch: this._webGLVersion !== 1,
+ blendMinMax: false,
+ multiview: this._gl.getExtension("OVR_multiview2"),
+ oculusMultiview: this._gl.getExtension("OCULUS_multiview"),
+ depthTextureExtension: false,
+ canUseGLInstanceID: this._webGLVersion > 1,
+ canUseGLVertexID: this._webGLVersion > 1,
+ supportComputeShaders: false,
+ supportSRGBBuffers: false,
+ supportTransformFeedbacks: this._webGLVersion > 1,
+ textureMaxLevel: this._webGLVersion > 1,
+ texture2DArrayMaxLayerCount: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS) : 128,
+ disableMorphTargetTexture: false,
+ textureNorm16: this._gl.getExtension("EXT_texture_norm16") ? true : false,
+ };
+ this._caps.supportFloatTexturesResolve = this._caps.colorBufferFloat;
+ this._caps.rg11b10ufColorRenderable = this._caps.colorBufferFloat;
+ // Infos
+ this._glVersion = this._gl.getParameter(this._gl.VERSION);
+ const rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
+ if (rendererInfo != null) {
+ this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
+ this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
+ }
+ if (!this._glVendor) {
+ this._glVendor = this._gl.getParameter(this._gl.VENDOR) || "Unknown vendor";
+ }
+ if (!this._glRenderer) {
+ this._glRenderer = this._gl.getParameter(this._gl.RENDERER) || "Unknown renderer";
+ }
+ // Constants
+ if (this._gl.HALF_FLOAT_OES !== 0x8d61) {
+ this._gl.HALF_FLOAT_OES = 0x8d61; // Half floating-point type (16-bit).
+ }
+ if (this._gl.RGBA16F !== 0x881a) {
+ this._gl.RGBA16F = 0x881a; // RGBA 16-bit floating-point color-renderable internal sized format.
+ }
+ if (this._gl.RGBA32F !== 0x8814) {
+ this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
+ }
+ if (this._gl.DEPTH24_STENCIL8 !== 35056) {
+ this._gl.DEPTH24_STENCIL8 = 35056;
+ }
+ // Extensions
+ if (this._caps.timerQuery) {
+ if (this._webGLVersion === 1) {
+ this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
+ }
+ // WebGLQuery casted to number to avoid TS error
+ this._caps.canUseTimestampForTimerQuery = (this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) ?? 0) > 0;
+ }
+ this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension
+ ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT)
+ : 0;
+ this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension("OES_texture_float_linear") ? true : false;
+ this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
+ this._caps.textureHalfFloatLinearFiltering =
+ this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension("OES_texture_half_float_linear")) ? true : false;
+ if (this._caps.textureNorm16) {
+ this._gl.R16_EXT = 0x822a;
+ this._gl.RG16_EXT = 0x822c;
+ this._gl.RGB16_EXT = 0x8054;
+ this._gl.RGBA16_EXT = 0x805b;
+ this._gl.R16_SNORM_EXT = 0x8f98;
+ this._gl.RG16_SNORM_EXT = 0x8f99;
+ this._gl.RGB16_SNORM_EXT = 0x8f9a;
+ this._gl.RGBA16_SNORM_EXT = 0x8f9b;
+ }
+ // Compressed formats
+ if (this._caps.astc) {
+ this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
+ }
+ if (this._caps.bptc) {
+ this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;
+ }
+ if (this._caps.s3tc_srgb) {
+ this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT;
+ this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
+ this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
+ }
+ if (this._caps.etc2) {
+ this._gl.COMPRESSED_SRGB8_ETC2 = this._caps.etc2.COMPRESSED_SRGB8_ETC2;
+ this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
+ }
+ // Checks if some of the format renders first to allow the use of webgl inspector.
+ if (this._webGLVersion > 1) {
+ if (this._gl.HALF_FLOAT_OES !== 0x140b) {
+ this._gl.HALF_FLOAT_OES = 0x140b;
+ }
+ }
+ this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
+ // Draw buffers
+ if (this._webGLVersion > 1) {
+ this._caps.drawBuffersExtension = true;
+ this._caps.maxMSAASamples = this._maxMSAASamplesOverride !== null ? this._maxMSAASamplesOverride : this._gl.getParameter(this._gl.MAX_SAMPLES);
+ this._caps.maxDrawBuffers = this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);
+ }
+ else {
+ const drawBuffersExtension = this._gl.getExtension("WEBGL_draw_buffers");
+ if (drawBuffersExtension !== null) {
+ this._caps.drawBuffersExtension = true;
+ this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
+ this._caps.maxDrawBuffers = this._gl.getParameter(drawBuffersExtension.MAX_DRAW_BUFFERS_WEBGL);
+ this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
+ for (let i = 0; i < 16; i++) {
+ this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
+ }
+ }
+ }
+ // Depth Texture
+ if (this._webGLVersion > 1) {
+ this._caps.depthTextureExtension = true;
+ }
+ else {
+ const depthTextureExtension = this._gl.getExtension("WEBGL_depth_texture");
+ if (depthTextureExtension != null) {
+ this._caps.depthTextureExtension = true;
+ this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
+ }
+ }
+ // Vertex array object
+ if (this.disableVertexArrayObjects) {
+ this._caps.vertexArrayObject = false;
+ }
+ else if (this._webGLVersion > 1) {
+ this._caps.vertexArrayObject = true;
+ }
+ else {
+ const vertexArrayObjectExtension = this._gl.getExtension("OES_vertex_array_object");
+ if (vertexArrayObjectExtension != null) {
+ this._caps.vertexArrayObject = true;
+ this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
+ this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
+ this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
+ }
+ }
+ // Instances count
+ if (this._webGLVersion > 1) {
+ this._caps.instancedArrays = true;
+ }
+ else {
+ const instanceExtension = this._gl.getExtension("ANGLE_instanced_arrays");
+ if (instanceExtension != null) {
+ this._caps.instancedArrays = true;
+ this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
+ this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
+ this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
+ }
+ else {
+ this._caps.instancedArrays = false;
+ }
+ }
+ if (this._gl.getShaderPrecisionFormat) {
+ const vertexhighp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
+ const fragmenthighp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
+ if (vertexhighp && fragmenthighp) {
+ this._caps.highPrecisionShaderSupported = vertexhighp.precision !== 0 && fragmenthighp.precision !== 0;
+ }
+ }
+ if (this._webGLVersion > 1) {
+ this._caps.blendMinMax = true;
+ }
+ else {
+ const blendMinMaxExtension = this._gl.getExtension("EXT_blend_minmax");
+ if (blendMinMaxExtension != null) {
+ this._caps.blendMinMax = true;
+ this._gl.MAX = blendMinMaxExtension.MAX_EXT;
+ this._gl.MIN = blendMinMaxExtension.MIN_EXT;
+ }
+ }
+ // sRGB buffers
+ // only run this if not already set to true (in the constructor, for example)
+ if (!this._caps.supportSRGBBuffers) {
+ if (this._webGLVersion > 1) {
+ this._caps.supportSRGBBuffers = true;
+ this._glSRGBExtensionValues = {
+ SRGB: WebGL2RenderingContext.SRGB,
+ SRGB8: WebGL2RenderingContext.SRGB8,
+ SRGB8_ALPHA8: WebGL2RenderingContext.SRGB8_ALPHA8,
+ };
+ }
+ else {
+ const sRGBExtension = this._gl.getExtension("EXT_sRGB");
+ if (sRGBExtension != null) {
+ this._caps.supportSRGBBuffers = true;
+ this._glSRGBExtensionValues = {
+ SRGB: sRGBExtension.SRGB_EXT,
+ SRGB8: sRGBExtension.SRGB_ALPHA_EXT,
+ SRGB8_ALPHA8: sRGBExtension.SRGB_ALPHA_EXT,
+ };
+ }
+ }
+ // take into account the forced state that was provided in options
+ if (this._creationOptions) {
+ const forceSRGBBufferSupportState = this._creationOptions.forceSRGBBufferSupportState;
+ if (forceSRGBBufferSupportState !== undefined) {
+ this._caps.supportSRGBBuffers = this._caps.supportSRGBBuffers && forceSRGBBufferSupportState;
+ }
+ }
+ }
+ // Depth buffer
+ this._depthCullingState.depthTest = true;
+ this._depthCullingState.depthFunc = this._gl.LEQUAL;
+ this._depthCullingState.depthMask = true;
+ // Texture maps
+ this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
+ for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
+ this._nextFreeTextureSlots.push(slot);
+ }
+ if (this._glRenderer === "Mali-G72") {
+ // Overcome a bug when using a texture to store morph targets on Mali-G72
+ this._caps.disableMorphTargetTexture = true;
+ }
+ }
+ _initFeatures() {
+ this._features = {
+ forceBitmapOverHTMLImageElement: typeof HTMLImageElement === "undefined",
+ supportRenderAndCopyToLodForFloatTextures: this._webGLVersion !== 1,
+ supportDepthStencilTexture: this._webGLVersion !== 1,
+ supportShadowSamplers: this._webGLVersion !== 1,
+ uniformBufferHardCheckMatrix: false,
+ allowTexturePrefiltering: this._webGLVersion !== 1,
+ trackUbosInFrame: false,
+ checkUbosContentBeforeUpload: false,
+ supportCSM: this._webGLVersion !== 1,
+ basisNeedsPOT: this._webGLVersion === 1,
+ support3DTextures: this._webGLVersion !== 1,
+ needTypeSuffixInShaderConstants: this._webGLVersion !== 1,
+ supportMSAA: this._webGLVersion !== 1,
+ supportSSAO2: this._webGLVersion !== 1,
+ supportIBLShadows: this._webGLVersion !== 1,
+ supportExtendedTextureFormats: this._webGLVersion !== 1,
+ supportSwitchCaseInShader: this._webGLVersion !== 1,
+ supportSyncTextureRead: true,
+ needsInvertingBitmap: true,
+ useUBOBindingCache: true,
+ needShaderCodeInlining: false,
+ needToAlwaysBindUniformBuffers: false,
+ supportRenderPasses: false,
+ supportSpriteInstancing: true,
+ forceVertexBufferStrideAndOffsetMultiple4Bytes: false,
+ _checkNonFloatVertexBuffersDontRecreatePipelineContext: false,
+ _collectUbosUpdatedInFrame: false,
+ };
+ }
+ /**
+ * Gets version of the current webGL context
+ * Keep it for back compat - use version instead
+ */
+ get webGLVersion() {
+ return this._webGLVersion;
+ }
+ /**
+ * Gets a string identifying the name of the class
+ * @returns "Engine" string
+ */
+ getClassName() {
+ return "ThinEngine";
+ }
+ /** @internal */
+ _prepareWorkingCanvas() {
+ if (this._workingCanvas) {
+ return;
+ }
+ this._workingCanvas = this.createCanvas(1, 1);
+ const context = this._workingCanvas.getContext("2d");
+ if (context) {
+ this._workingContext = context;
+ }
+ }
+ /**
+ * Gets an object containing information about the current engine context
+ * @returns an object containing the vendor, the renderer and the version of the current engine context
+ */
+ getInfo() {
+ return this.getGlInfo();
+ }
+ /**
+ * Gets an object containing information about the current webGL context
+ * @returns an object containing the vendor, the renderer and the version of the current webGL context
+ */
+ getGlInfo() {
+ return {
+ vendor: this._glVendor,
+ renderer: this._glRenderer,
+ version: this._glVersion,
+ };
+ }
+ /**Gets driver info if available */
+ extractDriverInfo() {
+ const glInfo = this.getGlInfo();
+ if (glInfo && glInfo.renderer) {
+ return glInfo.renderer;
+ }
+ return "";
+ }
+ /**
+ * Gets the current render width
+ * @param useScreen defines if screen size must be used (or the current render target if any)
+ * @returns a number defining the current render width
+ */
+ getRenderWidth(useScreen = false) {
+ if (!useScreen && this._currentRenderTarget) {
+ return this._currentRenderTarget.width;
+ }
+ return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth;
+ }
+ /**
+ * Gets the current render height
+ * @param useScreen defines if screen size must be used (or the current render target if any)
+ * @returns a number defining the current render height
+ */
+ getRenderHeight(useScreen = false) {
+ if (!useScreen && this._currentRenderTarget) {
+ return this._currentRenderTarget.height;
+ }
+ return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight;
+ }
+ /**
+ * Clear the current render buffer or the current render target (if any is set up)
+ * @param color defines the color to use
+ * @param backBuffer defines if the back buffer must be cleared
+ * @param depth defines if the depth buffer must be cleared
+ * @param stencil defines if the stencil buffer must be cleared
+ */
+ clear(color, backBuffer, depth, stencil = false) {
+ const useStencilGlobalOnly = this.stencilStateComposer.useStencilGlobalOnly;
+ this.stencilStateComposer.useStencilGlobalOnly = true; // make sure the stencil mask is coming from the global stencil and not from a material (effect) which would currently be in effect
+ this.applyStates();
+ this.stencilStateComposer.useStencilGlobalOnly = useStencilGlobalOnly;
+ let mode = 0;
+ if (backBuffer && color) {
+ let setBackBufferColor = true;
+ if (this._currentRenderTarget) {
+ const textureFormat = this._currentRenderTarget.texture?.format;
+ if (textureFormat === 8 ||
+ textureFormat === 9 ||
+ textureFormat === 10 ||
+ textureFormat === 11) {
+ const textureType = this._currentRenderTarget.texture?.type;
+ if (textureType === 7 || textureType === 5) {
+ ThinEngine._TempClearColorUint32[0] = color.r * 255;
+ ThinEngine._TempClearColorUint32[1] = color.g * 255;
+ ThinEngine._TempClearColorUint32[2] = color.b * 255;
+ ThinEngine._TempClearColorUint32[3] = color.a * 255;
+ this._gl.clearBufferuiv(this._gl.COLOR, 0, ThinEngine._TempClearColorUint32);
+ setBackBufferColor = false;
+ }
+ else {
+ ThinEngine._TempClearColorInt32[0] = color.r * 255;
+ ThinEngine._TempClearColorInt32[1] = color.g * 255;
+ ThinEngine._TempClearColorInt32[2] = color.b * 255;
+ ThinEngine._TempClearColorInt32[3] = color.a * 255;
+ this._gl.clearBufferiv(this._gl.COLOR, 0, ThinEngine._TempClearColorInt32);
+ setBackBufferColor = false;
+ }
+ }
+ }
+ if (setBackBufferColor) {
+ this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
+ mode |= this._gl.COLOR_BUFFER_BIT;
+ }
+ }
+ if (depth) {
+ if (this.useReverseDepthBuffer) {
+ this._depthCullingState.depthFunc = this._gl.GEQUAL;
+ this._gl.clearDepth(0.0);
+ }
+ else {
+ this._gl.clearDepth(1.0);
+ }
+ mode |= this._gl.DEPTH_BUFFER_BIT;
+ }
+ if (stencil) {
+ this._gl.clearStencil(0);
+ mode |= this._gl.STENCIL_BUFFER_BIT;
+ }
+ this._gl.clear(mode);
+ }
+ /**
+ * @internal
+ */
+ _viewport(x, y, width, height) {
+ if (x !== this._viewportCached.x || y !== this._viewportCached.y || width !== this._viewportCached.z || height !== this._viewportCached.w) {
+ this._viewportCached.x = x;
+ this._viewportCached.y = y;
+ this._viewportCached.z = width;
+ this._viewportCached.w = height;
+ this._gl.viewport(x, y, width, height);
+ }
+ }
+ /**
+ * End the current frame
+ */
+ endFrame() {
+ super.endFrame();
+ // Force a flush in case we are using a bad OS.
+ if (this._badOS) {
+ this.flushFramebuffer();
+ }
+ }
+ /**
+ * Gets the performance monitor attached to this engine
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation
+ */
+ get performanceMonitor() {
+ throw new Error("Not Supported by ThinEngine");
+ }
+ /**
+ * Binds the frame buffer to the specified texture.
+ * @param rtWrapper The render target wrapper to render to
+ * @param faceIndex The face of the texture to render to in case of cube texture and if the render target wrapper is not a multi render target
+ * @param requiredWidth The width of the target to render to
+ * @param requiredHeight The height of the target to render to
+ * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
+ * @param lodLevel Defines the lod level to bind to the frame buffer
+ * @param layer Defines the 2d array index to bind to the frame buffer if the render target wrapper is not a multi render target
+ */
+ bindFramebuffer(rtWrapper, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) {
+ const webglRTWrapper = rtWrapper;
+ if (this._currentRenderTarget) {
+ this.unBindFramebuffer(this._currentRenderTarget);
+ }
+ this._currentRenderTarget = rtWrapper;
+ this._bindUnboundFramebuffer(webglRTWrapper._framebuffer);
+ const gl = this._gl;
+ if (!rtWrapper.isMulti) {
+ if (rtWrapper.is2DArray || rtWrapper.is3D) {
+ gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel, layer);
+ webglRTWrapper._currentLOD = lodLevel;
+ }
+ else if (rtWrapper.isCube) {
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel);
+ }
+ else if (webglRTWrapper._currentLOD !== lodLevel) {
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel);
+ webglRTWrapper._currentLOD = lodLevel;
+ }
+ }
+ const depthStencilTexture = rtWrapper._depthStencilTexture;
+ if (depthStencilTexture) {
+ if (rtWrapper.is3D) {
+ if (rtWrapper.texture.width !== depthStencilTexture.width ||
+ rtWrapper.texture.height !== depthStencilTexture.height ||
+ rtWrapper.texture.depth !== depthStencilTexture.depth) {
+ Logger.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment");
+ }
+ }
+ const attachment = rtWrapper._depthStencilTextureWithStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
+ if (rtWrapper.is2DArray || rtWrapper.is3D) {
+ gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel, layer);
+ }
+ else if (rtWrapper.isCube) {
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel);
+ }
+ else {
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel);
+ }
+ }
+ if (webglRTWrapper._MSAAFramebuffer) {
+ this._bindUnboundFramebuffer(webglRTWrapper._MSAAFramebuffer);
+ }
+ if (this._cachedViewport && !forceFullscreenViewport) {
+ this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
+ }
+ else {
+ if (!requiredWidth) {
+ requiredWidth = rtWrapper.width;
+ if (lodLevel) {
+ requiredWidth = requiredWidth / Math.pow(2, lodLevel);
+ }
+ }
+ if (!requiredHeight) {
+ requiredHeight = rtWrapper.height;
+ if (lodLevel) {
+ requiredHeight = requiredHeight / Math.pow(2, lodLevel);
+ }
+ }
+ this._viewport(0, 0, requiredWidth, requiredHeight);
+ }
+ this.wipeCaches();
+ }
+ setStateCullFaceType(cullBackFaces, force) {
+ const cullFace = (this.cullBackFaces ?? cullBackFaces ?? true) ? this._gl.BACK : this._gl.FRONT;
+ if (this._depthCullingState.cullFace !== cullFace || force) {
+ this._depthCullingState.cullFace = cullFace;
+ }
+ }
+ /**
+ * Set various states to the webGL context
+ * @param culling defines culling state: true to enable culling, false to disable it
+ * @param zOffset defines the value to apply to zOffset (0 by default)
+ * @param force defines if states must be applied even if cache is up to date
+ * @param reverseSide defines if culling must be reversed (CCW if false, CW if true)
+ * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled)
+ * @param stencil stencil states to set
+ * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default)
+ */
+ setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) {
+ // Culling
+ if (this._depthCullingState.cull !== culling || force) {
+ this._depthCullingState.cull = culling;
+ }
+ // Cull face
+ this.setStateCullFaceType(cullBackFaces, force);
+ // Z offset
+ this.setZOffset(zOffset);
+ this.setZOffsetUnits(zOffsetUnits);
+ // Front face
+ const frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
+ if (this._depthCullingState.frontFace !== frontFace || force) {
+ this._depthCullingState.frontFace = frontFace;
+ }
+ this._stencilStateComposer.stencilMaterial = stencil;
+ }
+ /**
+ * @internal
+ */
+ _bindUnboundFramebuffer(framebuffer) {
+ if (this._currentFramebuffer !== framebuffer) {
+ this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
+ this._currentFramebuffer = framebuffer;
+ }
+ }
+ /** @internal */
+ _currentFrameBufferIsDefaultFrameBuffer() {
+ return this._currentFramebuffer === null;
+ }
+ /**
+ * Generates the mipmaps for a texture
+ * @param texture texture to generate the mipmaps for
+ */
+ generateMipmaps(texture) {
+ const target = this._getTextureTarget(texture);
+ this._bindTextureDirectly(target, texture, true);
+ this._gl.generateMipmap(target);
+ this._bindTextureDirectly(target, null);
+ }
+ /**
+ * Unbind the current render target texture from the webGL context
+ * @param texture defines the render target wrapper to unbind
+ * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
+ * @param onBeforeUnbind defines a function which will be called before the effective unbind
+ */
+ unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) {
+ const webglRTWrapper = texture;
+ this._currentRenderTarget = null;
+ if (!webglRTWrapper.disableAutomaticMSAAResolve) {
+ if (texture.isMulti) {
+ this.resolveMultiFramebuffer(texture);
+ }
+ else {
+ this.resolveFramebuffer(texture);
+ }
+ }
+ if (!disableGenerateMipMaps) {
+ if (texture.isMulti) {
+ this.generateMipMapsMultiFramebuffer(texture);
+ }
+ else {
+ this.generateMipMapsFramebuffer(texture);
+ }
+ }
+ if (onBeforeUnbind) {
+ if (webglRTWrapper._MSAAFramebuffer) {
+ // Bind the correct framebuffer
+ this._bindUnboundFramebuffer(webglRTWrapper._framebuffer);
+ }
+ onBeforeUnbind();
+ }
+ this._bindUnboundFramebuffer(null);
+ }
+ /**
+ * Generates mipmaps for the texture of the (single) render target
+ * @param texture The render target containing the texture to generate the mipmaps for
+ */
+ generateMipMapsFramebuffer(texture) {
+ if (!texture.isMulti && texture.texture?.generateMipMaps && !texture.isCube) {
+ this.generateMipmaps(texture.texture);
+ }
+ }
+ /**
+ * Resolves the MSAA texture of the (single) render target into its non-MSAA version.
+ * Note that if "texture" is not a MSAA render target, no resolve is performed.
+ * @param texture The render target texture containing the MSAA textures to resolve
+ */
+ resolveFramebuffer(texture) {
+ const rtWrapper = texture;
+ const gl = this._gl;
+ if (!rtWrapper._MSAAFramebuffer || rtWrapper.isMulti) {
+ return;
+ }
+ let bufferBits = rtWrapper.resolveMSAAColors ? gl.COLOR_BUFFER_BIT : 0;
+ bufferBits |= rtWrapper._generateDepthBuffer && rtWrapper.resolveMSAADepth ? gl.DEPTH_BUFFER_BIT : 0;
+ bufferBits |= rtWrapper._generateStencilBuffer && rtWrapper.resolveMSAAStencil ? gl.STENCIL_BUFFER_BIT : 0;
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer);
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer);
+ gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, bufferBits, gl.NEAREST);
+ }
+ /**
+ * Force a webGL flush (ie. a flush of all waiting webGL commands)
+ */
+ flushFramebuffer() {
+ this._gl.flush();
+ }
+ /**
+ * Unbind the current render target and bind the default framebuffer
+ */
+ restoreDefaultFramebuffer() {
+ if (this._currentRenderTarget) {
+ this.unBindFramebuffer(this._currentRenderTarget);
+ }
+ else {
+ this._bindUnboundFramebuffer(null);
+ }
+ if (this._cachedViewport) {
+ this.setViewport(this._cachedViewport);
+ }
+ this.wipeCaches();
+ }
+ // VBOs
+ /** @internal */
+ _resetVertexBufferBinding() {
+ this.bindArrayBuffer(null);
+ this._cachedVertexBuffers = null;
+ }
+ /**
+ * Creates a vertex buffer
+ * @param data the data or size for the vertex buffer
+ * @param _updatable whether the buffer should be created as updatable
+ * @param _label defines the label of the buffer (for debug purpose)
+ * @returns the new WebGL static buffer
+ */
+ createVertexBuffer(data, _updatable, _label) {
+ return this._createVertexBuffer(data, this._gl.STATIC_DRAW);
+ }
+ _createVertexBuffer(data, usage) {
+ const vbo = this._gl.createBuffer();
+ if (!vbo) {
+ throw new Error("Unable to create vertex buffer");
+ }
+ const dataBuffer = new WebGLDataBuffer(vbo);
+ this.bindArrayBuffer(dataBuffer);
+ if (typeof data !== "number") {
+ if (data instanceof Array) {
+ this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), usage);
+ dataBuffer.capacity = data.length * 4;
+ }
+ else {
+ this._gl.bufferData(this._gl.ARRAY_BUFFER, data, usage);
+ dataBuffer.capacity = data.byteLength;
+ }
+ }
+ else {
+ this._gl.bufferData(this._gl.ARRAY_BUFFER, new Uint8Array(data), usage);
+ dataBuffer.capacity = data;
+ }
+ this._resetVertexBufferBinding();
+ dataBuffer.references = 1;
+ return dataBuffer;
+ }
+ /**
+ * Creates a dynamic vertex buffer
+ * @param data the data for the dynamic vertex buffer
+ * @param _label defines the label of the buffer (for debug purpose)
+ * @returns the new WebGL dynamic buffer
+ */
+ createDynamicVertexBuffer(data, _label) {
+ return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW);
+ }
+ _resetIndexBufferBinding() {
+ this.bindIndexBuffer(null);
+ this._cachedIndexBuffer = null;
+ }
+ /**
+ * Creates a new index buffer
+ * @param indices defines the content of the index buffer
+ * @param updatable defines if the index buffer must be updatable
+ * @param _label defines the label of the buffer (for debug purpose)
+ * @returns a new webGL buffer
+ */
+ createIndexBuffer(indices, updatable, _label) {
+ const vbo = this._gl.createBuffer();
+ const dataBuffer = new WebGLDataBuffer(vbo);
+ if (!vbo) {
+ throw new Error("Unable to create index buffer");
+ }
+ this.bindIndexBuffer(dataBuffer);
+ const data = this._normalizeIndexData(indices);
+ this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, data, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
+ this._resetIndexBufferBinding();
+ dataBuffer.references = 1;
+ dataBuffer.is32Bits = data.BYTES_PER_ELEMENT === 4;
+ return dataBuffer;
+ }
+ _normalizeIndexData(indices) {
+ const bytesPerElement = indices.BYTES_PER_ELEMENT;
+ if (bytesPerElement === 2) {
+ return indices;
+ }
+ // Check 32 bit support
+ if (this._caps.uintIndices) {
+ if (indices instanceof Uint32Array) {
+ return indices;
+ }
+ else {
+ // number[] or Int32Array, check if 32 bit is necessary
+ for (let index = 0; index < indices.length; index++) {
+ if (indices[index] >= 65535) {
+ return new Uint32Array(indices);
+ }
+ }
+ return new Uint16Array(indices);
+ }
+ }
+ // No 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
+ return new Uint16Array(indices);
+ }
+ /**
+ * Bind a webGL buffer to the webGL context
+ * @param buffer defines the buffer to bind
+ */
+ bindArrayBuffer(buffer) {
+ if (!this._vaoRecordInProgress) {
+ this._unbindVertexArrayObject();
+ }
+ this._bindBuffer(buffer, this._gl.ARRAY_BUFFER);
+ }
+ /**
+ * Bind a specific block at a given index in a specific shader program
+ * @param pipelineContext defines the pipeline context to use
+ * @param blockName defines the block name
+ * @param index defines the index where to bind the block
+ */
+ bindUniformBlock(pipelineContext, blockName, index) {
+ const program = pipelineContext.program;
+ const uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
+ this._gl.uniformBlockBinding(program, uniformLocation, index);
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ bindIndexBuffer(buffer) {
+ if (!this._vaoRecordInProgress) {
+ this._unbindVertexArrayObject();
+ }
+ this._bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
+ }
+ _bindBuffer(buffer, target) {
+ if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
+ this._gl.bindBuffer(target, buffer ? buffer.underlyingResource : null);
+ this._currentBoundBuffer[target] = buffer;
+ }
+ }
+ /**
+ * update the bound buffer with the given data
+ * @param data defines the data to update
+ */
+ updateArrayBuffer(data) {
+ this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
+ }
+ _vertexAttribPointer(buffer, indx, size, type, normalized, stride, offset) {
+ const pointer = this._currentBufferPointers[indx];
+ if (!pointer) {
+ return;
+ }
+ let changed = false;
+ if (!pointer.active) {
+ changed = true;
+ pointer.active = true;
+ pointer.index = indx;
+ pointer.size = size;
+ pointer.type = type;
+ pointer.normalized = normalized;
+ pointer.stride = stride;
+ pointer.offset = offset;
+ pointer.buffer = buffer;
+ }
+ else {
+ if (pointer.buffer !== buffer) {
+ pointer.buffer = buffer;
+ changed = true;
+ }
+ if (pointer.size !== size) {
+ pointer.size = size;
+ changed = true;
+ }
+ if (pointer.type !== type) {
+ pointer.type = type;
+ changed = true;
+ }
+ if (pointer.normalized !== normalized) {
+ pointer.normalized = normalized;
+ changed = true;
+ }
+ if (pointer.stride !== stride) {
+ pointer.stride = stride;
+ changed = true;
+ }
+ if (pointer.offset !== offset) {
+ pointer.offset = offset;
+ changed = true;
+ }
+ }
+ if (changed || this._vaoRecordInProgress) {
+ this.bindArrayBuffer(buffer);
+ if (type === this._gl.UNSIGNED_INT || type === this._gl.INT) {
+ this._gl.vertexAttribIPointer(indx, size, type, stride, offset);
+ }
+ else {
+ this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
+ }
+ }
+ }
+ /**
+ * @internal
+ */
+ _bindIndexBufferWithCache(indexBuffer) {
+ if (indexBuffer == null) {
+ return;
+ }
+ if (this._cachedIndexBuffer !== indexBuffer) {
+ this._cachedIndexBuffer = indexBuffer;
+ this.bindIndexBuffer(indexBuffer);
+ this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
+ }
+ }
+ _bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers) {
+ const attributes = effect.getAttributesNames();
+ if (!this._vaoRecordInProgress) {
+ this._unbindVertexArrayObject();
+ }
+ this.unbindAllAttributes();
+ for (let index = 0; index < attributes.length; index++) {
+ const order = effect.getAttributeLocation(index);
+ if (order >= 0) {
+ const ai = attributes[index];
+ let vertexBuffer = null;
+ if (overrideVertexBuffers) {
+ vertexBuffer = overrideVertexBuffers[ai];
+ }
+ if (!vertexBuffer) {
+ vertexBuffer = vertexBuffers[ai];
+ }
+ if (!vertexBuffer) {
+ continue;
+ }
+ this._gl.enableVertexAttribArray(order);
+ if (!this._vaoRecordInProgress) {
+ this._vertexAttribArraysEnabled[order] = true;
+ }
+ const buffer = vertexBuffer.getBuffer();
+ if (buffer) {
+ this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
+ if (vertexBuffer.getIsInstanced()) {
+ this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
+ if (!this._vaoRecordInProgress) {
+ this._currentInstanceLocations.push(order);
+ this._currentInstanceBuffers.push(buffer);
+ }
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Records a vertex array object
+ * @see https://doc.babylonjs.com/setup/support/webGL2#vertex-array-objects
+ * @param vertexBuffers defines the list of vertex buffers to store
+ * @param indexBuffer defines the index buffer to store
+ * @param effect defines the effect to store
+ * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers
+ * @returns the new vertex array object
+ */
+ recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {
+ const vao = this._gl.createVertexArray();
+ if (!vao) {
+ throw new Error("Unable to create VAO");
+ }
+ this._vaoRecordInProgress = true;
+ this._gl.bindVertexArray(vao);
+ this._mustWipeVertexAttributes = true;
+ this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers);
+ this.bindIndexBuffer(indexBuffer);
+ this._vaoRecordInProgress = false;
+ this._gl.bindVertexArray(null);
+ return vao;
+ }
+ /**
+ * Bind a specific vertex array object
+ * @see https://doc.babylonjs.com/setup/support/webGL2#vertex-array-objects
+ * @param vertexArrayObject defines the vertex array object to bind
+ * @param indexBuffer defines the index buffer to bind
+ */
+ bindVertexArrayObject(vertexArrayObject, indexBuffer) {
+ if (this._cachedVertexArrayObject !== vertexArrayObject) {
+ this._cachedVertexArrayObject = vertexArrayObject;
+ this._gl.bindVertexArray(vertexArrayObject);
+ this._cachedVertexBuffers = null;
+ this._cachedIndexBuffer = null;
+ this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
+ this._mustWipeVertexAttributes = true;
+ }
+ }
+ /**
+ * Bind webGl buffers directly to the webGL context
+ * @param vertexBuffer defines the vertex buffer to bind
+ * @param indexBuffer defines the index buffer to bind
+ * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
+ * @param vertexStrideSize defines the vertex stride of the vertex buffer
+ * @param effect defines the effect associated with the vertex buffer
+ */
+ bindBuffersDirectly(vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
+ if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
+ this._cachedVertexBuffers = vertexBuffer;
+ this._cachedEffectForVertexBuffers = effect;
+ const attributesCount = effect.getAttributesCount();
+ this._unbindVertexArrayObject();
+ this.unbindAllAttributes();
+ let offset = 0;
+ for (let index = 0; index < attributesCount; index++) {
+ if (index < vertexDeclaration.length) {
+ const order = effect.getAttributeLocation(index);
+ if (order >= 0) {
+ this._gl.enableVertexAttribArray(order);
+ this._vertexAttribArraysEnabled[order] = true;
+ this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
+ }
+ offset += vertexDeclaration[index] * 4;
+ }
+ }
+ }
+ this._bindIndexBufferWithCache(indexBuffer);
+ }
+ _unbindVertexArrayObject() {
+ if (!this._cachedVertexArrayObject) {
+ return;
+ }
+ this._cachedVertexArrayObject = null;
+ this._gl.bindVertexArray(null);
+ }
+ /**
+ * Bind a list of vertex buffers to the webGL context
+ * @param vertexBuffers defines the list of vertex buffers to bind
+ * @param indexBuffer defines the index buffer to bind
+ * @param effect defines the effect associated with the vertex buffers
+ * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers
+ */
+ bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {
+ if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
+ this._cachedVertexBuffers = vertexBuffers;
+ this._cachedEffectForVertexBuffers = effect;
+ this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers);
+ }
+ this._bindIndexBufferWithCache(indexBuffer);
+ }
+ /**
+ * Unbind all instance attributes
+ */
+ unbindInstanceAttributes() {
+ let boundBuffer;
+ for (let i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
+ const instancesBuffer = this._currentInstanceBuffers[i];
+ if (boundBuffer != instancesBuffer && instancesBuffer.references) {
+ boundBuffer = instancesBuffer;
+ this.bindArrayBuffer(instancesBuffer);
+ }
+ const offsetLocation = this._currentInstanceLocations[i];
+ this._gl.vertexAttribDivisor(offsetLocation, 0);
+ }
+ this._currentInstanceBuffers.length = 0;
+ this._currentInstanceLocations.length = 0;
+ }
+ /**
+ * Release and free the memory of a vertex array object
+ * @param vao defines the vertex array object to delete
+ */
+ releaseVertexArrayObject(vao) {
+ this._gl.deleteVertexArray(vao);
+ }
+ /**
+ * @internal
+ */
+ _releaseBuffer(buffer) {
+ buffer.references--;
+ if (buffer.references === 0) {
+ this._deleteBuffer(buffer);
+ return true;
+ }
+ return false;
+ }
+ _deleteBuffer(buffer) {
+ this._gl.deleteBuffer(buffer.underlyingResource);
+ }
+ /**
+ * Update the content of a webGL buffer used with instantiation and bind it to the webGL context
+ * @param instancesBuffer defines the webGL buffer to update and bind
+ * @param data defines the data to store in the buffer
+ * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
+ */
+ updateAndBindInstancesBuffer(instancesBuffer, data, offsetLocations) {
+ this.bindArrayBuffer(instancesBuffer);
+ if (data) {
+ this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
+ }
+ if (offsetLocations[0].index !== undefined) {
+ this.bindInstancesBuffer(instancesBuffer, offsetLocations, true);
+ }
+ else {
+ for (let index = 0; index < 4; index++) {
+ const offsetLocation = offsetLocations[index];
+ if (!this._vertexAttribArraysEnabled[offsetLocation]) {
+ this._gl.enableVertexAttribArray(offsetLocation);
+ this._vertexAttribArraysEnabled[offsetLocation] = true;
+ }
+ this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
+ this._gl.vertexAttribDivisor(offsetLocation, 1);
+ this._currentInstanceLocations.push(offsetLocation);
+ this._currentInstanceBuffers.push(instancesBuffer);
+ }
+ }
+ }
+ /**
+ * Bind the content of a webGL buffer used with instantiation
+ * @param instancesBuffer defines the webGL buffer to bind
+ * @param attributesInfo defines the offsets or attributes information used to determine where data must be stored in the buffer
+ * @param computeStride defines Whether to compute the strides from the info or use the default 0
+ */
+ bindInstancesBuffer(instancesBuffer, attributesInfo, computeStride = true) {
+ this.bindArrayBuffer(instancesBuffer);
+ let stride = 0;
+ if (computeStride) {
+ for (let i = 0; i < attributesInfo.length; i++) {
+ const ai = attributesInfo[i];
+ stride += ai.attributeSize * 4;
+ }
+ }
+ for (let i = 0; i < attributesInfo.length; i++) {
+ const ai = attributesInfo[i];
+ if (ai.index === undefined) {
+ ai.index = this._currentEffect.getAttributeLocationByName(ai.attributeName);
+ }
+ if (ai.index < 0) {
+ continue;
+ }
+ if (!this._vertexAttribArraysEnabled[ai.index]) {
+ this._gl.enableVertexAttribArray(ai.index);
+ this._vertexAttribArraysEnabled[ai.index] = true;
+ }
+ this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attributeType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
+ this._gl.vertexAttribDivisor(ai.index, ai.divisor === undefined ? 1 : ai.divisor);
+ this._currentInstanceLocations.push(ai.index);
+ this._currentInstanceBuffers.push(instancesBuffer);
+ }
+ }
+ /**
+ * Disable the instance attribute corresponding to the name in parameter
+ * @param name defines the name of the attribute to disable
+ */
+ disableInstanceAttributeByName(name) {
+ if (!this._currentEffect) {
+ return;
+ }
+ const attributeLocation = this._currentEffect.getAttributeLocationByName(name);
+ this.disableInstanceAttribute(attributeLocation);
+ }
+ /**
+ * Disable the instance attribute corresponding to the location in parameter
+ * @param attributeLocation defines the attribute location of the attribute to disable
+ */
+ disableInstanceAttribute(attributeLocation) {
+ let shouldClean = false;
+ let index;
+ while ((index = this._currentInstanceLocations.indexOf(attributeLocation)) !== -1) {
+ this._currentInstanceLocations.splice(index, 1);
+ this._currentInstanceBuffers.splice(index, 1);
+ shouldClean = true;
+ index = this._currentInstanceLocations.indexOf(attributeLocation);
+ }
+ if (shouldClean) {
+ this._gl.vertexAttribDivisor(attributeLocation, 0);
+ this.disableAttributeByIndex(attributeLocation);
+ }
+ }
+ /**
+ * Disable the attribute corresponding to the location in parameter
+ * @param attributeLocation defines the attribute location of the attribute to disable
+ */
+ disableAttributeByIndex(attributeLocation) {
+ this._gl.disableVertexAttribArray(attributeLocation);
+ this._vertexAttribArraysEnabled[attributeLocation] = false;
+ this._currentBufferPointers[attributeLocation].active = false;
+ }
+ /**
+ * Send a draw order
+ * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
+ * @param indexStart defines the starting index
+ * @param indexCount defines the number of index to draw
+ * @param instancesCount defines the number of instances to draw (if instantiation is enabled)
+ */
+ draw(useTriangles, indexStart, indexCount, instancesCount) {
+ this.drawElementsType(useTriangles ? 0 : 1, indexStart, indexCount, instancesCount);
+ }
+ /**
+ * Draw a list of points
+ * @param verticesStart defines the index of first vertex to draw
+ * @param verticesCount defines the count of vertices to draw
+ * @param instancesCount defines the number of instances to draw (if instantiation is enabled)
+ */
+ drawPointClouds(verticesStart, verticesCount, instancesCount) {
+ this.drawArraysType(2, verticesStart, verticesCount, instancesCount);
+ }
+ /**
+ * Draw a list of unindexed primitives
+ * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
+ * @param verticesStart defines the index of first vertex to draw
+ * @param verticesCount defines the count of vertices to draw
+ * @param instancesCount defines the number of instances to draw (if instantiation is enabled)
+ */
+ drawUnIndexed(useTriangles, verticesStart, verticesCount, instancesCount) {
+ this.drawArraysType(useTriangles ? 0 : 1, verticesStart, verticesCount, instancesCount);
+ }
+ /**
+ * Draw a list of indexed primitives
+ * @param fillMode defines the primitive to use
+ * @param indexStart defines the starting index
+ * @param indexCount defines the number of index to draw
+ * @param instancesCount defines the number of instances to draw (if instantiation is enabled)
+ */
+ drawElementsType(fillMode, indexStart, indexCount, instancesCount) {
+ // Apply states
+ this.applyStates();
+ this._reportDrawCall();
+ // Render
+ const drawMode = this._drawMode(fillMode);
+ const indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
+ const mult = this._uintIndicesCurrentlySet ? 4 : 2;
+ if (instancesCount) {
+ this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
+ }
+ else {
+ this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
+ }
+ }
+ /**
+ * Draw a list of unindexed primitives
+ * @param fillMode defines the primitive to use
+ * @param verticesStart defines the index of first vertex to draw
+ * @param verticesCount defines the count of vertices to draw
+ * @param instancesCount defines the number of instances to draw (if instantiation is enabled)
+ */
+ drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) {
+ // Apply states
+ this.applyStates();
+ this._reportDrawCall();
+ const drawMode = this._drawMode(fillMode);
+ if (instancesCount) {
+ this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
+ }
+ else {
+ this._gl.drawArrays(drawMode, verticesStart, verticesCount);
+ }
+ }
+ _drawMode(fillMode) {
+ switch (fillMode) {
+ // Triangle views
+ case 0:
+ return this._gl.TRIANGLES;
+ case 2:
+ return this._gl.POINTS;
+ case 1:
+ return this._gl.LINES;
+ // Draw modes
+ case 3:
+ return this._gl.POINTS;
+ case 4:
+ return this._gl.LINES;
+ case 5:
+ return this._gl.LINE_LOOP;
+ case 6:
+ return this._gl.LINE_STRIP;
+ case 7:
+ return this._gl.TRIANGLE_STRIP;
+ case 8:
+ return this._gl.TRIANGLE_FAN;
+ default:
+ return this._gl.TRIANGLES;
+ }
+ }
+ // Shaders
+ /**
+ * @internal
+ */
+ _releaseEffect(effect) {
+ if (this._compiledEffects[effect._key]) {
+ delete this._compiledEffects[effect._key];
+ }
+ const pipelineContext = effect.getPipelineContext();
+ if (pipelineContext) {
+ this._deletePipelineContext(pipelineContext);
+ }
+ }
+ /**
+ * @internal
+ */
+ _deletePipelineContext(pipelineContext) {
+ const webGLPipelineContext = pipelineContext;
+ if (webGLPipelineContext && webGLPipelineContext.program) {
+ webGLPipelineContext.program.__SPECTOR_rebuildProgram = null;
+ resetCachedPipeline(webGLPipelineContext);
+ if (this._gl) {
+ this._gl.deleteProgram(webGLPipelineContext.program);
+ }
+ }
+ }
+ /**
+ * @internal
+ */
+ _getGlobalDefines(defines) {
+ return _getGlobalDefines(defines, this.isNDCHalfZRange, this.useReverseDepthBuffer, this.useExactSrgbConversions);
+ }
+ /**
+ * Create a new effect (used to store vertex/fragment shaders)
+ * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
+ * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object
+ * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
+ * @param samplers defines an array of string used to represent textures
+ * @param defines defines the string containing the defines to use to compile the shaders
+ * @param fallbacks defines the list of potential fallbacks to use if shader compilation fails
+ * @param onCompiled defines a function to call when the effect creation is successful
+ * @param onError defines a function to call when the effect creation has failed
+ * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
+ * @param shaderLanguage the language the shader is written in (default: GLSL)
+ * @param extraInitializationsAsync additional async code to run before preparing the effect
+ * @returns the new Effect
+ */
+ createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = 0 /* ShaderLanguage.GLSL */, extraInitializationsAsync) {
+ const vertex = typeof baseName === "string" ? baseName : baseName.vertexToken || baseName.vertexSource || baseName.vertexElement || baseName.vertex;
+ const fragment = typeof baseName === "string" ? baseName : baseName.fragmentToken || baseName.fragmentSource || baseName.fragmentElement || baseName.fragment;
+ const globalDefines = this._getGlobalDefines();
+ const isOptions = attributesNamesOrOptions.attributes !== undefined;
+ let fullDefines = defines ?? attributesNamesOrOptions.defines ?? "";
+ if (globalDefines) {
+ fullDefines += globalDefines;
+ }
+ const name = vertex + "+" + fragment + "@" + fullDefines;
+ if (this._compiledEffects[name]) {
+ const compiledEffect = this._compiledEffects[name];
+ if (onCompiled && compiledEffect.isReady()) {
+ onCompiled(compiledEffect);
+ }
+ compiledEffect._refCount++;
+ return compiledEffect;
+ }
+ if (this._gl) {
+ getStateObject(this._gl);
+ }
+ const effect = new Effect(baseName, attributesNamesOrOptions, isOptions ? this : uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, attributesNamesOrOptions.shaderLanguage ?? shaderLanguage, attributesNamesOrOptions.extraInitializationsAsync ?? extraInitializationsAsync);
+ this._compiledEffects[name] = effect;
+ return effect;
+ }
+ /**
+ * @internal
+ */
+ _getShaderSource(shader) {
+ return this._gl.getShaderSource(shader);
+ }
+ /**
+ * Directly creates a webGL program
+ * @param pipelineContext defines the pipeline context to attach to
+ * @param vertexCode defines the vertex shader code to use
+ * @param fragmentCode defines the fragment shader code to use
+ * @param context defines the webGL context to use (if not set, the current one will be used)
+ * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
+ * @returns the new webGL program
+ */
+ createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings = null) {
+ const stateObject = getStateObject(this._gl);
+ stateObject._contextWasLost = this._contextWasLost;
+ stateObject.validateShaderPrograms = this.validateShaderPrograms;
+ return createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context || this._gl, transformFeedbackVaryings);
+ }
+ /**
+ * Creates a webGL program
+ * @param pipelineContext defines the pipeline context to attach to
+ * @param vertexCode defines the vertex shader code to use
+ * @param fragmentCode defines the fragment shader code to use
+ * @param defines defines the string containing the defines to use to compile the shaders
+ * @param context defines the webGL context to use (if not set, the current one will be used)
+ * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
+ * @returns the new webGL program
+ */
+ createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) {
+ const stateObject = getStateObject(this._gl);
+ // assure the state object is correct
+ stateObject._contextWasLost = this._contextWasLost;
+ stateObject.validateShaderPrograms = this.validateShaderPrograms;
+ return createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context || this._gl, transformFeedbackVaryings);
+ }
+ /**
+ * Inline functions in shader code that are marked to be inlined
+ * @param code code to inline
+ * @returns inlined code
+ */
+ inlineShaderCode(code) {
+ // no inlining needed in the WebGL engine
+ return code;
+ }
+ /**
+ * Creates a new pipeline context
+ * @param shaderProcessingContext defines the shader processing context used during the processing if available
+ * @returns the new pipeline
+ */
+ createPipelineContext(shaderProcessingContext) {
+ if (this._gl) {
+ const stateObject = getStateObject(this._gl);
+ stateObject.parallelShaderCompile = this._caps.parallelShaderCompile;
+ }
+ const context = createPipelineContext(this._gl);
+ context.engine = this;
+ return context;
+ }
+ /**
+ * Creates a new material context
+ * @returns the new context
+ */
+ createMaterialContext() {
+ return undefined;
+ }
+ /**
+ * Creates a new draw context
+ * @returns the new context
+ */
+ createDrawContext() {
+ return undefined;
+ }
+ _finalizePipelineContext(pipelineContext) {
+ return _finalizePipelineContext(pipelineContext, this._gl, this.validateShaderPrograms);
+ }
+ /**
+ * @internal
+ */
+ _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, key, onReady) {
+ const stateObject = getStateObject(this._gl);
+ stateObject._contextWasLost = this._contextWasLost;
+ stateObject.validateShaderPrograms = this.validateShaderPrograms;
+ stateObject._createShaderProgramInjection = this._createShaderProgram.bind(this);
+ stateObject.createRawShaderProgramInjection = this.createRawShaderProgram.bind(this);
+ stateObject.createShaderProgramInjection = this.createShaderProgram.bind(this);
+ stateObject.loadFileInjection = this._loadFile.bind(this);
+ return _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, key, onReady);
+ }
+ _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) {
+ return _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
+ }
+ /**
+ * @internal
+ */
+ _isRenderingStateCompiled(pipelineContext) {
+ if (this._isDisposed) {
+ return false;
+ }
+ return _isRenderingStateCompiled(pipelineContext, this._gl, this.validateShaderPrograms);
+ }
+ /**
+ * @internal
+ */
+ _executeWhenRenderingStateIsCompiled(pipelineContext, action) {
+ _executeWhenRenderingStateIsCompiled(pipelineContext, action);
+ }
+ /**
+ * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
+ * @param pipelineContext defines the pipeline context to use
+ * @param uniformsNames defines the list of uniform names
+ * @returns an array of webGL uniform locations
+ */
+ getUniforms(pipelineContext, uniformsNames) {
+ const results = new Array();
+ const webGLPipelineContext = pipelineContext;
+ for (let index = 0; index < uniformsNames.length; index++) {
+ results.push(this._gl.getUniformLocation(webGLPipelineContext.program, uniformsNames[index]));
+ }
+ return results;
+ }
+ /**
+ * Gets the list of active attributes for a given webGL program
+ * @param pipelineContext defines the pipeline context to use
+ * @param attributesNames defines the list of attribute names to get
+ * @returns an array of indices indicating the offset of each attribute
+ */
+ getAttributes(pipelineContext, attributesNames) {
+ const results = [];
+ const webGLPipelineContext = pipelineContext;
+ for (let index = 0; index < attributesNames.length; index++) {
+ try {
+ results.push(this._gl.getAttribLocation(webGLPipelineContext.program, attributesNames[index]));
+ }
+ catch (e) {
+ results.push(-1);
+ }
+ }
+ return results;
+ }
+ /**
+ * Activates an effect, making it the current one (ie. the one used for rendering)
+ * @param effect defines the effect to activate
+ */
+ enableEffect(effect) {
+ effect = effect !== null && IsWrapper(effect) ? effect.effect : effect; // get only the effect, we don't need a Wrapper in the WebGL engine
+ if (!effect || effect === this._currentEffect) {
+ return;
+ }
+ this._stencilStateComposer.stencilMaterial = undefined;
+ effect = effect;
+ // Use program
+ this.bindSamplers(effect);
+ this._currentEffect = effect;
+ if (effect.onBind) {
+ effect.onBind(effect);
+ }
+ if (effect._onBindObservable) {
+ effect._onBindObservable.notifyObservers(effect);
+ }
+ }
+ /**
+ * Set the value of an uniform to a number (int)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param value defines the int number to store
+ * @returns true if the value was set
+ */
+ setInt(uniform, value) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform1i(uniform, value);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a int2
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @returns true if the value was set
+ */
+ setInt2(uniform, x, y) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform2i(uniform, x, y);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a int3
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @param z defines the 3rd component of the value
+ * @returns true if the value was set
+ */
+ setInt3(uniform, x, y, z) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform3i(uniform, x, y, z);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a int4
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @param z defines the 3rd component of the value
+ * @param w defines the 4th component of the value
+ * @returns true if the value was set
+ */
+ setInt4(uniform, x, y, z, w) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform4i(uniform, x, y, z, w);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of int32
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of int32 to store
+ * @returns true if the value was set
+ */
+ setIntArray(uniform, array) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform1iv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of int32 (stored as vec2)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of int32 to store
+ * @returns true if the value was set
+ */
+ setIntArray2(uniform, array) {
+ if (!uniform || array.length % 2 !== 0) {
+ return false;
+ }
+ this._gl.uniform2iv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of int32 (stored as vec3)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of int32 to store
+ * @returns true if the value was set
+ */
+ setIntArray3(uniform, array) {
+ if (!uniform || array.length % 3 !== 0) {
+ return false;
+ }
+ this._gl.uniform3iv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of int32 (stored as vec4)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of int32 to store
+ * @returns true if the value was set
+ */
+ setIntArray4(uniform, array) {
+ if (!uniform || array.length % 4 !== 0) {
+ return false;
+ }
+ this._gl.uniform4iv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a number (unsigned int)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param value defines the unsigned int number to store
+ * @returns true if the value was set
+ */
+ setUInt(uniform, value) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform1ui(uniform, value);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a unsigned int2
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @returns true if the value was set
+ */
+ setUInt2(uniform, x, y) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform2ui(uniform, x, y);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a unsigned int3
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @param z defines the 3rd component of the value
+ * @returns true if the value was set
+ */
+ setUInt3(uniform, x, y, z) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform3ui(uniform, x, y, z);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a unsigned int4
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @param z defines the 3rd component of the value
+ * @param w defines the 4th component of the value
+ * @returns true if the value was set
+ */
+ setUInt4(uniform, x, y, z, w) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform4ui(uniform, x, y, z, w);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of unsigned int32
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of unsigned int32 to store
+ * @returns true if the value was set
+ */
+ setUIntArray(uniform, array) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform1uiv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of unsigned int32 (stored as vec2)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of unsigned int32 to store
+ * @returns true if the value was set
+ */
+ setUIntArray2(uniform, array) {
+ if (!uniform || array.length % 2 !== 0) {
+ return false;
+ }
+ this._gl.uniform2uiv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of unsigned int32 (stored as vec3)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of unsigned int32 to store
+ * @returns true if the value was set
+ */
+ setUIntArray3(uniform, array) {
+ if (!uniform || array.length % 3 !== 0) {
+ return false;
+ }
+ this._gl.uniform3uiv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of unsigned int32 (stored as vec4)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of unsigned int32 to store
+ * @returns true if the value was set
+ */
+ setUIntArray4(uniform, array) {
+ if (!uniform || array.length % 4 !== 0) {
+ return false;
+ }
+ this._gl.uniform4uiv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of number
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of number to store
+ * @returns true if the value was set
+ */
+ setArray(uniform, array) {
+ if (!uniform) {
+ return false;
+ }
+ if (array.length < 1) {
+ return false;
+ }
+ this._gl.uniform1fv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of number (stored as vec2)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of number to store
+ * @returns true if the value was set
+ */
+ setArray2(uniform, array) {
+ if (!uniform || array.length % 2 !== 0) {
+ return false;
+ }
+ this._gl.uniform2fv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of number (stored as vec3)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of number to store
+ * @returns true if the value was set
+ */
+ setArray3(uniform, array) {
+ if (!uniform || array.length % 3 !== 0) {
+ return false;
+ }
+ this._gl.uniform3fv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of number (stored as vec4)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param array defines the array of number to store
+ * @returns true if the value was set
+ */
+ setArray4(uniform, array) {
+ if (!uniform || array.length % 4 !== 0) {
+ return false;
+ }
+ this._gl.uniform4fv(uniform, array);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to an array of float32 (stored as matrices)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param matrices defines the array of float32 to store
+ * @returns true if the value was set
+ */
+ setMatrices(uniform, matrices) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniformMatrix4fv(uniform, false, matrices);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a matrix (3x3)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param matrix defines the Float32Array representing the 3x3 matrix to store
+ * @returns true if the value was set
+ */
+ setMatrix3x3(uniform, matrix) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniformMatrix3fv(uniform, false, matrix);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a matrix (2x2)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param matrix defines the Float32Array representing the 2x2 matrix to store
+ * @returns true if the value was set
+ */
+ setMatrix2x2(uniform, matrix) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniformMatrix2fv(uniform, false, matrix);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a number (float)
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param value defines the float number to store
+ * @returns true if the value was transferred
+ */
+ setFloat(uniform, value) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform1f(uniform, value);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a vec2
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @returns true if the value was set
+ */
+ setFloat2(uniform, x, y) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform2f(uniform, x, y);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a vec3
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @param z defines the 3rd component of the value
+ * @returns true if the value was set
+ */
+ setFloat3(uniform, x, y, z) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform3f(uniform, x, y, z);
+ return true;
+ }
+ /**
+ * Set the value of an uniform to a vec4
+ * @param uniform defines the webGL uniform location where to store the value
+ * @param x defines the 1st component of the value
+ * @param y defines the 2nd component of the value
+ * @param z defines the 3rd component of the value
+ * @param w defines the 4th component of the value
+ * @returns true if the value was set
+ */
+ setFloat4(uniform, x, y, z, w) {
+ if (!uniform) {
+ return false;
+ }
+ this._gl.uniform4f(uniform, x, y, z, w);
+ return true;
+ }
+ // States
+ /**
+ * Apply all cached states (depth, culling, stencil and alpha)
+ */
+ applyStates() {
+ this._depthCullingState.apply(this._gl);
+ this._stencilStateComposer.apply(this._gl);
+ this._alphaState.apply(this._gl);
+ if (this._colorWriteChanged) {
+ this._colorWriteChanged = false;
+ const enable = this._colorWrite;
+ this._gl.colorMask(enable, enable, enable, enable);
+ }
+ }
+ // Textures
+ /**
+ * Force the entire cache to be cleared
+ * You should not have to use this function unless your engine needs to share the webGL context with another engine
+ * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
+ */
+ wipeCaches(bruteForce) {
+ if (this.preventCacheWipeBetweenFrames && !bruteForce) {
+ return;
+ }
+ this._currentEffect = null;
+ this._viewportCached.x = 0;
+ this._viewportCached.y = 0;
+ this._viewportCached.z = 0;
+ this._viewportCached.w = 0;
+ // Done before in case we clean the attributes
+ this._unbindVertexArrayObject();
+ if (bruteForce) {
+ this._currentProgram = null;
+ this.resetTextureCache();
+ this._stencilStateComposer.reset();
+ this._depthCullingState.reset();
+ this._depthCullingState.depthFunc = this._gl.LEQUAL;
+ this._alphaState.reset();
+ this._alphaMode = 1;
+ this._alphaEquation = 0;
+ this._colorWrite = true;
+ this._colorWriteChanged = true;
+ this._unpackFlipYCached = null;
+ this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
+ this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
+ this._mustWipeVertexAttributes = true;
+ this.unbindAllAttributes();
+ }
+ this._resetVertexBufferBinding();
+ this._cachedIndexBuffer = null;
+ this._cachedEffectForVertexBuffers = null;
+ this.bindIndexBuffer(null);
+ }
+ /**
+ * @internal
+ */
+ _getSamplingParameters(samplingMode, generateMipMaps) {
+ const gl = this._gl;
+ let magFilter = gl.NEAREST;
+ let minFilter = gl.NEAREST;
+ switch (samplingMode) {
+ case 11:
+ magFilter = gl.LINEAR;
+ if (generateMipMaps) {
+ minFilter = gl.LINEAR_MIPMAP_NEAREST;
+ }
+ else {
+ minFilter = gl.LINEAR;
+ }
+ break;
+ case 3:
+ magFilter = gl.LINEAR;
+ if (generateMipMaps) {
+ minFilter = gl.LINEAR_MIPMAP_LINEAR;
+ }
+ else {
+ minFilter = gl.LINEAR;
+ }
+ break;
+ case 8:
+ magFilter = gl.NEAREST;
+ if (generateMipMaps) {
+ minFilter = gl.NEAREST_MIPMAP_LINEAR;
+ }
+ else {
+ minFilter = gl.NEAREST;
+ }
+ break;
+ case 4:
+ magFilter = gl.NEAREST;
+ if (generateMipMaps) {
+ minFilter = gl.NEAREST_MIPMAP_NEAREST;
+ }
+ else {
+ minFilter = gl.NEAREST;
+ }
+ break;
+ case 5:
+ magFilter = gl.NEAREST;
+ if (generateMipMaps) {
+ minFilter = gl.LINEAR_MIPMAP_NEAREST;
+ }
+ else {
+ minFilter = gl.LINEAR;
+ }
+ break;
+ case 6:
+ magFilter = gl.NEAREST;
+ if (generateMipMaps) {
+ minFilter = gl.LINEAR_MIPMAP_LINEAR;
+ }
+ else {
+ minFilter = gl.LINEAR;
+ }
+ break;
+ case 7:
+ magFilter = gl.NEAREST;
+ minFilter = gl.LINEAR;
+ break;
+ case 1:
+ magFilter = gl.NEAREST;
+ minFilter = gl.NEAREST;
+ break;
+ case 9:
+ magFilter = gl.LINEAR;
+ if (generateMipMaps) {
+ minFilter = gl.NEAREST_MIPMAP_NEAREST;
+ }
+ else {
+ minFilter = gl.NEAREST;
+ }
+ break;
+ case 10:
+ magFilter = gl.LINEAR;
+ if (generateMipMaps) {
+ minFilter = gl.NEAREST_MIPMAP_LINEAR;
+ }
+ else {
+ minFilter = gl.NEAREST;
+ }
+ break;
+ case 2:
+ magFilter = gl.LINEAR;
+ minFilter = gl.LINEAR;
+ break;
+ case 12:
+ magFilter = gl.LINEAR;
+ minFilter = gl.NEAREST;
+ break;
+ }
+ return {
+ min: minFilter,
+ mag: magFilter,
+ };
+ }
+ /** @internal */
+ _createTexture() {
+ const texture = this._gl.createTexture();
+ if (!texture) {
+ throw new Error("Unable to create texture");
+ }
+ return texture;
+ }
+ /** @internal */
+ _createHardwareTexture() {
+ return new WebGLHardwareTexture(this._createTexture(), this._gl);
+ }
+ /**
+ * Creates an internal texture without binding it to a framebuffer
+ * @internal
+ * @param size defines the size of the texture
+ * @param options defines the options used to create the texture
+ * @param delayGPUTextureCreation true to delay the texture creation the first time it is really needed. false to create it right away
+ * @param source source type of the texture
+ * @returns a new internal texture
+ */
+ _createInternalTexture(size, options, delayGPUTextureCreation = true, source = 0 /* InternalTextureSource.Unknown */) {
+ let generateMipMaps = false;
+ let createMipMaps = false;
+ let type = 0;
+ let samplingMode = 3;
+ let format = 5;
+ let useSRGBBuffer = false;
+ let samples = 1;
+ let label;
+ let createMSAATexture = false;
+ let comparisonFunction = 0;
+ if (options !== undefined && typeof options === "object") {
+ generateMipMaps = !!options.generateMipMaps;
+ createMipMaps = !!options.createMipMaps;
+ type = options.type === undefined ? 0 : options.type;
+ samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;
+ format = options.format === undefined ? 5 : options.format;
+ useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer;
+ samples = options.samples ?? 1;
+ label = options.label;
+ createMSAATexture = !!options.createMSAATexture;
+ comparisonFunction = options.comparisonFunction || 0;
+ }
+ else {
+ generateMipMaps = !!options;
+ }
+ useSRGBBuffer && (useSRGBBuffer = this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU));
+ if (type === 1 && !this._caps.textureFloatLinearFiltering) {
+ // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
+ samplingMode = 1;
+ }
+ else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
+ // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
+ samplingMode = 1;
+ }
+ if (type === 1 && !this._caps.textureFloat) {
+ type = 0;
+ Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE");
+ }
+ const isDepthTexture = IsDepthTexture(format);
+ const hasStencil = HasStencilAspect(format);
+ const gl = this._gl;
+ const texture = new InternalTexture(this, source);
+ const width = size.width || size;
+ const height = size.height || size;
+ const depth = size.depth || 0;
+ const layers = size.layers || 0;
+ const filters = this._getSamplingParameters(samplingMode, (generateMipMaps || createMipMaps) && !isDepthTexture);
+ const target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : depth !== 0 ? gl.TEXTURE_3D : gl.TEXTURE_2D;
+ const sizedFormat = isDepthTexture
+ ? this._getInternalFormatFromDepthTextureFormat(format, true, hasStencil)
+ : this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);
+ const internalFormat = isDepthTexture ? (hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT) : this._getInternalFormat(format);
+ const textureType = isDepthTexture ? this._getWebGLTextureTypeFromDepthTextureFormat(format) : this._getWebGLTextureType(type);
+ // Bind
+ this._bindTextureDirectly(target, texture);
+ if (layers !== 0) {
+ texture.is2DArray = true;
+ gl.texImage3D(target, 0, sizedFormat, width, height, layers, 0, internalFormat, textureType, null);
+ }
+ else if (depth !== 0) {
+ texture.is3D = true;
+ gl.texImage3D(target, 0, sizedFormat, width, height, depth, 0, internalFormat, textureType, null);
+ }
+ else {
+ gl.texImage2D(target, 0, sizedFormat, width, height, 0, internalFormat, textureType, null);
+ }
+ gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag);
+ gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min);
+ gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ if (isDepthTexture && this.webGLVersion > 1) {
+ if (comparisonFunction === 0) {
+ gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, 515);
+ gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
+ }
+ else {
+ gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
+ gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
+ }
+ }
+ // MipMaps
+ if (generateMipMaps || createMipMaps) {
+ this._gl.generateMipmap(target);
+ }
+ this._bindTextureDirectly(target, null);
+ texture._useSRGBBuffer = useSRGBBuffer;
+ texture.baseWidth = width;
+ texture.baseHeight = height;
+ texture.width = width;
+ texture.height = height;
+ texture.depth = layers || depth;
+ texture.isReady = true;
+ texture.samples = samples;
+ texture.generateMipMaps = generateMipMaps;
+ texture.samplingMode = samplingMode;
+ texture.type = type;
+ texture.format = format;
+ texture.label = label;
+ texture.comparisonFunction = comparisonFunction;
+ this._internalTexturesCache.push(texture);
+ if (createMSAATexture) {
+ let renderBuffer = null;
+ if (IsDepthTexture(texture.format)) {
+ renderBuffer = this._setupFramebufferDepthAttachments(HasStencilAspect(texture.format), texture.format !== 19, texture.width, texture.height, samples, texture.format, true);
+ }
+ else {
+ renderBuffer = this._createRenderBuffer(texture.width, texture.height, samples, -1 /* not used */, this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer), -1 /* attachment */);
+ }
+ if (!renderBuffer) {
+ throw new Error("Unable to create render buffer");
+ }
+ texture._autoMSAAManagement = true;
+ let hardwareTexture = texture._hardwareTexture;
+ if (!hardwareTexture) {
+ hardwareTexture = texture._hardwareTexture = this._createHardwareTexture();
+ }
+ hardwareTexture.addMSAARenderBuffer(renderBuffer);
+ }
+ return texture;
+ }
+ /**
+ * @internal
+ */
+ _getUseSRGBBuffer(useSRGBBuffer, noMipmap) {
+ // Generating mipmaps for sRGB textures is not supported in WebGL1 so we must disable the support if mipmaps is enabled
+ return useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || noMipmap);
+ }
+ /**
+ * Usually called from Texture.ts.
+ * Passed information to create a WebGLTexture
+ * @param url defines a value which contains one of the following:
+ * * A conventional http URL, e.g. 'http://...' or 'file://...'
+ * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
+ * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
+ * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
+ * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
+ * @param scene needed for loading to the correct scene
+ * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
+ * @param onLoad optional callback to be called upon successful completion
+ * @param onError optional callback to be called upon failure
+ * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
+ * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
+ * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
+ * @param forcedExtension defines the extension to use to pick the right loader
+ * @param mimeType defines an optional mime type
+ * @param loaderOptions options to be passed to the loader
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).
+ * @returns a InternalTexture for assignment back into BABYLON.Texture
+ */
+ createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) {
+ return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, (...args) => this._prepareWebGLTexture(...args, format), (potWidth, potHeight, img, extension, texture, continuationCallback) => {
+ const gl = this._gl;
+ const isPot = img.width === potWidth && img.height === potHeight;
+ texture._creationFlags = creationFlags ?? 0;
+ const tip = this._getTexImageParametersForCreateTexture(texture.format, texture._useSRGBBuffer);
+ if (isPot) {
+ gl.texImage2D(gl.TEXTURE_2D, 0, tip.internalFormat, tip.format, tip.type, img);
+ return false;
+ }
+ const maxTextureSize = this._caps.maxTextureSize;
+ if (img.width > maxTextureSize || img.height > maxTextureSize || !this._supportsHardwareTextureRescaling) {
+ this._prepareWorkingCanvas();
+ if (!this._workingCanvas || !this._workingContext) {
+ return false;
+ }
+ this._workingCanvas.width = potWidth;
+ this._workingCanvas.height = potHeight;
+ this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
+ gl.texImage2D(gl.TEXTURE_2D, 0, tip.internalFormat, tip.format, tip.type, this._workingCanvas);
+ texture.width = potWidth;
+ texture.height = potHeight;
+ return false;
+ }
+ else {
+ // Using shaders when possible to rescale because canvas.drawImage is lossy
+ const source = new InternalTexture(this, 2 /* InternalTextureSource.Temp */);
+ this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
+ gl.texImage2D(gl.TEXTURE_2D, 0, tip.internalFormat, tip.format, tip.type, img);
+ this._rescaleTexture(source, texture, scene, tip.format, () => {
+ this._releaseTexture(source);
+ this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
+ continuationCallback();
+ });
+ }
+ return true;
+ }, buffer, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer);
+ }
+ /**
+ * Calls to the GL texImage2D and texImage3D functions require three arguments describing the pixel format of the texture.
+ * createTexture derives these from the babylonFormat and useSRGBBuffer arguments and also the file extension of the URL it's working with.
+ * This function encapsulates that derivation for easy unit testing.
+ * @param babylonFormat Babylon's format enum, as specified in ITextureCreationOptions.
+ * @param fileExtension The file extension including the dot, e.g. .jpg.
+ * @param useSRGBBuffer Use SRGB not linear.
+ * @returns The options to pass to texImage2D or texImage3D calls.
+ * @internal
+ */
+ _getTexImageParametersForCreateTexture(babylonFormat, useSRGBBuffer) {
+ let format, internalFormat;
+ if (this.webGLVersion === 1) {
+ // In WebGL 1, format and internalFormat must be the same and taken from a limited set of values, see https://docs.gl/es2/glTexImage2D.
+ // The SRGB extension (https://developer.mozilla.org/en-US/docs/Web/API/EXT_sRGB) adds some extra values, hence passing useSRGBBuffer
+ // to getInternalFormat.
+ format = this._getInternalFormat(babylonFormat, useSRGBBuffer);
+ internalFormat = format;
+ }
+ else {
+ // In WebGL 2, format has a wider range of values and internal format can be one of the sized formats, see
+ // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml.
+ // SRGB is included in the sized format and should not be passed in "format", hence always passing useSRGBBuffer as false.
+ format = this._getInternalFormat(babylonFormat, false);
+ internalFormat = this._getRGBABufferInternalSizedFormat(0, babylonFormat, useSRGBBuffer);
+ }
+ return {
+ internalFormat,
+ format,
+ type: this._gl.UNSIGNED_BYTE,
+ };
+ }
+ /**
+ * @internal
+ */
+ _rescaleTexture(source, destination, scene, internalFormat, onComplete) { }
+ /**
+ * @internal
+ */
+ _unpackFlipY(value) {
+ if (this._unpackFlipYCached !== value) {
+ this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
+ if (this.enableUnpackFlipYCached) {
+ this._unpackFlipYCached = value;
+ }
+ }
+ }
+ /** @internal */
+ _getUnpackAlignement() {
+ return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
+ }
+ /** @internal */
+ _getTextureTarget(texture) {
+ if (texture.isCube) {
+ return this._gl.TEXTURE_CUBE_MAP;
+ }
+ else if (texture.is3D) {
+ return this._gl.TEXTURE_3D;
+ }
+ else if (texture.is2DArray || texture.isMultiview) {
+ return this._gl.TEXTURE_2D_ARRAY;
+ }
+ return this._gl.TEXTURE_2D;
+ }
+ /**
+ * Update the sampling mode of a given texture
+ * @param samplingMode defines the required sampling mode
+ * @param texture defines the texture to update
+ * @param generateMipMaps defines whether to generate mipmaps for the texture
+ */
+ updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) {
+ const target = this._getTextureTarget(texture);
+ const filters = this._getSamplingParameters(samplingMode, texture.useMipMaps || generateMipMaps);
+ this._setTextureParameterInteger(target, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
+ this._setTextureParameterInteger(target, this._gl.TEXTURE_MIN_FILTER, filters.min);
+ if (generateMipMaps) {
+ texture.generateMipMaps = true;
+ this._gl.generateMipmap(target);
+ }
+ this._bindTextureDirectly(target, null);
+ texture.samplingMode = samplingMode;
+ }
+ /**
+ * Update the dimensions of a texture
+ * @param texture texture to update
+ * @param width new width of the texture
+ * @param height new height of the texture
+ * @param depth new depth of the texture
+ */
+ updateTextureDimensions(texture, width, height, depth = 1) { }
+ /**
+ * Update the sampling mode of a given texture
+ * @param texture defines the texture to update
+ * @param wrapU defines the texture wrap mode of the u coordinates
+ * @param wrapV defines the texture wrap mode of the v coordinates
+ * @param wrapR defines the texture wrap mode of the r coordinates
+ */
+ updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) {
+ const target = this._getTextureTarget(texture);
+ if (wrapU !== null) {
+ this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(wrapU), texture);
+ texture._cachedWrapU = wrapU;
+ }
+ if (wrapV !== null) {
+ this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(wrapV), texture);
+ texture._cachedWrapV = wrapV;
+ }
+ if ((texture.is2DArray || texture.is3D) && wrapR !== null) {
+ this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(wrapR), texture);
+ texture._cachedWrapR = wrapR;
+ }
+ this._bindTextureDirectly(target, null);
+ }
+ /**
+ * @internal
+ */
+ _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) {
+ const gl = this._gl;
+ let target = gl.TEXTURE_2D;
+ if (texture.isCube) {
+ target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
+ }
+ if (texture._useSRGBBuffer) {
+ switch (internalFormat) {
+ case 37492:
+ case 36196:
+ // Note, if using ETC1 and sRGB is requested, this will use ETC2 if available.
+ if (this._caps.etc2) {
+ internalFormat = gl.COMPRESSED_SRGB8_ETC2;
+ }
+ else {
+ texture._useSRGBBuffer = false;
+ }
+ break;
+ case 37496:
+ if (this._caps.etc2) {
+ internalFormat = gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
+ }
+ else {
+ texture._useSRGBBuffer = false;
+ }
+ break;
+ case 36492:
+ internalFormat = gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;
+ break;
+ case 37808:
+ internalFormat = gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
+ break;
+ case 33776:
+ if (this._caps.s3tc_srgb) {
+ internalFormat = gl.COMPRESSED_SRGB_S3TC_DXT1_EXT;
+ }
+ else {
+ // S3TC sRGB extension not supported
+ texture._useSRGBBuffer = false;
+ }
+ break;
+ case 33777:
+ if (this._caps.s3tc_srgb) {
+ internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
+ }
+ else {
+ // S3TC sRGB extension not supported
+ texture._useSRGBBuffer = false;
+ }
+ break;
+ case 33779:
+ if (this._caps.s3tc_srgb) {
+ internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
+ }
+ else {
+ // S3TC sRGB extension not supported
+ texture._useSRGBBuffer = false;
+ }
+ break;
+ default:
+ // We don't support a sRGB format corresponding to internalFormat, so revert to non sRGB format
+ texture._useSRGBBuffer = false;
+ break;
+ }
+ }
+ this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
+ }
+ /**
+ * @internal
+ */
+ _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) {
+ const gl = this._gl;
+ const textureType = this._getWebGLTextureType(texture.type);
+ const format = this._getInternalFormat(texture.format);
+ const internalFormat = babylonInternalFormat === undefined
+ ? this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer)
+ : this._getInternalFormat(babylonInternalFormat, texture._useSRGBBuffer);
+ this._unpackFlipY(texture.invertY);
+ let target = gl.TEXTURE_2D;
+ if (texture.isCube) {
+ target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
+ }
+ const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
+ const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
+ const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
+ const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
+ gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
+ }
+ /**
+ * Update a portion of an internal texture
+ * @param texture defines the texture to update
+ * @param imageData defines the data to store into the texture
+ * @param xOffset defines the x coordinates of the update rectangle
+ * @param yOffset defines the y coordinates of the update rectangle
+ * @param width defines the width of the update rectangle
+ * @param height defines the height of the update rectangle
+ * @param faceIndex defines the face index if texture is a cube (0 by default)
+ * @param lod defines the lod level to update (0 by default)
+ * @param generateMipMaps defines whether to generate mipmaps or not
+ */
+ updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) {
+ const gl = this._gl;
+ const textureType = this._getWebGLTextureType(texture.type);
+ const format = this._getInternalFormat(texture.format);
+ this._unpackFlipY(texture.invertY);
+ let targetForBinding = gl.TEXTURE_2D;
+ let target = gl.TEXTURE_2D;
+ if (texture.isCube) {
+ target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
+ targetForBinding = gl.TEXTURE_CUBE_MAP;
+ }
+ this._bindTextureDirectly(targetForBinding, texture, true);
+ gl.texSubImage2D(target, lod, xOffset, yOffset, width, height, format, textureType, imageData);
+ if (generateMipMaps) {
+ this._gl.generateMipmap(target);
+ }
+ this._bindTextureDirectly(targetForBinding, null);
+ }
+ /**
+ * @internal
+ */
+ _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) {
+ const gl = this._gl;
+ const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
+ this._bindTextureDirectly(bindTarget, texture, true);
+ this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
+ this._bindTextureDirectly(bindTarget, null, true);
+ }
+ _prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode) {
+ const gl = this._gl;
+ if (!gl) {
+ return;
+ }
+ const filters = this._getSamplingParameters(samplingMode, !noMipmap);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
+ if (!noMipmap && !isCompressed) {
+ gl.generateMipmap(gl.TEXTURE_2D);
+ }
+ this._bindTextureDirectly(gl.TEXTURE_2D, null);
+ // this.resetTextureCache();
+ if (scene) {
+ scene.removePendingData(texture);
+ }
+ texture.onLoadedObservable.notifyObservers(texture);
+ texture.onLoadedObservable.clear();
+ }
+ _prepareWebGLTexture(texture, extension, scene, img, invertY, noMipmap, isCompressed, processFunction, samplingMode, format) {
+ const maxTextureSize = this.getCaps().maxTextureSize;
+ const potWidth = Math.min(maxTextureSize, this.needPOTTextures ? GetExponentOfTwo(img.width, maxTextureSize) : img.width);
+ const potHeight = Math.min(maxTextureSize, this.needPOTTextures ? GetExponentOfTwo(img.height, maxTextureSize) : img.height);
+ const gl = this._gl;
+ if (!gl) {
+ return;
+ }
+ if (!texture._hardwareTexture) {
+ // this.resetTextureCache();
+ if (scene) {
+ scene.removePendingData(texture);
+ }
+ return;
+ }
+ this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
+ this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);
+ texture.baseWidth = img.width;
+ texture.baseHeight = img.height;
+ texture.width = potWidth;
+ texture.height = potHeight;
+ texture.isReady = true;
+ texture.type = texture.type !== -1 ? texture.type : 0;
+ texture.format =
+ texture.format !== -1 ? texture.format : (format ?? (extension === ".jpg" && !texture._useSRGBBuffer ? 4 : 5));
+ if (processFunction(potWidth, potHeight, img, extension, texture, () => {
+ this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
+ })) {
+ // Returning as texture needs extra async steps
+ return;
+ }
+ this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
+ }
+ _getInternalFormatFromDepthTextureFormat(textureFormat, hasDepth, hasStencil) {
+ const gl = this._gl;
+ if (!hasDepth) {
+ return gl.STENCIL_INDEX8;
+ }
+ const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT;
+ let internalFormat = format;
+ if (this.webGLVersion > 1) {
+ if (textureFormat === 15) {
+ internalFormat = gl.DEPTH_COMPONENT16;
+ }
+ else if (textureFormat === 16) {
+ internalFormat = gl.DEPTH_COMPONENT24;
+ }
+ else if (textureFormat === 17 || textureFormat === 13) {
+ internalFormat = hasStencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
+ }
+ else if (textureFormat === 14) {
+ internalFormat = gl.DEPTH_COMPONENT32F;
+ }
+ else if (textureFormat === 18) {
+ internalFormat = hasStencil ? gl.DEPTH32F_STENCIL8 : gl.DEPTH_COMPONENT32F;
+ }
+ }
+ else {
+ internalFormat = gl.DEPTH_COMPONENT16;
+ }
+ return internalFormat;
+ }
+ _getWebGLTextureTypeFromDepthTextureFormat(textureFormat) {
+ const gl = this._gl;
+ let type = gl.UNSIGNED_INT;
+ if (textureFormat === 15) {
+ type = gl.UNSIGNED_SHORT;
+ }
+ else if (textureFormat === 17 || textureFormat === 13) {
+ type = gl.UNSIGNED_INT_24_8;
+ }
+ else if (textureFormat === 14) {
+ type = gl.FLOAT;
+ }
+ else if (textureFormat === 18) {
+ type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
+ }
+ else if (textureFormat === 19) {
+ type = gl.UNSIGNED_BYTE;
+ }
+ return type;
+ }
+ /**
+ * @internal
+ */
+ _setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height, samples = 1, depthTextureFormat, dontBindRenderBufferToFrameBuffer = false) {
+ const gl = this._gl;
+ depthTextureFormat = depthTextureFormat ?? (generateStencilBuffer ? 13 : 14);
+ const internalFormat = this._getInternalFormatFromDepthTextureFormat(depthTextureFormat, generateDepthBuffer, generateStencilBuffer);
+ // Create the depth/stencil buffer
+ if (generateStencilBuffer && generateDepthBuffer) {
+ return this._createRenderBuffer(width, height, samples, gl.DEPTH_STENCIL, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.DEPTH_STENCIL_ATTACHMENT);
+ }
+ if (generateDepthBuffer) {
+ return this._createRenderBuffer(width, height, samples, internalFormat, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.DEPTH_ATTACHMENT);
+ }
+ if (generateStencilBuffer) {
+ return this._createRenderBuffer(width, height, samples, internalFormat, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.STENCIL_ATTACHMENT);
+ }
+ return null;
+ }
+ /**
+ * @internal
+ */
+ _createRenderBuffer(width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer = true) {
+ const gl = this._gl;
+ const renderBuffer = gl.createRenderbuffer();
+ return this._updateRenderBuffer(renderBuffer, width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer);
+ }
+ _updateRenderBuffer(renderBuffer, width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer = true) {
+ const gl = this._gl;
+ gl.bindRenderbuffer(gl.RENDERBUFFER, renderBuffer);
+ if (samples > 1 && gl.renderbufferStorageMultisample) {
+ gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, msInternalFormat, width, height);
+ }
+ else {
+ gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height);
+ }
+ if (attachment !== -1) {
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, renderBuffer);
+ }
+ if (unbindBuffer) {
+ gl.bindRenderbuffer(gl.RENDERBUFFER, null);
+ }
+ return renderBuffer;
+ }
+ /**
+ * @internal
+ */
+ _releaseTexture(texture) {
+ this._deleteTexture(texture._hardwareTexture);
+ // Unbind channels
+ this.unbindAllTextures();
+ const index = this._internalTexturesCache.indexOf(texture);
+ if (index !== -1) {
+ this._internalTexturesCache.splice(index, 1);
+ }
+ // Integrated fixed lod samplers.
+ if (texture._lodTextureHigh) {
+ texture._lodTextureHigh.dispose();
+ }
+ if (texture._lodTextureMid) {
+ texture._lodTextureMid.dispose();
+ }
+ if (texture._lodTextureLow) {
+ texture._lodTextureLow.dispose();
+ }
+ // Integrated irradiance map.
+ if (texture._irradianceTexture) {
+ texture._irradianceTexture.dispose();
+ }
+ }
+ _deleteTexture(texture) {
+ texture?.release();
+ }
+ _setProgram(program) {
+ if (this._currentProgram !== program) {
+ _setProgram(program, this._gl);
+ this._currentProgram = program;
+ }
+ }
+ /**
+ * Binds an effect to the webGL context
+ * @param effect defines the effect to bind
+ */
+ bindSamplers(effect) {
+ const webGLPipelineContext = effect.getPipelineContext();
+ this._setProgram(webGLPipelineContext.program);
+ const samplers = effect.getSamplers();
+ for (let index = 0; index < samplers.length; index++) {
+ const uniform = effect.getUniform(samplers[index]);
+ if (uniform) {
+ this._boundUniforms[index] = uniform;
+ }
+ }
+ this._currentEffect = null;
+ }
+ _activateCurrentTexture() {
+ if (this._currentTextureChannel !== this._activeChannel) {
+ this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
+ this._currentTextureChannel = this._activeChannel;
+ }
+ }
+ /**
+ * @internal
+ */
+ _bindTextureDirectly(target, texture, forTextureDataUpdate = false, force = false) {
+ let wasPreviouslyBound = false;
+ const isTextureForRendering = texture && texture._associatedChannel > -1;
+ if (forTextureDataUpdate && isTextureForRendering) {
+ this._activeChannel = texture._associatedChannel;
+ }
+ const currentTextureBound = this._boundTexturesCache[this._activeChannel];
+ if (currentTextureBound !== texture || force) {
+ this._activateCurrentTexture();
+ if (texture && texture.isMultiview) {
+ //this._gl.bindTexture(target, texture ? texture._colorTextureArray : null);
+ Logger.Error(["_bindTextureDirectly called with a multiview texture!", target, texture]);
+ // eslint-disable-next-line no-throw-literal
+ throw "_bindTextureDirectly called with a multiview texture!";
+ }
+ else {
+ this._gl.bindTexture(target, texture?._hardwareTexture?.underlyingResource ?? null);
+ }
+ this._boundTexturesCache[this._activeChannel] = texture;
+ if (texture) {
+ texture._associatedChannel = this._activeChannel;
+ }
+ }
+ else if (forTextureDataUpdate) {
+ wasPreviouslyBound = true;
+ this._activateCurrentTexture();
+ }
+ if (isTextureForRendering && !forTextureDataUpdate) {
+ this._bindSamplerUniformToChannel(texture._associatedChannel, this._activeChannel);
+ }
+ return wasPreviouslyBound;
+ }
+ /**
+ * @internal
+ */
+ _bindTexture(channel, texture, name) {
+ if (channel === undefined) {
+ return;
+ }
+ if (texture) {
+ texture._associatedChannel = channel;
+ }
+ this._activeChannel = channel;
+ const target = texture ? this._getTextureTarget(texture) : this._gl.TEXTURE_2D;
+ this._bindTextureDirectly(target, texture);
+ }
+ /**
+ * Unbind all textures from the webGL context
+ */
+ unbindAllTextures() {
+ for (let channel = 0; channel < this._maxSimultaneousTextures; channel++) {
+ this._activeChannel = channel;
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
+ this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
+ if (this.webGLVersion > 1) {
+ this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
+ this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
+ }
+ }
+ }
+ /**
+ * Sets a texture to the according uniform.
+ * @param channel The texture channel
+ * @param uniform The uniform to set
+ * @param texture The texture to apply
+ * @param name The name of the uniform in the effect
+ */
+ setTexture(channel, uniform, texture, name) {
+ if (channel === undefined) {
+ return;
+ }
+ if (uniform) {
+ this._boundUniforms[channel] = uniform;
+ }
+ this._setTexture(channel, texture);
+ }
+ _bindSamplerUniformToChannel(sourceSlot, destination) {
+ const uniform = this._boundUniforms[sourceSlot];
+ if (!uniform || uniform._currentState === destination) {
+ return;
+ }
+ this._gl.uniform1i(uniform, destination);
+ uniform._currentState = destination;
+ }
+ _getTextureWrapMode(mode) {
+ switch (mode) {
+ case 1:
+ return this._gl.REPEAT;
+ case 0:
+ return this._gl.CLAMP_TO_EDGE;
+ case 2:
+ return this._gl.MIRRORED_REPEAT;
+ }
+ return this._gl.REPEAT;
+ }
+ _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false, name = "") {
+ // Not ready?
+ if (!texture) {
+ if (this._boundTexturesCache[channel] != null) {
+ this._activeChannel = channel;
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
+ this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
+ if (this.webGLVersion > 1) {
+ this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
+ this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
+ }
+ }
+ return false;
+ }
+ // Video
+ if (texture.video) {
+ this._activeChannel = channel;
+ const videoInternalTexture = texture.getInternalTexture();
+ if (videoInternalTexture) {
+ videoInternalTexture._associatedChannel = channel;
+ }
+ texture.update();
+ }
+ else if (texture.delayLoadState === 4) {
+ // Delay loading
+ texture.delayLoad();
+ return false;
+ }
+ let internalTexture;
+ if (depthStencilTexture) {
+ internalTexture = texture.depthStencilTexture;
+ }
+ else if (texture.isReady()) {
+ internalTexture = texture.getInternalTexture();
+ }
+ else if (texture.isCube) {
+ internalTexture = this.emptyCubeTexture;
+ }
+ else if (texture.is3D) {
+ internalTexture = this.emptyTexture3D;
+ }
+ else if (texture.is2DArray) {
+ internalTexture = this.emptyTexture2DArray;
+ }
+ else {
+ internalTexture = this.emptyTexture;
+ }
+ if (!isPartOfTextureArray && internalTexture) {
+ internalTexture._associatedChannel = channel;
+ }
+ let needToBind = true;
+ if (this._boundTexturesCache[channel] === internalTexture) {
+ if (!isPartOfTextureArray) {
+ this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel);
+ }
+ needToBind = false;
+ }
+ this._activeChannel = channel;
+ const target = this._getTextureTarget(internalTexture);
+ if (needToBind) {
+ this._bindTextureDirectly(target, internalTexture, isPartOfTextureArray);
+ }
+ if (internalTexture && !internalTexture.isMultiview) {
+ // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
+ if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
+ internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
+ const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5
+ ? 1
+ : 0;
+ texture.wrapU = textureWrapMode;
+ texture.wrapV = textureWrapMode;
+ }
+ if (internalTexture._cachedWrapU !== texture.wrapU) {
+ internalTexture._cachedWrapU = texture.wrapU;
+ this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
+ }
+ if (internalTexture._cachedWrapV !== texture.wrapV) {
+ internalTexture._cachedWrapV = texture.wrapV;
+ this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
+ }
+ if (internalTexture.is3D && internalTexture._cachedWrapR !== texture.wrapR) {
+ internalTexture._cachedWrapR = texture.wrapR;
+ this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
+ }
+ this._setAnisotropicLevel(target, internalTexture, texture.anisotropicFilteringLevel);
+ }
+ return true;
+ }
+ /**
+ * Sets an array of texture to the webGL context
+ * @param channel defines the channel where the texture array must be set
+ * @param uniform defines the associated uniform location
+ * @param textures defines the array of textures to bind
+ * @param name name of the channel
+ */
+ setTextureArray(channel, uniform, textures, name) {
+ if (channel === undefined || !uniform) {
+ return;
+ }
+ if (!this._textureUnits || this._textureUnits.length !== textures.length) {
+ this._textureUnits = new Int32Array(textures.length);
+ }
+ for (let i = 0; i < textures.length; i++) {
+ const texture = textures[i].getInternalTexture();
+ if (texture) {
+ this._textureUnits[i] = channel + i;
+ texture._associatedChannel = channel + i;
+ }
+ else {
+ this._textureUnits[i] = -1;
+ }
+ }
+ this._gl.uniform1iv(uniform, this._textureUnits);
+ for (let index = 0; index < textures.length; index++) {
+ this._setTexture(this._textureUnits[index], textures[index], true);
+ }
+ }
+ /**
+ * @internal
+ */
+ _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) {
+ const anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
+ if (internalTexture.samplingMode !== 11 &&
+ internalTexture.samplingMode !== 3 &&
+ internalTexture.samplingMode !== 2) {
+ anisotropicFilteringLevel = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
+ }
+ if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {
+ this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy), internalTexture);
+ internalTexture._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel;
+ }
+ }
+ _setTextureParameterFloat(target, parameter, value, texture) {
+ this._bindTextureDirectly(target, texture, true, true);
+ this._gl.texParameterf(target, parameter, value);
+ }
+ _setTextureParameterInteger(target, parameter, value, texture) {
+ if (texture) {
+ this._bindTextureDirectly(target, texture, true, true);
+ }
+ this._gl.texParameteri(target, parameter, value);
+ }
+ /**
+ * Unbind all vertex attributes from the webGL context
+ */
+ unbindAllAttributes() {
+ if (this._mustWipeVertexAttributes) {
+ this._mustWipeVertexAttributes = false;
+ for (let i = 0; i < this._caps.maxVertexAttribs; i++) {
+ this.disableAttributeByIndex(i);
+ }
+ return;
+ }
+ for (let i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
+ if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
+ continue;
+ }
+ this.disableAttributeByIndex(i);
+ }
+ }
+ /**
+ * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
+ */
+ releaseEffects() {
+ this._compiledEffects = {};
+ this.onReleaseEffectsObservable.notifyObservers(this);
+ }
+ /**
+ * Dispose and release all associated resources
+ */
+ dispose() {
+ // Events
+ if (IsWindowObjectExist()) {
+ if (this._renderingCanvas) {
+ this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
+ if (this._onContextRestored) {
+ this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
+ }
+ }
+ }
+ // Should not be moved up of renderingCanvas will be null.
+ super.dispose();
+ if (this._dummyFramebuffer) {
+ this._gl.deleteFramebuffer(this._dummyFramebuffer);
+ }
+ // Unbind
+ this.unbindAllAttributes();
+ this._boundUniforms = {};
+ this._workingCanvas = null;
+ this._workingContext = null;
+ this._currentBufferPointers.length = 0;
+ this._currentProgram = null;
+ if (this._creationOptions.loseContextOnDispose) {
+ this._gl.getExtension("WEBGL_lose_context")?.loseContext();
+ }
+ // clear the state object
+ deleteStateObject(this._gl);
+ }
+ /**
+ * Attach a new callback raised when context lost event is fired
+ * @param callback defines the callback to call
+ */
+ attachContextLostEvent(callback) {
+ if (this._renderingCanvas) {
+ this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
+ }
+ }
+ /**
+ * Attach a new callback raised when context restored event is fired
+ * @param callback defines the callback to call
+ */
+ attachContextRestoredEvent(callback) {
+ if (this._renderingCanvas) {
+ this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
+ }
+ }
+ /**
+ * Get the current error code of the webGL context
+ * @returns the error code
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
+ */
+ getError() {
+ return this._gl.getError();
+ }
+ _canRenderToFloatFramebuffer() {
+ if (this._webGLVersion > 1) {
+ return this._caps.colorBufferFloat;
+ }
+ return this._canRenderToFramebuffer(1);
+ }
+ _canRenderToHalfFloatFramebuffer() {
+ if (this._webGLVersion > 1) {
+ return this._caps.colorBufferFloat;
+ }
+ return this._canRenderToFramebuffer(2);
+ }
+ // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
+ _canRenderToFramebuffer(type) {
+ const gl = this._gl;
+ //clear existing errors
+ // eslint-disable-next-line no-empty
+ while (gl.getError() !== gl.NO_ERROR) { }
+ let successful = true;
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ const fb = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
+ successful = successful && status === gl.FRAMEBUFFER_COMPLETE;
+ successful = successful && gl.getError() === gl.NO_ERROR;
+ //try render by clearing frame buffer's color buffer
+ if (successful) {
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ successful = successful && gl.getError() === gl.NO_ERROR;
+ }
+ //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
+ if (successful) {
+ //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ const readFormat = gl.RGBA;
+ const readType = gl.UNSIGNED_BYTE;
+ const buffer = new Uint8Array(4);
+ gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
+ successful = successful && gl.getError() === gl.NO_ERROR;
+ }
+ //clean up
+ gl.deleteTexture(texture);
+ gl.deleteFramebuffer(fb);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ //clear accumulated errors
+ // eslint-disable-next-line no-empty
+ while (!successful && gl.getError() !== gl.NO_ERROR) { }
+ return successful;
+ }
+ /**
+ * @internal
+ */
+ _getWebGLTextureType(type) {
+ if (this._webGLVersion === 1) {
+ switch (type) {
+ case 1:
+ return this._gl.FLOAT;
+ case 2:
+ return this._gl.HALF_FLOAT_OES;
+ case 0:
+ return this._gl.UNSIGNED_BYTE;
+ case 8:
+ return this._gl.UNSIGNED_SHORT_4_4_4_4;
+ case 9:
+ return this._gl.UNSIGNED_SHORT_5_5_5_1;
+ case 10:
+ return this._gl.UNSIGNED_SHORT_5_6_5;
+ }
+ return this._gl.UNSIGNED_BYTE;
+ }
+ switch (type) {
+ case 3:
+ return this._gl.BYTE;
+ case 0:
+ return this._gl.UNSIGNED_BYTE;
+ case 4:
+ return this._gl.SHORT;
+ case 5:
+ return this._gl.UNSIGNED_SHORT;
+ case 6:
+ return this._gl.INT;
+ case 7: // Refers to UNSIGNED_INT
+ return this._gl.UNSIGNED_INT;
+ case 1:
+ return this._gl.FLOAT;
+ case 2:
+ return this._gl.HALF_FLOAT;
+ case 8:
+ return this._gl.UNSIGNED_SHORT_4_4_4_4;
+ case 9:
+ return this._gl.UNSIGNED_SHORT_5_5_5_1;
+ case 10:
+ return this._gl.UNSIGNED_SHORT_5_6_5;
+ case 11:
+ return this._gl.UNSIGNED_INT_2_10_10_10_REV;
+ case 12:
+ return this._gl.UNSIGNED_INT_24_8;
+ case 13:
+ return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
+ case 14:
+ return this._gl.UNSIGNED_INT_5_9_9_9_REV;
+ case 15:
+ return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
+ }
+ return this._gl.UNSIGNED_BYTE;
+ }
+ /**
+ * @internal
+ */
+ _getInternalFormat(format, useSRGBBuffer = false) {
+ let internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA;
+ switch (format) {
+ case 0:
+ internalFormat = this._gl.ALPHA;
+ break;
+ case 1:
+ internalFormat = this._gl.LUMINANCE;
+ break;
+ case 2:
+ internalFormat = this._gl.LUMINANCE_ALPHA;
+ break;
+ case 6:
+ case 33322:
+ case 36760:
+ internalFormat = this._gl.RED;
+ break;
+ case 7:
+ case 33324:
+ case 36761:
+ internalFormat = this._gl.RG;
+ break;
+ case 4:
+ case 32852:
+ case 36762:
+ internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB : this._gl.RGB;
+ break;
+ case 5:
+ case 32859:
+ case 36763:
+ internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA;
+ break;
+ }
+ if (this._webGLVersion > 1) {
+ switch (format) {
+ case 8:
+ internalFormat = this._gl.RED_INTEGER;
+ break;
+ case 9:
+ internalFormat = this._gl.RG_INTEGER;
+ break;
+ case 10:
+ internalFormat = this._gl.RGB_INTEGER;
+ break;
+ case 11:
+ internalFormat = this._gl.RGBA_INTEGER;
+ break;
+ }
+ }
+ return internalFormat;
+ }
+ /**
+ * @internal
+ */
+ _getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer = false) {
+ if (this._webGLVersion === 1) {
+ if (format !== undefined) {
+ switch (format) {
+ case 0:
+ return this._gl.ALPHA;
+ case 1:
+ return this._gl.LUMINANCE;
+ case 2:
+ return this._gl.LUMINANCE_ALPHA;
+ case 4:
+ return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB : this._gl.RGB;
+ }
+ }
+ return this._gl.RGBA;
+ }
+ switch (type) {
+ case 3:
+ switch (format) {
+ case 6:
+ return this._gl.R8_SNORM;
+ case 7:
+ return this._gl.RG8_SNORM;
+ case 4:
+ return this._gl.RGB8_SNORM;
+ case 8:
+ return this._gl.R8I;
+ case 9:
+ return this._gl.RG8I;
+ case 10:
+ return this._gl.RGB8I;
+ case 11:
+ return this._gl.RGBA8I;
+ default:
+ return this._gl.RGBA8_SNORM;
+ }
+ case 0:
+ switch (format) {
+ case 6:
+ return this._gl.R8;
+ case 7:
+ return this._gl.RG8;
+ case 4:
+ return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8 : this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
+ case 5:
+ return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
+ case 8:
+ return this._gl.R8UI;
+ case 9:
+ return this._gl.RG8UI;
+ case 10:
+ return this._gl.RGB8UI;
+ case 11:
+ return this._gl.RGBA8UI;
+ case 0:
+ return this._gl.ALPHA;
+ case 1:
+ return this._gl.LUMINANCE;
+ case 2:
+ return this._gl.LUMINANCE_ALPHA;
+ default:
+ return this._gl.RGBA8;
+ }
+ case 4:
+ switch (format) {
+ case 8:
+ return this._gl.R16I;
+ case 36760:
+ return this._gl.R16_SNORM_EXT;
+ case 36761:
+ return this._gl.RG16_SNORM_EXT;
+ case 36762:
+ return this._gl.RGB16_SNORM_EXT;
+ case 36763:
+ return this._gl.RGBA16_SNORM_EXT;
+ case 9:
+ return this._gl.RG16I;
+ case 10:
+ return this._gl.RGB16I;
+ case 11:
+ return this._gl.RGBA16I;
+ default:
+ return this._gl.RGBA16I;
+ }
+ case 5:
+ switch (format) {
+ case 8:
+ return this._gl.R16UI;
+ case 33322:
+ return this._gl.R16_EXT;
+ case 33324:
+ return this._gl.RG16_EXT;
+ case 32852:
+ return this._gl.RGB16_EXT;
+ case 32859:
+ return this._gl.RGBA16_EXT;
+ case 9:
+ return this._gl.RG16UI;
+ case 10:
+ return this._gl.RGB16UI;
+ case 11:
+ return this._gl.RGBA16UI;
+ default:
+ return this._gl.RGBA16UI;
+ }
+ case 6:
+ switch (format) {
+ case 8:
+ return this._gl.R32I;
+ case 9:
+ return this._gl.RG32I;
+ case 10:
+ return this._gl.RGB32I;
+ case 11:
+ return this._gl.RGBA32I;
+ default:
+ return this._gl.RGBA32I;
+ }
+ case 7: // Refers to UNSIGNED_INT
+ switch (format) {
+ case 8:
+ return this._gl.R32UI;
+ case 9:
+ return this._gl.RG32UI;
+ case 10:
+ return this._gl.RGB32UI;
+ case 11:
+ return this._gl.RGBA32UI;
+ default:
+ return this._gl.RGBA32UI;
+ }
+ case 1:
+ switch (format) {
+ case 6:
+ return this._gl.R32F; // By default. Other possibility is R16F.
+ case 7:
+ return this._gl.RG32F; // By default. Other possibility is RG16F.
+ case 4:
+ return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
+ case 5:
+ return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
+ default:
+ return this._gl.RGBA32F;
+ }
+ case 2:
+ switch (format) {
+ case 6:
+ return this._gl.R16F;
+ case 7:
+ return this._gl.RG16F;
+ case 4:
+ return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
+ case 5:
+ return this._gl.RGBA16F;
+ default:
+ return this._gl.RGBA16F;
+ }
+ case 10:
+ return this._gl.RGB565;
+ case 13:
+ return this._gl.R11F_G11F_B10F;
+ case 14:
+ return this._gl.RGB9_E5;
+ case 8:
+ return this._gl.RGBA4;
+ case 9:
+ return this._gl.RGB5_A1;
+ case 11:
+ switch (format) {
+ case 5:
+ return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
+ case 11:
+ return this._gl.RGB10_A2UI;
+ default:
+ return this._gl.RGB10_A2;
+ }
+ }
+ return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8;
+ }
+ /**
+ * Reads pixels from the current frame buffer. Please note that this function can be slow
+ * @param x defines the x coordinate of the rectangle where pixels must be read
+ * @param y defines the y coordinate of the rectangle where pixels must be read
+ * @param width defines the width of the rectangle where pixels must be read
+ * @param height defines the height of the rectangle where pixels must be read
+ * @param hasAlpha defines whether the output should have alpha or not (defaults to true)
+ * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels
+ * @param data defines the data to fill with the read pixels (if not provided, a new one will be created)
+ * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors
+ */
+ readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true, data = null) {
+ const numChannels = hasAlpha ? 4 : 3;
+ const format = hasAlpha ? this._gl.RGBA : this._gl.RGB;
+ const dataLength = width * height * numChannels;
+ if (!data) {
+ data = new Uint8Array(dataLength);
+ }
+ else if (data.length < dataLength) {
+ Logger.Error(`Data buffer is too small to store the read pixels (${data.length} should be more than ${dataLength})`);
+ return Promise.resolve(data);
+ }
+ if (flushRenderer) {
+ this.flushFramebuffer();
+ }
+ this._gl.readPixels(x, y, width, height, format, this._gl.UNSIGNED_BYTE, data);
+ return Promise.resolve(data);
+ }
+ /**
+ * Gets a Promise indicating if the engine can be instantiated (ie. if a webGL context can be found)
+ */
+ static get IsSupportedAsync() {
+ return Promise.resolve(this.isSupported());
+ }
+ /**
+ * Gets a boolean indicating if the engine can be instantiated (ie. if a webGL context can be found)
+ */
+ static get IsSupported() {
+ return this.isSupported(); // Backward compat
+ }
+ /**
+ * Gets a boolean indicating if the engine can be instantiated (ie. if a webGL context can be found)
+ * @returns true if the engine can be created
+ * @ignorenaming
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static isSupported() {
+ if (this._HasMajorPerformanceCaveat !== null) {
+ return !this._HasMajorPerformanceCaveat; // We know it is performant so WebGL is supported
+ }
+ if (this._IsSupported === null) {
+ try {
+ const tempcanvas = AbstractEngine._CreateCanvas(1, 1);
+ const gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
+ this._IsSupported = gl != null && !!window.WebGLRenderingContext;
+ }
+ catch (e) {
+ this._IsSupported = false;
+ }
+ }
+ return this._IsSupported;
+ }
+ /**
+ * Gets a boolean indicating if the engine can be instantiated on a performant device (ie. if a webGL context can be found and it does not use a slow implementation)
+ */
+ static get HasMajorPerformanceCaveat() {
+ if (this._HasMajorPerformanceCaveat === null) {
+ try {
+ const tempcanvas = AbstractEngine._CreateCanvas(1, 1);
+ const gl = tempcanvas.getContext("webgl", { failIfMajorPerformanceCaveat: true }) ||
+ tempcanvas.getContext("experimental-webgl", { failIfMajorPerformanceCaveat: true });
+ this._HasMajorPerformanceCaveat = !gl;
+ }
+ catch (e) {
+ this._HasMajorPerformanceCaveat = false;
+ }
+ }
+ return this._HasMajorPerformanceCaveat;
+ }
+}
+ThinEngine._TempClearColorUint32 = new Uint32Array(4);
+ThinEngine._TempClearColorInt32 = new Int32Array(4);
+/** Use this array to turn off some WebGL2 features on known buggy browsers version */
+ThinEngine.ExceptionList = [
+ { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
+ { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
+ { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
+ { key: "Chrome/72.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
+ { key: "Chrome/73.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
+ { key: "Chrome/74.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
+ { key: "Mac OS.+Chrome/71", capture: null, captureConstraint: null, targets: ["vao"] },
+ { key: "Mac OS.+Chrome/72", capture: null, captureConstraint: null, targets: ["vao"] },
+ { key: "Mac OS.+Chrome", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
+ { key: "Chrome/12\\d\\..+?Mobile", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
+ // desktop osx safari 15.4
+ { key: ".*AppleWebKit.*(15.4).*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] },
+ // mobile browsers using safari 15.4 on ios
+ { key: ".*(15.4).*AppleWebKit.*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] },
+];
+// eslint-disable-next-line @typescript-eslint/naming-convention
+ThinEngine._ConcatenateShader = _ConcatenateShader;
+// Statics
+ThinEngine._IsSupported = null;
+ThinEngine._HasMajorPerformanceCaveat = null;
+
+const thinEngine = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ ThinEngine
+}, Symbol.toStringTag, { value: 'Module' }));
+
+/**
+ * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
+ */
+class PerformanceMonitor {
+ /**
+ * constructor
+ * @param frameSampleSize The number of samples required to saturate the sliding window
+ */
+ constructor(frameSampleSize = 30) {
+ this._enabled = true;
+ this._rollingFrameTime = new RollingAverage(frameSampleSize);
+ }
+ /**
+ * Samples current frame
+ * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
+ */
+ sampleFrame(timeMs = PrecisionDate.Now) {
+ if (!this._enabled) {
+ return;
+ }
+ if (this._lastFrameTimeMs != null) {
+ const dt = timeMs - this._lastFrameTimeMs;
+ this._rollingFrameTime.add(dt);
+ }
+ this._lastFrameTimeMs = timeMs;
+ }
+ /**
+ * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
+ */
+ get averageFrameTime() {
+ return this._rollingFrameTime.average;
+ }
+ /**
+ * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
+ */
+ get averageFrameTimeVariance() {
+ return this._rollingFrameTime.variance;
+ }
+ /**
+ * Returns the frame time of the most recent frame
+ */
+ get instantaneousFrameTime() {
+ return this._rollingFrameTime.history(0);
+ }
+ /**
+ * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
+ */
+ get averageFPS() {
+ return 1000.0 / this._rollingFrameTime.average;
+ }
+ /**
+ * Returns the average framerate in frames per second using the most recent frame time
+ */
+ get instantaneousFPS() {
+ const history = this._rollingFrameTime.history(0);
+ if (history === 0) {
+ return 0;
+ }
+ return 1000.0 / history;
+ }
+ /**
+ * Returns true if enough samples have been taken to completely fill the sliding window
+ */
+ get isSaturated() {
+ return this._rollingFrameTime.isSaturated();
+ }
+ /**
+ * Enables contributions to the sliding window sample set
+ */
+ enable() {
+ this._enabled = true;
+ }
+ /**
+ * Disables contributions to the sliding window sample set
+ * Samples will not be interpolated over the disabled period
+ */
+ disable() {
+ this._enabled = false;
+ //clear last sample to avoid interpolating over the disabled period when next enabled
+ this._lastFrameTimeMs = null;
+ }
+ /**
+ * Returns true if sampling is enabled
+ */
+ get isEnabled() {
+ return this._enabled;
+ }
+ /**
+ * Resets performance monitor
+ */
+ reset() {
+ //clear last sample to avoid interpolating over the disabled period when next enabled
+ this._lastFrameTimeMs = null;
+ //wipe record
+ this._rollingFrameTime.reset();
+ }
+}
+/**
+ * RollingAverage
+ *
+ * Utility to efficiently compute the rolling average and variance over a sliding window of samples
+ */
+class RollingAverage {
+ /**
+ * constructor
+ * @param length The number of samples required to saturate the sliding window
+ */
+ constructor(length) {
+ this._samples = new Array(length);
+ this.reset();
+ }
+ /**
+ * Adds a sample to the sample set
+ * @param v The sample value
+ */
+ add(v) {
+ //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
+ let delta;
+ //we need to check if we've already wrapped round
+ if (this.isSaturated()) {
+ //remove bottom of stack from mean
+ const bottomValue = this._samples[this._pos];
+ delta = bottomValue - this.average;
+ this.average -= delta / (this._sampleCount - 1);
+ this._m2 -= delta * (bottomValue - this.average);
+ }
+ else {
+ this._sampleCount++;
+ }
+ //add new value to mean
+ delta = v - this.average;
+ this.average += delta / this._sampleCount;
+ this._m2 += delta * (v - this.average);
+ //set the new variance
+ this.variance = this._m2 / (this._sampleCount - 1);
+ this._samples[this._pos] = v;
+ this._pos++;
+ this._pos %= this._samples.length; //positive wrap around
+ }
+ /**
+ * Returns previously added values or null if outside of history or outside the sliding window domain
+ * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
+ * @returns Value previously recorded with add() or null if outside of range
+ */
+ history(i) {
+ if (i >= this._sampleCount || i >= this._samples.length) {
+ return 0;
+ }
+ const i0 = this._wrapPosition(this._pos - 1.0);
+ return this._samples[this._wrapPosition(i0 - i)];
+ }
+ /**
+ * Returns true if enough samples have been taken to completely fill the sliding window
+ * @returns true if sample-set saturated
+ */
+ isSaturated() {
+ return this._sampleCount >= this._samples.length;
+ }
+ /**
+ * Resets the rolling average (equivalent to 0 samples taken so far)
+ */
+ reset() {
+ this.average = 0;
+ this.variance = 0;
+ this._sampleCount = 0;
+ this._pos = 0;
+ this._m2 = 0;
+ }
+ /**
+ * Wraps a value around the sample range boundaries
+ * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
+ * @returns Wrapped position in sample range
+ */
+ _wrapPosition(i) {
+ const max = this._samples.length;
+ return ((i % max) + max) % max;
+ }
+}
+
+ThinEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) {
+ if (this._alphaMode === mode) {
+ if (!noDepthWriteChange) {
+ // Make sure we still have the correct depth mask according to the alpha mode (a transparent material could have forced writting to the depth buffer, for instance)
+ const depthMask = mode === 0;
+ if (this.depthCullingState.depthMask !== depthMask) {
+ this.depthCullingState.depthMask = depthMask;
+ }
+ }
+ return;
+ }
+ switch (mode) {
+ case 0:
+ this._alphaState.alphaBlend = false;
+ break;
+ case 7:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 8:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 2:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 6:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 1:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 3:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 4:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 5:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 9:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 10:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 11:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 12:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ZERO);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 13:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE_MINUS_DST_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 14:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 15:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ZERO);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 16:
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ZERO, this._gl.ONE);
+ this._alphaState.alphaBlend = true;
+ break;
+ case 17:
+ // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency
+ this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
+ this._alphaState.alphaBlend = true;
+ break;
+ }
+ if (!noDepthWriteChange) {
+ this.depthCullingState.depthMask = mode === 0;
+ }
+ this._alphaMode = mode;
+};
+
+ThinEngine.prototype.updateRawTexture = function (texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {
+ if (!texture) {
+ return;
+ }
+ // Babylon's internalSizedFomat but gl's texImage2D internalFormat
+ const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);
+ // Babylon's internalFormat but gl's texImage2D format
+ const internalFormat = this._getInternalFormat(format);
+ const textureType = this._getWebGLTextureType(type);
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
+ this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);
+ if (!this._doNotHandleContextLost) {
+ texture._bufferView = data;
+ texture.format = format;
+ texture.type = type;
+ texture.invertY = invertY;
+ texture._compression = compression;
+ }
+ if (texture.width % 4 !== 0) {
+ this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
+ }
+ if (compression && data) {
+ this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
+ }
+ else {
+ this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
+ }
+ if (texture.generateMipMaps) {
+ this._gl.generateMipmap(this._gl.TEXTURE_2D);
+ }
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
+ // this.resetTextureCache();
+ texture.isReady = true;
+};
+ThinEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0,
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+creationFlags = 0, useSRGBBuffer = false) {
+ const texture = new InternalTexture(this, 3 /* InternalTextureSource.Raw */);
+ texture.baseWidth = width;
+ texture.baseHeight = height;
+ texture.width = width;
+ texture.height = height;
+ texture.format = format;
+ texture.generateMipMaps = generateMipMaps;
+ texture.samplingMode = samplingMode;
+ texture.invertY = invertY;
+ texture._compression = compression;
+ texture.type = type;
+ texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);
+ if (!this._doNotHandleContextLost) {
+ texture._bufferView = data;
+ }
+ this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer);
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
+ // Filters
+ const filters = this._getSamplingParameters(samplingMode, generateMipMaps);
+ this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
+ this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
+ if (generateMipMaps) {
+ this._gl.generateMipmap(this._gl.TEXTURE_2D);
+ }
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
+ this._internalTexturesCache.push(texture);
+ return texture;
+};
+ThinEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) {
+ const gl = this._gl;
+ const texture = new InternalTexture(this, 8 /* InternalTextureSource.CubeRaw */);
+ texture.isCube = true;
+ texture.format = format;
+ texture.type = type;
+ if (!this._doNotHandleContextLost) {
+ texture._bufferViewArray = data;
+ }
+ const textureType = this._getWebGLTextureType(type);
+ let internalFormat = this._getInternalFormat(format);
+ if (internalFormat === gl.RGB) {
+ internalFormat = gl.RGBA;
+ }
+ // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
+ if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
+ generateMipMaps = false;
+ samplingMode = 1;
+ Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
+ }
+ else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
+ generateMipMaps = false;
+ samplingMode = 1;
+ Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
+ }
+ else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
+ generateMipMaps = false;
+ Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
+ }
+ else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
+ generateMipMaps = false;
+ Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
+ }
+ const width = size;
+ const height = width;
+ texture.width = width;
+ texture.height = height;
+ texture.invertY = invertY;
+ texture._compression = compression;
+ // Double check on POT to generate Mips.
+ const isPot = !this.needPOTTextures || (IsExponentOfTwo(texture.width) && IsExponentOfTwo(texture.height));
+ if (!isPot) {
+ generateMipMaps = false;
+ }
+ // Upload data if needed. The texture won't be ready until then.
+ if (data) {
+ this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
+ }
+ else {
+ const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
+ const level = 0;
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
+ for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
+ if (compression) {
+ gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, undefined);
+ }
+ else {
+ gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, null);
+ }
+ }
+ this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
+ }
+ this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
+ // Filters
+ if (data && generateMipMaps) {
+ this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
+ }
+ const filters = this._getSamplingParameters(samplingMode, generateMipMaps);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
+ texture.generateMipMaps = generateMipMaps;
+ texture.samplingMode = samplingMode;
+ texture.isReady = true;
+ return texture;
+};
+ThinEngine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression = null, level = 0) {
+ texture._bufferViewArray = data;
+ texture.format = format;
+ texture.type = type;
+ texture.invertY = invertY;
+ texture._compression = compression;
+ const gl = this._gl;
+ const textureType = this._getWebGLTextureType(type);
+ let internalFormat = this._getInternalFormat(format);
+ const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
+ let needConversion = false;
+ if (internalFormat === gl.RGB) {
+ internalFormat = gl.RGBA;
+ needConversion = true;
+ }
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
+ this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);
+ if (texture.width % 4 !== 0) {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
+ }
+ // Data are known to be in +X +Y +Z -X -Y -Z
+ for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
+ let faceData = data[faceIndex];
+ if (compression) {
+ gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
+ }
+ else {
+ if (needConversion) {
+ faceData = _convertRGBtoRGBATextureData$1(faceData, texture.width, texture.height, type);
+ }
+ gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
+ }
+ }
+ const isPot = !this.needPOTTextures || (IsExponentOfTwo(texture.width) && IsExponentOfTwo(texture.height));
+ if (isPot && texture.generateMipMaps && level === 0) {
+ this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
+ }
+ this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
+ // this.resetTextureCache();
+ texture.isReady = true;
+};
+ThinEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) {
+ const gl = this._gl;
+ const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);
+ scene?.addPendingData(texture);
+ texture.url = url;
+ texture.isReady = false;
+ this._internalTexturesCache.push(texture);
+ const onerror = (request, exception) => {
+ scene?.removePendingData(texture);
+ if (onError && request) {
+ onError(request.status + " " + request.statusText, exception);
+ }
+ };
+ const internalCallback = (data) => {
+ // If the texture has been disposed
+ if (!texture._hardwareTexture) {
+ return;
+ }
+ const width = texture.width;
+ const faceDataArrays = callback(data);
+ if (!faceDataArrays) {
+ return;
+ }
+ if (mipmapGenerator) {
+ const textureType = this._getWebGLTextureType(type);
+ let internalFormat = this._getInternalFormat(format);
+ const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
+ let needConversion = false;
+ if (internalFormat === gl.RGB) {
+ internalFormat = gl.RGBA;
+ needConversion = true;
+ }
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
+ this._unpackFlipY(false);
+ const mipData = mipmapGenerator(faceDataArrays);
+ for (let level = 0; level < mipData.length; level++) {
+ const mipSize = width >> level;
+ for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
+ let mipFaceData = mipData[level][faceIndex];
+ if (needConversion) {
+ mipFaceData = _convertRGBtoRGBATextureData$1(mipFaceData, mipSize, mipSize, type);
+ }
+ gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
+ }
+ }
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
+ }
+ else {
+ this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
+ }
+ texture.isReady = true;
+ // this.resetTextureCache();
+ scene?.removePendingData(texture);
+ texture.onLoadedObservable.notifyObservers(texture);
+ texture.onLoadedObservable.clear();
+ if (onLoad) {
+ onLoad();
+ }
+ };
+ this._loadFile(url, (data) => {
+ internalCallback(data);
+ }, undefined, scene?.offlineProvider, true, onerror);
+ return texture;
+};
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function _convertRGBtoRGBATextureData$1(rgbData, width, height, textureType) {
+ // Create new RGBA data container.
+ let rgbaData;
+ let val1 = 1;
+ if (textureType === 1) {
+ rgbaData = new Float32Array(width * height * 4);
+ }
+ else if (textureType === 2) {
+ rgbaData = new Uint16Array(width * height * 4);
+ val1 = 15360; // 15360 is the encoding of 1 in half float
+ }
+ else if (textureType === 7) {
+ rgbaData = new Uint32Array(width * height * 4);
+ }
+ else {
+ rgbaData = new Uint8Array(width * height * 4);
+ }
+ // Convert each pixel.
+ for (let x = 0; x < width; x++) {
+ for (let y = 0; y < height; y++) {
+ const index = (y * width + x) * 3;
+ const newIndex = (y * width + x) * 4;
+ // Map Old Value to new value.
+ rgbaData[newIndex + 0] = rgbData[index + 0];
+ rgbaData[newIndex + 1] = rgbData[index + 1];
+ rgbaData[newIndex + 2] = rgbData[index + 2];
+ // Add fully opaque alpha channel.
+ rgbaData[newIndex + 3] = val1;
+ }
+ }
+ return rgbaData;
+}
+/**
+ * Create a function for createRawTexture3D/createRawTexture2DArray
+ * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function _makeCreateRawTextureFunction(is3D) {
+ return function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) {
+ const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;
+ const source = is3D ? 10 /* InternalTextureSource.Raw3D */ : 11 /* InternalTextureSource.Raw2DArray */;
+ const texture = new InternalTexture(this, source);
+ texture.baseWidth = width;
+ texture.baseHeight = height;
+ texture.baseDepth = depth;
+ texture.width = width;
+ texture.height = height;
+ texture.depth = depth;
+ texture.format = format;
+ texture.type = textureType;
+ texture.generateMipMaps = generateMipMaps;
+ texture.samplingMode = samplingMode;
+ if (is3D) {
+ texture.is3D = true;
+ }
+ else {
+ texture.is2DArray = true;
+ }
+ if (!this._doNotHandleContextLost) {
+ texture._bufferView = data;
+ }
+ if (is3D) {
+ this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
+ }
+ else {
+ this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType);
+ }
+ this._bindTextureDirectly(target, texture, true);
+ // Filters
+ const filters = this._getSamplingParameters(samplingMode, generateMipMaps);
+ this._gl.texParameteri(target, this._gl.TEXTURE_MAG_FILTER, filters.mag);
+ this._gl.texParameteri(target, this._gl.TEXTURE_MIN_FILTER, filters.min);
+ if (generateMipMaps) {
+ this._gl.generateMipmap(target);
+ }
+ this._bindTextureDirectly(target, null);
+ this._internalTexturesCache.push(texture);
+ return texture;
+ };
+}
+ThinEngine.prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(false);
+ThinEngine.prototype.createRawTexture3D = _makeCreateRawTextureFunction(true);
+/**
+ * Create a function for updateRawTexture3D/updateRawTexture2DArray
+ * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function _makeUpdateRawTextureFunction(is3D) {
+ return function (texture, data, format, invertY, compression = null, textureType = 0) {
+ const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;
+ const internalType = this._getWebGLTextureType(textureType);
+ const internalFormat = this._getInternalFormat(format);
+ const internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
+ this._bindTextureDirectly(target, texture, true);
+ this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);
+ if (!this._doNotHandleContextLost) {
+ texture._bufferView = data;
+ texture.format = format;
+ texture.invertY = invertY;
+ texture._compression = compression;
+ }
+ if (texture.width % 4 !== 0) {
+ this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
+ }
+ if (compression && data) {
+ this._gl.compressedTexImage3D(target, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
+ }
+ else {
+ this._gl.texImage3D(target, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
+ }
+ if (texture.generateMipMaps) {
+ this._gl.generateMipmap(target);
+ }
+ this._bindTextureDirectly(target, null);
+ // this.resetTextureCache();
+ texture.isReady = true;
+ };
+}
+ThinEngine.prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(false);
+ThinEngine.prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(true);
+
+ThinEngine.prototype._readTexturePixelsSync = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {
+ const gl = this._gl;
+ if (!gl) {
+ throw new Error("Engine does not have gl rendering context.");
+ }
+ if (!this._dummyFramebuffer) {
+ const dummy = gl.createFramebuffer();
+ if (!dummy) {
+ throw new Error("Unable to create dummy framebuffer");
+ }
+ this._dummyFramebuffer = dummy;
+ }
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
+ if (faceIndex > -1) {
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._hardwareTexture?.underlyingResource, level);
+ }
+ else {
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture?.underlyingResource, level);
+ }
+ let readType = texture.type !== undefined ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
+ if (!noDataConversion) {
+ switch (readType) {
+ case gl.UNSIGNED_BYTE:
+ if (!buffer) {
+ buffer = new Uint8Array(4 * width * height);
+ }
+ readType = gl.UNSIGNED_BYTE;
+ break;
+ default:
+ if (!buffer) {
+ buffer = new Float32Array(4 * width * height);
+ }
+ readType = gl.FLOAT;
+ break;
+ }
+ }
+ else if (!buffer) {
+ buffer = allocateAndCopyTypedBuffer(texture.type, 4 * width * height);
+ }
+ if (flushRenderer) {
+ this.flushFramebuffer();
+ }
+ gl.readPixels(x, y, width, height, gl.RGBA, readType, buffer);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
+ return buffer;
+};
+ThinEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {
+ return Promise.resolve(this._readTexturePixelsSync(texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y));
+};
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+ThinEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset = 0) {
+ // Force cache update
+ this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
+ this.bindIndexBuffer(indexBuffer);
+ let view;
+ if (indexBuffer.is32Bits) {
+ // anything else than Uint32Array needs to be converted to Uint32Array
+ view = indices instanceof Uint32Array ? indices : new Uint32Array(indices);
+ }
+ else {
+ // anything else than Uint16Array needs to be converted to Uint16Array
+ view = indices instanceof Uint16Array ? indices : new Uint16Array(indices);
+ }
+ this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, view, this._gl.DYNAMIC_DRAW);
+ this._resetIndexBufferBinding();
+};
+ThinEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
+ this.bindArrayBuffer(vertexBuffer);
+ if (byteOffset === undefined) {
+ byteOffset = 0;
+ }
+ const dataLength = data.byteLength || data.length;
+ if (byteLength === undefined || (byteLength >= dataLength && byteOffset === 0)) {
+ if (data instanceof Array) {
+ this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
+ }
+ else {
+ this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
+ }
+ }
+ else {
+ if (data instanceof Array) {
+ this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data).subarray(0, byteLength / 4));
+ }
+ else {
+ if (data instanceof ArrayBuffer) {
+ data = new Uint8Array(data, 0, byteLength);
+ }
+ else {
+ data = new Uint8Array(data.buffer, data.byteOffset, byteLength);
+ }
+ this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
+ }
+ }
+ this._resetVertexBufferBinding();
+};
+
+ThinEngine.prototype._createDepthStencilCubeTexture = function (size, options) {
+ const internalTexture = new InternalTexture(this, 12 /* InternalTextureSource.DepthStencil */);
+ internalTexture.isCube = true;
+ if (this.webGLVersion === 1) {
+ Logger.Error("Depth cube texture is not supported by WebGL 1.");
+ return internalTexture;
+ }
+ const internalOptions = {
+ bilinearFiltering: false,
+ comparisonFunction: 0,
+ generateStencil: false,
+ ...options,
+ };
+ const gl = this._gl;
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
+ this._setupDepthStencilTexture(internalTexture, size, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
+ // Create the depth/stencil buffer
+ for (let face = 0; face < 6; face++) {
+ if (internalOptions.generateStencil) {
+ gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
+ }
+ else {
+ gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
+ }
+ }
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
+ this._internalTexturesCache.push(internalTexture);
+ return internalTexture;
+};
+ThinEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) {
+ const gl = this._gl;
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ texture.samplingMode = loadMipmap ? 3 : 2;
+ if (loadMipmap && this.getCaps().textureMaxLevel && maxLevel !== undefined && maxLevel > 0) {
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAX_LEVEL, maxLevel);
+ texture._maxLodLevel = maxLevel;
+ }
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
+};
+ThinEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false, buffer = null) {
+ const gl = this._gl;
+ return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, (texture) => this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true), (texture, imgs) => {
+ const width = this.needPOTTextures ? GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
+ const height = width;
+ const faces = [
+ gl.TEXTURE_CUBE_MAP_POSITIVE_X,
+ gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
+ gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
+ gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
+ gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
+ gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
+ ];
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
+ this._unpackFlipY(false);
+ const internalFormat = format ? this._getInternalFormat(format, texture._useSRGBBuffer) : texture._useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : gl.RGBA;
+ let texelFormat = format ? this._getInternalFormat(format) : gl.RGBA;
+ if (texture._useSRGBBuffer && this.webGLVersion === 1) {
+ texelFormat = internalFormat;
+ }
+ for (let index = 0; index < faces.length; index++) {
+ if (imgs[index].width !== width || imgs[index].height !== height) {
+ this._prepareWorkingCanvas();
+ if (!this._workingCanvas || !this._workingContext) {
+ Logger.Warn("Cannot create canvas to resize texture.");
+ return;
+ }
+ this._workingCanvas.width = width;
+ this._workingCanvas.height = height;
+ this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
+ gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
+ }
+ else {
+ gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, imgs[index]);
+ }
+ }
+ if (!noMipmap) {
+ gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
+ }
+ this._setCubeMapTextureParams(texture, !noMipmap);
+ texture.width = width;
+ texture.height = height;
+ texture.isReady = true;
+ if (format) {
+ texture.format = format;
+ }
+ texture.onLoadedObservable.notifyObservers(texture);
+ texture.onLoadedObservable.clear();
+ if (onLoad) {
+ onLoad();
+ }
+ }, !!useSRGBBuffer, buffer);
+};
+ThinEngine.prototype.generateMipMapsForCubemap = function (texture, unbind = true) {
+ if (texture.generateMipMaps) {
+ const gl = this._gl;
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
+ gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
+ if (unbind) {
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
+ }
+ }
+};
+
+/**
+ * Wrapper around a render target (either single or multi textures)
+ */
+class RenderTargetWrapper {
+ /**
+ * Gets the depth/stencil texture
+ */
+ get depthStencilTexture() {
+ return this._depthStencilTexture;
+ }
+ /**
+ * Sets the depth/stencil texture
+ * @param texture The depth/stencil texture to set
+ * @param disposeExisting True to dispose the existing depth/stencil texture (if any) before replacing it (default: true)
+ */
+ setDepthStencilTexture(texture, disposeExisting = true) {
+ if (disposeExisting && this._depthStencilTexture) {
+ this._depthStencilTexture.dispose();
+ }
+ this._depthStencilTexture = texture;
+ this._generateDepthBuffer = this._generateStencilBuffer = this._depthStencilTextureWithStencil = false;
+ if (texture) {
+ this._generateDepthBuffer = true;
+ this._generateStencilBuffer = this._depthStencilTextureWithStencil = HasStencilAspect(texture.format);
+ }
+ }
+ /**
+ * Indicates if the depth/stencil texture has a stencil aspect
+ */
+ get depthStencilTextureWithStencil() {
+ return this._depthStencilTextureWithStencil;
+ }
+ /**
+ * Defines if the render target wrapper is for a cube texture or if false a 2d texture
+ */
+ get isCube() {
+ return this._isCube;
+ }
+ /**
+ * Defines if the render target wrapper is for a single or multi target render wrapper
+ */
+ get isMulti() {
+ return this._isMulti;
+ }
+ /**
+ * Defines if the render target wrapper is for a single or an array of textures
+ */
+ get is2DArray() {
+ return this.layers > 0;
+ }
+ /**
+ * Defines if the render target wrapper is for a 3D texture
+ */
+ get is3D() {
+ return this.depth > 0;
+ }
+ /**
+ * Gets the size of the render target wrapper (used for cubes, as width=height in this case)
+ */
+ get size() {
+ return this.width;
+ }
+ /**
+ * Gets the width of the render target wrapper
+ */
+ get width() {
+ return this._size.width ?? this._size;
+ }
+ /**
+ * Gets the height of the render target wrapper
+ */
+ get height() {
+ return this._size.height ?? this._size;
+ }
+ /**
+ * Gets the number of layers of the render target wrapper (only used if is2DArray is true and wrapper is not a multi render target)
+ */
+ get layers() {
+ return this._size.layers || 0;
+ }
+ /**
+ * Gets the depth of the render target wrapper (only used if is3D is true and wrapper is not a multi render target)
+ */
+ get depth() {
+ return this._size.depth || 0;
+ }
+ /**
+ * Gets the render texture. If this is a multi render target, gets the first texture
+ */
+ get texture() {
+ return this._textures?.[0] ?? null;
+ }
+ /**
+ * Gets the list of render textures. If we are not in a multi render target, the list will be null (use the texture getter instead)
+ */
+ get textures() {
+ return this._textures;
+ }
+ /**
+ * Gets the face indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null
+ */
+ get faceIndices() {
+ return this._faceIndices;
+ }
+ /**
+ * Gets the layer indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null
+ */
+ get layerIndices() {
+ return this._layerIndices;
+ }
+ /**
+ * Gets the base array layer of a texture in the textures array
+ * This is an number that is calculated based on the layer and face indices set for this texture at that index
+ * @param index The index of the texture in the textures array to get the base array layer for
+ * @returns the base array layer of the texture at the given index
+ */
+ getBaseArrayLayer(index) {
+ if (!this._textures) {
+ return -1;
+ }
+ const texture = this._textures[index];
+ const layerIndex = this._layerIndices?.[index] ?? 0;
+ const faceIndex = this._faceIndices?.[index] ?? 0;
+ return texture.isCube ? layerIndex * 6 + faceIndex : texture.is3D ? 0 : layerIndex;
+ }
+ /**
+ * Gets the sample count of the render target
+ */
+ get samples() {
+ return this._samples;
+ }
+ /**
+ * Sets the sample count of the render target
+ * @param value sample count
+ * @param initializeBuffers If set to true, the engine will make an initializing call to drawBuffers (only used when isMulti=true).
+ * @param force true to force calling the update sample count engine function even if the current sample count is equal to value
+ * @returns the sample count that has been set
+ */
+ setSamples(value, initializeBuffers = true, force = false) {
+ if (this.samples === value && !force) {
+ return value;
+ }
+ const result = this._isMulti
+ ? this._engine.updateMultipleRenderTargetTextureSampleCount(this, value, initializeBuffers)
+ : this._engine.updateRenderTargetTextureSampleCount(this, value);
+ this._samples = value;
+ return result;
+ }
+ /**
+ * Resolves the MSAA textures into their non-MSAA version.
+ * Note that if samples equals 1 (no MSAA), no resolve is performed.
+ */
+ resolveMSAATextures() {
+ if (this.isMulti) {
+ this._engine.resolveMultiFramebuffer(this);
+ }
+ else {
+ this._engine.resolveFramebuffer(this);
+ }
+ }
+ /**
+ * Generates mipmaps for each texture of the render target
+ */
+ generateMipMaps() {
+ if (this._engine._currentRenderTarget === this) {
+ this._engine.unBindFramebuffer(this, true);
+ }
+ if (this.isMulti) {
+ this._engine.generateMipMapsMultiFramebuffer(this);
+ }
+ else {
+ this._engine.generateMipMapsFramebuffer(this);
+ }
+ }
+ /**
+ * Initializes the render target wrapper
+ * @param isMulti true if the wrapper is a multi render target
+ * @param isCube true if the wrapper should render to a cube texture
+ * @param size size of the render target (width/height/layers)
+ * @param engine engine used to create the render target
+ * @param label defines the label to use for the wrapper (for debugging purpose only)
+ */
+ constructor(isMulti, isCube, size, engine, label) {
+ this._textures = null;
+ this._faceIndices = null;
+ this._layerIndices = null;
+ /** @internal */
+ this._samples = 1;
+ /** @internal */
+ this._attachments = null;
+ /** @internal */
+ this._generateStencilBuffer = false;
+ /** @internal */
+ this._generateDepthBuffer = false;
+ /** @internal */
+ this._depthStencilTextureWithStencil = false;
+ /**
+ * Sets this property to true to disable the automatic MSAA resolve that happens when the render target wrapper is unbound (default is false)
+ */
+ this.disableAutomaticMSAAResolve = false;
+ /**
+ * Indicates if MSAA color texture(s) should be resolved when a resolve occur (either automatically by the engine or manually by the user) (default is true)
+ * Note that you can trigger a MSAA resolve at any time by calling resolveMSAATextures()
+ */
+ this.resolveMSAAColors = true;
+ /**
+ * Indicates if MSAA depth texture should be resolved when a resolve occur (either automatically by the engine or manually by the user) (default is false)
+ */
+ this.resolveMSAADepth = false;
+ /**
+ * Indicates if MSAA stencil texture should be resolved when a resolve occur (either automatically by the engine or manually by the user) (default is false)
+ */
+ this.resolveMSAAStencil = false;
+ this._isMulti = isMulti;
+ this._isCube = isCube;
+ this._size = size;
+ this._engine = engine;
+ this._depthStencilTexture = null;
+ this.label = label;
+ }
+ /**
+ * Sets the render target texture(s)
+ * @param textures texture(s) to set
+ */
+ setTextures(textures) {
+ if (Array.isArray(textures)) {
+ this._textures = textures;
+ }
+ else if (textures) {
+ this._textures = [textures];
+ }
+ else {
+ this._textures = null;
+ }
+ }
+ /**
+ * Set a texture in the textures array
+ * @param texture The texture to set
+ * @param index The index in the textures array to set
+ * @param disposePrevious If this function should dispose the previous texture
+ */
+ setTexture(texture, index = 0, disposePrevious = true) {
+ if (!this._textures) {
+ this._textures = [];
+ }
+ if (this._textures[index] === texture) {
+ return;
+ }
+ if (this._textures[index] && disposePrevious) {
+ this._textures[index].dispose();
+ }
+ this._textures[index] = texture;
+ }
+ /**
+ * Sets the layer and face indices of every render target texture bound to each color attachment
+ * @param layers The layers of each texture to be set
+ * @param faces The faces of each texture to be set
+ */
+ setLayerAndFaceIndices(layers, faces) {
+ this._layerIndices = layers;
+ this._faceIndices = faces;
+ }
+ /**
+ * Sets the layer and face indices of a texture in the textures array that should be bound to each color attachment
+ * @param index The index of the texture in the textures array to modify
+ * @param layer The layer of the texture to be set
+ * @param face The face of the texture to be set
+ */
+ setLayerAndFaceIndex(index = 0, layer, face) {
+ if (!this._layerIndices) {
+ this._layerIndices = [];
+ }
+ if (!this._faceIndices) {
+ this._faceIndices = [];
+ }
+ if (layer !== undefined && layer >= 0) {
+ this._layerIndices[index] = layer;
+ }
+ if (face !== undefined && face >= 0) {
+ this._faceIndices[index] = face;
+ }
+ }
+ /**
+ * Creates the depth/stencil texture
+ * @param comparisonFunction Comparison function to use for the texture
+ * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture
+ * @param generateStencil Not used anymore. "format" will be used to determine if stencil should be created
+ * @param samples sample count to use when creating the texture (default: 1)
+ * @param format format of the depth texture (default: 14)
+ * @param label defines the label to use for the texture (for debugging purpose only)
+ * @returns the depth/stencil created texture
+ */
+ createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) {
+ this._depthStencilTexture?.dispose();
+ this._depthStencilTextureWithStencil = generateStencil;
+ this._depthStencilTextureLabel = label;
+ this._depthStencilTexture = this._engine.createDepthStencilTexture(this._size, {
+ bilinearFiltering,
+ comparisonFunction,
+ generateStencil,
+ isCube: this._isCube,
+ samples,
+ depthTextureFormat: format,
+ label,
+ }, this);
+ return this._depthStencilTexture;
+ }
+ /**
+ * @deprecated Use shareDepth instead
+ * @param renderTarget Destination renderTarget
+ */
+ _shareDepth(renderTarget) {
+ this.shareDepth(renderTarget);
+ }
+ /**
+ * Shares the depth buffer of this render target with another render target.
+ * @param renderTarget Destination renderTarget
+ */
+ shareDepth(renderTarget) {
+ if (this._depthStencilTexture) {
+ if (renderTarget._depthStencilTexture) {
+ renderTarget._depthStencilTexture.dispose();
+ }
+ renderTarget._depthStencilTexture = this._depthStencilTexture;
+ renderTarget._depthStencilTextureWithStencil = this._depthStencilTextureWithStencil;
+ this._depthStencilTexture.incrementReferences();
+ }
+ }
+ /**
+ * @internal
+ */
+ _swapAndDie(target) {
+ if (this.texture) {
+ this.texture._swapAndDie(target);
+ }
+ this._textures = null;
+ this.dispose(true);
+ }
+ _cloneRenderTargetWrapper() {
+ let rtw = null;
+ if (this._isMulti) {
+ const textureArray = this.textures;
+ if (textureArray && textureArray.length > 0) {
+ let generateDepthTexture = false;
+ let textureCount = textureArray.length;
+ let depthTextureFormat = -1;
+ const lastTextureSource = textureArray[textureArray.length - 1]._source;
+ if (lastTextureSource === 14 /* InternalTextureSource.Depth */ || lastTextureSource === 12 /* InternalTextureSource.DepthStencil */) {
+ generateDepthTexture = true;
+ depthTextureFormat = textureArray[textureArray.length - 1].format;
+ textureCount--;
+ }
+ const samplingModes = [];
+ const types = [];
+ const formats = [];
+ const targetTypes = [];
+ const faceIndex = [];
+ const layerIndex = [];
+ const layerCounts = [];
+ const internalTexture2Index = {};
+ for (let i = 0; i < textureCount; ++i) {
+ const texture = textureArray[i];
+ samplingModes.push(texture.samplingMode);
+ types.push(texture.type);
+ formats.push(texture.format);
+ const index = internalTexture2Index[texture.uniqueId];
+ if (index !== undefined) {
+ targetTypes.push(-1);
+ layerCounts.push(0);
+ }
+ else {
+ internalTexture2Index[texture.uniqueId] = i;
+ if (texture.is2DArray) {
+ targetTypes.push(35866);
+ layerCounts.push(texture.depth);
+ }
+ else if (texture.isCube) {
+ targetTypes.push(34067);
+ layerCounts.push(0);
+ } /*else if (texture.isCubeArray) {
+ targetTypes.push(3735928559);
+ layerCounts.push(texture.depth);
+ }*/
+ else if (texture.is3D) {
+ targetTypes.push(32879);
+ layerCounts.push(texture.depth);
+ }
+ else {
+ targetTypes.push(3553);
+ layerCounts.push(0);
+ }
+ }
+ if (this._faceIndices) {
+ faceIndex.push(this._faceIndices[i] ?? 0);
+ }
+ if (this._layerIndices) {
+ layerIndex.push(this._layerIndices[i] ?? 0);
+ }
+ }
+ const optionsMRT = {
+ samplingModes,
+ generateMipMaps: textureArray[0].generateMipMaps,
+ generateDepthBuffer: this._generateDepthBuffer,
+ generateStencilBuffer: this._generateStencilBuffer,
+ generateDepthTexture,
+ depthTextureFormat,
+ types,
+ formats,
+ textureCount,
+ targetTypes,
+ faceIndex,
+ layerIndex,
+ layerCounts,
+ label: this.label,
+ };
+ const size = {
+ width: this.width,
+ height: this.height,
+ depth: this.depth,
+ };
+ rtw = this._engine.createMultipleRenderTarget(size, optionsMRT);
+ for (let i = 0; i < textureCount; ++i) {
+ if (targetTypes[i] !== -1) {
+ continue;
+ }
+ const index = internalTexture2Index[textureArray[i].uniqueId];
+ rtw.setTexture(rtw.textures[index], i);
+ }
+ }
+ }
+ else {
+ const options = {};
+ options.generateDepthBuffer = this._generateDepthBuffer;
+ options.generateMipMaps = this.texture?.generateMipMaps ?? false;
+ options.generateStencilBuffer = this._generateStencilBuffer;
+ options.samplingMode = this.texture?.samplingMode;
+ options.type = this.texture?.type;
+ options.format = this.texture?.format;
+ options.noColorAttachment = !this._textures;
+ options.label = this.label;
+ if (this.isCube) {
+ rtw = this._engine.createRenderTargetCubeTexture(this.width, options);
+ }
+ else {
+ const size = {
+ width: this.width,
+ height: this.height,
+ layers: this.is2DArray || this.is3D ? this.texture?.depth : undefined,
+ };
+ rtw = this._engine.createRenderTargetTexture(size, options);
+ }
+ if (rtw.texture) {
+ rtw.texture.isReady = true;
+ }
+ }
+ return rtw;
+ }
+ _swapRenderTargetWrapper(target) {
+ if (this._textures && target._textures) {
+ for (let i = 0; i < this._textures.length; ++i) {
+ this._textures[i]._swapAndDie(target._textures[i], false);
+ target._textures[i].isReady = true;
+ }
+ }
+ if (this._depthStencilTexture && target._depthStencilTexture) {
+ this._depthStencilTexture._swapAndDie(target._depthStencilTexture);
+ target._depthStencilTexture.isReady = true;
+ }
+ this._textures = null;
+ this._depthStencilTexture = null;
+ }
+ /** @internal */
+ _rebuild() {
+ const rtw = this._cloneRenderTargetWrapper();
+ if (!rtw) {
+ return;
+ }
+ if (this._depthStencilTexture) {
+ const samplingMode = this._depthStencilTexture.samplingMode;
+ const format = this._depthStencilTexture.format;
+ const bilinear = samplingMode === 2 ||
+ samplingMode === 3 ||
+ samplingMode === 11;
+ rtw.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction, bilinear, this._depthStencilTextureWithStencil, this._depthStencilTexture.samples, format, this._depthStencilTextureLabel);
+ }
+ if (this.samples > 1) {
+ rtw.setSamples(this.samples);
+ }
+ rtw._swapRenderTargetWrapper(this);
+ rtw.dispose();
+ }
+ /**
+ * Releases the internal render textures
+ */
+ releaseTextures() {
+ if (this._textures) {
+ for (let i = 0; i < this._textures.length; ++i) {
+ this._textures[i].dispose();
+ }
+ }
+ this._textures = null;
+ }
+ /**
+ * Disposes the whole render target wrapper
+ * @param disposeOnlyFramebuffers true if only the frame buffers should be released (used for the WebGL engine). If false, all the textures will also be released
+ */
+ dispose(disposeOnlyFramebuffers = false) {
+ if (!disposeOnlyFramebuffers) {
+ this._depthStencilTexture?.dispose();
+ this._depthStencilTexture = null;
+ this.releaseTextures();
+ }
+ this._engine._releaseRenderTargetWrapper(this);
+ }
+}
+
+/** @internal */
+class WebGLRenderTargetWrapper extends RenderTargetWrapper {
+ setDepthStencilTexture(texture, disposeExisting = true) {
+ super.setDepthStencilTexture(texture, disposeExisting);
+ if (!texture) {
+ return;
+ }
+ const engine = this._engine;
+ const gl = this._context;
+ const hardwareTexture = texture._hardwareTexture;
+ if (hardwareTexture && texture._autoMSAAManagement && this._MSAAFramebuffer) {
+ const currentFB = engine._currentFramebuffer;
+ engine._bindUnboundFramebuffer(this._MSAAFramebuffer);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, HasStencilAspect(texture.format) ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, hardwareTexture.getMSAARenderBuffer());
+ engine._bindUnboundFramebuffer(currentFB);
+ }
+ }
+ constructor(isMulti, isCube, size, engine, context) {
+ super(isMulti, isCube, size, engine);
+ /**
+ * @internal
+ */
+ this._framebuffer = null;
+ /**
+ * @internal
+ */
+ this._depthStencilBuffer = null;
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ this._MSAAFramebuffer = null;
+ // Multiview
+ /**
+ * @internal
+ */
+ this._colorTextureArray = null;
+ /**
+ * @internal
+ */
+ this._depthStencilTextureArray = null;
+ /**
+ * @internal
+ */
+ this._disposeOnlyFramebuffers = false;
+ /**
+ * @internal
+ */
+ this._currentLOD = 0;
+ this._context = context;
+ }
+ _cloneRenderTargetWrapper() {
+ let rtw = null;
+ if (this._colorTextureArray && this._depthStencilTextureArray) {
+ rtw = this._engine.createMultiviewRenderTargetTexture(this.width, this.height);
+ rtw.texture.isReady = true;
+ }
+ else {
+ rtw = super._cloneRenderTargetWrapper();
+ }
+ return rtw;
+ }
+ _swapRenderTargetWrapper(target) {
+ super._swapRenderTargetWrapper(target);
+ target._framebuffer = this._framebuffer;
+ target._depthStencilBuffer = this._depthStencilBuffer;
+ target._MSAAFramebuffer = this._MSAAFramebuffer;
+ target._colorTextureArray = this._colorTextureArray;
+ target._depthStencilTextureArray = this._depthStencilTextureArray;
+ this._framebuffer = this._depthStencilBuffer = this._MSAAFramebuffer = this._colorTextureArray = this._depthStencilTextureArray = null;
+ }
+ /**
+ * Creates the depth/stencil texture
+ * @param comparisonFunction Comparison function to use for the texture
+ * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture
+ * @param generateStencil true if the stencil aspect should also be created
+ * @param samples sample count to use when creating the texture
+ * @param format format of the depth texture
+ * @param label defines the label to use for the texture (for debugging purpose only)
+ * @returns the depth/stencil created texture
+ */
+ createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) {
+ if (this._depthStencilBuffer) {
+ const engine = this._engine;
+ // Dispose previous depth/stencil render buffers and clear the corresponding attachment.
+ // Next time this framebuffer is bound, the new depth/stencil texture will be attached.
+ const currentFrameBuffer = engine._currentFramebuffer;
+ const gl = this._context;
+ engine._bindUnboundFramebuffer(this._framebuffer);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, null);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, null);
+ engine._bindUnboundFramebuffer(currentFrameBuffer);
+ gl.deleteRenderbuffer(this._depthStencilBuffer);
+ this._depthStencilBuffer = null;
+ }
+ return super.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format, label);
+ }
+ /**
+ * Shares the depth buffer of this render target with another render target.
+ * @param renderTarget Destination renderTarget
+ */
+ shareDepth(renderTarget) {
+ super.shareDepth(renderTarget);
+ const gl = this._context;
+ const depthbuffer = this._depthStencilBuffer;
+ const framebuffer = renderTarget._MSAAFramebuffer || renderTarget._framebuffer;
+ const engine = this._engine;
+ if (renderTarget._depthStencilBuffer && renderTarget._depthStencilBuffer !== depthbuffer) {
+ gl.deleteRenderbuffer(renderTarget._depthStencilBuffer);
+ }
+ renderTarget._depthStencilBuffer = depthbuffer;
+ const attachment = renderTarget._generateStencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
+ engine._bindUnboundFramebuffer(framebuffer);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, depthbuffer);
+ engine._bindUnboundFramebuffer(null);
+ }
+ /**
+ * Binds a texture to this render target on a specific attachment
+ * @param texture The texture to bind to the framebuffer
+ * @param attachmentIndex Index of the attachment
+ * @param faceIndexOrLayer The face or layer of the texture to render to in case of cube texture or array texture
+ * @param lodLevel defines the lod level to bind to the frame buffer
+ */
+ _bindTextureRenderTarget(texture, attachmentIndex = 0, faceIndexOrLayer, lodLevel = 0) {
+ const hardwareTexture = texture._hardwareTexture;
+ if (!hardwareTexture) {
+ return;
+ }
+ const framebuffer = this._framebuffer;
+ const engine = this._engine;
+ const currentFB = engine._currentFramebuffer;
+ engine._bindUnboundFramebuffer(framebuffer);
+ let attachment;
+ if (engine.webGLVersion > 1) {
+ const gl = this._context;
+ attachment = gl["COLOR_ATTACHMENT" + attachmentIndex];
+ if (texture.is2DArray || texture.is3D) {
+ faceIndexOrLayer = faceIndexOrLayer ?? this.layerIndices?.[attachmentIndex] ?? 0;
+ gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, hardwareTexture.underlyingResource, lodLevel, faceIndexOrLayer);
+ }
+ else if (texture.isCube) {
+ // if face index is not specified, try to query it from faceIndices
+ // default is face 0
+ faceIndexOrLayer = faceIndexOrLayer ?? this.faceIndices?.[attachmentIndex] ?? 0;
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer, hardwareTexture.underlyingResource, lodLevel);
+ }
+ else {
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, hardwareTexture.underlyingResource, lodLevel);
+ }
+ }
+ else {
+ // Default behavior (WebGL)
+ const gl = this._context;
+ attachment = gl["COLOR_ATTACHMENT" + attachmentIndex + "_WEBGL"];
+ const target = faceIndexOrLayer !== undefined ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer : gl.TEXTURE_2D;
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, target, hardwareTexture.underlyingResource, lodLevel);
+ }
+ if (texture._autoMSAAManagement && this._MSAAFramebuffer) {
+ const gl = this._context;
+ engine._bindUnboundFramebuffer(this._MSAAFramebuffer);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, hardwareTexture.getMSAARenderBuffer());
+ }
+ engine._bindUnboundFramebuffer(currentFB);
+ }
+ /**
+ * Set a texture in the textures array
+ * @param texture the texture to set
+ * @param index the index in the textures array to set
+ * @param disposePrevious If this function should dispose the previous texture
+ */
+ setTexture(texture, index = 0, disposePrevious = true) {
+ super.setTexture(texture, index, disposePrevious);
+ this._bindTextureRenderTarget(texture, index);
+ }
+ /**
+ * Sets the layer and face indices of every render target texture
+ * @param layers The layer of the texture to be set (make negative to not modify)
+ * @param faces The face of the texture to be set (make negative to not modify)
+ */
+ setLayerAndFaceIndices(layers, faces) {
+ super.setLayerAndFaceIndices(layers, faces);
+ if (!this.textures || !this.layerIndices || !this.faceIndices) {
+ return;
+ }
+ // the length of this._attachments is the right one as it does not count the depth texture, in case we generated it
+ const textureCount = this._attachments?.length ?? this.textures.length;
+ for (let index = 0; index < textureCount; index++) {
+ const texture = this.textures[index];
+ if (!texture) {
+ // The target type was probably -1 at creation time and setTexture has not been called yet for this index
+ continue;
+ }
+ if (texture.is2DArray || texture.is3D) {
+ this._bindTextureRenderTarget(texture, index, this.layerIndices[index]);
+ }
+ else if (texture.isCube) {
+ this._bindTextureRenderTarget(texture, index, this.faceIndices[index]);
+ }
+ else {
+ this._bindTextureRenderTarget(texture, index);
+ }
+ }
+ }
+ /**
+ * Set the face and layer indices of a texture in the textures array
+ * @param index The index of the texture in the textures array to modify
+ * @param layer The layer of the texture to be set
+ * @param face The face of the texture to be set
+ */
+ setLayerAndFaceIndex(index = 0, layer, face) {
+ super.setLayerAndFaceIndex(index, layer, face);
+ if (!this.textures || !this.layerIndices || !this.faceIndices) {
+ return;
+ }
+ const texture = this.textures[index];
+ if (texture.is2DArray || texture.is3D) {
+ this._bindTextureRenderTarget(this.textures[index], index, this.layerIndices[index]);
+ }
+ else if (texture.isCube) {
+ this._bindTextureRenderTarget(this.textures[index], index, this.faceIndices[index]);
+ }
+ }
+ resolveMSAATextures() {
+ const engine = this._engine;
+ const currentFramebuffer = engine._currentFramebuffer;
+ engine._bindUnboundFramebuffer(this._MSAAFramebuffer);
+ super.resolveMSAATextures();
+ engine._bindUnboundFramebuffer(currentFramebuffer);
+ }
+ dispose(disposeOnlyFramebuffers = this._disposeOnlyFramebuffers) {
+ const gl = this._context;
+ if (!disposeOnlyFramebuffers) {
+ if (this._colorTextureArray) {
+ this._context.deleteTexture(this._colorTextureArray);
+ this._colorTextureArray = null;
+ }
+ if (this._depthStencilTextureArray) {
+ this._context.deleteTexture(this._depthStencilTextureArray);
+ this._depthStencilTextureArray = null;
+ }
+ }
+ if (this._framebuffer) {
+ gl.deleteFramebuffer(this._framebuffer);
+ this._framebuffer = null;
+ }
+ if (this._depthStencilBuffer) {
+ gl.deleteRenderbuffer(this._depthStencilBuffer);
+ this._depthStencilBuffer = null;
+ }
+ if (this._MSAAFramebuffer) {
+ gl.deleteFramebuffer(this._MSAAFramebuffer);
+ this._MSAAFramebuffer = null;
+ }
+ super.dispose(disposeOnlyFramebuffers);
+ }
+}
+
+AbstractEngine.prototype.createDepthStencilTexture = function (size, options, rtWrapper) {
+ if (options.isCube) {
+ const width = size.width || size;
+ return this._createDepthStencilCubeTexture(width, options);
+ }
+ else {
+ return this._createDepthStencilTexture(size, options, rtWrapper);
+ }
+};
+
+ThinEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) {
+ const rtWrapper = new WebGLRenderTargetWrapper(isMulti, isCube, size, this, this._gl);
+ this._renderTargetWrapperCache.push(rtWrapper);
+ return rtWrapper;
+};
+ThinEngine.prototype.createRenderTargetTexture = function (size, options) {
+ const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);
+ let generateDepthBuffer = true;
+ let generateStencilBuffer = false;
+ let noColorAttachment = false;
+ let colorAttachment = undefined;
+ let samples = 1;
+ let label = undefined;
+ if (options !== undefined && typeof options === "object") {
+ generateDepthBuffer = options.generateDepthBuffer ?? true;
+ generateStencilBuffer = !!options.generateStencilBuffer;
+ noColorAttachment = !!options.noColorAttachment;
+ colorAttachment = options.colorAttachment;
+ samples = options.samples ?? 1;
+ label = options.label;
+ }
+ const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, 5 /* InternalTextureSource.RenderTarget */));
+ const width = size.width || size;
+ const height = size.height || size;
+ const currentFrameBuffer = this._currentFramebuffer;
+ const gl = this._gl;
+ // Create the framebuffer
+ const framebuffer = gl.createFramebuffer();
+ this._bindUnboundFramebuffer(framebuffer);
+ rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
+ // No need to rebind on every frame
+ if (texture && !texture.is2DArray && !texture.is3D) {
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, 0);
+ }
+ this._bindUnboundFramebuffer(currentFrameBuffer);
+ rtWrapper.label = label ?? "RenderTargetWrapper";
+ rtWrapper._framebuffer = framebuffer;
+ rtWrapper._generateDepthBuffer = generateDepthBuffer;
+ rtWrapper._generateStencilBuffer = generateStencilBuffer;
+ rtWrapper.setTextures(texture);
+ if (!colorAttachment) {
+ this.updateRenderTargetTextureSampleCount(rtWrapper, samples);
+ }
+ else {
+ rtWrapper._samples = colorAttachment.samples;
+ if (colorAttachment.samples > 1) {
+ const msaaRenderBuffer = colorAttachment._hardwareTexture.getMSAARenderBuffer(0);
+ rtWrapper._MSAAFramebuffer = gl.createFramebuffer();
+ this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderBuffer);
+ this._bindUnboundFramebuffer(null);
+ }
+ }
+ return rtWrapper;
+};
+ThinEngine.prototype._createDepthStencilTexture = function (size, options, rtWrapper) {
+ const gl = this._gl;
+ const layers = size.layers || 0;
+ const depth = size.depth || 0;
+ let target = gl.TEXTURE_2D;
+ if (layers !== 0) {
+ target = gl.TEXTURE_2D_ARRAY;
+ }
+ else if (depth !== 0) {
+ target = gl.TEXTURE_3D;
+ }
+ const internalTexture = new InternalTexture(this, 12 /* InternalTextureSource.DepthStencil */);
+ internalTexture.label = options.label;
+ if (!this._caps.depthTextureExtension) {
+ Logger.Error("Depth texture is not supported by your browser or hardware.");
+ return internalTexture;
+ }
+ const internalOptions = {
+ bilinearFiltering: false,
+ comparisonFunction: 0,
+ generateStencil: false,
+ ...options,
+ };
+ this._bindTextureDirectly(target, internalTexture, true);
+ this._setupDepthStencilTexture(internalTexture, size, internalOptions.comparisonFunction === 0 ? false : internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);
+ if (internalOptions.depthTextureFormat !== undefined) {
+ if (internalOptions.depthTextureFormat !== 15 &&
+ internalOptions.depthTextureFormat !== 16 &&
+ internalOptions.depthTextureFormat !== 17 &&
+ internalOptions.depthTextureFormat !== 13 &&
+ internalOptions.depthTextureFormat !== 14 &&
+ internalOptions.depthTextureFormat !== 18) {
+ Logger.Error(`Depth texture ${internalOptions.depthTextureFormat} format is not supported.`);
+ return internalTexture;
+ }
+ internalTexture.format = internalOptions.depthTextureFormat;
+ }
+ else {
+ internalTexture.format = internalOptions.generateStencil ? 13 : 16;
+ }
+ const hasStencil = HasStencilAspect(internalTexture.format);
+ const type = this._getWebGLTextureTypeFromDepthTextureFormat(internalTexture.format);
+ const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT;
+ const internalFormat = this._getInternalFormatFromDepthTextureFormat(internalTexture.format, true, hasStencil);
+ if (internalTexture.is2DArray) {
+ gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, layers, 0, format, type, null);
+ }
+ else if (internalTexture.is3D) {
+ gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, depth, 0, format, type, null);
+ }
+ else {
+ gl.texImage2D(target, 0, internalFormat, internalTexture.width, internalTexture.height, 0, format, type, null);
+ }
+ this._bindTextureDirectly(target, null);
+ this._internalTexturesCache.push(internalTexture);
+ if (rtWrapper._depthStencilBuffer) {
+ gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer);
+ rtWrapper._depthStencilBuffer = null;
+ }
+ this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer ?? rtWrapper._framebuffer);
+ rtWrapper._generateStencilBuffer = hasStencil;
+ rtWrapper._depthStencilTextureWithStencil = hasStencil;
+ rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, rtWrapper.samples, internalTexture.format);
+ this._bindUnboundFramebuffer(null);
+ return internalTexture;
+};
+ThinEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) {
+ if (this.webGLVersion < 2 || !rtWrapper) {
+ return 1;
+ }
+ if (rtWrapper.samples === samples) {
+ return samples;
+ }
+ const gl = this._gl;
+ samples = Math.min(samples, this.getCaps().maxMSAASamples);
+ // Dispose previous render buffers
+ if (rtWrapper._depthStencilBuffer) {
+ gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer);
+ rtWrapper._depthStencilBuffer = null;
+ }
+ if (rtWrapper._MSAAFramebuffer) {
+ gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer);
+ rtWrapper._MSAAFramebuffer = null;
+ }
+ const hardwareTexture = rtWrapper.texture?._hardwareTexture;
+ hardwareTexture?.releaseMSAARenderBuffers();
+ if (rtWrapper.texture && samples > 1 && typeof gl.renderbufferStorageMultisample === "function") {
+ const framebuffer = gl.createFramebuffer();
+ if (!framebuffer) {
+ throw new Error("Unable to create multi sampled framebuffer");
+ }
+ rtWrapper._MSAAFramebuffer = framebuffer;
+ this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer);
+ const colorRenderbuffer = this._createRenderBuffer(rtWrapper.texture.width, rtWrapper.texture.height, samples, -1 /* not used */, this._getRGBABufferInternalSizedFormat(rtWrapper.texture.type, rtWrapper.texture.format, rtWrapper.texture._useSRGBBuffer), gl.COLOR_ATTACHMENT0, false);
+ if (!colorRenderbuffer) {
+ throw new Error("Unable to create multi sampled framebuffer");
+ }
+ hardwareTexture?.addMSAARenderBuffer(colorRenderbuffer);
+ }
+ this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer ?? rtWrapper._framebuffer);
+ if (rtWrapper.texture) {
+ rtWrapper.texture.samples = samples;
+ }
+ rtWrapper._samples = samples;
+ const depthFormat = rtWrapper._depthStencilTexture ? rtWrapper._depthStencilTexture.format : undefined;
+ rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, samples, depthFormat);
+ this._bindUnboundFramebuffer(null);
+ return samples;
+};
+ThinEngine.prototype._setupDepthStencilTexture = function (internalTexture, size, bilinearFiltering, comparisonFunction, samples = 1) {
+ const width = size.width ?? size;
+ const height = size.height ?? size;
+ const layers = size.layers || 0;
+ const depth = size.depth || 0;
+ internalTexture.baseWidth = width;
+ internalTexture.baseHeight = height;
+ internalTexture.width = width;
+ internalTexture.height = height;
+ internalTexture.is2DArray = layers > 0;
+ internalTexture.depth = layers || depth;
+ internalTexture.isReady = true;
+ internalTexture.samples = samples;
+ internalTexture.generateMipMaps = false;
+ internalTexture.samplingMode = bilinearFiltering ? 2 : 1;
+ internalTexture.type = 0;
+ internalTexture._comparisonFunction = comparisonFunction;
+ const gl = this._gl;
+ const target = this._getTextureTarget(internalTexture);
+ const samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
+ gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
+ gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
+ gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ // TEXTURE_COMPARE_FUNC/MODE are only availble in WebGL2.
+ if (this.webGLVersion > 1) {
+ if (comparisonFunction === 0) {
+ gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, 515);
+ gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
+ }
+ else {
+ gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
+ gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
+ }
+ }
+};
+
+ThinEngine.prototype.setDepthStencilTexture = function (channel, uniform, texture, name) {
+ if (channel === undefined) {
+ return;
+ }
+ if (uniform) {
+ this._boundUniforms[channel] = uniform;
+ }
+ if (!texture || !texture.depthStencilTexture) {
+ this._setTexture(channel, null, undefined, undefined, name);
+ }
+ else {
+ this._setTexture(channel, texture, false, true, name);
+ }
+};
+
+ThinEngine.prototype.createRenderTargetCubeTexture = function (size, options) {
+ const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size);
+ const fullOptions = {
+ generateMipMaps: true,
+ generateDepthBuffer: true,
+ generateStencilBuffer: false,
+ type: 0,
+ samplingMode: 3,
+ format: 5,
+ ...options,
+ };
+ fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
+ if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) {
+ // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
+ fullOptions.samplingMode = 1;
+ }
+ else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
+ // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
+ fullOptions.samplingMode = 1;
+ }
+ const gl = this._gl;
+ const texture = new InternalTexture(this, 5 /* InternalTextureSource.RenderTarget */);
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
+ const filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
+ if (fullOptions.type === 1 && !this._caps.textureFloat) {
+ fullOptions.type = 0;
+ Logger.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
+ }
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ for (let face = 0; face < 6; face++) {
+ gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
+ }
+ // Create the framebuffer
+ const framebuffer = gl.createFramebuffer();
+ this._bindUnboundFramebuffer(framebuffer);
+ rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
+ // MipMaps
+ if (fullOptions.generateMipMaps) {
+ gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
+ }
+ // Unbind
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
+ this._bindUnboundFramebuffer(null);
+ rtWrapper._framebuffer = framebuffer;
+ rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;
+ rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer;
+ texture.width = size;
+ texture.height = size;
+ texture.isReady = true;
+ texture.isCube = true;
+ texture.samples = 1;
+ texture.generateMipMaps = fullOptions.generateMipMaps;
+ texture.samplingMode = fullOptions.samplingMode;
+ texture.type = fullOptions.type;
+ texture.format = fullOptions.format;
+ this._internalTexturesCache.push(texture);
+ rtWrapper.setTextures(texture);
+ return rtWrapper;
+};
+
+/**
+ * Constant used to convert a value to gamma space
+ * @ignorenaming
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const ToGammaSpace = 1 / 2.2;
+/**
+ * Constant used to convert a value to linear space
+ * @ignorenaming
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const ToLinearSpace = 2.2;
+/**
+ * Constant Golden Ratio value in Babylon.js
+ * @ignorenaming
+ */
+const PHI = (1 + Math.sqrt(5)) / 2;
+/**
+ * Constant used to define the minimal number value in Babylon.js
+ * @ignorenaming
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const Epsilon = 0.001;
+
+/* eslint-disable @typescript-eslint/naming-convention */
+/**
+ * Returns an array of the given size filled with elements built from the given constructor and the parameters.
+ * @param size the number of element to construct and put in the array.
+ * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.
+ * @returns a new array filled with new objects.
+ */
+function BuildArray(size, itemBuilder) {
+ const a = [];
+ for (let i = 0; i < size; ++i) {
+ a.push(itemBuilder());
+ }
+ return a;
+}
+/**
+ * Returns a tuple of the given size filled with elements built from the given constructor and the parameters.
+ * @param size he number of element to construct and put in the tuple.
+ * @param itemBuilder a callback responsible for creating new instance of item. Called once per tuple entry.
+ * @returns a new tuple filled with new objects.
+ */
+function BuildTuple(size, itemBuilder) {
+ return BuildArray(size, itemBuilder);
+}
+/**
+ * Observes a function and calls the given callback when it is called.
+ * @param object Defines the object the function to observe belongs to.
+ * @param functionName Defines the name of the function to observe.
+ * @param callback Defines the callback to call when the function is called.
+ * @returns A function to call to stop observing
+ */
+function _observeArrayfunction(object, functionName, callback) {
+ // Finds the function to observe
+ const oldFunction = object[functionName];
+ if (typeof oldFunction !== "function") {
+ return null;
+ }
+ // Creates a new function that calls the callback and the old function
+ const newFunction = function () {
+ const previousLength = object.length;
+ const returnValue = newFunction.previous.apply(object, arguments);
+ callback(functionName, previousLength);
+ return returnValue;
+ };
+ // Doublishly links the new function and the old function
+ oldFunction.next = newFunction;
+ newFunction.previous = oldFunction;
+ // Replaces the old function with the new function
+ object[functionName] = newFunction;
+ // Returns a function to disable the hook
+ return () => {
+ // Only unhook if the function is still hooked
+ const previous = newFunction.previous;
+ if (!previous) {
+ return;
+ }
+ // Finds the ref to the next function in the chain
+ const next = newFunction.next;
+ // If in the middle of the chain, link the previous and next functions
+ if (next) {
+ previous.next = next;
+ next.previous = previous;
+ }
+ // If at the end of the chain, remove the reference to the previous function
+ // and restore the previous function
+ else {
+ previous.next = undefined;
+ object[functionName] = previous;
+ }
+ // Lose reference to the previous and next functions
+ newFunction.next = undefined;
+ newFunction.previous = undefined;
+ };
+}
+/**
+ * Defines the list of functions to proxy when observing an array.
+ * The scope is currently reduced to the common functions used in the render target render list and the scene cameras.
+ */
+const observedArrayFunctions = ["push", "splice", "pop", "shift", "unshift"];
+/**
+ * Observes an array and notifies the given observer when the array is modified.
+ * @param array Defines the array to observe
+ * @param callback Defines the function to call when the array is modified (in the limit of the observed array functions)
+ * @returns A function to call to stop observing the array
+ * @internal
+ */
+function _ObserveArray(array, callback) {
+ // Observes all the required array functions and stores the unhook functions
+ const unObserveFunctions = observedArrayFunctions.map((name) => {
+ return _observeArrayfunction(array, name, callback);
+ });
+ // Returns a function that unhook all the observed functions
+ return () => {
+ unObserveFunctions.forEach((unObserveFunction) => {
+ unObserveFunction?.();
+ });
+ };
+}
+
+/** @internal */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const _RegisteredTypes = {};
+/**
+ * @internal
+ */
+function RegisterClass(className, type) {
+ _RegisteredTypes[className] = type;
+}
+/**
+ * @internal
+ */
+function GetClass(fqdn) {
+ return _RegisteredTypes[fqdn];
+}
+
+/**
+ * Extract int value
+ * @param value number value
+ * @returns int value
+ */
+function ExtractAsInt(value) {
+ return parseInt(value.toString().replace(/\W/g, ""));
+}
+/**
+ * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
+ * @param a number
+ * @param b number
+ * @param epsilon (default = 1.401298E-45)
+ * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
+ */
+function WithinEpsilon(a, b, epsilon = 1.401298e-45) {
+ return Math.abs(a - b) <= epsilon;
+}
+/**
+ * Boolean : true if the number is outside a range
+ * @param num number
+ * @param min min value
+ * @param max max value
+ * @param epsilon (default = Number.EPSILON)
+ * @returns true if the number is between min and max values
+ */
+function OutsideRange(num, min, max, epsilon = 1.401298e-45) {
+ return num < min - epsilon || num > max + epsilon;
+}
+/**
+ * Returns a random float number between and min and max values
+ * @param min min value of random
+ * @param max max value of random
+ * @returns random value
+ */
+function RandomRange(min, max) {
+ if (min === max) {
+ return min;
+ }
+ return Math.random() * (max - min) + min;
+}
+/**
+ * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
+ * @param start start value
+ * @param end target value
+ * @param amount amount to lerp between
+ * @returns the lerped value
+ */
+function Lerp(start, end, amount) {
+ return start + (end - start) * amount;
+}
+/**
+ * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
+ * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
+ * @param start start value
+ * @param end target value
+ * @param amount amount to lerp between
+ * @returns the lerped value
+ */
+function LerpAngle(start, end, amount) {
+ let num = Repeat(end - start, 360.0);
+ if (num > 180.0) {
+ num -= 360.0;
+ }
+ return start + num * Clamp(amount);
+}
+/**
+ * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
+ * @param a start value
+ * @param b target value
+ * @param value value between a and b
+ * @returns the inverseLerp value
+ */
+function InverseLerp(a, b, value) {
+ let result = 0;
+ if (a != b) {
+ result = Clamp((value - a) / (b - a));
+ }
+ else {
+ result = 0.0;
+ }
+ return result;
+}
+/**
+ * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
+ * @see http://mathworld.wolfram.com/HermitePolynomial.html
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param amount defines the amount on the interpolation spline (between 0 and 1)
+ * @returns hermite result
+ */
+function Hermite(value1, tangent1, value2, tangent2, amount) {
+ const squared = amount * amount;
+ const cubed = amount * squared;
+ const part1 = 2.0 * cubed - 3.0 * squared + 1.0;
+ const part2 = -2 * cubed + 3.0 * squared;
+ const part3 = cubed - 2.0 * squared + amount;
+ const part4 = cubed - squared;
+ return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4;
+}
+/**
+ * Returns a new scalar which is the 1st derivative of the Hermite spline defined by the scalars "value1", "value2", "tangent1", "tangent2".
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @returns 1st derivative
+ */
+function Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
+ const t2 = time * time;
+ return (t2 - time) * 6 * value1 + (3 * t2 - 4 * time + 1) * tangent1 + (-t2 + time) * 6 * value2 + (3 * t2 - 2 * time) * tangent2;
+}
+/**
+ * Returns the value itself if it's between min and max.
+ * Returns min if the value is lower than min.
+ * Returns max if the value is greater than max.
+ * @param value the value to clmap
+ * @param min the min value to clamp to (default: 0)
+ * @param max the max value to clamp to (default: 1)
+ * @returns the clamped value
+ */
+function Clamp(value, min = 0, max = 1) {
+ return Math.min(max, Math.max(min, value));
+}
+/**
+ * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
+ * @param angle The angle to normalize in radian.
+ * @returns The converted angle.
+ */
+function NormalizeRadians(angle) {
+ // More precise but slower version kept for reference.
+ // angle = angle % Tools.TwoPi;
+ // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
+ //if (angle > Math.PI) {
+ // angle -= Tools.TwoPi;
+ //}
+ angle -= Math.PI * 2 * Math.floor((angle + Math.PI) / (Math.PI * 2));
+ return angle;
+}
+/**
+ * Returns a string : the upper case translation of the number i to hexadecimal.
+ * @param i number
+ * @returns the upper case translation of the number i to hexadecimal.
+ */
+function ToHex(i) {
+ const str = i.toString(16);
+ if (i <= 15) {
+ return ("0" + str).toUpperCase();
+ }
+ return str.toUpperCase();
+}
+/**
+ * the floor part of a log2 value.
+ * @param value the value to compute log2 of
+ * @returns the log2 of value.
+ */
+function ILog2(value) {
+ if (Math.log2) {
+ return Math.floor(Math.log2(value));
+ }
+ if (value < 0) {
+ return NaN;
+ }
+ else if (value === 0) {
+ return -Infinity;
+ }
+ let n = 0;
+ if (value < 1) {
+ while (value < 1) {
+ n++;
+ value = value * 2;
+ }
+ n = -n;
+ }
+ else if (value > 1) {
+ while (value > 1) {
+ n++;
+ value = Math.floor(value / 2);
+ }
+ }
+ return n;
+}
+/**
+ * Loops the value, so that it is never larger than length and never smaller than 0.
+ *
+ * This is similar to the modulo operator but it works with floating point numbers.
+ * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
+ * With t = 5 and length = 2.5, the result would be 0.0.
+ * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
+ * @param value the value
+ * @param length the length
+ * @returns the looped value
+ */
+function Repeat(value, length) {
+ return value - Math.floor(value / length) * length;
+}
+/**
+ * Normalize the value between 0.0 and 1.0 using min and max values
+ * @param value value to normalize
+ * @param min max to normalize between
+ * @param max min to normalize between
+ * @returns the normalized value
+ */
+function Normalize(value, min, max) {
+ return (value - min) / (max - min);
+}
+/**
+ * Denormalize the value from 0.0 and 1.0 using min and max values
+ * @param normalized value to denormalize
+ * @param min max to denormalize between
+ * @param max min to denormalize between
+ * @returns the denormalized value
+ */
+function Denormalize(normalized, min, max) {
+ return normalized * (max - min) + min;
+}
+/**
+ * Calculates the shortest difference between two given angles given in degrees.
+ * @param current current angle in degrees
+ * @param target target angle in degrees
+ * @returns the delta
+ */
+function DeltaAngle(current, target) {
+ let num = Repeat(target - current, 360.0);
+ if (num > 180.0) {
+ num -= 360.0;
+ }
+ return num;
+}
+/**
+ * PingPongs the value t, so that it is never larger than length and never smaller than 0.
+ * @param tx value
+ * @param length length
+ * @returns The returned value will move back and forth between 0 and length
+ */
+function PingPong(tx, length) {
+ const t = Repeat(tx, length * 2.0);
+ return length - Math.abs(t - length);
+}
+/**
+ * Interpolates between min and max with smoothing at the limits.
+ *
+ * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
+ * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
+ * @param from from
+ * @param to to
+ * @param tx value
+ * @returns the smooth stepped value
+ */
+function SmoothStep(from, to, tx) {
+ let t = Clamp(tx);
+ t = -2 * t * t * t + 3.0 * t * t;
+ return to * t + from * (1.0 - t);
+}
+/**
+ * Moves a value current towards target.
+ *
+ * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
+ * Negative values of maxDelta pushes the value away from target.
+ * @param current current value
+ * @param target target value
+ * @param maxDelta max distance to move
+ * @returns resulting value
+ */
+function MoveTowards(current, target, maxDelta) {
+ let result = 0;
+ if (Math.abs(target - current) <= maxDelta) {
+ result = target;
+ }
+ else {
+ result = current + Math.sign(target - current) * maxDelta;
+ }
+ return result;
+}
+/**
+ * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
+ *
+ * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
+ * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
+ * @param current current value
+ * @param target target value
+ * @param maxDelta max distance to move
+ * @returns resulting angle
+ */
+function MoveTowardsAngle(current, target, maxDelta) {
+ const num = DeltaAngle(current, target);
+ let result = 0;
+ if (-maxDelta < num && num < maxDelta) {
+ result = target;
+ }
+ else {
+ target = current + num;
+ result = MoveTowards(current, target, maxDelta);
+ }
+ return result;
+}
+/**
+ * This function returns percentage of a number in a given range.
+ *
+ * RangeToPercent(40,20,60) will return 0.5 (50%)
+ * RangeToPercent(34,0,100) will return 0.34 (34%)
+ * @param number to convert to percentage
+ * @param min min range
+ * @param max max range
+ * @returns the percentage
+ */
+function RangeToPercent(number, min, max) {
+ return (number - min) / (max - min);
+}
+/**
+ * This function returns number that corresponds to the percentage in a given range.
+ *
+ * PercentToRange(0.34,0,100) will return 34.
+ * @param percent to convert to number
+ * @param min min range
+ * @param max max range
+ * @returns the number
+ */
+function PercentToRange(percent, min, max) {
+ return (max - min) * percent + min;
+}
+/**
+ * Returns the highest common factor of two integers.
+ * @param a first parameter
+ * @param b second parameter
+ * @returns HCF of a and b
+ */
+function HighestCommonFactor(a, b) {
+ const r = a % b;
+ if (r === 0) {
+ return b;
+ }
+ return HighestCommonFactor(b, r);
+}
+
+const functions = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ Clamp,
+ DeltaAngle,
+ Denormalize,
+ ExtractAsInt,
+ Hermite,
+ Hermite1stDerivative,
+ HighestCommonFactor,
+ ILog2,
+ InverseLerp,
+ Lerp,
+ LerpAngle,
+ MoveTowards,
+ MoveTowardsAngle,
+ Normalize,
+ NormalizeRadians,
+ OutsideRange,
+ PercentToRange,
+ PingPong,
+ RandomRange,
+ RangeToPercent,
+ Repeat,
+ SmoothStep,
+ ToHex,
+ WithinEpsilon
+}, Symbol.toStringTag, { value: 'Module' }));
+
+/* eslint-disable @typescript-eslint/naming-convention */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const _ExtractAsInt = (value) => {
+ return parseInt(value.toString().replace(/\W/g, ""));
+};
+/**
+ * Class representing a vector containing 2 coordinates
+ * Example Playground - Overview - https://playground.babylonjs.com/#QYBWV4#9
+ */
+class Vector2 {
+ /**
+ * Creates a new Vector2 from the given x and y coordinates
+ * @param x defines the first coordinate
+ * @param y defines the second coordinate
+ */
+ constructor(
+ /** [0] defines the first coordinate */
+ x = 0,
+ /** [0] defines the second coordinate */
+ y = 0) {
+ this.x = x;
+ this.y = y;
+ }
+ /**
+ * Gets a string with the Vector2 coordinates
+ * @returns a string with the Vector2 coordinates
+ */
+ toString() {
+ return `{X: ${this.x} Y: ${this.y}}`;
+ }
+ /**
+ * Gets class name
+ * @returns the string "Vector2"
+ */
+ getClassName() {
+ return "Vector2";
+ }
+ /**
+ * Gets current vector hash code
+ * @returns the Vector2 hash code as a number
+ */
+ getHashCode() {
+ const x = _ExtractAsInt(this.x);
+ const y = _ExtractAsInt(this.y);
+ let hash = x;
+ hash = (hash * 397) ^ y;
+ return hash;
+ }
+ // Operators
+ /**
+ * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#15
+ * @param array defines the source array
+ * @param index defines the offset in source array
+ * @returns the current Vector2
+ */
+ toArray(array, index = 0) {
+ array[index] = this.x;
+ array[index + 1] = this.y;
+ return this;
+ }
+ /**
+ * Update the current vector from an array
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#39
+ * @param array defines the destination array
+ * @param offset defines the offset in the destination array
+ * @returns the current Vector2
+ */
+ fromArray(array, offset = 0) {
+ Vector2.FromArrayToRef(array, offset, this);
+ return this;
+ }
+ /**
+ * Copy the current vector to an array
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#40
+ * @returns a new array with 2 elements: the Vector2 coordinates.
+ */
+ asArray() {
+ return [this.x, this.y];
+ }
+ /**
+ * Sets the Vector2 coordinates with the given Vector2 coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#24
+ * @param source defines the source Vector2
+ * @returns the current updated Vector2
+ */
+ copyFrom(source) {
+ this.x = source.x;
+ this.y = source.y;
+ return this;
+ }
+ /**
+ * Sets the Vector2 coordinates with the given floats
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#25
+ * @param x defines the first coordinate
+ * @param y defines the second coordinate
+ * @returns the current updated Vector2
+ */
+ copyFromFloats(x, y) {
+ this.x = x;
+ this.y = y;
+ return this;
+ }
+ /**
+ * Sets the Vector2 coordinates with the given floats
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#62
+ * @param x defines the first coordinate
+ * @param y defines the second coordinate
+ * @returns the current updated Vector2
+ */
+ set(x, y) {
+ return this.copyFromFloats(x, y);
+ }
+ /**
+ * Copies the given float to the current Vector2 coordinates
+ * @param v defines the x and y coordinates of the operand
+ * @returns the current updated Vector2
+ */
+ setAll(v) {
+ return this.copyFromFloats(v, v);
+ }
+ /**
+ * Add another vector with the current one
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#11
+ * @param otherVector defines the other vector
+ * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
+ */
+ add(otherVector) {
+ return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
+ }
+ /**
+ * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#12
+ * @param otherVector defines the other vector
+ * @param result defines the target vector
+ * @returns result input
+ */
+ addToRef(otherVector, result) {
+ result.x = this.x + otherVector.x;
+ result.y = this.y + otherVector.y;
+ return result;
+ }
+ /**
+ * Set the Vector2 coordinates by adding the given Vector2 coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#13
+ * @param otherVector defines the other vector
+ * @returns the current updated Vector2
+ */
+ addInPlace(otherVector) {
+ this.x += otherVector.x;
+ this.y += otherVector.y;
+ return this;
+ }
+ /**
+ * Adds the given coordinates to the current Vector2
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @returns the current updated Vector2
+ */
+ addInPlaceFromFloats(x, y) {
+ this.x += x;
+ this.y += y;
+ return this;
+ }
+ /**
+ * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#14
+ * @param otherVector defines the other vector
+ * @returns a new Vector2
+ */
+ addVector3(otherVector) {
+ return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
+ }
+ /**
+ * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#61
+ * @param otherVector defines the other vector
+ * @returns a new Vector2
+ */
+ subtract(otherVector) {
+ return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
+ }
+ /**
+ * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#63
+ * @param otherVector defines the other vector
+ * @param result defines the target vector
+ * @returns result input
+ */
+ subtractToRef(otherVector, result) {
+ result.x = this.x - otherVector.x;
+ result.y = this.y - otherVector.y;
+ return result;
+ }
+ /**
+ * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#88
+ * @param otherVector defines the other vector
+ * @returns the current updated Vector2
+ */
+ subtractInPlace(otherVector) {
+ this.x -= otherVector.x;
+ this.y -= otherVector.y;
+ return this;
+ }
+ /**
+ * Multiplies in place the current Vector2 coordinates by the given ones
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#43
+ * @param otherVector defines the other vector
+ * @returns the current updated Vector2
+ */
+ multiplyInPlace(otherVector) {
+ this.x *= otherVector.x;
+ this.y *= otherVector.y;
+ return this;
+ }
+ /**
+ * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#42
+ * @param otherVector defines the other vector
+ * @returns a new Vector2
+ */
+ multiply(otherVector) {
+ return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
+ }
+ /**
+ * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#44
+ * @param otherVector defines the other vector
+ * @param result defines the target vector
+ * @returns result input
+ */
+ multiplyToRef(otherVector, result) {
+ result.x = this.x * otherVector.x;
+ result.y = this.y * otherVector.y;
+ return result;
+ }
+ /**
+ * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#89
+ * @param x defines the first coordinate
+ * @param y defines the second coordinate
+ * @returns a new Vector2
+ */
+ multiplyByFloats(x, y) {
+ return new Vector2(this.x * x, this.y * y);
+ }
+ /**
+ * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#27
+ * @param otherVector defines the other vector
+ * @returns a new Vector2
+ */
+ divide(otherVector) {
+ return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
+ }
+ /**
+ * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#30
+ * @param otherVector defines the other vector
+ * @param result defines the target vector
+ * @returns result input
+ */
+ divideToRef(otherVector, result) {
+ result.x = this.x / otherVector.x;
+ result.y = this.y / otherVector.y;
+ return result;
+ }
+ /**
+ * Divides the current Vector2 coordinates by the given ones
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#28
+ * @param otherVector defines the other vector
+ * @returns the current updated Vector2
+ */
+ divideInPlace(otherVector) {
+ this.x = this.x / otherVector.x;
+ this.y = this.y / otherVector.y;
+ return this;
+ }
+ /**
+ * Updates the current Vector2 with the minimal coordinate values between its and the given vector ones
+ * @param other defines the second operand
+ * @returns the current updated Vector2
+ */
+ minimizeInPlace(other) {
+ return this.minimizeInPlaceFromFloats(other.x, other.y);
+ }
+ /**
+ * Updates the current Vector2 with the maximal coordinate values between its and the given vector ones.
+ * @param other defines the second operand
+ * @returns the current updated Vector2
+ */
+ maximizeInPlace(other) {
+ return this.maximizeInPlaceFromFloats(other.x, other.y);
+ }
+ /**
+ * Updates the current Vector2 with the minimal coordinate values between its and the given coordinates
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @returns the current updated Vector2
+ */
+ minimizeInPlaceFromFloats(x, y) {
+ this.x = Math.min(x, this.x);
+ this.y = Math.min(y, this.y);
+ return this;
+ }
+ /**
+ * Updates the current Vector2 with the maximal coordinate values between its and the given coordinates.
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @returns the current updated Vector2
+ */
+ maximizeInPlaceFromFloats(x, y) {
+ this.x = Math.max(x, this.x);
+ this.y = Math.max(y, this.y);
+ return this;
+ }
+ /**
+ * Returns a new Vector2 set with the subtraction of the given floats from the current Vector2 coordinates
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @returns the resulting Vector2
+ */
+ subtractFromFloats(x, y) {
+ return new Vector2(this.x - x, this.y - y);
+ }
+ /**
+ * Subtracts the given floats from the current Vector2 coordinates and set the given vector "result" with this result
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param result defines the Vector2 object where to store the result
+ * @returns the result
+ */
+ subtractFromFloatsToRef(x, y, result) {
+ result.x = this.x - x;
+ result.y = this.y - y;
+ return result;
+ }
+ /**
+ * Gets a new Vector2 with current Vector2 negated coordinates
+ * @returns a new Vector2
+ */
+ negate() {
+ return new Vector2(-this.x, -this.y);
+ }
+ /**
+ * Negate this vector in place
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#23
+ * @returns this
+ */
+ negateInPlace() {
+ this.x *= -1;
+ this.y *= -1;
+ return this;
+ }
+ /**
+ * Negate the current Vector2 and stores the result in the given vector "result" coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#41
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ negateToRef(result) {
+ result.x = -this.x;
+ result.y = -this.y;
+ return result;
+ }
+ /**
+ * Multiply the Vector2 coordinates by
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#59
+ * @param scale defines the scaling factor
+ * @returns the current updated Vector2
+ */
+ scaleInPlace(scale) {
+ this.x *= scale;
+ this.y *= scale;
+ return this;
+ }
+ /**
+ * Returns a new Vector2 scaled by "scale" from the current Vector2
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#52
+ * @param scale defines the scaling factor
+ * @returns a new Vector2
+ */
+ scale(scale) {
+ return new Vector2(this.x * scale, this.y * scale);
+ }
+ /**
+ * Scale the current Vector2 values by a factor to a given Vector2
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#57
+ * @param scale defines the scale factor
+ * @param result defines the Vector2 object where to store the result
+ * @returns result input
+ */
+ scaleToRef(scale, result) {
+ result.x = this.x * scale;
+ result.y = this.y * scale;
+ return result;
+ }
+ /**
+ * Scale the current Vector2 values by a factor and add the result to a given Vector2
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#58
+ * @param scale defines the scale factor
+ * @param result defines the Vector2 object where to store the result
+ * @returns result input
+ */
+ scaleAndAddToRef(scale, result) {
+ result.x += this.x * scale;
+ result.y += this.y * scale;
+ return result;
+ }
+ /**
+ * Gets a boolean if two vectors are equals
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#31
+ * @param otherVector defines the other vector
+ * @returns true if the given vector coordinates strictly equal the current Vector2 ones
+ */
+ equals(otherVector) {
+ return otherVector && this.x === otherVector.x && this.y === otherVector.y;
+ }
+ /**
+ * Gets a boolean if two vectors are equals (using an epsilon value)
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#32
+ * @param otherVector defines the other vector
+ * @param epsilon defines the minimal distance to consider equality
+ * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
+ */
+ equalsWithEpsilon(otherVector, epsilon = Epsilon) {
+ return otherVector && WithinEpsilon(this.x, otherVector.x, epsilon) && WithinEpsilon(this.y, otherVector.y, epsilon);
+ }
+ /**
+ * Returns true if the current Vector2 coordinates equals the given floats
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @returns true if both vectors are equal
+ */
+ equalsToFloats(x, y) {
+ return this.x === x && this.y === y;
+ }
+ /**
+ * Gets a new Vector2 from current Vector2 floored values
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#35
+ * eg (1.2, 2.31) returns (1, 2)
+ * @returns a new Vector2
+ */
+ floor() {
+ return new Vector2(Math.floor(this.x), Math.floor(this.y));
+ }
+ /**
+ * Gets the current Vector2's floored values and stores them in result
+ * @param result the Vector2 to store the result in
+ * @returns the result Vector2
+ */
+ floorToRef(result) {
+ result.x = Math.floor(this.x);
+ result.y = Math.floor(this.y);
+ return result;
+ }
+ /**
+ * Gets a new Vector2 from current Vector2 fractional values
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#34
+ * eg (1.2, 2.31) returns (0.2, 0.31)
+ * @returns a new Vector2
+ */
+ fract() {
+ return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
+ }
+ /**
+ * Gets the current Vector2's fractional values and stores them in result
+ * @param result the Vector2 to store the result in
+ * @returns the result Vector2
+ */
+ fractToRef(result) {
+ result.x = this.x - Math.floor(this.x);
+ result.y = this.y - Math.floor(this.y);
+ return result;
+ }
+ /**
+ * Rotate the current vector into a given result vector
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#49
+ * @param angle defines the rotation angle
+ * @param result defines the result vector where to store the rotated vector
+ * @returns result input
+ */
+ rotateToRef(angle, result) {
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const x = cos * this.x - sin * this.y;
+ const y = sin * this.x + cos * this.y;
+ result.x = x;
+ result.y = y;
+ return result;
+ }
+ // Properties
+ /**
+ * Gets the length of the vector
+ * @returns the vector length (float)
+ */
+ length() {
+ return Math.sqrt(this.x * this.x + this.y * this.y);
+ }
+ /**
+ * Gets the vector squared length
+ * @returns the vector squared length (float)
+ */
+ lengthSquared() {
+ return this.x * this.x + this.y * this.y;
+ }
+ // Methods
+ /**
+ * Normalize the vector
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#48
+ * @returns the current updated Vector2
+ */
+ normalize() {
+ return this.normalizeFromLength(this.length());
+ }
+ /**
+ * Normalize the current Vector2 with the given input length.
+ * Please note that this is an in place operation.
+ * @param len the length of the vector
+ * @returns the current updated Vector2
+ */
+ normalizeFromLength(len) {
+ if (len === 0 || len === 1.0) {
+ return this;
+ }
+ return this.scaleInPlace(1.0 / len);
+ }
+ /**
+ * Normalize the current Vector2 to a new vector
+ * @returns the new Vector2
+ */
+ normalizeToNew() {
+ const normalized = new Vector2();
+ this.normalizeToRef(normalized);
+ return normalized;
+ }
+ /**
+ * Normalize the current Vector2 to the reference
+ * @param result define the Vector to update
+ * @returns the updated Vector2
+ */
+ normalizeToRef(result) {
+ const len = this.length();
+ if (len === 0) {
+ result.x = this.x;
+ result.y = this.y;
+ }
+ return this.scaleToRef(1.0 / len, result);
+ }
+ /**
+ * Gets a new Vector2 copied from the Vector2
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#20
+ * @returns a new Vector2
+ */
+ clone() {
+ return new Vector2(this.x, this.y);
+ }
+ /**
+ * Gets the dot product of the current vector and the vector "otherVector"
+ * @param otherVector defines second vector
+ * @returns the dot product (float)
+ */
+ dot(otherVector) {
+ return this.x * otherVector.x + this.y * otherVector.y;
+ }
+ // Statics
+ /**
+ * Gets a new Vector2(0, 0)
+ * @returns a new Vector2
+ */
+ static Zero() {
+ return new Vector2(0, 0);
+ }
+ /**
+ * Gets a new Vector2(1, 1)
+ * @returns a new Vector2
+ */
+ static One() {
+ return new Vector2(1, 1);
+ }
+ /**
+ * Returns a new Vector2 with random values between min and max
+ * @param min the minimum random value
+ * @param max the maximum random value
+ * @returns a Vector2 with random values between min and max
+ */
+ static Random(min = 0, max = 1) {
+ return new Vector2(RandomRange(min, max), RandomRange(min, max));
+ }
+ /**
+ * Sets a Vector2 with random values between min and max
+ * @param min the minimum random value
+ * @param max the maximum random value
+ * @param ref the ref to store the values in
+ * @returns the ref with random values between min and max
+ */
+ static RandomToRef(min = 0, max = 1, ref) {
+ return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max));
+ }
+ /**
+ * Gets a zero Vector2 that must not be updated
+ */
+ static get ZeroReadOnly() {
+ return Vector2._ZeroReadOnly;
+ }
+ /**
+ * Gets a new Vector2 set from the given index element of the given array
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#79
+ * @param array defines the data source
+ * @param offset defines the offset in the data source
+ * @returns a new Vector2
+ */
+ static FromArray(array, offset = 0) {
+ return new Vector2(array[offset], array[offset + 1]);
+ }
+ /**
+ * Sets "result" from the given index element of the given array
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#80
+ * @param array defines the data source
+ * @param offset defines the offset in the data source
+ * @param result defines the target vector
+ * @returns result input
+ */
+ static FromArrayToRef(array, offset, result) {
+ result.x = array[offset];
+ result.y = array[offset + 1];
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the given floats.
+ * @param x defines the x coordinate of the source
+ * @param y defines the y coordinate of the source
+ * @param result defines the Vector2 where to store the result
+ * @returns the result vector
+ */
+ static FromFloatsToRef(x, y, result) {
+ result.copyFromFloats(x, y);
+ return result;
+ }
+ /**
+ * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#65
+ * @param value1 defines 1st point of control
+ * @param value2 defines 2nd point of control
+ * @param value3 defines 3rd point of control
+ * @param value4 defines 4th point of control
+ * @param amount defines the interpolation factor
+ * @returns a new Vector2
+ */
+ static CatmullRom(value1, value2, value3, value4, amount) {
+ const squared = amount * amount;
+ const cubed = amount * squared;
+ const x = 0.5 *
+ (2.0 * value2.x +
+ (-value1.x + value3.x) * amount +
+ (2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared +
+ (-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed);
+ const y = 0.5 *
+ (2.0 * value2.y +
+ (-value1.y + value3.y) * amount +
+ (2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared +
+ (-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed);
+ return new Vector2(x, y);
+ }
+ /**
+ * Sets reference with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
+ * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
+ * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
+ * @param value defines the value to clamp
+ * @param min defines the lower limit
+ * @param max defines the upper limit
+ * @param ref the reference
+ * @returns the reference
+ */
+ static ClampToRef(value, min, max, ref) {
+ ref.x = Clamp(value.x, min.x, max.x);
+ ref.y = Clamp(value.y, min.y, max.y);
+ return ref;
+ }
+ /**
+ * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
+ * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
+ * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#76
+ * @param value defines the value to clamp
+ * @param min defines the lower limit
+ * @param max defines the upper limit
+ * @returns a new Vector2
+ */
+ static Clamp(value, min, max) {
+ const x = Clamp(value.x, min.x, max.x);
+ const y = Clamp(value.y, min.y, max.y);
+ return new Vector2(x, y);
+ }
+ /**
+ * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2"
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#81
+ * @param value1 defines the 1st control point
+ * @param tangent1 defines the outgoing tangent
+ * @param value2 defines the 2nd control point
+ * @param tangent2 defines the incoming tangent
+ * @param amount defines the interpolation factor
+ * @returns a new Vector2
+ */
+ static Hermite(value1, tangent1, value2, tangent2, amount) {
+ const squared = amount * amount;
+ const cubed = amount * squared;
+ const part1 = 2.0 * cubed - 3.0 * squared + 1.0;
+ const part2 = -2 * cubed + 3.0 * squared;
+ const part3 = cubed - 2.0 * squared + amount;
+ const part4 = cubed - squared;
+ const x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4;
+ const y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4;
+ return new Vector2(x, y);
+ }
+ /**
+ * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#82
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @returns 1st derivative
+ */
+ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
+ return this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, new Vector2());
+ }
+ /**
+ * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#83
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @param result define where the derivative will be stored
+ * @returns result input
+ */
+ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {
+ const t2 = time * time;
+ result.x = (t2 - time) * 6 * value1.x + (3 * t2 - 4 * time + 1) * tangent1.x + (-t2 + time) * 6 * value2.x + (3 * t2 - 2 * time) * tangent2.x;
+ result.y = (t2 - time) * 6 * value1.y + (3 * t2 - 4 * time + 1) * tangent1.y + (-t2 + time) * 6 * value2.y + (3 * t2 - 2 * time) * tangent2.y;
+ return result;
+ }
+ /**
+ * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#84
+ * @param start defines the start vector
+ * @param end defines the end vector
+ * @param amount defines the interpolation factor
+ * @returns a new Vector2
+ */
+ static Lerp(start, end, amount) {
+ return Vector2.LerpToRef(start, end, amount, new Vector2());
+ }
+ /**
+ * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
+ * @param start defines the start value
+ * @param end defines the end value
+ * @param amount max defines amount between both (between 0 and 1)
+ * @param result defines the Vector2 where to store the result
+ * @returns result input
+ */
+ static LerpToRef(start, end, amount, result) {
+ result.x = start.x + (end.x - start.x) * amount;
+ result.y = start.y + (end.y - start.y) * amount;
+ return result;
+ }
+ /**
+ * Gets the dot product of the vector "left" and the vector "right"
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#90
+ * @param left defines first vector
+ * @param right defines second vector
+ * @returns the dot product (float)
+ */
+ static Dot(left, right) {
+ return left.x * right.x + left.y * right.y;
+ }
+ /**
+ * Returns a new Vector2 equal to the normalized given vector
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#46
+ * @param vector defines the vector to normalize
+ * @returns a new Vector2
+ */
+ static Normalize(vector) {
+ return Vector2.NormalizeToRef(vector, new Vector2());
+ }
+ /**
+ * Normalize a given vector into a second one
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#50
+ * @param vector defines the vector to normalize
+ * @param result defines the vector where to store the result
+ * @returns result input
+ */
+ static NormalizeToRef(vector, result) {
+ vector.normalizeToRef(result);
+ return result;
+ }
+ /**
+ * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#86
+ * @param left defines 1st vector
+ * @param right defines 2nd vector
+ * @returns a new Vector2
+ */
+ static Minimize(left, right) {
+ const x = left.x < right.x ? left.x : right.x;
+ const y = left.y < right.y ? left.y : right.y;
+ return new Vector2(x, y);
+ }
+ /**
+ * Gets a new Vector2 set with the maximal coordinate values from the "left" and "right" vectors
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#86
+ * @param left defines 1st vector
+ * @param right defines 2nd vector
+ * @returns a new Vector2
+ */
+ static Maximize(left, right) {
+ const x = left.x > right.x ? left.x : right.x;
+ const y = left.y > right.y ? left.y : right.y;
+ return new Vector2(x, y);
+ }
+ /**
+ * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#17
+ * @param vector defines the vector to transform
+ * @param transformation defines the matrix to apply
+ * @returns a new Vector2
+ */
+ static Transform(vector, transformation) {
+ return Vector2.TransformToRef(vector, transformation, new Vector2());
+ }
+ /**
+ * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#19
+ * @param vector defines the vector to transform
+ * @param transformation defines the matrix to apply
+ * @param result defines the target vector
+ * @returns result input
+ */
+ static TransformToRef(vector, transformation, result) {
+ const m = transformation.m;
+ const x = vector.x * m[0] + vector.y * m[4] + m[12];
+ const y = vector.x * m[1] + vector.y * m[5] + m[13];
+ result.x = x;
+ result.y = y;
+ return result;
+ }
+ /**
+ * Determines if a given vector is included in a triangle
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#87
+ * @param p defines the vector to test
+ * @param p0 defines 1st triangle point
+ * @param p1 defines 2nd triangle point
+ * @param p2 defines 3rd triangle point
+ * @returns true if the point "p" is in the triangle defined by the vectors "p0", "p1", "p2"
+ */
+ static PointInTriangle(p, p0, p1, p2) {
+ const a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
+ const sign = a < 0 ? -1 : 1;
+ const s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
+ const t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
+ return s > 0 && t > 0 && s + t < 2 * a * sign;
+ }
+ /**
+ * Gets the distance between the vectors "value1" and "value2"
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#71
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @returns the distance between vectors
+ */
+ static Distance(value1, value2) {
+ return Math.sqrt(Vector2.DistanceSquared(value1, value2));
+ }
+ /**
+ * Returns the squared distance between the vectors "value1" and "value2"
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#72
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @returns the squared distance between vectors
+ */
+ static DistanceSquared(value1, value2) {
+ const x = value1.x - value2.x;
+ const y = value1.y - value2.y;
+ return x * x + y * y;
+ }
+ /**
+ * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#86
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#66
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @returns a new Vector2
+ */
+ static Center(value1, value2) {
+ return Vector2.CenterToRef(value1, value2, new Vector2());
+ }
+ /**
+ * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref"
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#66
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @param ref defines third vector
+ * @returns ref
+ */
+ static CenterToRef(value1, value2, ref) {
+ return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2);
+ }
+ /**
+ * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
+ * Example Playground https://playground.babylonjs.com/#QYBWV4#77
+ * @param p defines the middle point
+ * @param segA defines one point of the segment
+ * @param segB defines the other point of the segment
+ * @returns the shortest distance
+ */
+ static DistanceOfPointFromSegment(p, segA, segB) {
+ const l2 = Vector2.DistanceSquared(segA, segB);
+ if (l2 === 0.0) {
+ return Vector2.Distance(p, segA);
+ }
+ const v = segB.subtract(segA);
+ const t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
+ const proj = segA.add(v.multiplyByFloats(t, t));
+ return Vector2.Distance(p, proj);
+ }
+}
+/**
+ * If the first vector is flagged with integers (as everything is 0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet.
+ * If subsequent vectors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers,
+ * and henceforth it will use floating-point representation for all Vector2 instances that it creates.
+ * But the original Vector2 instances are unchanged and has a "deprecated map".
+ * If we keep using the Vector2 instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches.
+ */
+Vector2._V8PerformanceHack = new Vector2(0.5, 0.5);
+Vector2._ZeroReadOnly = Vector2.Zero();
+Object.defineProperties(Vector2.prototype, {
+ dimension: { value: [2] },
+ rank: { value: 1 },
+});
+/**
+ * Class used to store (x,y,z) vector representation
+ * A Vector3 is the main object used in 3D geometry
+ * It can represent either the coordinates of a point the space, either a direction
+ * Reminder: js uses a left handed forward facing system
+ * Example Playground - Overview - https://playground.babylonjs.com/#R1F8YU
+ */
+class Vector3 {
+ /** Gets or sets the x coordinate */
+ get x() {
+ return this._x;
+ }
+ set x(value) {
+ this._x = value;
+ this._isDirty = true;
+ }
+ /** Gets or sets the y coordinate */
+ get y() {
+ return this._y;
+ }
+ set y(value) {
+ this._y = value;
+ this._isDirty = true;
+ }
+ /** Gets or sets the z coordinate */
+ get z() {
+ return this._z;
+ }
+ set z(value) {
+ this._z = value;
+ this._isDirty = true;
+ }
+ /**
+ * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
+ * @param x defines the first coordinates (on X axis)
+ * @param y defines the second coordinates (on Y axis)
+ * @param z defines the third coordinates (on Z axis)
+ */
+ constructor(x = 0, y = 0, z = 0) {
+ /** @internal */
+ this._isDirty = true;
+ this._x = x;
+ this._y = y;
+ this._z = z;
+ }
+ /**
+ * Creates a string representation of the Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#67
+ * @returns a string with the Vector3 coordinates.
+ */
+ toString() {
+ return `{X: ${this._x} Y: ${this._y} Z: ${this._z}}`;
+ }
+ /**
+ * Gets the class name
+ * @returns the string "Vector3"
+ */
+ getClassName() {
+ return "Vector3";
+ }
+ /**
+ * Creates the Vector3 hash code
+ * @returns a number which tends to be unique between Vector3 instances
+ */
+ getHashCode() {
+ const x = _ExtractAsInt(this._x);
+ const y = _ExtractAsInt(this._y);
+ const z = _ExtractAsInt(this._z);
+ let hash = x;
+ hash = (hash * 397) ^ y;
+ hash = (hash * 397) ^ z;
+ return hash;
+ }
+ // Operators
+ /**
+ * Creates an array containing three elements : the coordinates of the Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#10
+ * @returns a new array of numbers
+ */
+ asArray() {
+ return [this._x, this._y, this._z];
+ }
+ /**
+ * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#65
+ * @param array defines the destination array
+ * @param index defines the offset in the destination array
+ * @returns the current Vector3
+ */
+ toArray(array, index = 0) {
+ array[index] = this._x;
+ array[index + 1] = this._y;
+ array[index + 2] = this._z;
+ return this;
+ }
+ /**
+ * Update the current vector from an array
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#24
+ * @param array defines the destination array
+ * @param offset defines the offset in the destination array
+ * @returns the current Vector3
+ */
+ fromArray(array, offset = 0) {
+ Vector3.FromArrayToRef(array, offset, this);
+ return this;
+ }
+ /**
+ * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#66
+ * @returns a new Quaternion object, computed from the Vector3 coordinates
+ */
+ toQuaternion() {
+ return Quaternion.RotationYawPitchRoll(this._y, this._x, this._z);
+ }
+ /**
+ * Adds the given vector to the current Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#4
+ * @param otherVector defines the second operand
+ * @returns the current updated Vector3
+ */
+ addInPlace(otherVector) {
+ this._x += otherVector._x;
+ this._y += otherVector._y;
+ this._z += otherVector._z;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Adds the given coordinates to the current Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#5
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @returns the current updated Vector3
+ */
+ addInPlaceFromFloats(x, y, z) {
+ this._x += x;
+ this._y += y;
+ this._z += z;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Gets a new Vector3, result of the addition the current Vector3 and the given vector
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#3
+ * @param otherVector defines the second operand
+ * @returns the resulting Vector3
+ */
+ add(otherVector) {
+ return new Vector3(this._x + otherVector._x, this._y + otherVector._y, this._z + otherVector._z);
+ }
+ /**
+ * Adds the current Vector3 to the given one and stores the result in the vector "result"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#6
+ * @param otherVector defines the second operand
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ addToRef(otherVector, result) {
+ result._x = this._x + otherVector._x;
+ result._y = this._y + otherVector._y;
+ result._z = this._z + otherVector._z;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Subtract the given vector from the current Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#61
+ * @param otherVector defines the second operand
+ * @returns the current updated Vector3
+ */
+ subtractInPlace(otherVector) {
+ this._x -= otherVector._x;
+ this._y -= otherVector._y;
+ this._z -= otherVector._z;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#60
+ * @param otherVector defines the second operand
+ * @returns the resulting Vector3
+ */
+ subtract(otherVector) {
+ return new Vector3(this._x - otherVector._x, this._y - otherVector._y, this._z - otherVector._z);
+ }
+ /**
+ * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#63
+ * @param otherVector defines the second operand
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ subtractToRef(otherVector, result) {
+ return this.subtractFromFloatsToRef(otherVector._x, otherVector._y, otherVector._z, result);
+ }
+ /**
+ * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#62
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @returns the resulting Vector3
+ */
+ subtractFromFloats(x, y, z) {
+ return new Vector3(this._x - x, this._y - y, this._z - z);
+ }
+ /**
+ * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#64
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ subtractFromFloatsToRef(x, y, z, result) {
+ result._x = this._x - x;
+ result._y = this._y - y;
+ result._z = this._z - z;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Gets a new Vector3 set with the current Vector3 negated coordinates
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#35
+ * @returns a new Vector3
+ */
+ negate() {
+ return new Vector3(-this._x, -this._y, -this._z);
+ }
+ /**
+ * Negate this vector in place
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#36
+ * @returns this
+ */
+ negateInPlace() {
+ this._x *= -1;
+ this._y *= -1;
+ this._z *= -1;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Negate the current Vector3 and stores the result in the given vector "result" coordinates
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#37
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ negateToRef(result) {
+ result._x = this._x * -1;
+ result._y = this._y * -1;
+ result._z = this._z * -1;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Multiplies the Vector3 coordinates by the float "scale"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#56
+ * @param scale defines the multiplier factor
+ * @returns the current updated Vector3
+ */
+ scaleInPlace(scale) {
+ this._x *= scale;
+ this._y *= scale;
+ this._z *= scale;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#53
+ * @param scale defines the multiplier factor
+ * @returns a new Vector3
+ */
+ scale(scale) {
+ return new Vector3(this._x * scale, this._y * scale, this._z * scale);
+ }
+ /**
+ * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#57
+ * @param scale defines the multiplier factor
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ scaleToRef(scale, result) {
+ result._x = this._x * scale;
+ result._y = this._y * scale;
+ result._z = this._z * scale;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Creates a vector normal (perpendicular) to the current Vector3 and stores the result in the given vector
+ * Out of the infinite possibilities the normal chosen is the one formed by rotating the current vector
+ * 90 degrees about an axis which lies perpendicular to the current vector
+ * and its projection on the xz plane. In the case of a current vector in the xz plane
+ * the normal is calculated to be along the y axis.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#230
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#231
+ * @param result defines the Vector3 object where to store the resultant normal
+ * @returns the result
+ */
+ getNormalToRef(result) {
+ /**
+ * Calculates the spherical coordinates of the current vector
+ * so saves on memory rather than importing whole Spherical Class
+ */
+ const radius = this.length();
+ let theta = Math.acos(this.y / radius);
+ const phi = Math.atan2(this.z, this.x);
+ //makes angle 90 degs to current vector
+ if (theta > Math.PI / 2) {
+ theta -= Math.PI / 2;
+ }
+ else {
+ theta += Math.PI / 2;
+ }
+ //Calculates resutant normal vector from spherical coordinate of perpendicular vector
+ const x = radius * Math.sin(theta) * Math.cos(phi);
+ const y = radius * Math.cos(theta);
+ const z = radius * Math.sin(theta) * Math.sin(phi);
+ result.set(x, y, z);
+ return result;
+ }
+ /**
+ * Rotates the vector using the given unit quaternion and stores the new vector in result
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#9
+ * @param q the unit quaternion representing the rotation
+ * @param result the output vector
+ * @returns the result
+ */
+ applyRotationQuaternionToRef(q, result) {
+ // Derived from https://raw.org/proof/vector-rotation-using-quaternions/
+ const vx = this._x, vy = this._y, vz = this._z;
+ const qx = q._x, qy = q._y, qz = q._z, qw = q._w;
+ // t = 2q x v
+ const tx = 2 * (qy * vz - qz * vy);
+ const ty = 2 * (qz * vx - qx * vz);
+ const tz = 2 * (qx * vy - qy * vx);
+ // v + w t + q x t
+ result._x = vx + qw * tx + qy * tz - qz * ty;
+ result._y = vy + qw * ty + qz * tx - qx * tz;
+ result._z = vz + qw * tz + qx * ty - qy * tx;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Rotates the vector in place using the given unit quaternion
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#8
+ * @param q the unit quaternion representing the rotation
+ * @returns the current updated Vector3
+ */
+ applyRotationQuaternionInPlace(q) {
+ return this.applyRotationQuaternionToRef(q, this);
+ }
+ /**
+ * Rotates the vector using the given unit quaternion and returns the new vector
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#7
+ * @param q the unit quaternion representing the rotation
+ * @returns a new Vector3
+ */
+ applyRotationQuaternion(q) {
+ return this.applyRotationQuaternionToRef(q, new Vector3());
+ }
+ /**
+ * Scale the current Vector3 values by a factor and add the result to a given Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#55
+ * @param scale defines the scale factor
+ * @param result defines the Vector3 object where to store the result
+ * @returns result input
+ */
+ scaleAndAddToRef(scale, result) {
+ result._x += this._x * scale;
+ result._y += this._y * scale;
+ result._z += this._z * scale;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Projects the current point Vector3 to a plane along a ray starting from a specified origin and passing through the current point Vector3.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#48
+ * @param plane defines the plane to project to
+ * @param origin defines the origin of the projection ray
+ * @returns the projected vector3
+ */
+ projectOnPlane(plane, origin) {
+ return this.projectOnPlaneToRef(plane, origin, new Vector3());
+ }
+ /**
+ * Projects the current point Vector3 to a plane along a ray starting from a specified origin and passing through the current point Vector3.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#49
+ * @param plane defines the plane to project to
+ * @param origin defines the origin of the projection ray
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ projectOnPlaneToRef(plane, origin, result) {
+ const n = plane.normal;
+ const d = plane.d;
+ const V = MathTmp.Vector3[0];
+ // ray direction
+ this.subtractToRef(origin, V);
+ V.normalize();
+ const denom = Vector3.Dot(V, n);
+ //When the ray is close to parallel to the plane return infinity vector
+ if (Math.abs(denom) < 0.0000000001) {
+ result.setAll(Infinity);
+ }
+ else {
+ const t = -(Vector3.Dot(origin, n) + d) / denom;
+ // P = P0 + t*V
+ const scaledV = V.scaleInPlace(t);
+ origin.addToRef(scaledV, result);
+ }
+ return result;
+ }
+ /**
+ * Returns true if the current Vector3 and the given vector coordinates are strictly equal
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#19
+ * @param otherVector defines the second operand
+ * @returns true if both vectors are equals
+ */
+ equals(otherVector) {
+ return otherVector && this._x === otherVector._x && this._y === otherVector._y && this._z === otherVector._z;
+ }
+ /**
+ * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#21
+ * @param otherVector defines the second operand
+ * @param epsilon defines the minimal distance to define values as equals
+ * @returns true if both vectors are distant less than epsilon
+ */
+ equalsWithEpsilon(otherVector, epsilon = Epsilon) {
+ return otherVector && WithinEpsilon(this._x, otherVector._x, epsilon) && WithinEpsilon(this._y, otherVector._y, epsilon) && WithinEpsilon(this._z, otherVector._z, epsilon);
+ }
+ /**
+ * Returns true if the current Vector3 coordinates equals the given floats
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#20
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @returns true if both vectors are equal
+ */
+ equalsToFloats(x, y, z) {
+ return this._x === x && this._y === y && this._z === z;
+ }
+ /**
+ * Multiplies the current Vector3 coordinates by the given ones
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#32
+ * @param otherVector defines the second operand
+ * @returns the current updated Vector3
+ */
+ multiplyInPlace(otherVector) {
+ this._x *= otherVector._x;
+ this._y *= otherVector._y;
+ this._z *= otherVector._z;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#31
+ * @param otherVector defines the second operand
+ * @returns the new Vector3
+ */
+ multiply(otherVector) {
+ return this.multiplyByFloats(otherVector._x, otherVector._y, otherVector._z);
+ }
+ /**
+ * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#33
+ * @param otherVector defines the second operand
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ multiplyToRef(otherVector, result) {
+ result._x = this._x * otherVector._x;
+ result._y = this._y * otherVector._y;
+ result._z = this._z * otherVector._z;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Returns a new Vector3 set with the result of the multiplication of the current Vector3 coordinates by the given floats
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#34
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @returns the new Vector3
+ */
+ multiplyByFloats(x, y, z) {
+ return new Vector3(this._x * x, this._y * y, this._z * z);
+ }
+ /**
+ * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#16
+ * @param otherVector defines the second operand
+ * @returns the new Vector3
+ */
+ divide(otherVector) {
+ return new Vector3(this._x / otherVector._x, this._y / otherVector._y, this._z / otherVector._z);
+ }
+ /**
+ * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#18
+ * @param otherVector defines the second operand
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ divideToRef(otherVector, result) {
+ result._x = this._x / otherVector._x;
+ result._y = this._y / otherVector._y;
+ result._z = this._z / otherVector._z;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Divides the current Vector3 coordinates by the given ones.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#17
+ * @param otherVector defines the second operand
+ * @returns the current updated Vector3
+ */
+ divideInPlace(otherVector) {
+ this._x = this._x / otherVector._x;
+ this._y = this._y / otherVector._y;
+ this._z = this._z / otherVector._z;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#29
+ * @param other defines the second operand
+ * @returns the current updated Vector3
+ */
+ minimizeInPlace(other) {
+ return this.minimizeInPlaceFromFloats(other._x, other._y, other._z);
+ }
+ /**
+ * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#27
+ * @param other defines the second operand
+ * @returns the current updated Vector3
+ */
+ maximizeInPlace(other) {
+ return this.maximizeInPlaceFromFloats(other._x, other._y, other._z);
+ }
+ /**
+ * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#30
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @returns the current updated Vector3
+ */
+ minimizeInPlaceFromFloats(x, y, z) {
+ if (x < this._x) {
+ this.x = x;
+ }
+ if (y < this._y) {
+ this.y = y;
+ }
+ if (z < this._z) {
+ this.z = z;
+ }
+ return this;
+ }
+ /**
+ * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#28
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @returns the current updated Vector3
+ */
+ maximizeInPlaceFromFloats(x, y, z) {
+ if (x > this._x) {
+ this.x = x;
+ }
+ if (y > this._y) {
+ this.y = y;
+ }
+ if (z > this._z) {
+ this.z = z;
+ }
+ return this;
+ }
+ /**
+ * Due to float precision, scale of a mesh could be uniform but float values are off by a small fraction
+ * Check if is non uniform within a certain amount of decimal places to account for this
+ * @param epsilon the amount the values can differ
+ * @returns if the vector is non uniform to a certain number of decimal places
+ */
+ isNonUniformWithinEpsilon(epsilon) {
+ const absX = Math.abs(this._x);
+ const absY = Math.abs(this._y);
+ if (!WithinEpsilon(absX, absY, epsilon)) {
+ return true;
+ }
+ const absZ = Math.abs(this._z);
+ if (!WithinEpsilon(absX, absZ, epsilon)) {
+ return true;
+ }
+ if (!WithinEpsilon(absY, absZ, epsilon)) {
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
+ */
+ get isNonUniform() {
+ const absX = Math.abs(this._x);
+ const absY = Math.abs(this._y);
+ if (absX !== absY) {
+ return true;
+ }
+ const absZ = Math.abs(this._z);
+ if (absX !== absZ) {
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Gets the current Vector3's floored values and stores them in result
+ * @param result the vector to store the result in
+ * @returns the result vector
+ */
+ floorToRef(result) {
+ result._x = Math.floor(this._x);
+ result._y = Math.floor(this._y);
+ result._z = Math.floor(this._z);
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Gets a new Vector3 from current Vector3 floored values
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#22
+ * @returns a new Vector3
+ */
+ floor() {
+ return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
+ }
+ /**
+ * Gets the current Vector3's fractional values and stores them in result
+ * @param result the vector to store the result in
+ * @returns the result vector
+ */
+ fractToRef(result) {
+ result._x = this.x - Math.floor(this._x);
+ result._y = this.y - Math.floor(this._y);
+ result._z = this.z - Math.floor(this._z);
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Gets a new Vector3 from current Vector3 fractional values
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#23
+ * @returns a new Vector3
+ */
+ fract() {
+ return new Vector3(this.x - Math.floor(this._x), this.y - Math.floor(this._y), this.z - Math.floor(this._z));
+ }
+ // Properties
+ /**
+ * Gets the length of the Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#25
+ * @returns the length of the Vector3
+ */
+ length() {
+ return Math.sqrt(this.lengthSquared());
+ }
+ /**
+ * Gets the squared length of the Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#26
+ * @returns squared length of the Vector3
+ */
+ lengthSquared() {
+ return this._x * this._x + this._y * this._y + this._z * this._z;
+ }
+ /**
+ * Gets a boolean indicating if the vector contains a zero in one of its components
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#1
+ */
+ get hasAZeroComponent() {
+ return this._x * this._y * this._z === 0;
+ }
+ /**
+ * Normalize the current Vector3.
+ * Please note that this is an in place operation.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#122
+ * @returns the current updated Vector3
+ */
+ normalize() {
+ return this.normalizeFromLength(this.length());
+ }
+ /**
+ * Reorders the x y z properties of the vector in place
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#44
+ * @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1)
+ * @returns the current updated vector
+ */
+ reorderInPlace(order) {
+ order = order.toLowerCase();
+ if (order === "xyz") {
+ return this;
+ }
+ const tem = MathTmp.Vector3[0].copyFrom(this);
+ this.x = tem[order[0]];
+ this.y = tem[order[1]];
+ this.z = tem[order[2]];
+ return this;
+ }
+ /**
+ * Rotates the vector around 0,0,0 by a quaternion
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#47
+ * @param quaternion the rotation quaternion
+ * @param result vector to store the result
+ * @returns the resulting vector
+ */
+ rotateByQuaternionToRef(quaternion, result) {
+ quaternion.toRotationMatrix(MathTmp.Matrix[0]);
+ Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result);
+ return result;
+ }
+ /**
+ * Rotates a vector around a given point
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#46
+ * @param quaternion the rotation quaternion
+ * @param point the point to rotate around
+ * @param result vector to store the result
+ * @returns the resulting vector
+ */
+ rotateByQuaternionAroundPointToRef(quaternion, point, result) {
+ this.subtractToRef(point, MathTmp.Vector3[0]);
+ MathTmp.Vector3[0].rotateByQuaternionToRef(quaternion, MathTmp.Vector3[0]);
+ point.addToRef(MathTmp.Vector3[0], result);
+ return result;
+ }
+ /**
+ * Returns a new Vector3 as the cross product of the current vector and the "other" one
+ * The cross product is then orthogonal to both current and "other"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#14
+ * @param other defines the right operand
+ * @returns the cross product
+ */
+ cross(other) {
+ return Vector3.CrossToRef(this, other, new Vector3());
+ }
+ /**
+ * Normalize the current Vector3 with the given input length.
+ * Please note that this is an in place operation.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#123
+ * @param len the length of the vector
+ * @returns the current updated Vector3
+ */
+ normalizeFromLength(len) {
+ if (len === 0 || len === 1.0) {
+ return this;
+ }
+ return this.scaleInPlace(1.0 / len);
+ }
+ /**
+ * Normalize the current Vector3 to a new vector
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#124
+ * @returns the new Vector3
+ */
+ normalizeToNew() {
+ return this.normalizeToRef(new Vector3());
+ }
+ /**
+ * Normalize the current Vector3 to the reference
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#125
+ * @param result define the Vector3 to update
+ * @returns the updated Vector3
+ */
+ normalizeToRef(result) {
+ const len = this.length();
+ if (len === 0 || len === 1.0) {
+ result._x = this._x;
+ result._y = this._y;
+ result._z = this._z;
+ result._isDirty = true;
+ return result;
+ }
+ return this.scaleToRef(1.0 / len, result);
+ }
+ /**
+ * Creates a new Vector3 copied from the current Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#11
+ * @returns the new Vector3
+ */
+ clone() {
+ return new Vector3(this._x, this._y, this._z);
+ }
+ /**
+ * Copies the given vector coordinates to the current Vector3 ones
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#12
+ * @param source defines the source Vector3
+ * @returns the current updated Vector3
+ */
+ copyFrom(source) {
+ return this.copyFromFloats(source._x, source._y, source._z);
+ }
+ /**
+ * Copies the given floats to the current Vector3 coordinates
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#13
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @returns the current updated Vector3
+ */
+ copyFromFloats(x, y, z) {
+ this._x = x;
+ this._y = y;
+ this._z = z;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Copies the given floats to the current Vector3 coordinates
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#58
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @returns the current updated Vector3
+ */
+ set(x, y, z) {
+ return this.copyFromFloats(x, y, z);
+ }
+ /**
+ * Copies the given float to the current Vector3 coordinates
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#59
+ * @param v defines the x, y and z coordinates of the operand
+ * @returns the current updated Vector3
+ */
+ setAll(v) {
+ this._x = this._y = this._z = v;
+ this._isDirty = true;
+ return this;
+ }
+ // Statics
+ /**
+ * Get the clip factor between two vectors
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#126
+ * @param vector0 defines the first operand
+ * @param vector1 defines the second operand
+ * @param axis defines the axis to use
+ * @param size defines the size along the axis
+ * @returns the clip factor
+ */
+ static GetClipFactor(vector0, vector1, axis, size) {
+ const d0 = Vector3.Dot(vector0, axis);
+ const d1 = Vector3.Dot(vector1, axis);
+ return (d0 - size) / (d0 - d1);
+ }
+ /**
+ * Get angle between two vectors
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#86
+ * @param vector0 the starting point
+ * @param vector1 the ending point
+ * @param normal direction of the normal
+ * @returns the angle between vector0 and vector1
+ */
+ static GetAngleBetweenVectors(vector0, vector1, normal) {
+ const v0 = vector0.normalizeToRef(MathTmp.Vector3[1]);
+ const v1 = vector1.normalizeToRef(MathTmp.Vector3[2]);
+ let dot = Vector3.Dot(v0, v1);
+ // Vectors are normalized so dot will be in [-1, 1] (aside precision issues enough to break the result which explains the below clamp)
+ dot = Clamp(dot, -1, 1);
+ const angle = Math.acos(dot);
+ const n = MathTmp.Vector3[3];
+ Vector3.CrossToRef(v0, v1, n);
+ if (Vector3.Dot(n, normal) > 0) {
+ return isNaN(angle) ? 0 : angle;
+ }
+ return isNaN(angle) ? -Math.PI : -Math.acos(dot);
+ }
+ /**
+ * Get angle between two vectors projected on a plane
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#87
+ * Expectation compute time: 0.01 ms (median) and 0.02 ms (percentile 95%)
+ * @param vector0 angle between vector0 and vector1
+ * @param vector1 angle between vector0 and vector1
+ * @param normal Normal of the projection plane
+ * @returns the angle in radians (float) between vector0 and vector1 projected on the plane with the specified normal
+ */
+ static GetAngleBetweenVectorsOnPlane(vector0, vector1, normal) {
+ MathTmp.Vector3[0].copyFrom(vector0);
+ const v0 = MathTmp.Vector3[0];
+ MathTmp.Vector3[1].copyFrom(vector1);
+ const v1 = MathTmp.Vector3[1];
+ MathTmp.Vector3[2].copyFrom(normal);
+ const vNormal = MathTmp.Vector3[2];
+ const right = MathTmp.Vector3[3];
+ const forward = MathTmp.Vector3[4];
+ v0.normalize();
+ v1.normalize();
+ vNormal.normalize();
+ Vector3.CrossToRef(vNormal, v0, right);
+ Vector3.CrossToRef(right, vNormal, forward);
+ const angle = Math.atan2(Vector3.Dot(v1, right), Vector3.Dot(v1, forward));
+ return NormalizeRadians(angle);
+ }
+ /**
+ * Gets the rotation that aligns the roll axis (Y) to the line joining the start point to the target point and stores it in the ref Vector3
+ * Example PG https://playground.babylonjs.com/#R1F8YU#189
+ * @param start the starting point
+ * @param target the target point
+ * @param ref the vector3 to store the result
+ * @returns ref in the form (pitch, yaw, 0)
+ */
+ static PitchYawRollToMoveBetweenPointsToRef(start, target, ref) {
+ const diff = TmpVectors.Vector3[0];
+ target.subtractToRef(start, diff);
+ ref._y = Math.atan2(diff.x, diff.z) || 0;
+ ref._x = Math.atan2(Math.sqrt(diff.x ** 2 + diff.z ** 2), diff.y) || 0;
+ ref._z = 0;
+ ref._isDirty = true;
+ return ref;
+ }
+ /**
+ * Gets the rotation that aligns the roll axis (Y) to the line joining the start point to the target point
+ * Example PG https://playground.babylonjs.com/#R1F8YU#188
+ * @param start the starting point
+ * @param target the target point
+ * @returns the rotation in the form (pitch, yaw, 0)
+ */
+ static PitchYawRollToMoveBetweenPoints(start, target) {
+ const ref = Vector3.Zero();
+ return Vector3.PitchYawRollToMoveBetweenPointsToRef(start, target, ref);
+ }
+ /**
+ * Slerp between two vectors. See also `SmoothToRef`
+ * Slerp is a spherical linear interpolation
+ * giving a slow in and out effect
+ * Example Playground 1 https://playground.babylonjs.com/#R1F8YU#108
+ * Example Playground 2 https://playground.babylonjs.com/#R1F8YU#109
+ * @param vector0 Start vector
+ * @param vector1 End vector
+ * @param slerp amount (will be clamped between 0 and 1)
+ * @param result The slerped vector
+ * @returns The slerped vector
+ */
+ static SlerpToRef(vector0, vector1, slerp, result) {
+ slerp = Clamp(slerp, 0, 1);
+ const vector0Dir = MathTmp.Vector3[0];
+ const vector1Dir = MathTmp.Vector3[1];
+ vector0Dir.copyFrom(vector0);
+ const vector0Length = vector0Dir.length();
+ vector0Dir.normalizeFromLength(vector0Length);
+ vector1Dir.copyFrom(vector1);
+ const vector1Length = vector1Dir.length();
+ vector1Dir.normalizeFromLength(vector1Length);
+ const dot = Vector3.Dot(vector0Dir, vector1Dir);
+ let scale0;
+ let scale1;
+ if (dot < 1 - Epsilon) {
+ const omega = Math.acos(dot);
+ const invSin = 1 / Math.sin(omega);
+ scale0 = Math.sin((1 - slerp) * omega) * invSin;
+ scale1 = Math.sin(slerp * omega) * invSin;
+ }
+ else {
+ // Use linear interpolation
+ scale0 = 1 - slerp;
+ scale1 = slerp;
+ }
+ vector0Dir.scaleInPlace(scale0);
+ vector1Dir.scaleInPlace(scale1);
+ result.copyFrom(vector0Dir).addInPlace(vector1Dir);
+ result.scaleInPlace(Lerp(vector0Length, vector1Length, slerp));
+ return result;
+ }
+ /**
+ * Smooth interpolation between two vectors using Slerp
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#110
+ * @param source source vector
+ * @param goal goal vector
+ * @param deltaTime current interpolation frame
+ * @param lerpTime total interpolation time
+ * @param result the smoothed vector
+ * @returns the smoothed vector
+ */
+ static SmoothToRef(source, goal, deltaTime, lerpTime, result) {
+ Vector3.SlerpToRef(source, goal, lerpTime === 0 ? 1 : deltaTime / lerpTime, result);
+ return result;
+ }
+ /**
+ * Returns a new Vector3 set from the index "offset" of the given array
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#83
+ * @param array defines the source array
+ * @param offset defines the offset in the source array
+ * @returns the new Vector3
+ */
+ static FromArray(array, offset = 0) {
+ return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
+ }
+ /**
+ * Returns a new Vector3 set from the index "offset" of the given Float32Array
+ * @param array defines the source array
+ * @param offset defines the offset in the source array
+ * @returns the new Vector3
+ * @deprecated Please use FromArray instead.
+ */
+ static FromFloatArray(array, offset) {
+ return Vector3.FromArray(array, offset);
+ }
+ /**
+ * Sets the given vector "result" with the element values from the index "offset" of the given array
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#84
+ * @param array defines the source array
+ * @param offset defines the offset in the source array
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static FromArrayToRef(array, offset, result) {
+ result._x = array[offset];
+ result._y = array[offset + 1];
+ result._z = array[offset + 2];
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
+ * @param array defines the source array
+ * @param offset defines the offset in the source array
+ * @param result defines the Vector3 where to store the result
+ * @deprecated Please use FromArrayToRef instead.
+ * @returns result input
+ */
+ static FromFloatArrayToRef(array, offset, result) {
+ return Vector3.FromArrayToRef(array, offset, result);
+ }
+ /**
+ * Sets the given vector "result" with the given floats.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#85
+ * @param x defines the x coordinate of the source
+ * @param y defines the y coordinate of the source
+ * @param z defines the z coordinate of the source
+ * @param result defines the Vector3 where to store the result
+ * @returns the result vector
+ */
+ static FromFloatsToRef(x, y, z, result) {
+ result.copyFromFloats(x, y, z);
+ return result;
+ }
+ /**
+ * Returns a new Vector3 set to (0.0, 0.0, 0.0)
+ * @returns a new empty Vector3
+ */
+ static Zero() {
+ return new Vector3(0.0, 0.0, 0.0);
+ }
+ /**
+ * Returns a new Vector3 set to (1.0, 1.0, 1.0)
+ * @returns a new Vector3
+ */
+ static One() {
+ return new Vector3(1.0, 1.0, 1.0);
+ }
+ /**
+ * Returns a new Vector3 set to (0.0, 1.0, 0.0)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#71
+ * @returns a new up Vector3
+ */
+ static Up() {
+ return new Vector3(0.0, 1.0, 0.0);
+ }
+ /**
+ * Gets an up Vector3 that must not be updated
+ */
+ static get UpReadOnly() {
+ return Vector3._UpReadOnly;
+ }
+ /**
+ * Gets a down Vector3 that must not be updated
+ */
+ static get DownReadOnly() {
+ return Vector3._DownReadOnly;
+ }
+ /**
+ * Gets a right Vector3 that must not be updated
+ */
+ static get RightReadOnly() {
+ return Vector3._RightReadOnly;
+ }
+ /**
+ * Gets a left Vector3 that must not be updated
+ */
+ static get LeftReadOnly() {
+ return Vector3._LeftReadOnly;
+ }
+ /**
+ * Gets a forward Vector3 that must not be updated
+ */
+ static get LeftHandedForwardReadOnly() {
+ return Vector3._LeftHandedForwardReadOnly;
+ }
+ /**
+ * Gets a forward Vector3 that must not be updated
+ */
+ static get RightHandedForwardReadOnly() {
+ return Vector3._RightHandedForwardReadOnly;
+ }
+ /**
+ * Gets a backward Vector3 that must not be updated
+ */
+ static get LeftHandedBackwardReadOnly() {
+ return Vector3._LeftHandedBackwardReadOnly;
+ }
+ /**
+ * Gets a backward Vector3 that must not be updated
+ */
+ static get RightHandedBackwardReadOnly() {
+ return Vector3._RightHandedBackwardReadOnly;
+ }
+ /**
+ * Gets a zero Vector3 that must not be updated
+ */
+ static get ZeroReadOnly() {
+ return Vector3._ZeroReadOnly;
+ }
+ /**
+ * Gets a one Vector3 that must not be updated
+ */
+ static get OneReadOnly() {
+ return Vector3._OneReadOnly;
+ }
+ /**
+ * Returns a new Vector3 set to (0.0, -1.0, 0.0)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#71
+ * @returns a new down Vector3
+ */
+ static Down() {
+ return new Vector3(0.0, -1, 0.0);
+ }
+ /**
+ * Returns a new Vector3 set to (0.0, 0.0, 1.0)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#71
+ * @param rightHandedSystem is the scene right-handed (negative z)
+ * @returns a new forward Vector3
+ */
+ static Forward(rightHandedSystem = false) {
+ return new Vector3(0.0, 0.0, rightHandedSystem ? -1 : 1.0);
+ }
+ /**
+ * Returns a new Vector3 set to (0.0, 0.0, -1.0)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#71
+ * @param rightHandedSystem is the scene right-handed (negative-z)
+ * @returns a new Backward Vector3
+ */
+ static Backward(rightHandedSystem = false) {
+ return new Vector3(0.0, 0.0, rightHandedSystem ? 1.0 : -1);
+ }
+ /**
+ * Returns a new Vector3 set to (1.0, 0.0, 0.0)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#71
+ * @returns a new right Vector3
+ */
+ static Right() {
+ return new Vector3(1.0, 0.0, 0.0);
+ }
+ /**
+ * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#71
+ * @returns a new left Vector3
+ */
+ static Left() {
+ return new Vector3(-1, 0.0, 0.0);
+ }
+ /**
+ * Returns a new Vector3 with random values between min and max
+ * @param min the minimum random value
+ * @param max the maximum random value
+ * @returns a Vector3 with random values between min and max
+ */
+ static Random(min = 0, max = 1) {
+ return new Vector3(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
+ }
+ /**
+ * Sets a Vector3 with random values between min and max
+ * @param min the minimum random value
+ * @param max the maximum random value
+ * @param ref the ref to store the values in
+ * @returns the ref with random values between min and max
+ */
+ static RandomToRef(min = 0, max = 1, ref) {
+ return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
+ }
+ /**
+ * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
+ * This method computes transformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#111
+ * @param vector defines the Vector3 to transform
+ * @param transformation defines the transformation matrix
+ * @returns the transformed Vector3
+ */
+ static TransformCoordinates(vector, transformation) {
+ const result = Vector3.Zero();
+ Vector3.TransformCoordinatesToRef(vector, transformation, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
+ * This method computes transformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#113
+ * @param vector defines the Vector3 to transform
+ * @param transformation defines the transformation matrix
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static TransformCoordinatesToRef(vector, transformation, result) {
+ Vector3.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
+ * This method computes transformed coordinates only, not transformed direction vectors
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#115
+ * @param x define the x coordinate of the source vector
+ * @param y define the y coordinate of the source vector
+ * @param z define the z coordinate of the source vector
+ * @param transformation defines the transformation matrix
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static TransformCoordinatesFromFloatsToRef(x, y, z, transformation, result) {
+ const m = transformation.m;
+ const rx = x * m[0] + y * m[4] + z * m[8] + m[12];
+ const ry = x * m[1] + y * m[5] + z * m[9] + m[13];
+ const rz = x * m[2] + y * m[6] + z * m[10] + m[14];
+ const rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
+ result._x = rx * rw;
+ result._y = ry * rw;
+ result._z = rz * rw;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
+ * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#112
+ * @param vector defines the Vector3 to transform
+ * @param transformation defines the transformation matrix
+ * @returns the new Vector3
+ */
+ static TransformNormal(vector, transformation) {
+ const result = Vector3.Zero();
+ Vector3.TransformNormalToRef(vector, transformation, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
+ * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#114
+ * @param vector defines the Vector3 to transform
+ * @param transformation defines the transformation matrix
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static TransformNormalToRef(vector, transformation, result) {
+ this.TransformNormalFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
+ * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#116
+ * @param x define the x coordinate of the source vector
+ * @param y define the y coordinate of the source vector
+ * @param z define the z coordinate of the source vector
+ * @param transformation defines the transformation matrix
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static TransformNormalFromFloatsToRef(x, y, z, transformation, result) {
+ const m = transformation.m;
+ result._x = x * m[0] + y * m[4] + z * m[8];
+ result._y = x * m[1] + y * m[5] + z * m[9];
+ result._z = x * m[2] + y * m[6] + z * m[10];
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#69
+ * @param value1 defines the first control point
+ * @param value2 defines the second control point
+ * @param value3 defines the third control point
+ * @param value4 defines the fourth control point
+ * @param amount defines the amount on the spline to use
+ * @returns the new Vector3
+ */
+ static CatmullRom(value1, value2, value3, value4, amount) {
+ const squared = amount * amount;
+ const cubed = amount * squared;
+ const x = 0.5 *
+ (2.0 * value2._x +
+ (-value1._x + value3._x) * amount +
+ (2.0 * value1._x - 5.0 * value2._x + 4.0 * value3._x - value4._x) * squared +
+ (-value1._x + 3.0 * value2._x - 3.0 * value3._x + value4._x) * cubed);
+ const y = 0.5 *
+ (2.0 * value2._y +
+ (-value1._y + value3._y) * amount +
+ (2.0 * value1._y - 5.0 * value2._y + 4.0 * value3._y - value4._y) * squared +
+ (-value1._y + 3.0 * value2._y - 3.0 * value3._y + value4._y) * cubed);
+ const z = 0.5 *
+ (2.0 * value2._z +
+ (-value1._z + value3._z) * amount +
+ (2.0 * value1._z - 5.0 * value2._z + 4.0 * value3._z - value4._z) * squared +
+ (-value1._z + 3.0 * value2._z - 3.0 * value3._z + value4._z) * cubed);
+ return new Vector3(x, y, z);
+ }
+ /**
+ * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
+ * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
+ * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#76
+ * @param value defines the current value
+ * @param min defines the lower range value
+ * @param max defines the upper range value
+ * @returns the new Vector3
+ */
+ static Clamp(value, min, max) {
+ const result = new Vector3();
+ Vector3.ClampToRef(value, min, max, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
+ * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
+ * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#77
+ * @param value defines the current value
+ * @param min defines the lower range value
+ * @param max defines the upper range value
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static ClampToRef(value, min, max, result) {
+ let x = value._x;
+ x = x > max._x ? max._x : x;
+ x = x < min._x ? min._x : x;
+ let y = value._y;
+ y = y > max._y ? max._y : y;
+ y = y < min._y ? min._y : y;
+ let z = value._z;
+ z = z > max._z ? max._z : z;
+ z = z < min._z ? min._z : z;
+ result.copyFromFloats(x, y, z);
+ return result;
+ }
+ /**
+ * Checks if a given vector is inside a specific range
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#75
+ * @param v defines the vector to test
+ * @param min defines the minimum range
+ * @param max defines the maximum range
+ */
+ static CheckExtends(v, min, max) {
+ min.minimizeInPlace(v);
+ max.maximizeInPlace(v);
+ }
+ /**
+ * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#89
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent vector
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent vector
+ * @param amount defines the amount on the interpolation spline (between 0 and 1)
+ * @returns the new Vector3
+ */
+ static Hermite(value1, tangent1, value2, tangent2, amount) {
+ const squared = amount * amount;
+ const cubed = amount * squared;
+ const part1 = 2.0 * cubed - 3.0 * squared + 1.0;
+ const part2 = -2 * cubed + 3.0 * squared;
+ const part3 = cubed - 2.0 * squared + amount;
+ const part4 = cubed - squared;
+ const x = value1._x * part1 + value2._x * part2 + tangent1._x * part3 + tangent2._x * part4;
+ const y = value1._y * part1 + value2._y * part2 + tangent1._y * part3 + tangent2._y * part4;
+ const z = value1._z * part1 + value2._z * part2 + tangent1._z * part3 + tangent2._z * part4;
+ return new Vector3(x, y, z);
+ }
+ /**
+ * Returns a new Vector3 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#90
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @returns 1st derivative
+ */
+ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
+ const result = new Vector3();
+ this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
+ return result;
+ }
+ /**
+ * Update a Vector3 with the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#91
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @param result define where to store the derivative
+ * @returns result input
+ */
+ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {
+ const t2 = time * time;
+ result._x = (t2 - time) * 6 * value1._x + (3 * t2 - 4 * time + 1) * tangent1._x + (-t2 + time) * 6 * value2._x + (3 * t2 - 2 * time) * tangent2._x;
+ result._y = (t2 - time) * 6 * value1._y + (3 * t2 - 4 * time + 1) * tangent1._y + (-t2 + time) * 6 * value2._y + (3 * t2 - 2 * time) * tangent2._y;
+ result._z = (t2 - time) * 6 * value1._z + (3 * t2 - 4 * time + 1) * tangent1._z + (-t2 + time) * 6 * value2._z + (3 * t2 - 2 * time) * tangent2._z;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#95
+ * @param start defines the start value
+ * @param end defines the end value
+ * @param amount max defines amount between both (between 0 and 1)
+ * @returns the new Vector3
+ */
+ static Lerp(start, end, amount) {
+ const result = new Vector3(0, 0, 0);
+ Vector3.LerpToRef(start, end, amount, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#93
+ * @param start defines the start value
+ * @param end defines the end value
+ * @param amount max defines amount between both (between 0 and 1)
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static LerpToRef(start, end, amount, result) {
+ result._x = start._x + (end._x - start._x) * amount;
+ result._y = start._y + (end._y - start._y) * amount;
+ result._z = start._z + (end._z - start._z) * amount;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Returns the dot product (float) between the vectors "left" and "right"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#82
+ * @param left defines the left operand
+ * @param right defines the right operand
+ * @returns the dot product
+ */
+ static Dot(left, right) {
+ return left._x * right._x + left._y * right._y + left._z * right._z;
+ }
+ /**
+ * Returns the dot product (float) between the current vectors and "otherVector"
+ * @param otherVector defines the right operand
+ * @returns the dot product
+ */
+ dot(otherVector) {
+ return this._x * otherVector._x + this._y * otherVector._y + this._z * otherVector._z;
+ }
+ /**
+ * Returns a new Vector3 as the cross product of the vectors "left" and "right"
+ * The cross product is then orthogonal to both "left" and "right"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#15
+ * @param left defines the left operand
+ * @param right defines the right operand
+ * @returns the cross product
+ */
+ static Cross(left, right) {
+ const result = new Vector3();
+ Vector3.CrossToRef(left, right, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the cross product of "left" and "right"
+ * The cross product is then orthogonal to both "left" and "right"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#78
+ * @param left defines the left operand
+ * @param right defines the right operand
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static CrossToRef(left, right, result) {
+ const x = left._y * right._z - left._z * right._y;
+ const y = left._z * right._x - left._x * right._z;
+ const z = left._x * right._y - left._y * right._x;
+ result.copyFromFloats(x, y, z);
+ return result;
+ }
+ /**
+ * Returns a new Vector3 as the normalization of the given vector
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#98
+ * @param vector defines the Vector3 to normalize
+ * @returns the new Vector3
+ */
+ static Normalize(vector) {
+ const result = Vector3.Zero();
+ Vector3.NormalizeToRef(vector, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the normalization of the given first vector
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#98
+ * @param vector defines the Vector3 to normalize
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static NormalizeToRef(vector, result) {
+ vector.normalizeToRef(result);
+ return result;
+ }
+ /**
+ * Project a Vector3 onto screen space
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#101
+ * @param vector defines the Vector3 to project
+ * @param world defines the world matrix to use
+ * @param transform defines the transform (view x projection) matrix to use
+ * @param viewport defines the screen viewport to use
+ * @returns the new Vector3
+ */
+ static Project(vector, world, transform, viewport) {
+ const result = new Vector3();
+ Vector3.ProjectToRef(vector, world, transform, viewport, result);
+ return result;
+ }
+ /**
+ * Project a Vector3 onto screen space to reference
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#102
+ * @param vector defines the Vector3 to project
+ * @param world defines the world matrix to use
+ * @param transform defines the transform (view x projection) matrix to use
+ * @param viewport defines the screen viewport to use
+ * @param result the vector in which the screen space will be stored
+ * @returns result input
+ */
+ static ProjectToRef(vector, world, transform, viewport, result) {
+ const cw = viewport.width;
+ const ch = viewport.height;
+ const cx = viewport.x;
+ const cy = viewport.y;
+ const viewportMatrix = MathTmp.Matrix[1];
+ const isNDCHalfZRange = EngineStore.LastCreatedEngine?.isNDCHalfZRange;
+ const zScale = isNDCHalfZRange ? 1 : 0.5;
+ const zOffset = isNDCHalfZRange ? 0 : 0.5;
+ Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zScale, 0, cx + cw / 2.0, ch / 2.0 + cy, zOffset, 1, viewportMatrix);
+ const matrix = MathTmp.Matrix[0];
+ world.multiplyToRef(transform, matrix);
+ matrix.multiplyToRef(viewportMatrix, matrix);
+ Vector3.TransformCoordinatesToRef(vector, matrix, result);
+ return result;
+ }
+ /**
+ * Reflects a vector off the plane defined by a normalized normal
+ * @param inDirection defines the vector direction
+ * @param normal defines the normal - Must be normalized
+ * @returns the resulting vector
+ */
+ static Reflect(inDirection, normal) {
+ return this.ReflectToRef(inDirection, normal, new Vector3());
+ }
+ /**
+ * Reflects a vector off the plane defined by a normalized normal to reference
+ * @param inDirection defines the vector direction
+ * @param normal defines the normal - Must be normalized
+ * @param ref defines the Vector3 where to store the result
+ * @returns the resulting vector
+ */
+ static ReflectToRef(inDirection, normal, ref) {
+ const tmp = TmpVectors.Vector3[0];
+ tmp.copyFrom(normal).scaleInPlace(2 * Vector3.Dot(inDirection, normal));
+ return ref.copyFrom(inDirection).subtractInPlace(tmp);
+ }
+ /**
+ * @internal
+ */
+ static _UnprojectFromInvertedMatrixToRef(source, matrix, result) {
+ Vector3.TransformCoordinatesToRef(source, matrix, result);
+ const m = matrix.m;
+ const num = source._x * m[3] + source._y * m[7] + source._z * m[11] + m[15];
+ if (WithinEpsilon(num, 1.0)) {
+ result.scaleInPlace(1.0 / num);
+ }
+ return result;
+ }
+ /**
+ * Unproject from screen space to object space
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#121
+ * @param source defines the screen space Vector3 to use
+ * @param viewportWidth defines the current width of the viewport
+ * @param viewportHeight defines the current height of the viewport
+ * @param world defines the world matrix to use (can be set to Identity to go to world space)
+ * @param transform defines the transform (view x projection) matrix to use
+ * @returns the new Vector3
+ */
+ static UnprojectFromTransform(source, viewportWidth, viewportHeight, world, transform) {
+ return this.Unproject(source, viewportWidth, viewportHeight, world, transform, Matrix.IdentityReadOnly);
+ }
+ /**
+ * Unproject from screen space to object space
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#117
+ * @param source defines the screen space Vector3 to use
+ * @param viewportWidth defines the current width of the viewport
+ * @param viewportHeight defines the current height of the viewport
+ * @param world defines the world matrix to use (can be set to Identity to go to world space)
+ * @param view defines the view matrix to use
+ * @param projection defines the projection matrix to use
+ * @returns the new Vector3
+ */
+ static Unproject(source, viewportWidth, viewportHeight, world, view, projection) {
+ const result = new Vector3();
+ Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
+ return result;
+ }
+ /**
+ * Unproject from screen space to object space
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#119
+ * @param source defines the screen space Vector3 to use
+ * @param viewportWidth defines the current width of the viewport
+ * @param viewportHeight defines the current height of the viewport
+ * @param world defines the world matrix to use (can be set to Identity to go to world space)
+ * @param view defines the view matrix to use
+ * @param projection defines the projection matrix to use
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result) {
+ Vector3.UnprojectFloatsToRef(source._x, source._y, source._z, viewportWidth, viewportHeight, world, view, projection, result);
+ return result;
+ }
+ /**
+ * Unproject from screen space to object space
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#120
+ * @param sourceX defines the screen space x coordinate to use
+ * @param sourceY defines the screen space y coordinate to use
+ * @param sourceZ defines the screen space z coordinate to use
+ * @param viewportWidth defines the current width of the viewport
+ * @param viewportHeight defines the current height of the viewport
+ * @param world defines the world matrix to use (can be set to Identity to go to world space)
+ * @param view defines the view matrix to use
+ * @param projection defines the projection matrix to use
+ * @param result defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static UnprojectFloatsToRef(sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
+ const matrix = MathTmp.Matrix[0];
+ world.multiplyToRef(view, matrix);
+ matrix.multiplyToRef(projection, matrix);
+ matrix.invert();
+ const screenSource = MathTmp.Vector3[0];
+ screenSource.x = (sourceX / viewportWidth) * 2 - 1;
+ screenSource.y = -((sourceY / viewportHeight) * 2 - 1);
+ if (EngineStore.LastCreatedEngine?.isNDCHalfZRange) {
+ screenSource.z = sourceZ;
+ }
+ else {
+ screenSource.z = 2 * sourceZ - 1.0;
+ }
+ Vector3._UnprojectFromInvertedMatrixToRef(screenSource, matrix, result);
+ return result;
+ }
+ /**
+ * Gets the minimal coordinate values between two Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#97
+ * @param left defines the first operand
+ * @param right defines the second operand
+ * @returns the new Vector3
+ */
+ static Minimize(left, right) {
+ const min = new Vector3();
+ min.copyFrom(left);
+ min.minimizeInPlace(right);
+ return min;
+ }
+ /**
+ * Gets the maximal coordinate values between two Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#96
+ * @param left defines the first operand
+ * @param right defines the second operand
+ * @returns the new Vector3
+ */
+ static Maximize(left, right) {
+ const max = new Vector3();
+ max.copyFrom(left);
+ max.maximizeInPlace(right);
+ return max;
+ }
+ /**
+ * Returns the distance between the vectors "value1" and "value2"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#81
+ * @param value1 defines the first operand
+ * @param value2 defines the second operand
+ * @returns the distance
+ */
+ static Distance(value1, value2) {
+ return Math.sqrt(Vector3.DistanceSquared(value1, value2));
+ }
+ /**
+ * Returns the squared distance between the vectors "value1" and "value2"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#80
+ * @param value1 defines the first operand
+ * @param value2 defines the second operand
+ * @returns the squared distance
+ */
+ static DistanceSquared(value1, value2) {
+ const x = value1._x - value2._x;
+ const y = value1._y - value2._y;
+ const z = value1._z - value2._z;
+ return x * x + y * y + z * z;
+ }
+ /**
+ * Projects "vector" on the triangle determined by its extremities "p0", "p1" and "p2", stores the result in "ref"
+ * and returns the distance to the projected point.
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#104
+ * From http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.104.4264&rep=rep1&type=pdf
+ *
+ * @param vector the vector to get distance from
+ * @param p0 extremity of the triangle
+ * @param p1 extremity of the triangle
+ * @param p2 extremity of the triangle
+ * @param ref variable to store the result to
+ * @returns The distance between "ref" and "vector"
+ */
+ static ProjectOnTriangleToRef(vector, p0, p1, p2, ref) {
+ const p1p0 = MathTmp.Vector3[0];
+ const p2p0 = MathTmp.Vector3[1];
+ const p2p1 = MathTmp.Vector3[2];
+ const normal = MathTmp.Vector3[3];
+ const vectorp0 = MathTmp.Vector3[4];
+ // Triangle vectors
+ p1.subtractToRef(p0, p1p0);
+ p2.subtractToRef(p0, p2p0);
+ p2.subtractToRef(p1, p2p1);
+ const p1p0L = p1p0.length();
+ const p2p0L = p2p0.length();
+ const p2p1L = p2p1.length();
+ if (p1p0L < Epsilon || p2p0L < Epsilon || p2p1L < Epsilon) {
+ // This is a degenerate triangle. As we assume this is part of a non-degenerate mesh,
+ // we will find a better intersection later.
+ // Let's just return one of the extremities
+ ref.copyFrom(p0);
+ return Vector3.Distance(vector, p0);
+ }
+ // Compute normal and vector to p0
+ vector.subtractToRef(p0, vectorp0);
+ Vector3.CrossToRef(p1p0, p2p0, normal);
+ const nl = normal.length();
+ if (nl < Epsilon) {
+ // Extremities are aligned, we are back on the case of a degenerate triangle
+ ref.copyFrom(p0);
+ return Vector3.Distance(vector, p0);
+ }
+ normal.normalizeFromLength(nl);
+ let l = vectorp0.length();
+ if (l < Epsilon) {
+ // Vector is p0
+ ref.copyFrom(p0);
+ return 0;
+ }
+ vectorp0.normalizeFromLength(l);
+ // Project to "proj" that lies on the triangle plane
+ const cosA = Vector3.Dot(normal, vectorp0);
+ const projVector = MathTmp.Vector3[5];
+ const proj = MathTmp.Vector3[6];
+ projVector.copyFrom(normal).scaleInPlace(-l * cosA);
+ proj.copyFrom(vector).addInPlace(projVector);
+ // Compute barycentric coordinates (v0, v1 and v2 are axis from barycenter to extremities)
+ const v0 = MathTmp.Vector3[4];
+ const v1 = MathTmp.Vector3[5];
+ const v2 = MathTmp.Vector3[7];
+ const tmp = MathTmp.Vector3[8];
+ v0.copyFrom(p1p0).scaleInPlace(1 / p1p0L);
+ tmp.copyFrom(p2p0).scaleInPlace(1 / p2p0L);
+ v0.addInPlace(tmp).scaleInPlace(-1);
+ v1.copyFrom(p1p0).scaleInPlace(-1 / p1p0L);
+ tmp.copyFrom(p2p1).scaleInPlace(1 / p2p1L);
+ v1.addInPlace(tmp).scaleInPlace(-1);
+ v2.copyFrom(p2p1).scaleInPlace(-1 / p2p1L);
+ tmp.copyFrom(p2p0).scaleInPlace(-1 / p2p0L);
+ v2.addInPlace(tmp).scaleInPlace(-1);
+ // Determines which edge of the triangle is closest to "proj"
+ const projP = MathTmp.Vector3[9];
+ let dot;
+ projP.copyFrom(proj).subtractInPlace(p0);
+ Vector3.CrossToRef(v0, projP, tmp);
+ dot = Vector3.Dot(tmp, normal);
+ const s0 = dot;
+ projP.copyFrom(proj).subtractInPlace(p1);
+ Vector3.CrossToRef(v1, projP, tmp);
+ dot = Vector3.Dot(tmp, normal);
+ const s1 = dot;
+ projP.copyFrom(proj).subtractInPlace(p2);
+ Vector3.CrossToRef(v2, projP, tmp);
+ dot = Vector3.Dot(tmp, normal);
+ const s2 = dot;
+ const edge = MathTmp.Vector3[10];
+ let e0, e1;
+ if (s0 > 0 && s1 < 0) {
+ edge.copyFrom(p1p0);
+ e0 = p0;
+ e1 = p1;
+ }
+ else if (s1 > 0 && s2 < 0) {
+ edge.copyFrom(p2p1);
+ e0 = p1;
+ e1 = p2;
+ }
+ else {
+ edge.copyFrom(p2p0).scaleInPlace(-1);
+ e0 = p2;
+ e1 = p0;
+ }
+ // Determines if "proj" lies inside the triangle
+ const tmp2 = MathTmp.Vector3[9];
+ const tmp3 = MathTmp.Vector3[4];
+ e0.subtractToRef(proj, tmp);
+ e1.subtractToRef(proj, tmp2);
+ Vector3.CrossToRef(tmp, tmp2, tmp3);
+ const isOutside = Vector3.Dot(tmp3, normal) < 0;
+ // If inside, we already found the projected point, "proj"
+ if (!isOutside) {
+ ref.copyFrom(proj);
+ return Math.abs(l * cosA);
+ }
+ // If outside, we find "triProj", the closest point from "proj" on the closest edge
+ const r = MathTmp.Vector3[5];
+ Vector3.CrossToRef(edge, tmp3, r);
+ r.normalize();
+ const e0proj = MathTmp.Vector3[9];
+ e0proj.copyFrom(e0).subtractInPlace(proj);
+ const e0projL = e0proj.length();
+ if (e0projL < Epsilon) {
+ // Proj is e0
+ ref.copyFrom(e0);
+ return Vector3.Distance(vector, e0);
+ }
+ e0proj.normalizeFromLength(e0projL);
+ const cosG = Vector3.Dot(r, e0proj);
+ const triProj = MathTmp.Vector3[7];
+ triProj.copyFrom(proj).addInPlace(r.scaleInPlace(e0projL * cosG));
+ // Now we clamp "triProj" so it lies between e0 and e1
+ tmp.copyFrom(triProj).subtractInPlace(e0);
+ l = edge.length();
+ edge.normalizeFromLength(l);
+ let t = Vector3.Dot(tmp, edge) / Math.max(l, Epsilon);
+ t = Clamp(t, 0, 1);
+ triProj.copyFrom(e0).addInPlace(edge.scaleInPlace(t * l));
+ ref.copyFrom(triProj);
+ return Vector3.Distance(vector, triProj);
+ }
+ /**
+ * Returns a new Vector3 located at the center between "value1" and "value2"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#72
+ * @param value1 defines the first operand
+ * @param value2 defines the second operand
+ * @returns the new Vector3
+ */
+ static Center(value1, value2) {
+ return Vector3.CenterToRef(value1, value2, Vector3.Zero());
+ }
+ /**
+ * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref"
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#73
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @param ref defines third vector
+ * @returns ref
+ */
+ static CenterToRef(value1, value2, ref) {
+ return ref.copyFromFloats((value1._x + value2._x) / 2, (value1._y + value2._y) / 2, (value1._z + value2._z) / 2);
+ }
+ /**
+ * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
+ * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
+ * to something in order to rotate it from its local system to the given target system
+ * Note: axis1, axis2 and axis3 are normalized during this operation
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#106
+ * @param axis1 defines the first axis
+ * @param axis2 defines the second axis
+ * @param axis3 defines the third axis
+ * @returns a new Vector3
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/target_align
+ */
+ static RotationFromAxis(axis1, axis2, axis3) {
+ const rotation = new Vector3();
+ Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
+ return rotation;
+ }
+ /**
+ * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#107
+ * @param axis1 defines the first axis
+ * @param axis2 defines the second axis
+ * @param axis3 defines the third axis
+ * @param ref defines the Vector3 where to store the result
+ * @returns result input
+ */
+ static RotationFromAxisToRef(axis1, axis2, axis3, ref) {
+ const quat = MathTmp.Quaternion[0];
+ Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
+ quat.toEulerAnglesToRef(ref);
+ return ref;
+ }
+}
+/**
+ * If the first vector is flagged with integers (as everything is 0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet.
+ * If subsequent vectors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers,
+ * and henceforth it will use floating-point representation for all Vector3 instances that it creates.
+ * But the original Vector3 instances are unchanged and has a "deprecated map".
+ * If we keep using the Vector3 instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches.
+ */
+Vector3._V8PerformanceHack = new Vector3(0.5, 0.5, 0.5);
+Vector3._UpReadOnly = Vector3.Up();
+Vector3._DownReadOnly = Vector3.Down();
+Vector3._LeftHandedForwardReadOnly = Vector3.Forward(false);
+Vector3._RightHandedForwardReadOnly = Vector3.Forward(true);
+Vector3._LeftHandedBackwardReadOnly = Vector3.Backward(false);
+Vector3._RightHandedBackwardReadOnly = Vector3.Backward(true);
+Vector3._RightReadOnly = Vector3.Right();
+Vector3._LeftReadOnly = Vector3.Left();
+Vector3._ZeroReadOnly = Vector3.Zero();
+Vector3._OneReadOnly = Vector3.One();
+Object.defineProperties(Vector3.prototype, {
+ dimension: { value: [3] },
+ rank: { value: 1 },
+});
+/**
+ * Vector4 class created for EulerAngle class conversion to Quaternion
+ */
+class Vector4 {
+ /**
+ * Creates a Vector4 object from the given floats.
+ * @param x x value of the vector
+ * @param y y value of the vector
+ * @param z z value of the vector
+ * @param w w value of the vector
+ */
+ constructor(
+ /** [0] x value of the vector */
+ x = 0,
+ /** [0] y value of the vector */
+ y = 0,
+ /** [0] z value of the vector */
+ z = 0,
+ /** [0] w value of the vector */
+ w = 0) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.w = w;
+ }
+ /**
+ * Returns the string with the Vector4 coordinates.
+ * @returns a string containing all the vector values
+ */
+ toString() {
+ return `{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`;
+ }
+ /**
+ * Returns the string "Vector4".
+ * @returns "Vector4"
+ */
+ getClassName() {
+ return "Vector4";
+ }
+ /**
+ * Returns the Vector4 hash code.
+ * @returns a unique hash code
+ */
+ getHashCode() {
+ const x = _ExtractAsInt(this.x);
+ const y = _ExtractAsInt(this.y);
+ const z = _ExtractAsInt(this.z);
+ const w = _ExtractAsInt(this.w);
+ let hash = x;
+ hash = (hash * 397) ^ y;
+ hash = (hash * 397) ^ z;
+ hash = (hash * 397) ^ w;
+ return hash;
+ }
+ // Operators
+ /**
+ * Returns a new array populated with 4 elements : the Vector4 coordinates.
+ * @returns the resulting array
+ */
+ asArray() {
+ return [this.x, this.y, this.z, this.w];
+ }
+ /**
+ * Populates the given array from the given index with the Vector4 coordinates.
+ * @param array array to populate
+ * @param index index of the array to start at (default: 0)
+ * @returns the Vector4.
+ */
+ toArray(array, index) {
+ if (index === undefined) {
+ index = 0;
+ }
+ array[index] = this.x;
+ array[index + 1] = this.y;
+ array[index + 2] = this.z;
+ array[index + 3] = this.w;
+ return this;
+ }
+ /**
+ * Update the current vector from an array
+ * @param array defines the destination array
+ * @param offset defines the offset in the destination array
+ * @returns the current Vector3
+ */
+ fromArray(array, offset = 0) {
+ Vector4.FromArrayToRef(array, offset, this);
+ return this;
+ }
+ /**
+ * Adds the given vector to the current Vector4.
+ * @param otherVector the vector to add
+ * @returns the updated Vector4.
+ */
+ addInPlace(otherVector) {
+ this.x += otherVector.x;
+ this.y += otherVector.y;
+ this.z += otherVector.z;
+ this.w += otherVector.w;
+ return this;
+ }
+ /**
+ * Adds the given coordinates to the current Vector4
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @param w defines the w coordinate of the operand
+ * @returns the current updated Vector4
+ */
+ addInPlaceFromFloats(x, y, z, w) {
+ this.x += x;
+ this.y += y;
+ this.z += z;
+ this.w += w;
+ return this;
+ }
+ /**
+ * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
+ * @param otherVector the vector to add
+ * @returns the resulting vector
+ */
+ add(otherVector) {
+ return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
+ }
+ /**
+ * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
+ * @param otherVector the vector to add
+ * @param result the vector to store the result
+ * @returns result input
+ */
+ addToRef(otherVector, result) {
+ result.x = this.x + otherVector.x;
+ result.y = this.y + otherVector.y;
+ result.z = this.z + otherVector.z;
+ result.w = this.w + otherVector.w;
+ return result;
+ }
+ /**
+ * Subtract in place the given vector from the current Vector4.
+ * @param otherVector the vector to subtract
+ * @returns the updated Vector4.
+ */
+ subtractInPlace(otherVector) {
+ this.x -= otherVector.x;
+ this.y -= otherVector.y;
+ this.z -= otherVector.z;
+ this.w -= otherVector.w;
+ return this;
+ }
+ /**
+ * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
+ * @param otherVector the vector to add
+ * @returns the new vector with the result
+ */
+ subtract(otherVector) {
+ return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
+ }
+ /**
+ * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
+ * @param otherVector the vector to subtract
+ * @param result the vector to store the result
+ * @returns result input
+ */
+ subtractToRef(otherVector, result) {
+ result.x = this.x - otherVector.x;
+ result.y = this.y - otherVector.y;
+ result.z = this.z - otherVector.z;
+ result.w = this.w - otherVector.w;
+ return result;
+ }
+ /**
+ * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
+ * @param x value to subtract
+ * @param y value to subtract
+ * @param z value to subtract
+ * @param w value to subtract
+ * @returns new vector containing the result
+ */
+ subtractFromFloats(x, y, z, w) {
+ return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
+ }
+ /**
+ * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
+ * @param x value to subtract
+ * @param y value to subtract
+ * @param z value to subtract
+ * @param w value to subtract
+ * @param result the vector to store the result in
+ * @returns result input
+ */
+ subtractFromFloatsToRef(x, y, z, w, result) {
+ result.x = this.x - x;
+ result.y = this.y - y;
+ result.z = this.z - z;
+ result.w = this.w - w;
+ return result;
+ }
+ /**
+ * Returns a new Vector4 set with the current Vector4 negated coordinates.
+ * @returns a new vector with the negated values
+ */
+ negate() {
+ return new Vector4(-this.x, -this.y, -this.z, -this.w);
+ }
+ /**
+ * Negate this vector in place
+ * @returns this
+ */
+ negateInPlace() {
+ this.x *= -1;
+ this.y *= -1;
+ this.z *= -1;
+ this.w *= -1;
+ return this;
+ }
+ /**
+ * Negate the current Vector4 and stores the result in the given vector "result" coordinates
+ * @param result defines the Vector3 object where to store the result
+ * @returns the result
+ */
+ negateToRef(result) {
+ result.x = -this.x;
+ result.y = -this.y;
+ result.z = -this.z;
+ result.w = -this.w;
+ return result;
+ }
+ /**
+ * Multiplies the current Vector4 coordinates by scale (float).
+ * @param scale the number to scale with
+ * @returns the updated Vector4.
+ */
+ scaleInPlace(scale) {
+ this.x *= scale;
+ this.y *= scale;
+ this.z *= scale;
+ this.w *= scale;
+ return this;
+ }
+ /**
+ * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
+ * @param scale the number to scale with
+ * @returns a new vector with the result
+ */
+ scale(scale) {
+ return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
+ }
+ /**
+ * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
+ * @param scale the number to scale with
+ * @param result a vector to store the result in
+ * @returns result input
+ */
+ scaleToRef(scale, result) {
+ result.x = this.x * scale;
+ result.y = this.y * scale;
+ result.z = this.z * scale;
+ result.w = this.w * scale;
+ return result;
+ }
+ /**
+ * Scale the current Vector4 values by a factor and add the result to a given Vector4
+ * @param scale defines the scale factor
+ * @param result defines the Vector4 object where to store the result
+ * @returns result input
+ */
+ scaleAndAddToRef(scale, result) {
+ result.x += this.x * scale;
+ result.y += this.y * scale;
+ result.z += this.z * scale;
+ result.w += this.w * scale;
+ return result;
+ }
+ /**
+ * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
+ * @param otherVector the vector to compare against
+ * @returns true if they are equal
+ */
+ equals(otherVector) {
+ return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
+ }
+ /**
+ * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
+ * @param otherVector vector to compare against
+ * @param epsilon (Default: very small number)
+ * @returns true if they are equal
+ */
+ equalsWithEpsilon(otherVector, epsilon = Epsilon) {
+ return (otherVector &&
+ WithinEpsilon(this.x, otherVector.x, epsilon) &&
+ WithinEpsilon(this.y, otherVector.y, epsilon) &&
+ WithinEpsilon(this.z, otherVector.z, epsilon) &&
+ WithinEpsilon(this.w, otherVector.w, epsilon));
+ }
+ /**
+ * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
+ * @param x x value to compare against
+ * @param y y value to compare against
+ * @param z z value to compare against
+ * @param w w value to compare against
+ * @returns true if equal
+ */
+ equalsToFloats(x, y, z, w) {
+ return this.x === x && this.y === y && this.z === z && this.w === w;
+ }
+ /**
+ * Multiplies in place the current Vector4 by the given one.
+ * @param otherVector vector to multiple with
+ * @returns the updated Vector4.
+ */
+ multiplyInPlace(otherVector) {
+ this.x *= otherVector.x;
+ this.y *= otherVector.y;
+ this.z *= otherVector.z;
+ this.w *= otherVector.w;
+ return this;
+ }
+ /**
+ * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
+ * @param otherVector vector to multiple with
+ * @returns resulting new vector
+ */
+ multiply(otherVector) {
+ return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
+ }
+ /**
+ * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
+ * @param otherVector vector to multiple with
+ * @param result vector to store the result
+ * @returns result input
+ */
+ multiplyToRef(otherVector, result) {
+ result.x = this.x * otherVector.x;
+ result.y = this.y * otherVector.y;
+ result.z = this.z * otherVector.z;
+ result.w = this.w * otherVector.w;
+ return result;
+ }
+ /**
+ * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
+ * @param x x value multiply with
+ * @param y y value multiply with
+ * @param z z value multiply with
+ * @param w w value multiply with
+ * @returns resulting new vector
+ */
+ multiplyByFloats(x, y, z, w) {
+ return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
+ }
+ /**
+ * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
+ * @param otherVector vector to devide with
+ * @returns resulting new vector
+ */
+ divide(otherVector) {
+ return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
+ }
+ /**
+ * Updates the given vector "result" with the division result of the current Vector4 by the given one.
+ * @param otherVector vector to devide with
+ * @param result vector to store the result
+ * @returns result input
+ */
+ divideToRef(otherVector, result) {
+ result.x = this.x / otherVector.x;
+ result.y = this.y / otherVector.y;
+ result.z = this.z / otherVector.z;
+ result.w = this.w / otherVector.w;
+ return result;
+ }
+ /**
+ * Divides the current Vector3 coordinates by the given ones.
+ * @param otherVector vector to devide with
+ * @returns the updated Vector3.
+ */
+ divideInPlace(otherVector) {
+ return this.divideToRef(otherVector, this);
+ }
+ /**
+ * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
+ * @param other defines the second operand
+ * @returns the current updated Vector4
+ */
+ minimizeInPlace(other) {
+ if (other.x < this.x) {
+ this.x = other.x;
+ }
+ if (other.y < this.y) {
+ this.y = other.y;
+ }
+ if (other.z < this.z) {
+ this.z = other.z;
+ }
+ if (other.w < this.w) {
+ this.w = other.w;
+ }
+ return this;
+ }
+ /**
+ * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
+ * @param other defines the second operand
+ * @returns the current updated Vector4
+ */
+ maximizeInPlace(other) {
+ if (other.x > this.x) {
+ this.x = other.x;
+ }
+ if (other.y > this.y) {
+ this.y = other.y;
+ }
+ if (other.z > this.z) {
+ this.z = other.z;
+ }
+ if (other.w > this.w) {
+ this.w = other.w;
+ }
+ return this;
+ }
+ /**
+ * Updates the current Vector4 with the minimal coordinate values between its and the given coordinates
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @param w defines the w coordinate of the operand
+ * @returns the current updated Vector4
+ */
+ minimizeInPlaceFromFloats(x, y, z, w) {
+ this.x = Math.min(x, this.x);
+ this.y = Math.min(y, this.y);
+ this.z = Math.min(z, this.z);
+ this.w = Math.min(w, this.w);
+ return this;
+ }
+ /**
+ * Updates the current Vector4 with the maximal coordinate values between its and the given coordinates.
+ * @param x defines the x coordinate of the operand
+ * @param y defines the y coordinate of the operand
+ * @param z defines the z coordinate of the operand
+ * @param w defines the w coordinate of the operand
+ * @returns the current updated Vector4
+ */
+ maximizeInPlaceFromFloats(x, y, z, w) {
+ this.x = Math.max(x, this.x);
+ this.y = Math.max(y, this.y);
+ this.z = Math.max(z, this.z);
+ this.w = Math.max(w, this.w);
+ return this;
+ }
+ /**
+ * Gets the current Vector4's floored values and stores them in result
+ * @param result the vector to store the result in
+ * @returns the result vector
+ */
+ floorToRef(result) {
+ result.x = Math.floor(this.x);
+ result.y = Math.floor(this.y);
+ result.z = Math.floor(this.z);
+ result.w = Math.floor(this.w);
+ return result;
+ }
+ /**
+ * Gets a new Vector4 from current Vector4 floored values
+ * @returns a new Vector4
+ */
+ floor() {
+ return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
+ }
+ /**
+ * Gets the current Vector4's fractional values and stores them in result
+ * @param result the vector to store the result in
+ * @returns the result vector
+ */
+ fractToRef(result) {
+ result.x = this.x - Math.floor(this.x);
+ result.y = this.y - Math.floor(this.y);
+ result.z = this.z - Math.floor(this.z);
+ result.w = this.w - Math.floor(this.w);
+ return result;
+ }
+ /**
+ * Gets a new Vector4 from current Vector4 fractional values
+ * @returns a new Vector4
+ */
+ fract() {
+ return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
+ }
+ // Properties
+ /**
+ * Returns the Vector4 length (float).
+ * @returns the length
+ */
+ length() {
+ return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
+ }
+ /**
+ * Returns the Vector4 squared length (float).
+ * @returns the length squared
+ */
+ lengthSquared() {
+ return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
+ }
+ // Methods
+ /**
+ * Normalizes in place the Vector4.
+ * @returns the updated Vector4.
+ */
+ normalize() {
+ return this.normalizeFromLength(this.length());
+ }
+ /**
+ * Normalize the current Vector4 with the given input length.
+ * Please note that this is an in place operation.
+ * @param len the length of the vector
+ * @returns the current updated Vector4
+ */
+ normalizeFromLength(len) {
+ if (len === 0 || len === 1.0) {
+ return this;
+ }
+ return this.scaleInPlace(1.0 / len);
+ }
+ /**
+ * Normalize the current Vector4 to a new vector
+ * @returns the new Vector4
+ */
+ normalizeToNew() {
+ return this.normalizeToRef(new Vector4());
+ }
+ /**
+ * Normalize the current Vector4 to the reference
+ * @param reference define the Vector4 to update
+ * @returns the updated Vector4
+ */
+ normalizeToRef(reference) {
+ const len = this.length();
+ if (len === 0 || len === 1.0) {
+ reference.x = this.x;
+ reference.y = this.y;
+ reference.z = this.z;
+ reference.w = this.w;
+ return reference;
+ }
+ return this.scaleToRef(1.0 / len, reference);
+ }
+ /**
+ * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
+ * @returns this converted to a new vector3
+ */
+ toVector3() {
+ return new Vector3(this.x, this.y, this.z);
+ }
+ /**
+ * Returns a new Vector4 copied from the current one.
+ * @returns the new cloned vector
+ */
+ clone() {
+ return new Vector4(this.x, this.y, this.z, this.w);
+ }
+ /**
+ * Updates the current Vector4 with the given one coordinates.
+ * @param source the source vector to copy from
+ * @returns the updated Vector4.
+ */
+ copyFrom(source) {
+ this.x = source.x;
+ this.y = source.y;
+ this.z = source.z;
+ this.w = source.w;
+ return this;
+ }
+ /**
+ * Updates the current Vector4 coordinates with the given floats.
+ * @param x float to copy from
+ * @param y float to copy from
+ * @param z float to copy from
+ * @param w float to copy from
+ * @returns the updated Vector4.
+ */
+ copyFromFloats(x, y, z, w) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.w = w;
+ return this;
+ }
+ /**
+ * Updates the current Vector4 coordinates with the given floats.
+ * @param x float to set from
+ * @param y float to set from
+ * @param z float to set from
+ * @param w float to set from
+ * @returns the updated Vector4.
+ */
+ set(x, y, z, w) {
+ return this.copyFromFloats(x, y, z, w);
+ }
+ /**
+ * Copies the given float to the current Vector4 coordinates
+ * @param v defines the x, y, z and w coordinates of the operand
+ * @returns the current updated Vector4
+ */
+ setAll(v) {
+ this.x = this.y = this.z = this.w = v;
+ return this;
+ }
+ /**
+ * Returns the dot product (float) between the current vectors and "otherVector"
+ * @param otherVector defines the right operand
+ * @returns the dot product
+ */
+ dot(otherVector) {
+ return this.x * otherVector.x + this.y * otherVector.y + this.z * otherVector.z + this.w * otherVector.w;
+ }
+ // Statics
+ /**
+ * Returns a new Vector4 set from the starting index of the given array.
+ * @param array the array to pull values from
+ * @param offset the offset into the array to start at
+ * @returns the new vector
+ */
+ static FromArray(array, offset) {
+ if (!offset) {
+ offset = 0;
+ }
+ return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
+ }
+ /**
+ * Updates the given vector "result" from the starting index of the given array.
+ * @param array the array to pull values from
+ * @param offset the offset into the array to start at
+ * @param result the vector to store the result in
+ * @returns result input
+ */
+ static FromArrayToRef(array, offset, result) {
+ result.x = array[offset];
+ result.y = array[offset + 1];
+ result.z = array[offset + 2];
+ result.w = array[offset + 3];
+ return result;
+ }
+ /**
+ * Updates the given vector "result" from the starting index of the given Float32Array.
+ * @param array the array to pull values from
+ * @param offset the offset into the array to start at
+ * @param result the vector to store the result in
+ * @returns result input
+ */
+ static FromFloatArrayToRef(array, offset, result) {
+ Vector4.FromArrayToRef(array, offset, result);
+ return result;
+ }
+ /**
+ * Updates the given vector "result" coordinates from the given floats.
+ * @param x float to set from
+ * @param y float to set from
+ * @param z float to set from
+ * @param w float to set from
+ * @param result the vector to the floats in
+ * @returns result input
+ */
+ static FromFloatsToRef(x, y, z, w, result) {
+ result.x = x;
+ result.y = y;
+ result.z = z;
+ result.w = w;
+ return result;
+ }
+ /**
+ * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
+ * @returns the new vector
+ */
+ static Zero() {
+ return new Vector4(0.0, 0.0, 0.0, 0.0);
+ }
+ /**
+ * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
+ * @returns the new vector
+ */
+ static One() {
+ return new Vector4(1.0, 1.0, 1.0, 1.0);
+ }
+ /**
+ * Returns a new Vector4 with random values between min and max
+ * @param min the minimum random value
+ * @param max the maximum random value
+ * @returns a Vector4 with random values between min and max
+ */
+ static Random(min = 0, max = 1) {
+ return new Vector4(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
+ }
+ /**
+ * Sets a Vector4 with random values between min and max
+ * @param min the minimum random value
+ * @param max the maximum random value
+ * @param ref the ref to store the values in
+ * @returns the ref with random values between min and max
+ */
+ static RandomToRef(min = 0, max = 1, ref) {
+ ref.x = RandomRange(min, max);
+ ref.y = RandomRange(min, max);
+ ref.z = RandomRange(min, max);
+ ref.w = RandomRange(min, max);
+ return ref;
+ }
+ /**
+ * Returns a new Vector4 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
+ * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
+ * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
+ * @param value defines the current value
+ * @param min defines the lower range value
+ * @param max defines the upper range value
+ * @returns the new Vector4
+ */
+ static Clamp(value, min, max) {
+ return Vector4.ClampToRef(value, min, max, new Vector4());
+ }
+ /**
+ * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
+ * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
+ * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
+ * @param value defines the current value
+ * @param min defines the lower range value
+ * @param max defines the upper range value
+ * @param result defines the Vector4 where to store the result
+ * @returns result input
+ */
+ static ClampToRef(value, min, max, result) {
+ result.x = Clamp(value.x, min.x, max.x);
+ result.y = Clamp(value.y, min.y, max.y);
+ result.z = Clamp(value.z, min.z, max.z);
+ result.w = Clamp(value.w, min.w, max.w);
+ return result;
+ }
+ /**
+ * Checks if a given vector is inside a specific range
+ * Example Playground https://playground.babylonjs.com/#R1F8YU#75
+ * @param v defines the vector to test
+ * @param min defines the minimum range
+ * @param max defines the maximum range
+ */
+ static CheckExtends(v, min, max) {
+ min.minimizeInPlace(v);
+ max.maximizeInPlace(v);
+ }
+ /**
+ * Gets a zero Vector4 that must not be updated
+ */
+ static get ZeroReadOnly() {
+ return Vector4._ZeroReadOnly;
+ }
+ /**
+ * Returns a new normalized Vector4 from the given one.
+ * @param vector the vector to normalize
+ * @returns the vector
+ */
+ static Normalize(vector) {
+ return Vector4.NormalizeToRef(vector, new Vector4());
+ }
+ /**
+ * Updates the given vector "result" from the normalization of the given one.
+ * @param vector the vector to normalize
+ * @param result the vector to store the result in
+ * @returns result input
+ */
+ static NormalizeToRef(vector, result) {
+ vector.normalizeToRef(result);
+ return result;
+ }
+ /**
+ * Returns a vector with the minimum values from the left and right vectors
+ * @param left left vector to minimize
+ * @param right right vector to minimize
+ * @returns a new vector with the minimum of the left and right vector values
+ */
+ static Minimize(left, right) {
+ const min = new Vector4();
+ min.copyFrom(left);
+ min.minimizeInPlace(right);
+ return min;
+ }
+ /**
+ * Returns a vector with the maximum values from the left and right vectors
+ * @param left left vector to maximize
+ * @param right right vector to maximize
+ * @returns a new vector with the maximum of the left and right vector values
+ */
+ static Maximize(left, right) {
+ const max = new Vector4();
+ max.copyFrom(left);
+ max.maximizeInPlace(right);
+ return max;
+ }
+ /**
+ * Returns the distance (float) between the vectors "value1" and "value2".
+ * @param value1 value to calulate the distance between
+ * @param value2 value to calulate the distance between
+ * @returns the distance between the two vectors
+ */
+ static Distance(value1, value2) {
+ return Math.sqrt(Vector4.DistanceSquared(value1, value2));
+ }
+ /**
+ * Returns the squared distance (float) between the vectors "value1" and "value2".
+ * @param value1 value to calulate the distance between
+ * @param value2 value to calulate the distance between
+ * @returns the distance between the two vectors squared
+ */
+ static DistanceSquared(value1, value2) {
+ const x = value1.x - value2.x;
+ const y = value1.y - value2.y;
+ const z = value1.z - value2.z;
+ const w = value1.w - value2.w;
+ return x * x + y * y + z * z + w * w;
+ }
+ /**
+ * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
+ * @param value1 value to calulate the center between
+ * @param value2 value to calulate the center between
+ * @returns the center between the two vectors
+ */
+ static Center(value1, value2) {
+ return Vector4.CenterToRef(value1, value2, new Vector4());
+ }
+ /**
+ * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref"
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @param ref defines third vector
+ * @returns ref
+ */
+ static CenterToRef(value1, value2, ref) {
+ ref.x = (value1.x + value2.x) / 2;
+ ref.y = (value1.y + value2.y) / 2;
+ ref.z = (value1.z + value2.z) / 2;
+ ref.w = (value1.w + value2.w) / 2;
+ return ref;
+ }
+ /**
+ * Returns a new Vector4 set with the result of the transformation by the given matrix of the given vector.
+ * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
+ * The difference with Vector3.TransformCoordinates is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead
+ * @param vector defines the Vector3 to transform
+ * @param transformation defines the transformation matrix
+ * @returns the transformed Vector4
+ */
+ static TransformCoordinates(vector, transformation) {
+ return Vector4.TransformCoordinatesToRef(vector, transformation, new Vector4());
+ }
+ /**
+ * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
+ * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
+ * The difference with Vector3.TransformCoordinatesToRef is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead
+ * @param vector defines the Vector3 to transform
+ * @param transformation defines the transformation matrix
+ * @param result defines the Vector4 where to store the result
+ * @returns result input
+ */
+ static TransformCoordinatesToRef(vector, transformation, result) {
+ Vector4.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result);
+ return result;
+ }
+ /**
+ * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
+ * This method computes tranformed coordinates only, not transformed direction vectors
+ * The difference with Vector3.TransformCoordinatesFromFloatsToRef is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead
+ * @param x define the x coordinate of the source vector
+ * @param y define the y coordinate of the source vector
+ * @param z define the z coordinate of the source vector
+ * @param transformation defines the transformation matrix
+ * @param result defines the Vector4 where to store the result
+ * @returns result input
+ */
+ static TransformCoordinatesFromFloatsToRef(x, y, z, transformation, result) {
+ const m = transformation.m;
+ const rx = x * m[0] + y * m[4] + z * m[8] + m[12];
+ const ry = x * m[1] + y * m[5] + z * m[9] + m[13];
+ const rz = x * m[2] + y * m[6] + z * m[10] + m[14];
+ const rw = x * m[3] + y * m[7] + z * m[11] + m[15];
+ result.x = rx;
+ result.y = ry;
+ result.z = rz;
+ result.w = rw;
+ return result;
+ }
+ /**
+ * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
+ * This methods computes transformed normalized direction vectors only.
+ * @param vector the vector to transform
+ * @param transformation the transformation matrix to apply
+ * @returns the new vector
+ */
+ static TransformNormal(vector, transformation) {
+ return Vector4.TransformNormalToRef(vector, transformation, new Vector4());
+ }
+ /**
+ * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
+ * This methods computes transformed normalized direction vectors only.
+ * @param vector the vector to transform
+ * @param transformation the transformation matrix to apply
+ * @param result the vector to store the result in
+ * @returns result input
+ */
+ static TransformNormalToRef(vector, transformation, result) {
+ const m = transformation.m;
+ const x = vector.x * m[0] + vector.y * m[4] + vector.z * m[8];
+ const y = vector.x * m[1] + vector.y * m[5] + vector.z * m[9];
+ const z = vector.x * m[2] + vector.y * m[6] + vector.z * m[10];
+ result.x = x;
+ result.y = y;
+ result.z = z;
+ result.w = vector.w;
+ return result;
+ }
+ /**
+ * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
+ * This methods computes transformed normalized direction vectors only.
+ * @param x value to transform
+ * @param y value to transform
+ * @param z value to transform
+ * @param w value to transform
+ * @param transformation the transformation matrix to apply
+ * @param result the vector to store the results in
+ * @returns result input
+ */
+ static TransformNormalFromFloatsToRef(x, y, z, w, transformation, result) {
+ const m = transformation.m;
+ result.x = x * m[0] + y * m[4] + z * m[8];
+ result.y = x * m[1] + y * m[5] + z * m[9];
+ result.z = x * m[2] + y * m[6] + z * m[10];
+ result.w = w;
+ return result;
+ }
+ /**
+ * Creates a new Vector4 from a Vector3
+ * @param source defines the source data
+ * @param w defines the 4th component (default is 0)
+ * @returns a new Vector4
+ */
+ static FromVector3(source, w = 0) {
+ return new Vector4(source._x, source._y, source._z, w);
+ }
+ /**
+ * Returns the dot product (float) between the vectors "left" and "right"
+ * @param left defines the left operand
+ * @param right defines the right operand
+ * @returns the dot product
+ */
+ static Dot(left, right) {
+ return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
+ }
+}
+/**
+ * If the first vector is flagged with integers (as everything is 0,0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet.
+ * If subsequent vectors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers,
+ * and henceforth it will use floating-point representation for all Vector4 instances that it creates.
+ * But the original Vector4 instances are unchanged and has a "deprecated map".
+ * If we keep using the Vector4 instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches.
+ */
+Vector4._V8PerformanceHack = new Vector4(0.5, 0.5, 0.5, 0.5);
+Vector4._ZeroReadOnly = Vector4.Zero();
+Object.defineProperties(Vector4.prototype, {
+ dimension: { value: [4] },
+ rank: { value: 1 },
+});
+/**
+ * Class used to store quaternion data
+ * Example Playground - Overview - https://playground.babylonjs.com/#L49EJ7#100
+ * @see https://en.wikipedia.org/wiki/Quaternion
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms
+ */
+class Quaternion {
+ /** Gets or sets the x coordinate */
+ get x() {
+ return this._x;
+ }
+ set x(value) {
+ this._x = value;
+ this._isDirty = true;
+ }
+ /** Gets or sets the y coordinate */
+ get y() {
+ return this._y;
+ }
+ set y(value) {
+ this._y = value;
+ this._isDirty = true;
+ }
+ /** Gets or sets the z coordinate */
+ get z() {
+ return this._z;
+ }
+ set z(value) {
+ this._z = value;
+ this._isDirty = true;
+ }
+ /** Gets or sets the w coordinate */
+ get w() {
+ return this._w;
+ }
+ set w(value) {
+ this._w = value;
+ this._isDirty = true;
+ }
+ /**
+ * Creates a new Quaternion from the given floats
+ * @param x defines the first component (0 by default)
+ * @param y defines the second component (0 by default)
+ * @param z defines the third component (0 by default)
+ * @param w defines the fourth component (1.0 by default)
+ */
+ constructor(x = 0.0, y = 0.0, z = 0.0, w = 1.0) {
+ /** @internal */
+ this._isDirty = true;
+ this._x = x;
+ this._y = y;
+ this._z = z;
+ this._w = w;
+ }
+ /**
+ * Gets a string representation for the current quaternion
+ * @returns a string with the Quaternion coordinates
+ */
+ toString() {
+ return `{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`;
+ }
+ /**
+ * Gets the class name of the quaternion
+ * @returns the string "Quaternion"
+ */
+ getClassName() {
+ return "Quaternion";
+ }
+ /**
+ * Gets a hash code for this quaternion
+ * @returns the quaternion hash code
+ */
+ getHashCode() {
+ const x = _ExtractAsInt(this._x);
+ const y = _ExtractAsInt(this._y);
+ const z = _ExtractAsInt(this._z);
+ const w = _ExtractAsInt(this._w);
+ let hash = x;
+ hash = (hash * 397) ^ y;
+ hash = (hash * 397) ^ z;
+ hash = (hash * 397) ^ w;
+ return hash;
+ }
+ /**
+ * Copy the quaternion to an array
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#13
+ * @returns a new array populated with 4 elements from the quaternion coordinates
+ */
+ asArray() {
+ return [this._x, this._y, this._z, this._w];
+ }
+ /**
+ * Stores from the starting index in the given array the Quaternion successive values
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#59
+ * @param array defines the array where to store the x,y,z,w components
+ * @param index defines an optional index in the target array to define where to start storing values
+ * @returns the current Quaternion object
+ */
+ toArray(array, index = 0) {
+ array[index] = this._x;
+ array[index + 1] = this._y;
+ array[index + 2] = this._z;
+ array[index + 3] = this._w;
+ return this;
+ }
+ fromArray(array, index = 0) {
+ return Quaternion.FromArrayToRef(array, index, this);
+ }
+ /**
+ * Check if two quaternions are equals
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#38
+ * @param otherQuaternion defines the second operand
+ * @returns true if the current quaternion and the given one coordinates are strictly equals
+ */
+ equals(otherQuaternion) {
+ return otherQuaternion && this._x === otherQuaternion._x && this._y === otherQuaternion._y && this._z === otherQuaternion._z && this._w === otherQuaternion._w;
+ }
+ /**
+ * Gets a boolean if two quaternions are equals (using an epsilon value)
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#37
+ * @param otherQuaternion defines the other quaternion
+ * @param epsilon defines the minimal distance to consider equality
+ * @returns true if the given quaternion coordinates are close to the current ones by a distance of epsilon.
+ */
+ equalsWithEpsilon(otherQuaternion, epsilon = Epsilon) {
+ return (otherQuaternion &&
+ WithinEpsilon(this._x, otherQuaternion._x, epsilon) &&
+ WithinEpsilon(this._y, otherQuaternion._y, epsilon) &&
+ WithinEpsilon(this._z, otherQuaternion._z, epsilon) &&
+ WithinEpsilon(this._w, otherQuaternion._w, epsilon));
+ }
+ /**
+ * Gets a boolean if two quaternions are equals (using an epsilon value), taking care of double cover : https://www.reedbeta.com/blog/why-quaternions-double-cover/
+ * @param otherQuaternion defines the other quaternion
+ * @param epsilon defines the minimal distance to consider equality
+ * @returns true if the given quaternion coordinates are close to the current ones by a distance of epsilon.
+ */
+ isApprox(otherQuaternion, epsilon = Epsilon) {
+ return (otherQuaternion &&
+ ((WithinEpsilon(this._x, otherQuaternion._x, epsilon) &&
+ WithinEpsilon(this._y, otherQuaternion._y, epsilon) &&
+ WithinEpsilon(this._z, otherQuaternion._z, epsilon) &&
+ WithinEpsilon(this._w, otherQuaternion._w, epsilon)) ||
+ (WithinEpsilon(this._x, -otherQuaternion._x, epsilon) &&
+ WithinEpsilon(this._y, -otherQuaternion._y, epsilon) &&
+ WithinEpsilon(this._z, -otherQuaternion._z, epsilon) &&
+ WithinEpsilon(this._w, -otherQuaternion._w, epsilon))));
+ }
+ /**
+ * Clone the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#12
+ * @returns a new quaternion copied from the current one
+ */
+ clone() {
+ return new Quaternion(this._x, this._y, this._z, this._w);
+ }
+ /**
+ * Copy a quaternion to the current one
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#86
+ * @param other defines the other quaternion
+ * @returns the updated current quaternion
+ */
+ copyFrom(other) {
+ this._x = other._x;
+ this._y = other._y;
+ this._z = other._z;
+ this._w = other._w;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Updates the current quaternion with the given float coordinates
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#87
+ * @param x defines the x coordinate
+ * @param y defines the y coordinate
+ * @param z defines the z coordinate
+ * @param w defines the w coordinate
+ * @returns the updated current quaternion
+ */
+ copyFromFloats(x, y, z, w) {
+ this._x = x;
+ this._y = y;
+ this._z = z;
+ this._w = w;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Updates the current quaternion from the given float coordinates
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#56
+ * @param x defines the x coordinate
+ * @param y defines the y coordinate
+ * @param z defines the z coordinate
+ * @param w defines the w coordinate
+ * @returns the updated current quaternion
+ */
+ set(x, y, z, w) {
+ return this.copyFromFloats(x, y, z, w);
+ }
+ setAll(value) {
+ return this.copyFromFloats(value, value, value, value);
+ }
+ /**
+ * Adds two quaternions
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#10
+ * @param other defines the second operand
+ * @returns a new quaternion as the addition result of the given one and the current quaternion
+ */
+ add(other) {
+ return new Quaternion(this._x + other._x, this._y + other._y, this._z + other._z, this._w + other._w);
+ }
+ /**
+ * Add a quaternion to the current one
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#11
+ * @param other defines the quaternion to add
+ * @returns the current quaternion
+ */
+ addInPlace(other) {
+ this._x += other._x;
+ this._y += other._y;
+ this._z += other._z;
+ this._w += other._w;
+ this._isDirty = true;
+ return this;
+ }
+ addToRef(other, result) {
+ result._x = this._x + other._x;
+ result._y = this._y + other._y;
+ result._z = this._z + other._z;
+ result._w = this._w + other._w;
+ result._isDirty = true;
+ return result;
+ }
+ addInPlaceFromFloats(x, y, z, w) {
+ this._x += x;
+ this._y += y;
+ this._z += z;
+ this._w += w;
+ this._isDirty = true;
+ return this;
+ }
+ subtractToRef(other, result) {
+ result._x = this._x - other._x;
+ result._y = this._y - other._y;
+ result._z = this._z - other._z;
+ result._w = this._w - other._w;
+ result._isDirty = true;
+ return result;
+ }
+ subtractFromFloats(x, y, z, w) {
+ return this.subtractFromFloatsToRef(x, y, z, w, new Quaternion());
+ }
+ subtractFromFloatsToRef(x, y, z, w, result) {
+ result._x = this._x - x;
+ result._y = this._y - y;
+ result._z = this._z - z;
+ result._w = this._w - w;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Subtract two quaternions
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#57
+ * @param other defines the second operand
+ * @returns a new quaternion as the subtraction result of the given one from the current one
+ */
+ subtract(other) {
+ return new Quaternion(this._x - other._x, this._y - other._y, this._z - other._z, this._w - other._w);
+ }
+ /**
+ * Subtract a quaternion to the current one
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#58
+ * @param other defines the quaternion to subtract
+ * @returns the current quaternion
+ */
+ subtractInPlace(other) {
+ this._x -= other._x;
+ this._y -= other._y;
+ this._z -= other._z;
+ this._w -= other._w;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Multiplies the current quaternion by a scale factor
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#88
+ * @param value defines the scale factor
+ * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
+ */
+ scale(value) {
+ return new Quaternion(this._x * value, this._y * value, this._z * value, this._w * value);
+ }
+ /**
+ * Scale the current quaternion values by a factor and stores the result to a given quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#89
+ * @param scale defines the scale factor
+ * @param result defines the Quaternion object where to store the result
+ * @returns result input
+ */
+ scaleToRef(scale, result) {
+ result._x = this._x * scale;
+ result._y = this._y * scale;
+ result._z = this._z * scale;
+ result._w = this._w * scale;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Multiplies in place the current quaternion by a scale factor
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#90
+ * @param value defines the scale factor
+ * @returns the current modified quaternion
+ */
+ scaleInPlace(value) {
+ this._x *= value;
+ this._y *= value;
+ this._z *= value;
+ this._w *= value;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Scale the current quaternion values by a factor and add the result to a given quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#91
+ * @param scale defines the scale factor
+ * @param result defines the Quaternion object where to store the result
+ * @returns result input
+ */
+ scaleAndAddToRef(scale, result) {
+ result._x += this._x * scale;
+ result._y += this._y * scale;
+ result._z += this._z * scale;
+ result._w += this._w * scale;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Multiplies two quaternions
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#43
+ * @param q1 defines the second operand
+ * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
+ */
+ multiply(q1) {
+ const result = new Quaternion(0, 0, 0, 1.0);
+ this.multiplyToRef(q1, result);
+ return result;
+ }
+ /**
+ * Sets the given "result" as the multiplication result of the current one with the given one "q1"
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#45
+ * @param q1 defines the second operand
+ * @param result defines the target quaternion
+ * @returns the current quaternion
+ */
+ multiplyToRef(q1, result) {
+ const x = this._x * q1._w + this._y * q1._z - this._z * q1._y + this._w * q1._x;
+ const y = -this._x * q1._z + this._y * q1._w + this._z * q1._x + this._w * q1._y;
+ const z = this._x * q1._y - this._y * q1._x + this._z * q1._w + this._w * q1._z;
+ const w = -this._x * q1._x - this._y * q1._y - this._z * q1._z + this._w * q1._w;
+ result.copyFromFloats(x, y, z, w);
+ return result;
+ }
+ /**
+ * Updates the current quaternion with the multiplication of itself with the given one "q1"
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#46
+ * @param other defines the second operand
+ * @returns the currentupdated quaternion
+ */
+ multiplyInPlace(other) {
+ return this.multiplyToRef(other, this);
+ }
+ multiplyByFloats(x, y, z, w) {
+ this._x *= x;
+ this._y *= y;
+ this._z *= z;
+ this._w *= w;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divide(_other) {
+ throw new ReferenceError("Can not divide a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divideToRef(_other, _result) {
+ throw new ReferenceError("Can not divide a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divideInPlace(_other) {
+ throw new ReferenceError("Can not divide a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ minimizeInPlace() {
+ throw new ReferenceError("Can not minimize a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ minimizeInPlaceFromFloats() {
+ throw new ReferenceError("Can not minimize a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ maximizeInPlace() {
+ throw new ReferenceError("Can not maximize a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ maximizeInPlaceFromFloats() {
+ throw new ReferenceError("Can not maximize a quaternion");
+ }
+ negate() {
+ return this.negateToRef(new Quaternion());
+ }
+ negateInPlace() {
+ this._x = -this._x;
+ this._y = -this._y;
+ this._z = -this._z;
+ this._w = -this._w;
+ this._isDirty = true;
+ return this;
+ }
+ negateToRef(result) {
+ result._x = -this._x;
+ result._y = -this._y;
+ result._z = -this._z;
+ result._w = -this._w;
+ result._isDirty = true;
+ return result;
+ }
+ equalsToFloats(x, y, z, w) {
+ return this._x === x && this._y === y && this._z === z && this._w === w;
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ floorToRef(_result) {
+ throw new ReferenceError("Can not floor a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ floor() {
+ throw new ReferenceError("Can not floor a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ fractToRef(_result) {
+ throw new ReferenceError("Can not fract a quaternion");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ fract() {
+ throw new ReferenceError("Can not fract a quaternion");
+ }
+ /**
+ * Conjugates the current quaternion and stores the result in the given quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#81
+ * @param ref defines the target quaternion
+ * @returns result input
+ */
+ conjugateToRef(ref) {
+ ref.copyFromFloats(-this._x, -this._y, -this._z, this._w);
+ return ref;
+ }
+ /**
+ * Conjugates in place the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#82
+ * @returns the current updated quaternion
+ */
+ conjugateInPlace() {
+ this._x *= -1;
+ this._y *= -1;
+ this._z *= -1;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Conjugates (1-q) the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#83
+ * @returns a new quaternion
+ */
+ conjugate() {
+ return new Quaternion(-this._x, -this._y, -this._z, this._w);
+ }
+ /**
+ * Returns the inverse of the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#84
+ * @returns a new quaternion
+ */
+ invert() {
+ const conjugate = this.conjugate();
+ const lengthSquared = this.lengthSquared();
+ if (lengthSquared == 0 || lengthSquared == 1) {
+ return conjugate;
+ }
+ conjugate.scaleInPlace(1 / lengthSquared);
+ return conjugate;
+ }
+ /**
+ * Invert in place the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#85
+ * @returns this quaternion
+ */
+ invertInPlace() {
+ this.conjugateInPlace();
+ const lengthSquared = this.lengthSquared();
+ if (lengthSquared == 0 || lengthSquared == 1) {
+ return this;
+ }
+ this.scaleInPlace(1 / lengthSquared);
+ return this;
+ }
+ /**
+ * Gets squared length of current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#29
+ * @returns the quaternion length (float)
+ */
+ lengthSquared() {
+ return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
+ }
+ /**
+ * Gets length of current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#28
+ * @returns the quaternion length (float)
+ */
+ length() {
+ return Math.sqrt(this.lengthSquared());
+ }
+ /**
+ * Normalize in place the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#54
+ * @returns the current updated quaternion
+ */
+ normalize() {
+ return this.normalizeFromLength(this.length());
+ }
+ /**
+ * Normalize the current quaternion with the given input length.
+ * Please note that this is an in place operation.
+ * @param len the length of the quaternion
+ * @returns the current updated Quaternion
+ */
+ normalizeFromLength(len) {
+ if (len === 0 || len === 1.0) {
+ return this;
+ }
+ return this.scaleInPlace(1.0 / len);
+ }
+ /**
+ * Normalize a copy of the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#55
+ * @returns the normalized quaternion
+ */
+ normalizeToNew() {
+ const normalized = new Quaternion(0, 0, 0, 1);
+ this.normalizeToRef(normalized);
+ return normalized;
+ }
+ /**
+ * Normalize the current Quaternion to the reference
+ * @param reference define the Quaternion to update
+ * @returns the updated Quaternion
+ */
+ normalizeToRef(reference) {
+ const len = this.length();
+ if (len === 0 || len === 1.0) {
+ return reference.copyFromFloats(this._x, this._y, this._z, this._w);
+ }
+ return this.scaleToRef(1.0 / len, reference);
+ }
+ /**
+ * Returns a new Vector3 set with the Euler angles translated from the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#32
+ * @returns a new Vector3 containing the Euler angles
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions
+ */
+ toEulerAngles() {
+ const result = Vector3.Zero();
+ this.toEulerAnglesToRef(result);
+ return result;
+ }
+ /**
+ * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#31
+ * @param result defines the vector which will be filled with the Euler angles
+ * @returns result input
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions
+ */
+ toEulerAnglesToRef(result) {
+ const qz = this._z;
+ const qx = this._x;
+ const qy = this._y;
+ const qw = this._w;
+ const zAxisY = qy * qz - qx * qw;
+ const limit = 0.4999999;
+ if (zAxisY < -limit) {
+ result._y = 2 * Math.atan2(qy, qw);
+ result._x = Math.PI / 2;
+ result._z = 0;
+ result._isDirty = true;
+ }
+ else if (zAxisY > limit) {
+ result._y = 2 * Math.atan2(qy, qw);
+ result._x = -Math.PI / 2;
+ result._z = 0;
+ result._isDirty = true;
+ }
+ else {
+ const sqw = qw * qw;
+ const sqz = qz * qz;
+ const sqx = qx * qx;
+ const sqy = qy * qy;
+ result._z = Math.atan2(2.0 * (qx * qy + qz * qw), -sqz - sqx + sqy + sqw);
+ result._x = Math.asin(-2 * zAxisY);
+ result._y = Math.atan2(2.0 * (qz * qx + qy * qw), sqz - sqx - sqy + sqw);
+ result._isDirty = true;
+ }
+ return result;
+ }
+ /**
+ * Sets the given vector3 "result" with the Alpha, Beta, Gamma Euler angles translated from the current quaternion
+ * @param result defines the vector which will be filled with the Euler angles
+ * @returns result input
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions
+ */
+ toAlphaBetaGammaToRef(result) {
+ const qz = this._z;
+ const qx = this._x;
+ const qy = this._y;
+ const qw = this._w;
+ // Compute intermediate values
+ const sinHalfBeta = Math.sqrt(qx * qx + qy * qy);
+ const cosHalfBeta = Math.sqrt(qz * qz + qw * qw);
+ // Calculate beta
+ const beta = 2 * Math.atan2(sinHalfBeta, cosHalfBeta);
+ // Calculate gamma + alpha
+ const gammaPlusAlpha = 2 * Math.atan2(qz, qw);
+ // Calculate gamma - alpha
+ const gammaMinusAlpha = 2 * Math.atan2(qy, qx);
+ // Calculate gamma and alpha
+ const gamma = (gammaPlusAlpha + gammaMinusAlpha) / 2;
+ const alpha = (gammaPlusAlpha - gammaMinusAlpha) / 2;
+ result.set(alpha, beta, gamma);
+ return result;
+ }
+ /**
+ * Updates the given rotation matrix with the current quaternion values
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#67
+ * @param result defines the target matrix
+ * @returns the updated matrix with the rotation
+ */
+ toRotationMatrix(result) {
+ Matrix.FromQuaternionToRef(this, result);
+ return result;
+ }
+ /**
+ * Updates the current quaternion from the given rotation matrix values
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#41
+ * @param matrix defines the source matrix
+ * @returns the current updated quaternion
+ */
+ fromRotationMatrix(matrix) {
+ Quaternion.FromRotationMatrixToRef(matrix, this);
+ return this;
+ }
+ /**
+ * Returns the dot product (float) between the current quaternions and "other"
+ * @param other defines the right operand
+ * @returns the dot product
+ */
+ dot(other) {
+ return this._x * other._x + this._y * other._y + this._z * other._z + this._w * other._w;
+ }
+ // Statics
+ /**
+ * Creates a new quaternion from a rotation matrix
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#101
+ * @param matrix defines the source matrix
+ * @returns a new quaternion created from the given rotation matrix values
+ */
+ static FromRotationMatrix(matrix) {
+ const result = new Quaternion();
+ Quaternion.FromRotationMatrixToRef(matrix, result);
+ return result;
+ }
+ /**
+ * Updates the given quaternion with the given rotation matrix values
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#102
+ * @param matrix defines the source matrix
+ * @param result defines the target quaternion
+ * @returns result input
+ */
+ static FromRotationMatrixToRef(matrix, result) {
+ const data = matrix.m;
+ const m11 = data[0], m12 = data[4], m13 = data[8];
+ const m21 = data[1], m22 = data[5], m23 = data[9];
+ const m31 = data[2], m32 = data[6], m33 = data[10];
+ const trace = m11 + m22 + m33;
+ let s;
+ if (trace > 0) {
+ s = 0.5 / Math.sqrt(trace + 1.0);
+ result._w = 0.25 / s;
+ result._x = (m32 - m23) * s;
+ result._y = (m13 - m31) * s;
+ result._z = (m21 - m12) * s;
+ result._isDirty = true;
+ }
+ else if (m11 > m22 && m11 > m33) {
+ s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
+ result._w = (m32 - m23) / s;
+ result._x = 0.25 * s;
+ result._y = (m12 + m21) / s;
+ result._z = (m13 + m31) / s;
+ result._isDirty = true;
+ }
+ else if (m22 > m33) {
+ s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
+ result._w = (m13 - m31) / s;
+ result._x = (m12 + m21) / s;
+ result._y = 0.25 * s;
+ result._z = (m23 + m32) / s;
+ result._isDirty = true;
+ }
+ else {
+ s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
+ result._w = (m21 - m12) / s;
+ result._x = (m13 + m31) / s;
+ result._y = (m23 + m32) / s;
+ result._z = 0.25 * s;
+ result._isDirty = true;
+ }
+ return result;
+ }
+ /**
+ * Returns the dot product (float) between the quaternions "left" and "right"
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#61
+ * @param left defines the left operand
+ * @param right defines the right operand
+ * @returns the dot product
+ */
+ static Dot(left, right) {
+ return left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w;
+ }
+ /**
+ * Checks if the orientations of two rotation quaternions are close to each other
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#60
+ * @param quat0 defines the first quaternion to check
+ * @param quat1 defines the second quaternion to check
+ * @param epsilon defines closeness, 0 same orientation, 1 PI apart, default 0.1
+ * @returns true if the two quaternions are close to each other within epsilon
+ */
+ static AreClose(quat0, quat1, epsilon = 0.1) {
+ const dot = Quaternion.Dot(quat0, quat1);
+ return 1 - dot * dot <= epsilon;
+ }
+ /**
+ * Smooth interpolation between two quaternions using Slerp
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#93
+ * @param source source quaternion
+ * @param goal goal quaternion
+ * @param deltaTime current interpolation frame
+ * @param lerpTime total interpolation time
+ * @param result the smoothed quaternion
+ * @returns the smoothed quaternion
+ */
+ static SmoothToRef(source, goal, deltaTime, lerpTime, result) {
+ let slerp = lerpTime === 0 ? 1 : deltaTime / lerpTime;
+ slerp = Clamp(slerp, 0, 1);
+ Quaternion.SlerpToRef(source, goal, slerp, result);
+ return result;
+ }
+ /**
+ * Creates an empty quaternion
+ * @returns a new quaternion set to (0.0, 0.0, 0.0)
+ */
+ static Zero() {
+ return new Quaternion(0.0, 0.0, 0.0, 0.0);
+ }
+ /**
+ * Inverse a given quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#103
+ * @param q defines the source quaternion
+ * @returns a new quaternion as the inverted current quaternion
+ */
+ static Inverse(q) {
+ return new Quaternion(-q._x, -q._y, -q._z, q._w);
+ }
+ /**
+ * Inverse a given quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#104
+ * @param q defines the source quaternion
+ * @param result the quaternion the result will be stored in
+ * @returns the result quaternion
+ */
+ static InverseToRef(q, result) {
+ result.set(-q._x, -q._y, -q._z, q._w);
+ return result;
+ }
+ /**
+ * Creates an identity quaternion
+ * @returns the identity quaternion
+ */
+ static Identity() {
+ return new Quaternion(0.0, 0.0, 0.0, 1.0);
+ }
+ /**
+ * Gets a boolean indicating if the given quaternion is identity
+ * @param quaternion defines the quaternion to check
+ * @returns true if the quaternion is identity
+ */
+ static IsIdentity(quaternion) {
+ return quaternion && quaternion._x === 0 && quaternion._y === 0 && quaternion._z === 0 && quaternion._w === 1;
+ }
+ /**
+ * Creates a quaternion from a rotation around an axis
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#72
+ * @param axis defines the axis to use
+ * @param angle defines the angle to use
+ * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
+ */
+ static RotationAxis(axis, angle) {
+ return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
+ }
+ /**
+ * Creates a rotation around an axis and stores it into the given quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#73
+ * @param axis defines the axis to use
+ * @param angle defines the angle to use
+ * @param result defines the target quaternion
+ * @returns the target quaternion
+ */
+ static RotationAxisToRef(axis, angle, result) {
+ result._w = Math.cos(angle / 2);
+ const sinByLength = Math.sin(angle / 2) / axis.length();
+ result._x = axis._x * sinByLength;
+ result._y = axis._y * sinByLength;
+ result._z = axis._z * sinByLength;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Creates a new quaternion from data stored into an array
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#63
+ * @param array defines the data source
+ * @param offset defines the offset in the source array where the data starts
+ * @returns a new quaternion
+ */
+ static FromArray(array, offset) {
+ if (!offset) {
+ offset = 0;
+ }
+ return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
+ }
+ /**
+ * Updates the given quaternion "result" from the starting index of the given array.
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#64
+ * @param array the array to pull values from
+ * @param offset the offset into the array to start at
+ * @param result the quaternion to store the result in
+ * @returns result input
+ */
+ static FromArrayToRef(array, offset, result) {
+ result._x = array[offset];
+ result._y = array[offset + 1];
+ result._z = array[offset + 2];
+ result._w = array[offset + 3];
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Sets the given quaternion "result" with the given floats.
+ * @param x defines the x coordinate of the source
+ * @param y defines the y coordinate of the source
+ * @param z defines the z coordinate of the source
+ * @param w defines the w coordinate of the source
+ * @param result defines the quaternion where to store the result
+ * @returns the result quaternion
+ */
+ static FromFloatsToRef(x, y, z, w, result) {
+ result.copyFromFloats(x, y, z, w);
+ return result;
+ }
+ /**
+ * Create a quaternion from Euler rotation angles
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#33
+ * @param x Pitch
+ * @param y Yaw
+ * @param z Roll
+ * @returns the new Quaternion
+ */
+ static FromEulerAngles(x, y, z) {
+ const q = new Quaternion();
+ Quaternion.RotationYawPitchRollToRef(y, x, z, q);
+ return q;
+ }
+ /**
+ * Updates a quaternion from Euler rotation angles
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#34
+ * @param x Pitch
+ * @param y Yaw
+ * @param z Roll
+ * @param result the quaternion to store the result
+ * @returns the updated quaternion
+ */
+ static FromEulerAnglesToRef(x, y, z, result) {
+ Quaternion.RotationYawPitchRollToRef(y, x, z, result);
+ return result;
+ }
+ /**
+ * Create a quaternion from Euler rotation vector
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#35
+ * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
+ * @returns the new Quaternion
+ */
+ static FromEulerVector(vec) {
+ const q = new Quaternion();
+ Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, q);
+ return q;
+ }
+ /**
+ * Updates a quaternion from Euler rotation vector
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#36
+ * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
+ * @param result the quaternion to store the result
+ * @returns the updated quaternion
+ */
+ static FromEulerVectorToRef(vec, result) {
+ Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, result);
+ return result;
+ }
+ /**
+ * Updates a quaternion so that it rotates vector vecFrom to vector vecTo
+ * Example Playground - https://playground.babylonjs.com/#L49EJ7#70
+ * @param vecFrom defines the direction vector from which to rotate
+ * @param vecTo defines the direction vector to which to rotate
+ * @param result the quaternion to store the result
+ * @param epsilon defines the minimal dot value to define vecs as opposite. Default: `BABYLON.Epsilon`
+ * @returns the updated quaternion
+ */
+ static FromUnitVectorsToRef(vecFrom, vecTo, result, epsilon = Epsilon) {
+ const r = Vector3.Dot(vecFrom, vecTo) + 1;
+ if (r < epsilon) {
+ if (Math.abs(vecFrom.x) > Math.abs(vecFrom.z)) {
+ result.set(-vecFrom.y, vecFrom.x, 0, 0);
+ }
+ else {
+ result.set(0, -vecFrom.z, vecFrom.y, 0);
+ }
+ }
+ else {
+ Vector3.CrossToRef(vecFrom, vecTo, TmpVectors.Vector3[0]);
+ result.set(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z, r);
+ }
+ return result.normalize();
+ }
+ /**
+ * Creates a new quaternion from the given Euler float angles (y, x, z)
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#77
+ * @param yaw defines the rotation around Y axis
+ * @param pitch defines the rotation around X axis
+ * @param roll defines the rotation around Z axis
+ * @returns the new quaternion
+ */
+ static RotationYawPitchRoll(yaw, pitch, roll) {
+ const q = new Quaternion();
+ Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
+ return q;
+ }
+ /**
+ * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#78
+ * @param yaw defines the rotation around Y axis
+ * @param pitch defines the rotation around X axis
+ * @param roll defines the rotation around Z axis
+ * @param result defines the target quaternion
+ * @returns result input
+ */
+ static RotationYawPitchRollToRef(yaw, pitch, roll, result) {
+ // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
+ const halfRoll = roll * 0.5;
+ const halfPitch = pitch * 0.5;
+ const halfYaw = yaw * 0.5;
+ const sinRoll = Math.sin(halfRoll);
+ const cosRoll = Math.cos(halfRoll);
+ const sinPitch = Math.sin(halfPitch);
+ const cosPitch = Math.cos(halfPitch);
+ const sinYaw = Math.sin(halfYaw);
+ const cosYaw = Math.cos(halfYaw);
+ result._x = cosYaw * sinPitch * cosRoll + sinYaw * cosPitch * sinRoll;
+ result._y = sinYaw * cosPitch * cosRoll - cosYaw * sinPitch * sinRoll;
+ result._z = cosYaw * cosPitch * sinRoll - sinYaw * sinPitch * cosRoll;
+ result._w = cosYaw * cosPitch * cosRoll + sinYaw * sinPitch * sinRoll;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#68
+ * @param alpha defines the rotation around first axis
+ * @param beta defines the rotation around second axis
+ * @param gamma defines the rotation around third axis
+ * @returns the new quaternion
+ */
+ static RotationAlphaBetaGamma(alpha, beta, gamma) {
+ const result = new Quaternion();
+ Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
+ return result;
+ }
+ /**
+ * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#69
+ * @param alpha defines the rotation around first axis
+ * @param beta defines the rotation around second axis
+ * @param gamma defines the rotation around third axis
+ * @param result defines the target quaternion
+ * @returns result input
+ */
+ static RotationAlphaBetaGammaToRef(alpha, beta, gamma, result) {
+ // Produces a quaternion from Euler angles in the z-x-z orientation
+ const halfGammaPlusAlpha = (gamma + alpha) * 0.5;
+ const halfGammaMinusAlpha = (gamma - alpha) * 0.5;
+ const halfBeta = beta * 0.5;
+ result._x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
+ result._y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
+ result._z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
+ result._w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#75
+ * @param axis1 defines the first axis
+ * @param axis2 defines the second axis
+ * @param axis3 defines the third axis
+ * @returns the new quaternion
+ */
+ static RotationQuaternionFromAxis(axis1, axis2, axis3) {
+ const quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
+ Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
+ return quat;
+ }
+ /**
+ * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#76
+ * @param axis1 defines the first axis
+ * @param axis2 defines the second axis
+ * @param axis3 defines the third axis
+ * @param ref defines the target quaternion
+ * @returns result input
+ */
+ static RotationQuaternionFromAxisToRef(axis1, axis2, axis3, ref) {
+ const rotMat = MathTmp.Matrix[0];
+ axis1 = axis1.normalizeToRef(MathTmp.Vector3[0]);
+ axis2 = axis2.normalizeToRef(MathTmp.Vector3[1]);
+ axis3 = axis3.normalizeToRef(MathTmp.Vector3[2]);
+ Matrix.FromXYZAxesToRef(axis1, axis2, axis3, rotMat);
+ Quaternion.FromRotationMatrixToRef(rotMat, ref);
+ return ref;
+ }
+ /**
+ * Creates a new rotation value to orient an object to look towards the given forward direction, the up direction being oriented like "up".
+ * This function works in left handed mode
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#96
+ * @param forward defines the forward direction - Must be normalized and orthogonal to up.
+ * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward.
+ * @returns A new quaternion oriented toward the specified forward and up.
+ */
+ static FromLookDirectionLH(forward, up) {
+ const quat = new Quaternion();
+ Quaternion.FromLookDirectionLHToRef(forward, up, quat);
+ return quat;
+ }
+ /**
+ * Creates a new rotation value to orient an object to look towards the given forward direction with the up direction being oriented like "up", and stores it in the target quaternion.
+ * This function works in left handed mode
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#97
+ * @param forward defines the forward direction - Must be normalized and orthogonal to up.
+ * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward.
+ * @param ref defines the target quaternion.
+ * @returns result input
+ */
+ static FromLookDirectionLHToRef(forward, up, ref) {
+ const rotMat = MathTmp.Matrix[0];
+ Matrix.LookDirectionLHToRef(forward, up, rotMat);
+ Quaternion.FromRotationMatrixToRef(rotMat, ref);
+ return ref;
+ }
+ /**
+ * Creates a new rotation value to orient an object to look towards the given forward direction, the up direction being oriented like "up".
+ * This function works in right handed mode
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#98
+ * @param forward defines the forward direction - Must be normalized and orthogonal to up.
+ * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward.
+ * @returns A new quaternion oriented toward the specified forward and up.
+ */
+ static FromLookDirectionRH(forward, up) {
+ const quat = new Quaternion();
+ Quaternion.FromLookDirectionRHToRef(forward, up, quat);
+ return quat;
+ }
+ /**
+ * Creates a new rotation value to orient an object to look towards the given forward direction with the up direction being oriented like "up", and stores it in the target quaternion.
+ * This function works in right handed mode
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#105
+ * @param forward defines the forward direction - Must be normalized and orthogonal to up.
+ * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward.
+ * @param ref defines the target quaternion.
+ * @returns result input
+ */
+ static FromLookDirectionRHToRef(forward, up, ref) {
+ const rotMat = MathTmp.Matrix[0];
+ Matrix.LookDirectionRHToRef(forward, up, rotMat);
+ return Quaternion.FromRotationMatrixToRef(rotMat, ref);
+ }
+ /**
+ * Interpolates between two quaternions
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#79
+ * @param left defines first quaternion
+ * @param right defines second quaternion
+ * @param amount defines the gradient to use
+ * @returns the new interpolated quaternion
+ */
+ static Slerp(left, right, amount) {
+ const result = Quaternion.Identity();
+ Quaternion.SlerpToRef(left, right, amount, result);
+ return result;
+ }
+ /**
+ * Interpolates between two quaternions and stores it into a target quaternion
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#92
+ * @param left defines first quaternion
+ * @param right defines second quaternion
+ * @param amount defines the gradient to use
+ * @param result defines the target quaternion
+ * @returns result input
+ */
+ static SlerpToRef(left, right, amount, result) {
+ let num2;
+ let num3;
+ let num4 = left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w;
+ let flag = false;
+ if (num4 < 0) {
+ flag = true;
+ num4 = -num4;
+ }
+ if (num4 > 0.999999) {
+ num3 = 1 - amount;
+ num2 = flag ? -amount : amount;
+ }
+ else {
+ const num5 = Math.acos(num4);
+ const num6 = 1.0 / Math.sin(num5);
+ num3 = Math.sin((1.0 - amount) * num5) * num6;
+ num2 = flag ? -Math.sin(amount * num5) * num6 : Math.sin(amount * num5) * num6;
+ }
+ result._x = num3 * left._x + num2 * right._x;
+ result._y = num3 * left._y + num2 * right._y;
+ result._z = num3 * left._z + num2 * right._z;
+ result._w = num3 * left._w + num2 * right._w;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Interpolate between two quaternions using Hermite interpolation
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#47
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-quaternion-spline
+ * @param value1 defines first quaternion
+ * @param tangent1 defines the incoming tangent
+ * @param value2 defines second quaternion
+ * @param tangent2 defines the outgoing tangent
+ * @param amount defines the target quaternion
+ * @returns the new interpolated quaternion
+ */
+ static Hermite(value1, tangent1, value2, tangent2, amount) {
+ const squared = amount * amount;
+ const cubed = amount * squared;
+ const part1 = 2.0 * cubed - 3.0 * squared + 1.0;
+ const part2 = -2 * cubed + 3.0 * squared;
+ const part3 = cubed - 2.0 * squared + amount;
+ const part4 = cubed - squared;
+ const x = value1._x * part1 + value2._x * part2 + tangent1._x * part3 + tangent2._x * part4;
+ const y = value1._y * part1 + value2._y * part2 + tangent1._y * part3 + tangent2._y * part4;
+ const z = value1._z * part1 + value2._z * part2 + tangent1._z * part3 + tangent2._z * part4;
+ const w = value1._w * part1 + value2._w * part2 + tangent1._w * part3 + tangent2._w * part4;
+ return new Quaternion(x, y, z, w);
+ }
+ /**
+ * Returns a new Quaternion which is the 1st derivative of the Hermite spline defined by the quaternions "value1", "value2", "tangent1", "tangent2".
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#48
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @returns 1st derivative
+ */
+ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
+ const result = new Quaternion();
+ this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
+ return result;
+ }
+ /**
+ * Update a Quaternion with the 1st derivative of the Hermite spline defined by the quaternions "value1", "value2", "tangent1", "tangent2".
+ * Example Playground https://playground.babylonjs.com/#L49EJ7#49
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @param result define where to store the derivative
+ * @returns result input
+ */
+ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {
+ const t2 = time * time;
+ result._x = (t2 - time) * 6 * value1._x + (3 * t2 - 4 * time + 1) * tangent1._x + (-t2 + time) * 6 * value2._x + (3 * t2 - 2 * time) * tangent2._x;
+ result._y = (t2 - time) * 6 * value1._y + (3 * t2 - 4 * time + 1) * tangent1._y + (-t2 + time) * 6 * value2._y + (3 * t2 - 2 * time) * tangent2._y;
+ result._z = (t2 - time) * 6 * value1._z + (3 * t2 - 4 * time + 1) * tangent1._z + (-t2 + time) * 6 * value2._z + (3 * t2 - 2 * time) * tangent2._z;
+ result._w = (t2 - time) * 6 * value1._w + (3 * t2 - 4 * time + 1) * tangent1._w + (-t2 + time) * 6 * value2._w + (3 * t2 - 2 * time) * tangent2._w;
+ result._isDirty = true;
+ return result;
+ }
+ /**
+ * Returns a new Quaternion as the normalization of the given Quaternion
+ * @param quat defines the Quaternion to normalize
+ * @returns the new Quaternion
+ */
+ static Normalize(quat) {
+ const result = Quaternion.Zero();
+ Quaternion.NormalizeToRef(quat, result);
+ return result;
+ }
+ /**
+ * Sets the given Quaternion "result" with the normalization of the given first Quaternion
+ * @param quat defines the Quaternion to normalize
+ * @param result defines the Quaternion where to store the result
+ * @returns result input
+ */
+ static NormalizeToRef(quat, result) {
+ quat.normalizeToRef(result);
+ return result;
+ }
+ /**
+ * Returns a new Quaternion set with the coordinates of "value", if the quaternion "value" is in the cube defined by the quaternions "min" and "max"
+ * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
+ * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
+ * @param value defines the current value
+ * @param min defines the lower range value
+ * @param max defines the upper range value
+ * @returns the new Quaternion
+ */
+ static Clamp(value, min, max) {
+ const result = new Quaternion();
+ Quaternion.ClampToRef(value, min, max, result);
+ return result;
+ }
+ /**
+ * Sets the given quaternion "result" with the coordinates of "value", if the quaternion "value" is in the cube defined by the quaternions "min" and "max"
+ * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
+ * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
+ * @param value defines the current value
+ * @param min defines the lower range value
+ * @param max defines the upper range value
+ * @param result defines the Quaternion where to store the result
+ * @returns result input
+ */
+ static ClampToRef(value, min, max, result) {
+ return result.copyFromFloats(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y), Clamp(value.z, min.z, max.z), Clamp(value.w, min.w, max.w));
+ }
+ /**
+ * Returns a new Quaternion with random values between min and max
+ * @param min the minimum random value
+ * @param max the maximum random value
+ * @returns a Quaternion with random values between min and max
+ */
+ static Random(min = 0, max = 1) {
+ return new Quaternion(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
+ }
+ /**
+ * Sets a Quaternion with random values between min and max
+ * @param min the minimum random value
+ * @param max the maximum random value
+ * @param ref the ref to store the values in
+ * @returns the ref with random values between min and max
+ */
+ static RandomToRef(min = 0, max = 1, ref) {
+ return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
+ }
+ /**
+ * Do not use
+ * @internal
+ */
+ static Minimize() {
+ throw new ReferenceError("Quaternion.Minimize does not make sense");
+ }
+ /**
+ * Do not use
+ * @internal
+ */
+ static Maximize() {
+ throw new ReferenceError("Quaternion.Maximize does not make sense");
+ }
+ /**
+ * Returns the distance (float) between the quaternions "value1" and "value2".
+ * @param value1 value to calulate the distance between
+ * @param value2 value to calulate the distance between
+ * @returns the distance between the two quaternions
+ */
+ static Distance(value1, value2) {
+ return Math.sqrt(Quaternion.DistanceSquared(value1, value2));
+ }
+ /**
+ * Returns the squared distance (float) between the quaternions "value1" and "value2".
+ * @param value1 value to calulate the distance between
+ * @param value2 value to calulate the distance between
+ * @returns the distance between the two quaternions squared
+ */
+ static DistanceSquared(value1, value2) {
+ const x = value1.x - value2.x;
+ const y = value1.y - value2.y;
+ const z = value1.z - value2.z;
+ const w = value1.w - value2.w;
+ return x * x + y * y + z * z + w * w;
+ }
+ /**
+ * Returns a new Quaternion located at the center between the quaternions "value1" and "value2".
+ * @param value1 value to calulate the center between
+ * @param value2 value to calulate the center between
+ * @returns the center between the two quaternions
+ */
+ static Center(value1, value2) {
+ return Quaternion.CenterToRef(value1, value2, Quaternion.Zero());
+ }
+ /**
+ * Gets the center of the quaternions "value1" and "value2" and stores the result in the quaternion "ref"
+ * @param value1 defines first quaternion
+ * @param value2 defines second quaternion
+ * @param ref defines third quaternion
+ * @returns ref
+ */
+ static CenterToRef(value1, value2, ref) {
+ return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2, (value1.z + value2.z) / 2, (value1.w + value2.w) / 2);
+ }
+}
+/**
+ * If the first quaternion is flagged with integers (as everything is 0,0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet.
+ * If subsequent quaternion are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers,
+ * and henceforth it will use floating-point representation for all quaternion instances that it creates.
+ * But the original quaternion instances are unchanged and has a "deprecated map".
+ * If we keep using the quaternion instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches.
+ */
+Quaternion._V8PerformanceHack = new Quaternion(0.5, 0.5, 0.5, 0.5);
+Object.defineProperties(Quaternion.prototype, {
+ dimension: { value: [4] },
+ rank: { value: 1 },
+});
+/**
+ * Class used to store matrix data (4x4)
+ * Note on matrix definitions in Babylon.js for setting values directly
+ * rather than using one of the methods available.
+ * Matrix size is given by rows x columns.
+ * A Vector3 is a 1 X 3 matrix [x, y, z].
+ *
+ * In Babylon.js multiplying a 1 x 3 matrix by a 4 x 4 matrix
+ * is done using BABYLON.Vector4.TransformCoordinates(Vector3, Matrix).
+ * and extending the passed Vector3 to a Vector4, V = [x, y, z, 1].
+ * Let M be a matrix with elements m(row, column), so that
+ * m(2, 3) is the element in row 2 column 3 of M.
+ *
+ * Multiplication is of the form VM and has the resulting Vector4
+ * VM = [xm(0, 0) + ym(1, 0) + zm(2, 0) + m(3, 0), xm(0, 1) + ym(1, 1) + zm(2, 1) + m(3, 1), xm(0, 2) + ym(1, 2) + zm(2, 2) + m(3, 2), xm(0, 3) + ym(1, 3) + zm(2, 3) + m(3, 3)].
+ * On the web you will find many examples that use the opposite convention of MV,
+ * in which case to make use of the examples you will need to transpose the matrix.
+ *
+ * Example Playground - Overview Linear Algebra - https://playground.babylonjs.com/#AV9X17
+ * Example Playground - Overview Transformation - https://playground.babylonjs.com/#AV9X17#1
+ * Example Playground - Overview Projection - https://playground.babylonjs.com/#AV9X17#2
+ */
+class Matrix {
+ /**
+ * Gets the precision of matrix computations
+ */
+ static get Use64Bits() {
+ return PerformanceConfigurator.MatrixUse64Bits;
+ }
+ /**
+ * Gets the internal data of the matrix
+ */
+ get m() {
+ return this._m;
+ }
+ /**
+ * Update the updateFlag to indicate that the matrix has been updated
+ */
+ markAsUpdated() {
+ this.updateFlag = Matrix._UpdateFlagSeed++;
+ this._isIdentity = false;
+ this._isIdentity3x2 = false;
+ this._isIdentityDirty = true;
+ this._isIdentity3x2Dirty = true;
+ }
+ _updateIdentityStatus(isIdentity, isIdentityDirty = false, isIdentity3x2 = false, isIdentity3x2Dirty = true) {
+ this._isIdentity = isIdentity;
+ this._isIdentity3x2 = isIdentity || isIdentity3x2;
+ this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty;
+ this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty;
+ }
+ /**
+ * Creates an empty matrix (filled with zeros)
+ */
+ constructor() {
+ this._isIdentity = false;
+ this._isIdentityDirty = true;
+ this._isIdentity3x2 = true;
+ this._isIdentity3x2Dirty = true;
+ /**
+ * Gets the update flag of the matrix which is an unique number for the matrix.
+ * It will be incremented every time the matrix data change.
+ * You can use it to speed the comparison between two versions of the same matrix.
+ */
+ this.updateFlag = -1;
+ if (PerformanceConfigurator.MatrixTrackPrecisionChange) {
+ PerformanceConfigurator.MatrixTrackedMatrices.push(this);
+ }
+ this._m = new PerformanceConfigurator.MatrixCurrentType(16);
+ this.markAsUpdated();
+ }
+ // Properties
+ /**
+ * Check if the current matrix is identity
+ * @returns true is the matrix is the identity matrix
+ */
+ isIdentity() {
+ if (this._isIdentityDirty) {
+ this._isIdentityDirty = false;
+ const m = this._m;
+ this._isIdentity =
+ m[0] === 1.0 &&
+ m[1] === 0.0 &&
+ m[2] === 0.0 &&
+ m[3] === 0.0 &&
+ m[4] === 0.0 &&
+ m[5] === 1.0 &&
+ m[6] === 0.0 &&
+ m[7] === 0.0 &&
+ m[8] === 0.0 &&
+ m[9] === 0.0 &&
+ m[10] === 1.0 &&
+ m[11] === 0.0 &&
+ m[12] === 0.0 &&
+ m[13] === 0.0 &&
+ m[14] === 0.0 &&
+ m[15] === 1.0;
+ }
+ return this._isIdentity;
+ }
+ /**
+ * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
+ * @returns true is the matrix is the identity matrix
+ */
+ isIdentityAs3x2() {
+ if (this._isIdentity3x2Dirty) {
+ this._isIdentity3x2Dirty = false;
+ if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
+ this._isIdentity3x2 = false;
+ }
+ else if (this._m[1] !== 0.0 ||
+ this._m[2] !== 0.0 ||
+ this._m[3] !== 0.0 ||
+ this._m[4] !== 0.0 ||
+ this._m[6] !== 0.0 ||
+ this._m[7] !== 0.0 ||
+ this._m[8] !== 0.0 ||
+ this._m[9] !== 0.0 ||
+ this._m[10] !== 0.0 ||
+ this._m[11] !== 0.0 ||
+ this._m[12] !== 0.0 ||
+ this._m[13] !== 0.0 ||
+ this._m[14] !== 0.0) {
+ this._isIdentity3x2 = false;
+ }
+ else {
+ this._isIdentity3x2 = true;
+ }
+ }
+ return this._isIdentity3x2;
+ }
+ /**
+ * Gets the determinant of the matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#34
+ * @returns the matrix determinant
+ */
+ determinant() {
+ if (this._isIdentity === true) {
+ return 1;
+ }
+ const m = this._m;
+ const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
+ const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
+ const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
+ const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
+ // https://en.wikipedia.org/wiki/Laplace_expansion
+ // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
+ // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
+ // Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
+ // where
+ // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
+ // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
+ //
+ // Here we do that for the 1st row.
+ const det_22_33 = m22 * m33 - m32 * m23;
+ const det_21_33 = m21 * m33 - m31 * m23;
+ const det_21_32 = m21 * m32 - m31 * m22;
+ const det_20_33 = m20 * m33 - m30 * m23;
+ const det_20_32 = m20 * m32 - m22 * m30;
+ const det_20_31 = m20 * m31 - m30 * m21;
+ const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
+ const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
+ const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
+ const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
+ return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
+ }
+ // Methods
+ /**
+ * Gets a string with the Matrix values
+ * @returns a string with the Matrix values
+ */
+ toString() {
+ return `{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`;
+ }
+ toArray(array = null, index = 0) {
+ if (!array) {
+ return this._m;
+ }
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ array[index + i] = m[i];
+ }
+ return this;
+ }
+ /**
+ * Returns the matrix as a Float32Array or Array
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#114
+ * @returns the matrix underlying array.
+ */
+ asArray() {
+ return this._m;
+ }
+ fromArray(array, index = 0) {
+ return Matrix.FromArrayToRef(array, index, this);
+ }
+ copyFromFloats(...floats) {
+ return Matrix.FromArrayToRef(floats, 0, this);
+ }
+ set(...values) {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ m[i] = values[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ setAll(value) {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ m[i] = value;
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * Inverts the current matrix in place
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#118
+ * @returns the current inverted matrix
+ */
+ invert() {
+ this.invertToRef(this);
+ return this;
+ }
+ /**
+ * Sets all the matrix elements to zero
+ * @returns the current matrix
+ */
+ reset() {
+ Matrix.FromValuesToRef(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, this);
+ this._updateIdentityStatus(false);
+ return this;
+ }
+ /**
+ * Adds the current matrix with a second one
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#44
+ * @param other defines the matrix to add
+ * @returns a new matrix as the addition of the current matrix and the given one
+ */
+ add(other) {
+ const result = new Matrix();
+ this.addToRef(other, result);
+ return result;
+ }
+ /**
+ * Sets the given matrix "result" to the addition of the current matrix and the given one
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#45
+ * @param other defines the matrix to add
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ addToRef(other, result) {
+ const m = this._m;
+ const resultM = result._m;
+ const otherM = other.m;
+ for (let index = 0; index < 16; index++) {
+ resultM[index] = m[index] + otherM[index];
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Adds in place the given matrix to the current matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#46
+ * @param other defines the second operand
+ * @returns the current updated matrix
+ */
+ addToSelf(other) {
+ const m = this._m;
+ const otherM = other.m;
+ m[0] += otherM[0];
+ m[1] += otherM[1];
+ m[2] += otherM[2];
+ m[3] += otherM[3];
+ m[4] += otherM[4];
+ m[5] += otherM[5];
+ m[6] += otherM[6];
+ m[7] += otherM[7];
+ m[8] += otherM[8];
+ m[9] += otherM[9];
+ m[10] += otherM[10];
+ m[11] += otherM[11];
+ m[12] += otherM[12];
+ m[13] += otherM[13];
+ m[14] += otherM[14];
+ m[15] += otherM[15];
+ this.markAsUpdated();
+ return this;
+ }
+ addInPlace(other) {
+ const m = this._m, otherM = other.m;
+ for (let i = 0; i < 16; i++) {
+ m[i] += otherM[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ addInPlaceFromFloats(...floats) {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ m[i] += floats[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ subtract(other) {
+ const m = this._m, otherM = other.m;
+ for (let i = 0; i < 16; i++) {
+ m[i] -= otherM[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ subtractToRef(other, result) {
+ const m = this._m, otherM = other.m, resultM = result._m;
+ for (let i = 0; i < 16; i++) {
+ resultM[i] = m[i] - otherM[i];
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ subtractInPlace(other) {
+ const m = this._m, otherM = other.m;
+ for (let i = 0; i < 16; i++) {
+ m[i] -= otherM[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ subtractFromFloats(...floats) {
+ return this.subtractFromFloatsToRef(...floats, new Matrix());
+ }
+ subtractFromFloatsToRef(...args) {
+ const result = args.pop(), m = this._m, resultM = result._m, values = args;
+ for (let i = 0; i < 16; i++) {
+ resultM[i] = m[i] - values[i];
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Sets the given matrix to the current inverted Matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#119
+ * @param other defines the target matrix
+ * @returns result input
+ */
+ invertToRef(other) {
+ if (this._isIdentity === true) {
+ Matrix.IdentityToRef(other);
+ return other;
+ }
+ // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
+ const m = this._m;
+ const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
+ const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
+ const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
+ const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
+ const det_22_33 = m22 * m33 - m32 * m23;
+ const det_21_33 = m21 * m33 - m31 * m23;
+ const det_21_32 = m21 * m32 - m31 * m22;
+ const det_20_33 = m20 * m33 - m30 * m23;
+ const det_20_32 = m20 * m32 - m22 * m30;
+ const det_20_31 = m20 * m31 - m30 * m21;
+ const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
+ const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
+ const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
+ const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
+ const det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
+ if (det === 0) {
+ // not invertible
+ other.copyFrom(this);
+ return other;
+ }
+ const detInv = 1 / det;
+ const det_12_33 = m12 * m33 - m32 * m13;
+ const det_11_33 = m11 * m33 - m31 * m13;
+ const det_11_32 = m11 * m32 - m31 * m12;
+ const det_10_33 = m10 * m33 - m30 * m13;
+ const det_10_32 = m10 * m32 - m30 * m12;
+ const det_10_31 = m10 * m31 - m30 * m11;
+ const det_12_23 = m12 * m23 - m22 * m13;
+ const det_11_23 = m11 * m23 - m21 * m13;
+ const det_11_22 = m11 * m22 - m21 * m12;
+ const det_10_23 = m10 * m23 - m20 * m13;
+ const det_10_22 = m10 * m22 - m20 * m12;
+ const det_10_21 = m10 * m21 - m20 * m11;
+ const cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32);
+ const cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32);
+ const cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31);
+ const cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31);
+ const cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32);
+ const cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32);
+ const cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31);
+ const cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31);
+ const cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22);
+ const cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22);
+ const cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21);
+ const cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21);
+ Matrix.FromValuesToRef(cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv, cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv, cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv, cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv, other);
+ return other;
+ }
+ /**
+ * add a value at the specified position in the current Matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#47
+ * @param index the index of the value within the matrix. between 0 and 15.
+ * @param value the value to be added
+ * @returns the current updated matrix
+ */
+ addAtIndex(index, value) {
+ this._m[index] += value;
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * mutiply the specified position in the current Matrix by a value
+ * @param index the index of the value within the matrix. between 0 and 15.
+ * @param value the value to be added
+ * @returns the current updated matrix
+ */
+ multiplyAtIndex(index, value) {
+ this._m[index] *= value;
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * Inserts the translation vector (using 3 floats) in the current matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#120
+ * @param x defines the 1st component of the translation
+ * @param y defines the 2nd component of the translation
+ * @param z defines the 3rd component of the translation
+ * @returns the current updated matrix
+ */
+ setTranslationFromFloats(x, y, z) {
+ this._m[12] = x;
+ this._m[13] = y;
+ this._m[14] = z;
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * Adds the translation vector (using 3 floats) in the current matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#20
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#48
+ * @param x defines the 1st component of the translation
+ * @param y defines the 2nd component of the translation
+ * @param z defines the 3rd component of the translation
+ * @returns the current updated matrix
+ */
+ addTranslationFromFloats(x, y, z) {
+ this._m[12] += x;
+ this._m[13] += y;
+ this._m[14] += z;
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * Inserts the translation vector in the current matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#121
+ * @param vector3 defines the translation to insert
+ * @returns the current updated matrix
+ */
+ setTranslation(vector3) {
+ return this.setTranslationFromFloats(vector3._x, vector3._y, vector3._z);
+ }
+ /**
+ * Gets the translation value of the current matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#122
+ * @returns a new Vector3 as the extracted translation from the matrix
+ */
+ getTranslation() {
+ return new Vector3(this._m[12], this._m[13], this._m[14]);
+ }
+ /**
+ * Fill a Vector3 with the extracted translation from the matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#123
+ * @param result defines the Vector3 where to store the translation
+ * @returns the current matrix
+ */
+ getTranslationToRef(result) {
+ result.x = this._m[12];
+ result.y = this._m[13];
+ result.z = this._m[14];
+ return result;
+ }
+ /**
+ * Remove rotation and scaling part from the matrix
+ * @returns the updated matrix
+ */
+ removeRotationAndScaling() {
+ const m = this.m;
+ Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, m[12], m[13], m[14], m[15], this);
+ this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);
+ return this;
+ }
+ /**
+ * Copy the current matrix from the given one
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#21
+ * @param other defines the source matrix
+ * @returns the current updated matrix
+ */
+ copyFrom(other) {
+ other.copyToArray(this._m);
+ const o = other;
+ this.updateFlag = o.updateFlag;
+ this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty);
+ return this;
+ }
+ /**
+ * Populates the given array from the starting index with the current matrix values
+ * @param array defines the target array
+ * @param offset defines the offset in the target array where to start storing values
+ * @returns the current matrix
+ */
+ copyToArray(array, offset = 0) {
+ const source = this._m;
+ array[offset] = source[0];
+ array[offset + 1] = source[1];
+ array[offset + 2] = source[2];
+ array[offset + 3] = source[3];
+ array[offset + 4] = source[4];
+ array[offset + 5] = source[5];
+ array[offset + 6] = source[6];
+ array[offset + 7] = source[7];
+ array[offset + 8] = source[8];
+ array[offset + 9] = source[9];
+ array[offset + 10] = source[10];
+ array[offset + 11] = source[11];
+ array[offset + 12] = source[12];
+ array[offset + 13] = source[13];
+ array[offset + 14] = source[14];
+ array[offset + 15] = source[15];
+ return this;
+ }
+ /**
+ * Multiply two matrices
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#15
+ * A.multiply(B) means apply B to A so result is B x A
+ * @param other defines the second operand
+ * @returns a new matrix set with the multiplication result of the current Matrix and the given one
+ */
+ multiply(other) {
+ const result = new Matrix();
+ this.multiplyToRef(other, result);
+ return result;
+ }
+ /**
+ * This method performs component-by-component in-place multiplication, rather than true matrix multiplication.
+ * Use multiply or multiplyToRef for matrix multiplication.
+ * @param other defines the second operand
+ * @returns the current updated matrix
+ */
+ multiplyInPlace(other) {
+ const m = this._m, otherM = other.m;
+ for (let i = 0; i < 16; i++) {
+ m[i] *= otherM[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * This method performs a component-by-component multiplication of the current matrix with the array of transmitted numbers.
+ * Use multiply or multiplyToRef for matrix multiplication.
+ * @param floats defines the array of numbers to multiply the matrix by
+ * @returns the current updated matrix
+ */
+ multiplyByFloats(...floats) {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ m[i] *= floats[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * Multiples the current matrix by the given floats and stores them in the given ref
+ * @param args The floats and ref
+ * @returns The updated ref
+ */
+ multiplyByFloatsToRef(...args) {
+ const result = args.pop(), m = this._m, resultM = result._m, values = args;
+ for (let i = 0; i < 16; i++) {
+ resultM[i] = m[i] * values[i];
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
+ * A.multiplyToRef(B, R) means apply B to A and store in R and R = B x A
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#16
+ * @param other defines the second operand
+ * @param result defines the matrix where to store the multiplication
+ * @returns result input
+ */
+ multiplyToRef(other, result) {
+ if (this._isIdentity) {
+ result.copyFrom(other);
+ return result;
+ }
+ if (other._isIdentity) {
+ result.copyFrom(this);
+ return result;
+ }
+ this.multiplyToArray(other, result._m, 0);
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
+ * @param other defines the second operand
+ * @param result defines the array where to store the multiplication
+ * @param offset defines the offset in the target array where to start storing values
+ * @returns the current matrix
+ */
+ multiplyToArray(other, result, offset) {
+ const m = this._m;
+ const otherM = other.m;
+ const tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];
+ const tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];
+ const tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];
+ const tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];
+ const om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];
+ const om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];
+ const om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];
+ const om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];
+ result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
+ result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
+ result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
+ result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
+ result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
+ result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
+ result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
+ result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
+ result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
+ result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
+ result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
+ result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
+ result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
+ result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
+ result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
+ result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
+ return this;
+ }
+ divide(other) {
+ return this.divideToRef(other, new Matrix());
+ }
+ divideToRef(other, result) {
+ const m = this._m, otherM = other.m, resultM = result._m;
+ for (let i = 0; i < 16; i++) {
+ resultM[i] = m[i] / otherM[i];
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ divideInPlace(other) {
+ const m = this._m, otherM = other.m;
+ for (let i = 0; i < 16; i++) {
+ m[i] /= otherM[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ minimizeInPlace(other) {
+ const m = this._m, otherM = other.m;
+ for (let i = 0; i < 16; i++) {
+ m[i] = Math.min(m[i], otherM[i]);
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ minimizeInPlaceFromFloats(...floats) {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ m[i] = Math.min(m[i], floats[i]);
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ maximizeInPlace(other) {
+ const m = this._m, otherM = other.m;
+ for (let i = 0; i < 16; i++) {
+ m[i] = Math.min(m[i], otherM[i]);
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ maximizeInPlaceFromFloats(...floats) {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ m[i] = Math.min(m[i], floats[i]);
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ negate() {
+ return this.negateToRef(new Matrix());
+ }
+ negateInPlace() {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ m[i] = -m[i];
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ negateToRef(result) {
+ const m = this._m, resultM = result._m;
+ for (let i = 0; i < 16; i++) {
+ resultM[i] = -m[i];
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Check equality between this matrix and a second one
+ * @param value defines the second matrix to compare
+ * @returns true is the current matrix and the given one values are strictly equal
+ */
+ equals(value) {
+ const other = value;
+ if (!other) {
+ return false;
+ }
+ if (this._isIdentity || other._isIdentity) {
+ if (!this._isIdentityDirty && !other._isIdentityDirty) {
+ return this._isIdentity && other._isIdentity;
+ }
+ }
+ const m = this.m;
+ const om = other.m;
+ return (m[0] === om[0] &&
+ m[1] === om[1] &&
+ m[2] === om[2] &&
+ m[3] === om[3] &&
+ m[4] === om[4] &&
+ m[5] === om[5] &&
+ m[6] === om[6] &&
+ m[7] === om[7] &&
+ m[8] === om[8] &&
+ m[9] === om[9] &&
+ m[10] === om[10] &&
+ m[11] === om[11] &&
+ m[12] === om[12] &&
+ m[13] === om[13] &&
+ m[14] === om[14] &&
+ m[15] === om[15]);
+ }
+ equalsWithEpsilon(other, epsilon = 0) {
+ const m = this._m, otherM = other.m;
+ for (let i = 0; i < 16; i++) {
+ if (!WithinEpsilon(m[i], otherM[i], epsilon)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ equalsToFloats(...floats) {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ if (m[i] != floats[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+ floor() {
+ return this.floorToRef(new Matrix());
+ }
+ floorToRef(result) {
+ const m = this._m, resultM = result._m;
+ for (let i = 0; i < 16; i++) {
+ resultM[i] = Math.floor(m[i]);
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ fract() {
+ return this.fractToRef(new Matrix());
+ }
+ fractToRef(result) {
+ const m = this._m, resultM = result._m;
+ for (let i = 0; i < 16; i++) {
+ resultM[i] = m[i] - Math.floor(m[i]);
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Clone the current matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#18
+ * @returns a new matrix from the current matrix
+ */
+ clone() {
+ const matrix = new Matrix();
+ matrix.copyFrom(this);
+ return matrix;
+ }
+ /**
+ * Returns the name of the current matrix class
+ * @returns the string "Matrix"
+ */
+ getClassName() {
+ return "Matrix";
+ }
+ /**
+ * Gets the hash code of the current matrix
+ * @returns the hash code
+ */
+ getHashCode() {
+ let hash = _ExtractAsInt(this._m[0]);
+ for (let i = 1; i < 16; i++) {
+ hash = (hash * 397) ^ _ExtractAsInt(this._m[i]);
+ }
+ return hash;
+ }
+ /**
+ * Decomposes the current Matrix into a translation, rotation and scaling components of the provided node
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#13
+ * @param node the node to decompose the matrix to
+ * @returns true if operation was successful
+ */
+ decomposeToTransformNode(node) {
+ node.rotationQuaternion = node.rotationQuaternion || new Quaternion();
+ return this.decompose(node.scaling, node.rotationQuaternion, node.position);
+ }
+ /**
+ * Decomposes the current Matrix into a translation, rotation and scaling components
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#12
+ * @param scale defines the scale vector3 given as a reference to update
+ * @param rotation defines the rotation quaternion given as a reference to update
+ * @param translation defines the translation vector3 given as a reference to update
+ * @param preserveScalingNode Use scaling sign coming from this node. Otherwise scaling sign might change.
+ * @param useAbsoluteScaling Use scaling sign coming from this absoluteScaling when true or scaling otherwise.
+ * @returns true if operation was successful
+ */
+ decompose(scale, rotation, translation, preserveScalingNode, useAbsoluteScaling = true) {
+ if (this._isIdentity) {
+ if (translation) {
+ translation.setAll(0);
+ }
+ if (scale) {
+ scale.setAll(1);
+ }
+ if (rotation) {
+ rotation.copyFromFloats(0, 0, 0, 1);
+ }
+ return true;
+ }
+ const m = this._m;
+ if (translation) {
+ translation.copyFromFloats(m[12], m[13], m[14]);
+ }
+ scale = scale || MathTmp.Vector3[0];
+ scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
+ scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
+ scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
+ if (preserveScalingNode) {
+ const signX = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.x : preserveScalingNode.scaling.x) < 0 ? -1 : 1;
+ const signY = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.y : preserveScalingNode.scaling.y) < 0 ? -1 : 1;
+ const signZ = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.z : preserveScalingNode.scaling.z) < 0 ? -1 : 1;
+ scale.x *= signX;
+ scale.y *= signY;
+ scale.z *= signZ;
+ }
+ else {
+ if (this.determinant() <= 0) {
+ scale.y *= -1;
+ }
+ }
+ if (scale._x === 0 || scale._y === 0 || scale._z === 0) {
+ if (rotation) {
+ rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0);
+ }
+ return false;
+ }
+ if (rotation) {
+ const sx = 1 / scale._x, sy = 1 / scale._y, sz = 1 / scale._z;
+ Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, MathTmp.Matrix[0]);
+ Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
+ }
+ return true;
+ }
+ /**
+ * Gets specific row of the matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#36
+ * @param index defines the number of the row to get
+ * @returns the index-th row of the current matrix as a new Vector4
+ */
+ getRow(index) {
+ if (index < 0 || index > 3) {
+ return null;
+ }
+ const i = index * 4;
+ return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]);
+ }
+ /**
+ * Gets specific row of the matrix to ref
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#36
+ * @param index defines the number of the row to get
+ * @param rowVector vector to store the index-th row of the current matrix
+ * @returns result input
+ */
+ getRowToRef(index, rowVector) {
+ if (index >= 0 && index <= 3) {
+ const i = index * 4;
+ rowVector.x = this._m[i + 0];
+ rowVector.y = this._m[i + 1];
+ rowVector.z = this._m[i + 2];
+ rowVector.w = this._m[i + 3];
+ }
+ return rowVector;
+ }
+ /**
+ * Sets the index-th row of the current matrix to the vector4 values
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#36
+ * @param index defines the number of the row to set
+ * @param row defines the target vector4
+ * @returns the updated current matrix
+ */
+ setRow(index, row) {
+ return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
+ }
+ /**
+ * Compute the transpose of the matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#40
+ * @returns the new transposed matrix
+ */
+ transpose() {
+ const result = new Matrix();
+ Matrix.TransposeToRef(this, result);
+ return result;
+ }
+ /**
+ * Compute the transpose of the matrix and store it in a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#41
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ transposeToRef(result) {
+ Matrix.TransposeToRef(this, result);
+ return result;
+ }
+ /**
+ * Sets the index-th row of the current matrix with the given 4 x float values
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#36
+ * @param index defines the row index
+ * @param x defines the x component to set
+ * @param y defines the y component to set
+ * @param z defines the z component to set
+ * @param w defines the w component to set
+ * @returns the updated current matrix
+ */
+ setRowFromFloats(index, x, y, z, w) {
+ if (index < 0 || index > 3) {
+ return this;
+ }
+ const i = index * 4;
+ this._m[i + 0] = x;
+ this._m[i + 1] = y;
+ this._m[i + 2] = z;
+ this._m[i + 3] = w;
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * Compute a new matrix set with the current matrix values multiplied by scale (float)
+ * @param scale defines the scale factor
+ * @returns a new matrix
+ */
+ scale(scale) {
+ const result = new Matrix();
+ this.scaleToRef(scale, result);
+ return result;
+ }
+ /**
+ * Scale the current matrix values by a factor to a given result matrix
+ * @param scale defines the scale factor
+ * @param result defines the matrix to store the result
+ * @returns result input
+ */
+ scaleToRef(scale, result) {
+ for (let index = 0; index < 16; index++) {
+ result._m[index] = this._m[index] * scale;
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Scale the current matrix values by a factor and add the result to a given matrix
+ * @param scale defines the scale factor
+ * @param result defines the Matrix to store the result
+ * @returns result input
+ */
+ scaleAndAddToRef(scale, result) {
+ for (let index = 0; index < 16; index++) {
+ result._m[index] += this._m[index] * scale;
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ scaleInPlace(scale) {
+ const m = this._m;
+ for (let i = 0; i < 16; i++) {
+ m[i] *= scale;
+ }
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#17
+ * @param ref matrix to store the result
+ * @returns the reference matrix
+ */
+ toNormalMatrix(ref) {
+ const tmp = MathTmp.Matrix[0];
+ this.invertToRef(tmp);
+ tmp.transposeToRef(ref);
+ const m = ref._m;
+ Matrix.FromValuesToRef(m[0], m[1], m[2], 0.0, m[4], m[5], m[6], 0.0, m[8], m[9], m[10], 0.0, 0.0, 0.0, 0.0, 1.0, ref);
+ return ref;
+ }
+ /**
+ * Gets only rotation part of the current matrix
+ * @returns a new matrix sets to the extracted rotation matrix from the current one
+ */
+ getRotationMatrix() {
+ const result = new Matrix();
+ this.getRotationMatrixToRef(result);
+ return result;
+ }
+ /**
+ * Extracts the rotation matrix from the current one and sets it as the given "result"
+ * @param result defines the target matrix to store data to
+ * @returns result input
+ */
+ getRotationMatrixToRef(result) {
+ const scale = MathTmp.Vector3[0];
+ if (!this.decompose(scale)) {
+ Matrix.IdentityToRef(result);
+ return result;
+ }
+ const m = this._m;
+ const sx = 1 / scale._x, sy = 1 / scale._y, sz = 1 / scale._z;
+ Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, result);
+ return result;
+ }
+ /**
+ * Toggles model matrix from being right handed to left handed in place and vice versa
+ * @returns the current updated matrix
+ */
+ toggleModelMatrixHandInPlace() {
+ const m = this._m;
+ m[2] *= -1;
+ m[6] *= -1;
+ m[8] *= -1;
+ m[9] *= -1;
+ m[14] *= -1;
+ this.markAsUpdated();
+ return this;
+ }
+ /**
+ * Toggles projection matrix from being right handed to left handed in place and vice versa
+ * @returns the current updated matrix
+ */
+ toggleProjectionMatrixHandInPlace() {
+ const m = this._m;
+ m[8] *= -1;
+ m[9] *= -1;
+ m[10] *= -1;
+ m[11] *= -1;
+ this.markAsUpdated();
+ return this;
+ }
+ // Statics
+ /**
+ * Creates a matrix from an array
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#42
+ * @param array defines the source array
+ * @param offset defines an offset in the source array
+ * @returns a new Matrix set from the starting index of the given array
+ */
+ static FromArray(array, offset = 0) {
+ const result = new Matrix();
+ Matrix.FromArrayToRef(array, offset, result);
+ return result;
+ }
+ /**
+ * Copy the content of an array into a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#43
+ * @param array defines the source array
+ * @param offset defines an offset in the source array
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static FromArrayToRef(array, offset, result) {
+ for (let index = 0; index < 16; index++) {
+ result._m[index] = array[index + offset];
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Stores an array into a matrix after having multiplied each component by a given factor
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#50
+ * @param array defines the source array
+ * @param offset defines the offset in the source array
+ * @param scale defines the scaling factor
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static FromFloat32ArrayToRefScaled(array, offset, scale, result) {
+ result._m[0] = array[0 + offset] * scale;
+ result._m[1] = array[1 + offset] * scale;
+ result._m[2] = array[2 + offset] * scale;
+ result._m[3] = array[3 + offset] * scale;
+ result._m[4] = array[4 + offset] * scale;
+ result._m[5] = array[5 + offset] * scale;
+ result._m[6] = array[6 + offset] * scale;
+ result._m[7] = array[7 + offset] * scale;
+ result._m[8] = array[8 + offset] * scale;
+ result._m[9] = array[9 + offset] * scale;
+ result._m[10] = array[10 + offset] * scale;
+ result._m[11] = array[11 + offset] * scale;
+ result._m[12] = array[12 + offset] * scale;
+ result._m[13] = array[13 + offset] * scale;
+ result._m[14] = array[14 + offset] * scale;
+ result._m[15] = array[15 + offset] * scale;
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Gets an identity matrix that must not be updated
+ */
+ static get IdentityReadOnly() {
+ return Matrix._IdentityReadOnly;
+ }
+ /**
+ * Stores a list of values (16) inside a given matrix
+ * @param initialM11 defines 1st value of 1st row
+ * @param initialM12 defines 2nd value of 1st row
+ * @param initialM13 defines 3rd value of 1st row
+ * @param initialM14 defines 4th value of 1st row
+ * @param initialM21 defines 1st value of 2nd row
+ * @param initialM22 defines 2nd value of 2nd row
+ * @param initialM23 defines 3rd value of 2nd row
+ * @param initialM24 defines 4th value of 2nd row
+ * @param initialM31 defines 1st value of 3rd row
+ * @param initialM32 defines 2nd value of 3rd row
+ * @param initialM33 defines 3rd value of 3rd row
+ * @param initialM34 defines 4th value of 3rd row
+ * @param initialM41 defines 1st value of 4th row
+ * @param initialM42 defines 2nd value of 4th row
+ * @param initialM43 defines 3rd value of 4th row
+ * @param initialM44 defines 4th value of 4th row
+ * @param result defines the target matrix
+ */
+ static FromValuesToRef(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
+ const m = result._m;
+ m[0] = initialM11;
+ m[1] = initialM12;
+ m[2] = initialM13;
+ m[3] = initialM14;
+ m[4] = initialM21;
+ m[5] = initialM22;
+ m[6] = initialM23;
+ m[7] = initialM24;
+ m[8] = initialM31;
+ m[9] = initialM32;
+ m[10] = initialM33;
+ m[11] = initialM34;
+ m[12] = initialM41;
+ m[13] = initialM42;
+ m[14] = initialM43;
+ m[15] = initialM44;
+ result.markAsUpdated();
+ }
+ /**
+ * Creates new matrix from a list of values (16)
+ * @param initialM11 defines 1st value of 1st row
+ * @param initialM12 defines 2nd value of 1st row
+ * @param initialM13 defines 3rd value of 1st row
+ * @param initialM14 defines 4th value of 1st row
+ * @param initialM21 defines 1st value of 2nd row
+ * @param initialM22 defines 2nd value of 2nd row
+ * @param initialM23 defines 3rd value of 2nd row
+ * @param initialM24 defines 4th value of 2nd row
+ * @param initialM31 defines 1st value of 3rd row
+ * @param initialM32 defines 2nd value of 3rd row
+ * @param initialM33 defines 3rd value of 3rd row
+ * @param initialM34 defines 4th value of 3rd row
+ * @param initialM41 defines 1st value of 4th row
+ * @param initialM42 defines 2nd value of 4th row
+ * @param initialM43 defines 3rd value of 4th row
+ * @param initialM44 defines 4th value of 4th row
+ * @returns the new matrix
+ */
+ static FromValues(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
+ const result = new Matrix();
+ const m = result._m;
+ m[0] = initialM11;
+ m[1] = initialM12;
+ m[2] = initialM13;
+ m[3] = initialM14;
+ m[4] = initialM21;
+ m[5] = initialM22;
+ m[6] = initialM23;
+ m[7] = initialM24;
+ m[8] = initialM31;
+ m[9] = initialM32;
+ m[10] = initialM33;
+ m[11] = initialM34;
+ m[12] = initialM41;
+ m[13] = initialM42;
+ m[14] = initialM43;
+ m[15] = initialM44;
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#24
+ * @param scale defines the scale vector3
+ * @param rotation defines the rotation quaternion
+ * @param translation defines the translation vector3
+ * @returns a new matrix
+ */
+ static Compose(scale, rotation, translation) {
+ const result = new Matrix();
+ Matrix.ComposeToRef(scale, rotation, translation, result);
+ return result;
+ }
+ /**
+ * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#25
+ * @param scale defines the scale vector3
+ * @param rotation defines the rotation quaternion
+ * @param translation defines the translation vector3
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static ComposeToRef(scale, rotation, translation, result) {
+ const m = result._m;
+ const x = rotation._x, y = rotation._y, z = rotation._z, w = rotation._w;
+ const x2 = x + x, y2 = y + y, z2 = z + z;
+ const xx = x * x2, xy = x * y2, xz = x * z2;
+ const yy = y * y2, yz = y * z2, zz = z * z2;
+ const wx = w * x2, wy = w * y2, wz = w * z2;
+ const sx = scale._x, sy = scale._y, sz = scale._z;
+ m[0] = (1 - (yy + zz)) * sx;
+ m[1] = (xy + wz) * sx;
+ m[2] = (xz - wy) * sx;
+ m[3] = 0;
+ m[4] = (xy - wz) * sy;
+ m[5] = (1 - (xx + zz)) * sy;
+ m[6] = (yz + wx) * sy;
+ m[7] = 0;
+ m[8] = (xz + wy) * sz;
+ m[9] = (yz - wx) * sz;
+ m[10] = (1 - (xx + yy)) * sz;
+ m[11] = 0;
+ m[12] = translation._x;
+ m[13] = translation._y;
+ m[14] = translation._z;
+ m[15] = 1;
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Creates a new identity matrix
+ * @returns a new identity matrix
+ */
+ static Identity() {
+ const identity = Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
+ identity._updateIdentityStatus(true);
+ return identity;
+ }
+ /**
+ * Creates a new identity matrix and stores the result in a given matrix
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static IdentityToRef(result) {
+ Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
+ result._updateIdentityStatus(true);
+ return result;
+ }
+ /**
+ * Creates a new zero matrix
+ * @returns a new zero matrix
+ */
+ static Zero() {
+ const zero = Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+ zero._updateIdentityStatus(false);
+ return zero;
+ }
+ /**
+ * Creates a new rotation matrix for "angle" radians around the X axis
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#97
+ * @param angle defines the angle (in radians) to use
+ * @returns the new matrix
+ */
+ static RotationX(angle) {
+ const result = new Matrix();
+ Matrix.RotationXToRef(angle, result);
+ return result;
+ }
+ /**
+ * Creates a new matrix as the invert of a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#124
+ * @param source defines the source matrix
+ * @returns the new matrix
+ */
+ static Invert(source) {
+ const result = new Matrix();
+ source.invertToRef(result);
+ return result;
+ }
+ /**
+ * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#98
+ * @param angle defines the angle (in radians) to use
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static RotationXToRef(angle, result) {
+ const s = Math.sin(angle);
+ const c = Math.cos(angle);
+ Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
+ result._updateIdentityStatus(c === 1 && s === 0);
+ return result;
+ }
+ /**
+ * Creates a new rotation matrix for "angle" radians around the Y axis
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#99
+ * @param angle defines the angle (in radians) to use
+ * @returns the new matrix
+ */
+ static RotationY(angle) {
+ const result = new Matrix();
+ Matrix.RotationYToRef(angle, result);
+ return result;
+ }
+ /**
+ * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#100
+ * @param angle defines the angle (in radians) to use
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static RotationYToRef(angle, result) {
+ const s = Math.sin(angle);
+ const c = Math.cos(angle);
+ Matrix.FromValuesToRef(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
+ result._updateIdentityStatus(c === 1 && s === 0);
+ return result;
+ }
+ /**
+ * Creates a new rotation matrix for "angle" radians around the Z axis
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#101
+ * @param angle defines the angle (in radians) to use
+ * @returns the new matrix
+ */
+ static RotationZ(angle) {
+ const result = new Matrix();
+ Matrix.RotationZToRef(angle, result);
+ return result;
+ }
+ /**
+ * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#102
+ * @param angle defines the angle (in radians) to use
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static RotationZToRef(angle, result) {
+ const s = Math.sin(angle);
+ const c = Math.cos(angle);
+ Matrix.FromValuesToRef(c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
+ result._updateIdentityStatus(c === 1 && s === 0);
+ return result;
+ }
+ /**
+ * Creates a new rotation matrix for "angle" radians around the given axis
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#96
+ * @param axis defines the axis to use
+ * @param angle defines the angle (in radians) to use
+ * @returns the new matrix
+ */
+ static RotationAxis(axis, angle) {
+ const result = new Matrix();
+ Matrix.RotationAxisToRef(axis, angle, result);
+ return result;
+ }
+ /**
+ * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#94
+ * @param axis defines the axis to use
+ * @param angle defines the angle (in radians) to use
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static RotationAxisToRef(axis, angle, result) {
+ const s = Math.sin(-angle);
+ const c = Math.cos(-angle);
+ const c1 = 1 - c;
+ axis = axis.normalizeToRef(MathTmp.Vector3[0]);
+ const m = result._m;
+ m[0] = axis._x * axis._x * c1 + c;
+ m[1] = axis._x * axis._y * c1 - axis._z * s;
+ m[2] = axis._x * axis._z * c1 + axis._y * s;
+ m[3] = 0.0;
+ m[4] = axis._y * axis._x * c1 + axis._z * s;
+ m[5] = axis._y * axis._y * c1 + c;
+ m[6] = axis._y * axis._z * c1 - axis._x * s;
+ m[7] = 0.0;
+ m[8] = axis._z * axis._x * c1 - axis._y * s;
+ m[9] = axis._z * axis._y * c1 + axis._x * s;
+ m[10] = axis._z * axis._z * c1 + c;
+ m[11] = 0.0;
+ m[12] = 0.0;
+ m[13] = 0.0;
+ m[14] = 0.0;
+ m[15] = 1.0;
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Takes normalised vectors and returns a rotation matrix to align "from" with "to".
+ * Taken from http://www.iquilezles.org/www/articles/noacos/noacos.htm
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#93
+ * @param from defines the vector to align
+ * @param to defines the vector to align to
+ * @param result defines the target matrix
+ * @param useYAxisForCoplanar defines a boolean indicating that we should favor Y axis for coplanar vectors (default is false)
+ * @returns result input
+ */
+ static RotationAlignToRef(from, to, result, useYAxisForCoplanar = false) {
+ const c = Vector3.Dot(to, from);
+ const m = result._m;
+ if (c < -1 + Epsilon) {
+ // from and to are colinear and opposite direction.
+ // compute a PI rotation on Y axis
+ m[0] = -1;
+ m[1] = 0;
+ m[2] = 0;
+ m[3] = 0;
+ m[4] = 0;
+ m[5] = useYAxisForCoplanar ? 1 : -1;
+ m[6] = 0;
+ m[7] = 0;
+ m[8] = 0;
+ m[9] = 0;
+ m[10] = useYAxisForCoplanar ? -1 : 1;
+ m[11] = 0;
+ }
+ else {
+ const v = Vector3.Cross(to, from);
+ const k = 1 / (1 + c);
+ m[0] = v._x * v._x * k + c;
+ m[1] = v._y * v._x * k - v._z;
+ m[2] = v._z * v._x * k + v._y;
+ m[3] = 0;
+ m[4] = v._x * v._y * k + v._z;
+ m[5] = v._y * v._y * k + c;
+ m[6] = v._z * v._y * k - v._x;
+ m[7] = 0;
+ m[8] = v._x * v._z * k - v._y;
+ m[9] = v._y * v._z * k + v._x;
+ m[10] = v._z * v._z * k + c;
+ m[11] = 0;
+ }
+ m[12] = 0;
+ m[13] = 0;
+ m[14] = 0;
+ m[15] = 1;
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Creates a rotation matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#103
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#105
+ * @param yaw defines the yaw angle in radians (Y axis)
+ * @param pitch defines the pitch angle in radians (X axis)
+ * @param roll defines the roll angle in radians (Z axis)
+ * @returns the new rotation matrix
+ */
+ static RotationYawPitchRoll(yaw, pitch, roll) {
+ const result = new Matrix();
+ Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
+ return result;
+ }
+ /**
+ * Creates a rotation matrix and stores it in a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#104
+ * @param yaw defines the yaw angle in radians (Y axis)
+ * @param pitch defines the pitch angle in radians (X axis)
+ * @param roll defines the roll angle in radians (Z axis)
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static RotationYawPitchRollToRef(yaw, pitch, roll, result) {
+ Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
+ MathTmp.Quaternion[0].toRotationMatrix(result);
+ return result;
+ }
+ /**
+ * Creates a scaling matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#107
+ * @param x defines the scale factor on X axis
+ * @param y defines the scale factor on Y axis
+ * @param z defines the scale factor on Z axis
+ * @returns the new matrix
+ */
+ static Scaling(x, y, z) {
+ const result = new Matrix();
+ Matrix.ScalingToRef(x, y, z, result);
+ return result;
+ }
+ /**
+ * Creates a scaling matrix and stores it in a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#108
+ * @param x defines the scale factor on X axis
+ * @param y defines the scale factor on Y axis
+ * @param z defines the scale factor on Z axis
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static ScalingToRef(x, y, z, result) {
+ Matrix.FromValuesToRef(x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
+ result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
+ return result;
+ }
+ /**
+ * Creates a translation matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#109
+ * @param x defines the translation on X axis
+ * @param y defines the translation on Y axis
+ * @param z defines the translationon Z axis
+ * @returns the new matrix
+ */
+ static Translation(x, y, z) {
+ const result = new Matrix();
+ Matrix.TranslationToRef(x, y, z, result);
+ return result;
+ }
+ /**
+ * Creates a translation matrix and stores it in a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#110
+ * @param x defines the translation on X axis
+ * @param y defines the translation on Y axis
+ * @param z defines the translationon Z axis
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static TranslationToRef(x, y, z, result) {
+ Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
+ result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
+ return result;
+ }
+ /**
+ * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#55
+ * @param startValue defines the start value
+ * @param endValue defines the end value
+ * @param gradient defines the gradient factor
+ * @returns the new matrix
+ */
+ static Lerp(startValue, endValue, gradient) {
+ const result = new Matrix();
+ Matrix.LerpToRef(startValue, endValue, gradient, result);
+ return result;
+ }
+ /**
+ * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#54
+ * @param startValue defines the start value
+ * @param endValue defines the end value
+ * @param gradient defines the gradient factor
+ * @param result defines the Matrix object where to store data
+ * @returns result input
+ */
+ static LerpToRef(startValue, endValue, gradient, result) {
+ const resultM = result._m;
+ const startM = startValue.m;
+ const endM = endValue.m;
+ for (let index = 0; index < 16; index++) {
+ resultM[index] = startM[index] * (1.0 - gradient) + endM[index] * gradient;
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Builds a new matrix whose values are computed by:
+ * * decomposing the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
+ * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
+ * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#22
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#51
+ * @param startValue defines the first matrix
+ * @param endValue defines the second matrix
+ * @param gradient defines the gradient between the two matrices
+ * @returns the new matrix
+ */
+ static DecomposeLerp(startValue, endValue, gradient) {
+ const result = new Matrix();
+ Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
+ return result;
+ }
+ /**
+ * Update a matrix to values which are computed by:
+ * * decomposing the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
+ * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
+ * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#23
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#53
+ * @param startValue defines the first matrix
+ * @param endValue defines the second matrix
+ * @param gradient defines the gradient between the two matrices
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static DecomposeLerpToRef(startValue, endValue, gradient, result) {
+ const startScale = MathTmp.Vector3[0];
+ const startRotation = MathTmp.Quaternion[0];
+ const startTranslation = MathTmp.Vector3[1];
+ startValue.decompose(startScale, startRotation, startTranslation);
+ const endScale = MathTmp.Vector3[2];
+ const endRotation = MathTmp.Quaternion[1];
+ const endTranslation = MathTmp.Vector3[3];
+ endValue.decompose(endScale, endRotation, endTranslation);
+ const resultScale = MathTmp.Vector3[4];
+ Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
+ const resultRotation = MathTmp.Quaternion[2];
+ Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
+ const resultTranslation = MathTmp.Vector3[5];
+ Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
+ Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
+ return result;
+ }
+ /**
+ * Creates a new matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera.
+ * This function generates a matrix suitable for a left handed coordinate system
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#58
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#59
+ * @param eye defines the final position of the entity
+ * @param target defines where the entity should look at
+ * @param up defines the up vector for the entity
+ * @returns the new matrix
+ */
+ static LookAtLH(eye, target, up) {
+ const result = new Matrix();
+ Matrix.LookAtLHToRef(eye, target, up, result);
+ return result;
+ }
+ /**
+ * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera.
+ * This function generates a matrix suitable for a left handed coordinate system
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#60
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#61
+ * @param eye defines the final position of the entity
+ * @param target defines where the entity should look at
+ * @param up defines the up vector for the entity
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static LookAtLHToRef(eye, target, up, result) {
+ const xAxis = MathTmp.Vector3[0];
+ const yAxis = MathTmp.Vector3[1];
+ const zAxis = MathTmp.Vector3[2];
+ // Z axis
+ target.subtractToRef(eye, zAxis);
+ zAxis.normalize();
+ // X axis
+ Vector3.CrossToRef(up, zAxis, xAxis);
+ const xSquareLength = xAxis.lengthSquared();
+ if (xSquareLength === 0) {
+ xAxis.x = 1.0;
+ }
+ else {
+ xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
+ }
+ // Y axis
+ Vector3.CrossToRef(zAxis, xAxis, yAxis);
+ yAxis.normalize();
+ // Eye angles
+ const ex = -Vector3.Dot(xAxis, eye);
+ const ey = -Vector3.Dot(yAxis, eye);
+ const ez = -Vector3.Dot(zAxis, eye);
+ Matrix.FromValuesToRef(xAxis._x, yAxis._x, zAxis._x, 0.0, xAxis._y, yAxis._y, zAxis._y, 0.0, xAxis._z, yAxis._z, zAxis._z, 0.0, ex, ey, ez, 1.0, result);
+ return result;
+ }
+ /**
+ * Creates a new matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera.
+ * This function generates a matrix suitable for a right handed coordinate system
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#62
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#63
+ * @param eye defines the final position of the entity
+ * @param target defines where the entity should look at
+ * @param up defines the up vector for the entity
+ * @returns the new matrix
+ */
+ static LookAtRH(eye, target, up) {
+ const result = new Matrix();
+ Matrix.LookAtRHToRef(eye, target, up, result);
+ return result;
+ }
+ /**
+ * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera.
+ * This function generates a matrix suitable for a right handed coordinate system
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#64
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#65
+ * @param eye defines the final position of the entity
+ * @param target defines where the entity should look at
+ * @param up defines the up vector for the entity
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static LookAtRHToRef(eye, target, up, result) {
+ const xAxis = MathTmp.Vector3[0];
+ const yAxis = MathTmp.Vector3[1];
+ const zAxis = MathTmp.Vector3[2];
+ // Z axis
+ eye.subtractToRef(target, zAxis);
+ zAxis.normalize();
+ // X axis
+ Vector3.CrossToRef(up, zAxis, xAxis);
+ const xSquareLength = xAxis.lengthSquared();
+ if (xSquareLength === 0) {
+ xAxis.x = 1.0;
+ }
+ else {
+ xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
+ }
+ // Y axis
+ Vector3.CrossToRef(zAxis, xAxis, yAxis);
+ yAxis.normalize();
+ // Eye angles
+ const ex = -Vector3.Dot(xAxis, eye);
+ const ey = -Vector3.Dot(yAxis, eye);
+ const ez = -Vector3.Dot(zAxis, eye);
+ Matrix.FromValuesToRef(xAxis._x, yAxis._x, zAxis._x, 0.0, xAxis._y, yAxis._y, zAxis._y, 0.0, xAxis._z, yAxis._z, zAxis._z, 0.0, ex, ey, ez, 1.0, result);
+ return result;
+ }
+ /**
+ * Creates a new matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0)
+ * This function generates a matrix suitable for a left handed coordinate system
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#66
+ * @param forward defines the forward direction - Must be normalized and orthogonal to up.
+ * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward.
+ * @returns the new matrix
+ */
+ static LookDirectionLH(forward, up) {
+ const result = new Matrix();
+ Matrix.LookDirectionLHToRef(forward, up, result);
+ return result;
+ }
+ /**
+ * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0)
+ * This function generates a matrix suitable for a left handed coordinate system
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#67
+ * @param forward defines the forward direction - Must be normalized and orthogonal to up.
+ * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward.
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static LookDirectionLHToRef(forward, up, result) {
+ const back = MathTmp.Vector3[0];
+ back.copyFrom(forward);
+ back.scaleInPlace(-1);
+ const left = MathTmp.Vector3[1];
+ Vector3.CrossToRef(up, back, left);
+ // Generate the rotation matrix.
+ Matrix.FromValuesToRef(left._x, left._y, left._z, 0.0, up._x, up._y, up._z, 0.0, back._x, back._y, back._z, 0.0, 0, 0, 0, 1.0, result);
+ return result;
+ }
+ /**
+ * Creates a new matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0)
+ * This function generates a matrix suitable for a right handed coordinate system
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#68
+ * @param forward defines the forward direction - Must be normalized and orthogonal to up.
+ * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward.
+ * @returns the new matrix
+ */
+ static LookDirectionRH(forward, up) {
+ const result = new Matrix();
+ Matrix.LookDirectionRHToRef(forward, up, result);
+ return result;
+ }
+ /**
+ * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0)
+ * This function generates a matrix suitable for a right handed coordinate system
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#69
+ * @param forward defines the forward direction - Must be normalized and orthogonal to up.
+ * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward.
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static LookDirectionRHToRef(forward, up, result) {
+ const right = MathTmp.Vector3[2];
+ Vector3.CrossToRef(up, forward, right);
+ // Generate the rotation matrix.
+ Matrix.FromValuesToRef(right._x, right._y, right._z, 0.0, up._x, up._y, up._z, 0.0, forward._x, forward._y, forward._z, 0.0, 0, 0, 0, 1.0, result);
+ return result;
+ }
+ /**
+ * Create a left-handed orthographic projection matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#70
+ * @param width defines the viewport width
+ * @param height defines the viewport height
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @returns a new matrix as a left-handed orthographic projection matrix
+ */
+ static OrthoLH(width, height, znear, zfar, halfZRange) {
+ const matrix = new Matrix();
+ Matrix.OrthoLHToRef(width, height, znear, zfar, matrix, halfZRange);
+ return matrix;
+ }
+ /**
+ * Store a left-handed orthographic projection to a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#71
+ * @param width defines the viewport width
+ * @param height defines the viewport height
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param result defines the target matrix
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @returns result input
+ */
+ static OrthoLHToRef(width, height, znear, zfar, result, halfZRange) {
+ const n = znear;
+ const f = zfar;
+ const a = 2.0 / width;
+ const b = 2.0 / height;
+ const c = 2.0 / (f - n);
+ const d = -(f + n) / (f - n);
+ Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
+ if (halfZRange) {
+ result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
+ }
+ result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
+ return result;
+ }
+ /**
+ * Create a left-handed orthographic projection matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#72
+ * @param left defines the viewport left coordinate
+ * @param right defines the viewport right coordinate
+ * @param bottom defines the viewport bottom coordinate
+ * @param top defines the viewport top coordinate
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @returns a new matrix as a left-handed orthographic projection matrix
+ */
+ static OrthoOffCenterLH(left, right, bottom, top, znear, zfar, halfZRange) {
+ const matrix = new Matrix();
+ Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix, halfZRange);
+ return matrix;
+ }
+ /**
+ * Stores a left-handed orthographic projection into a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#73
+ * @param left defines the viewport left coordinate
+ * @param right defines the viewport right coordinate
+ * @param bottom defines the viewport bottom coordinate
+ * @param top defines the viewport top coordinate
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param result defines the target matrix
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @returns result input
+ */
+ static OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) {
+ const n = znear;
+ const f = zfar;
+ const a = 2.0 / (right - left);
+ const b = 2.0 / (top - bottom);
+ const c = 2.0 / (f - n);
+ const d = -(f + n) / (f - n);
+ const i0 = (left + right) / (left - right);
+ const i1 = (top + bottom) / (bottom - top);
+ Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
+ if (halfZRange) {
+ result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
+ }
+ result.markAsUpdated();
+ return result;
+ }
+ /**
+ * Stores a left-handed oblique projection into a given matrix
+ * @param left defines the viewport left coordinate
+ * @param right defines the viewport right coordinate
+ * @param bottom defines the viewport bottom coordinate
+ * @param top defines the viewport top coordinate
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param length Length of the shear
+ * @param angle Angle (along X/Y Plane) to apply shear
+ * @param distance Distance from shear point
+ * @param result defines the target matrix
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @returns result input
+ */
+ static ObliqueOffCenterLHToRef(left, right, bottom, top, znear, zfar, length, angle, distance, result, halfZRange) {
+ const a = -length * Math.cos(angle);
+ const b = -length * Math.sin(angle);
+ Matrix.TranslationToRef(0, 0, -distance, MathTmp.Matrix[1]);
+ Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, a, b, 1, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
+ MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], MathTmp.Matrix[0]);
+ Matrix.TranslationToRef(0, 0, distance, MathTmp.Matrix[1]);
+ MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1], MathTmp.Matrix[0]);
+ Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange);
+ MathTmp.Matrix[0].multiplyToRef(result, result);
+ return result;
+ }
+ /**
+ * Creates a right-handed orthographic projection matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#76
+ * @param left defines the viewport left coordinate
+ * @param right defines the viewport right coordinate
+ * @param bottom defines the viewport bottom coordinate
+ * @param top defines the viewport top coordinate
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @returns a new matrix as a right-handed orthographic projection matrix
+ */
+ static OrthoOffCenterRH(left, right, bottom, top, znear, zfar, halfZRange) {
+ const matrix = new Matrix();
+ Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix, halfZRange);
+ return matrix;
+ }
+ /**
+ * Stores a right-handed orthographic projection into a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#77
+ * @param left defines the viewport left coordinate
+ * @param right defines the viewport right coordinate
+ * @param bottom defines the viewport bottom coordinate
+ * @param top defines the viewport top coordinate
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param result defines the target matrix
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @returns result input
+ */
+ static OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) {
+ Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange);
+ result._m[10] *= -1; // No need to call markAsUpdated as previous function already called it and let _isIdentityDirty to true
+ return result;
+ }
+ /**
+ * Stores a right-handed oblique projection into a given matrix
+ * @param left defines the viewport left coordinate
+ * @param right defines the viewport right coordinate
+ * @param bottom defines the viewport bottom coordinate
+ * @param top defines the viewport top coordinate
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param length Length of the shear
+ * @param angle Angle (along X/Y Plane) to apply shear
+ * @param distance Distance from shear point
+ * @param result defines the target matrix
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @returns result input
+ */
+ static ObliqueOffCenterRHToRef(left, right, bottom, top, znear, zfar, length, angle, distance, result, halfZRange) {
+ const a = length * Math.cos(angle);
+ const b = length * Math.sin(angle);
+ Matrix.TranslationToRef(0, 0, distance, MathTmp.Matrix[1]);
+ Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, a, b, 1, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
+ MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], MathTmp.Matrix[0]);
+ Matrix.TranslationToRef(0, 0, -distance, MathTmp.Matrix[1]);
+ MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1], MathTmp.Matrix[0]);
+ Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, result, halfZRange);
+ MathTmp.Matrix[0].multiplyToRef(result, result);
+ return result;
+ }
+ /**
+ * Creates a left-handed perspective projection matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#85
+ * @param width defines the viewport width
+ * @param height defines the viewport height
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal)
+ * @returns a new matrix as a left-handed perspective projection matrix
+ */
+ static PerspectiveLH(width, height, znear, zfar, halfZRange, projectionPlaneTilt = 0) {
+ const matrix = new Matrix();
+ const n = znear;
+ const f = zfar;
+ const a = (2.0 * n) / width;
+ const b = (2.0 * n) / height;
+ const c = (f + n) / (f - n);
+ const d = (-2 * f * n) / (f - n);
+ const rot = Math.tan(projectionPlaneTilt);
+ Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
+ if (halfZRange) {
+ matrix.multiplyToRef(mtxConvertNDCToHalfZRange, matrix);
+ }
+ matrix._updateIdentityStatus(false);
+ return matrix;
+ }
+ /**
+ * Creates a left-handed perspective projection matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#78
+ * @param fov defines the horizontal field of view
+ * @param aspect defines the aspect ratio
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal)
+ * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function)
+ * @returns a new matrix as a left-handed perspective projection matrix
+ */
+ static PerspectiveFovLH(fov, aspect, znear, zfar, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) {
+ const matrix = new Matrix();
+ Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix, true, halfZRange, projectionPlaneTilt, reverseDepthBufferMode);
+ return matrix;
+ }
+ /**
+ * Stores a left-handed perspective projection into a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#81
+ * @param fov defines the horizontal field of view
+ * @param aspect defines the aspect ratio
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode
+ * @param result defines the target matrix
+ * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal)
+ * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function)
+ * @returns result input
+ */
+ static PerspectiveFovLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) {
+ const n = znear;
+ const f = zfar;
+ const t = 1.0 / Math.tan(fov * 0.5);
+ const a = isVerticalFovFixed ? t / aspect : t;
+ const b = isVerticalFovFixed ? t : t * aspect;
+ const c = reverseDepthBufferMode && n === 0 ? -1 : f !== 0 ? (f + n) / (f - n) : 1;
+ const d = reverseDepthBufferMode && n === 0 ? 2 * f : f !== 0 ? (-2 * f * n) / (f - n) : -2 * n;
+ const rot = Math.tan(projectionPlaneTilt);
+ Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
+ if (halfZRange) {
+ result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
+ }
+ result._updateIdentityStatus(false);
+ return result;
+ }
+ /**
+ * Stores a left-handed perspective projection into a given matrix with depth reversed
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#89
+ * @param fov defines the horizontal field of view
+ * @param aspect defines the aspect ratio
+ * @param znear defines the near clip plane
+ * @param zfar not used as infinity is used as far clip
+ * @param result defines the target matrix
+ * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal)
+ * @returns result input
+ */
+ static PerspectiveFovReverseLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) {
+ const t = 1.0 / Math.tan(fov * 0.5);
+ const a = isVerticalFovFixed ? t / aspect : t;
+ const b = isVerticalFovFixed ? t : t * aspect;
+ const rot = Math.tan(projectionPlaneTilt);
+ Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, -znear, 1.0, 0.0, 0.0, 1.0, 0.0, result);
+ if (halfZRange) {
+ result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
+ }
+ result._updateIdentityStatus(false);
+ return result;
+ }
+ /**
+ * Creates a right-handed perspective projection matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#83
+ * @param fov defines the horizontal field of view
+ * @param aspect defines the aspect ratio
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal)
+ * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function)
+ * @returns a new matrix as a right-handed perspective projection matrix
+ */
+ static PerspectiveFovRH(fov, aspect, znear, zfar, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) {
+ const matrix = new Matrix();
+ Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix, true, halfZRange, projectionPlaneTilt, reverseDepthBufferMode);
+ return matrix;
+ }
+ /**
+ * Stores a right-handed perspective projection into a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#84
+ * @param fov defines the horizontal field of view
+ * @param aspect defines the aspect ratio
+ * @param znear defines the near clip plane
+ * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode
+ * @param result defines the target matrix
+ * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal)
+ * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function)
+ * @returns result input
+ */
+ static PerspectiveFovRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) {
+ //alternatively this could be expressed as:
+ // m = PerspectiveFovLHToRef
+ // m[10] *= -1.0;
+ // m[11] *= -1.0;
+ const n = znear;
+ const f = zfar;
+ const t = 1.0 / Math.tan(fov * 0.5);
+ const a = isVerticalFovFixed ? t / aspect : t;
+ const b = isVerticalFovFixed ? t : t * aspect;
+ const c = reverseDepthBufferMode && n === 0 ? 1 : f !== 0 ? -(f + n) / (f - n) : -1;
+ const d = reverseDepthBufferMode && n === 0 ? 2 * f : f !== 0 ? (-2 * f * n) / (f - n) : -2 * n;
+ const rot = Math.tan(projectionPlaneTilt);
+ Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, -1, 0.0, 0.0, d, 0.0, result);
+ if (halfZRange) {
+ result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
+ }
+ result._updateIdentityStatus(false);
+ return result;
+ }
+ /**
+ * Stores a right-handed perspective projection into a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#90
+ * @param fov defines the horizontal field of view
+ * @param aspect defines the aspect ratio
+ * @param znear defines the near clip plane
+ * @param zfar not used as infinity is used as far clip
+ * @param result defines the target matrix
+ * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
+ * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false)
+ * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal)
+ * @returns result input
+ */
+ static PerspectiveFovReverseRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) {
+ const t = 1.0 / Math.tan(fov * 0.5);
+ const a = isVerticalFovFixed ? t / aspect : t;
+ const b = isVerticalFovFixed ? t : t * aspect;
+ const rot = Math.tan(projectionPlaneTilt);
+ Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, -znear, -1, 0.0, 0.0, -1, 0.0, result);
+ if (halfZRange) {
+ result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
+ }
+ result._updateIdentityStatus(false);
+ return result;
+ }
+ /**
+ * Computes a complete transformation matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#113
+ * @param viewport defines the viewport to use
+ * @param world defines the world matrix
+ * @param view defines the view matrix
+ * @param projection defines the projection matrix
+ * @param zmin defines the near clip plane
+ * @param zmax defines the far clip plane
+ * @returns the transformation matrix
+ */
+ static GetFinalMatrix(viewport, world, view, projection, zmin, zmax) {
+ const cw = viewport.width;
+ const ch = viewport.height;
+ const cx = viewport.x;
+ const cy = viewport.y;
+ const viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1.0);
+ const matrix = new Matrix();
+ world.multiplyToRef(view, matrix);
+ matrix.multiplyToRef(projection, matrix);
+ return matrix.multiplyToRef(viewportMatrix, matrix);
+ }
+ /**
+ * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
+ * @param matrix defines the matrix to use
+ * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
+ */
+ static GetAsMatrix2x2(matrix) {
+ const m = matrix.m;
+ const arr = [m[0], m[1], m[4], m[5]];
+ return PerformanceConfigurator.MatrixUse64Bits ? arr : new Float32Array(arr);
+ }
+ /**
+ * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
+ * @param matrix defines the matrix to use
+ * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
+ */
+ static GetAsMatrix3x3(matrix) {
+ const m = matrix.m;
+ const arr = [m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]];
+ return PerformanceConfigurator.MatrixUse64Bits ? arr : new Float32Array(arr);
+ }
+ /**
+ * Compute the transpose of a given matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#111
+ * @param matrix defines the matrix to transpose
+ * @returns the new matrix
+ */
+ static Transpose(matrix) {
+ const result = new Matrix();
+ Matrix.TransposeToRef(matrix, result);
+ return result;
+ }
+ /**
+ * Compute the transpose of a matrix and store it in a target matrix
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#112
+ * @param matrix defines the matrix to transpose
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static TransposeToRef(matrix, result) {
+ const mm = matrix.m;
+ const rm0 = mm[0];
+ const rm1 = mm[4];
+ const rm2 = mm[8];
+ const rm3 = mm[12];
+ const rm4 = mm[1];
+ const rm5 = mm[5];
+ const rm6 = mm[9];
+ const rm7 = mm[13];
+ const rm8 = mm[2];
+ const rm9 = mm[6];
+ const rm10 = mm[10];
+ const rm11 = mm[14];
+ const rm12 = mm[3];
+ const rm13 = mm[7];
+ const rm14 = mm[11];
+ const rm15 = mm[15];
+ const rm = result._m;
+ rm[0] = rm0;
+ rm[1] = rm1;
+ rm[2] = rm2;
+ rm[3] = rm3;
+ rm[4] = rm4;
+ rm[5] = rm5;
+ rm[6] = rm6;
+ rm[7] = rm7;
+ rm[8] = rm8;
+ rm[9] = rm9;
+ rm[10] = rm10;
+ rm[11] = rm11;
+ rm[12] = rm12;
+ rm[13] = rm13;
+ rm[14] = rm14;
+ rm[15] = rm15;
+ result.markAsUpdated();
+ // identity-ness does not change when transposing
+ result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
+ return result;
+ }
+ /**
+ * Computes a reflection matrix from a plane
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#87
+ * @param plane defines the reflection plane
+ * @returns a new matrix
+ */
+ static Reflection(plane) {
+ const matrix = new Matrix();
+ Matrix.ReflectionToRef(plane, matrix);
+ return matrix;
+ }
+ /**
+ * Computes a reflection matrix from a plane
+ * Example Playground - https://playground.babylonjs.com/#AV9X17#88
+ * @param plane defines the reflection plane
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static ReflectionToRef(plane, result) {
+ plane.normalize();
+ const x = plane.normal.x;
+ const y = plane.normal.y;
+ const z = plane.normal.z;
+ const temp = -2 * x;
+ const temp2 = -2 * y;
+ const temp3 = -2 * z;
+ Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0.0, temp * y, temp2 * y + 1, temp3 * y, 0.0, temp * z, temp2 * z, temp3 * z + 1, 0.0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0, result);
+ return result;
+ }
+ /**
+ * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
+ * @param xaxis defines the value of the 1st axis
+ * @param yaxis defines the value of the 2nd axis
+ * @param zaxis defines the value of the 3rd axis
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static FromXYZAxesToRef(xaxis, yaxis, zaxis, result) {
+ Matrix.FromValuesToRef(xaxis._x, xaxis._y, xaxis._z, 0.0, yaxis._x, yaxis._y, yaxis._z, 0.0, zaxis._x, zaxis._y, zaxis._z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
+ return result;
+ }
+ /**
+ * Creates a rotation matrix from a quaternion and stores it in a target matrix
+ * @param quat defines the quaternion to use
+ * @param result defines the target matrix
+ * @returns result input
+ */
+ static FromQuaternionToRef(quat, result) {
+ const xx = quat._x * quat._x;
+ const yy = quat._y * quat._y;
+ const zz = quat._z * quat._z;
+ const xy = quat._x * quat._y;
+ const zw = quat._z * quat._w;
+ const zx = quat._z * quat._x;
+ const yw = quat._y * quat._w;
+ const yz = quat._y * quat._z;
+ const xw = quat._x * quat._w;
+ result._m[0] = 1.0 - 2.0 * (yy + zz);
+ result._m[1] = 2.0 * (xy + zw);
+ result._m[2] = 2.0 * (zx - yw);
+ result._m[3] = 0.0;
+ result._m[4] = 2.0 * (xy - zw);
+ result._m[5] = 1.0 - 2.0 * (zz + xx);
+ result._m[6] = 2.0 * (yz + xw);
+ result._m[7] = 0.0;
+ result._m[8] = 2.0 * (zx + yw);
+ result._m[9] = 2.0 * (yz - xw);
+ result._m[10] = 1.0 - 2.0 * (yy + xx);
+ result._m[11] = 0.0;
+ result._m[12] = 0.0;
+ result._m[13] = 0.0;
+ result._m[14] = 0.0;
+ result._m[15] = 1.0;
+ result.markAsUpdated();
+ return result;
+ }
+}
+Matrix._UpdateFlagSeed = 0;
+Matrix._IdentityReadOnly = Matrix.Identity();
+Object.defineProperties(Matrix.prototype, {
+ dimension: { value: [4, 4] },
+ rank: { value: 2 },
+});
+/**
+ * @internal
+ * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
+ */
+class MathTmp {
+}
+// Temporary Vector3s
+MathTmp.Vector3 = BuildTuple(11, Vector3.Zero);
+// Temporary Matricies
+MathTmp.Matrix = BuildTuple(2, Matrix.Identity);
+// Temporary Quaternions
+MathTmp.Quaternion = BuildTuple(3, Quaternion.Zero);
+/**
+ * @internal
+ */
+class TmpVectors {
+}
+/** 3 temp Vector2 at once should be enough */
+TmpVectors.Vector2 = BuildTuple(3, Vector2.Zero);
+/** 13 temp Vector3 at once should be enough */
+TmpVectors.Vector3 = BuildTuple(13, Vector3.Zero);
+/** 3 temp Vector4 at once should be enough */
+TmpVectors.Vector4 = BuildTuple(3, Vector4.Zero);
+/** 3 temp Quaternion at once should be enough */
+TmpVectors.Quaternion = BuildTuple(3, Quaternion.Zero);
+/** 8 temp Matrices at once should be enough */
+TmpVectors.Matrix = BuildTuple(8, Matrix.Identity);
+RegisterClass("BABYLON.Vector2", Vector2);
+RegisterClass("BABYLON.Vector3", Vector3);
+RegisterClass("BABYLON.Vector4", Vector4);
+RegisterClass("BABYLON.Matrix", Matrix);
+const mtxConvertNDCToHalfZRange = Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1);
+
+/** Defines supported spaces */
+var Space;
+(function (Space) {
+ /** Local (object) space */
+ Space[Space["LOCAL"] = 0] = "LOCAL";
+ /** World space */
+ Space[Space["WORLD"] = 1] = "WORLD";
+ /** Bone space */
+ Space[Space["BONE"] = 2] = "BONE";
+})(Space || (Space = {}));
+/** Defines the 3 main axes */
+class Axis {
+}
+/** X axis */
+Axis.X = new Vector3(1.0, 0.0, 0.0);
+/** Y axis */
+Axis.Y = new Vector3(0.0, 1.0, 0.0);
+/** Z axis */
+Axis.Z = new Vector3(0.0, 0.0, 1.0);
+/**
+ * Defines cartesian components.
+ */
+var Coordinate;
+(function (Coordinate) {
+ /** X axis */
+ Coordinate[Coordinate["X"] = 0] = "X";
+ /** Y axis */
+ Coordinate[Coordinate["Y"] = 1] = "Y";
+ /** Z axis */
+ Coordinate[Coordinate["Z"] = 2] = "Z";
+})(Coordinate || (Coordinate = {}));
+
+function colorChannelToLinearSpace(color) {
+ return Math.pow(color, ToLinearSpace);
+}
+function colorChannelToLinearSpaceExact(color) {
+ if (color <= 0.04045) {
+ return 0.0773993808 * color;
+ }
+ return Math.pow(0.947867299 * (color + 0.055), 2.4);
+}
+function colorChannelToGammaSpace(color) {
+ return Math.pow(color, ToGammaSpace);
+}
+function colorChannelToGammaSpaceExact(color) {
+ if (color <= 0.0031308) {
+ return 12.92 * color;
+ }
+ return 1.055 * Math.pow(color, 0.41666) - 0.055;
+}
+/**
+ * Class used to hold a RGB color
+ */
+class Color3 {
+ /**
+ * Creates a new Color3 object from red, green, blue values, all between 0 and 1
+ * @param r defines the red component (between 0 and 1, default is 0)
+ * @param g defines the green component (between 0 and 1, default is 0)
+ * @param b defines the blue component (between 0 and 1, default is 0)
+ */
+ constructor(
+ /**
+ * [0] Defines the red component (between 0 and 1, default is 0)
+ */
+ r = 0,
+ /**
+ * [0] Defines the green component (between 0 and 1, default is 0)
+ */
+ g = 0,
+ /**
+ * [0] Defines the blue component (between 0 and 1, default is 0)
+ */
+ b = 0) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ }
+ /**
+ * Creates a string with the Color3 current values
+ * @returns the string representation of the Color3 object
+ */
+ toString() {
+ return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
+ }
+ /**
+ * Returns the string "Color3"
+ * @returns "Color3"
+ */
+ getClassName() {
+ return "Color3";
+ }
+ /**
+ * Compute the Color3 hash code
+ * @returns an unique number that can be used to hash Color3 objects
+ */
+ getHashCode() {
+ let hash = (this.r * 255) | 0;
+ hash = (hash * 397) ^ ((this.g * 255) | 0);
+ hash = (hash * 397) ^ ((this.b * 255) | 0);
+ return hash;
+ }
+ // Operators
+ /**
+ * Stores in the given array from the given starting index the red, green, blue values as successive elements
+ * @param array defines the array where to store the r,g,b components
+ * @param index defines an optional index in the target array to define where to start storing values
+ * @returns the current Color3 object
+ */
+ toArray(array, index = 0) {
+ array[index] = this.r;
+ array[index + 1] = this.g;
+ array[index + 2] = this.b;
+ return this;
+ }
+ /**
+ * Update the current color with values stored in an array from the starting index of the given array
+ * @param array defines the source array
+ * @param offset defines an offset in the source array
+ * @returns the current Color3 object
+ */
+ fromArray(array, offset = 0) {
+ Color3.FromArrayToRef(array, offset, this);
+ return this;
+ }
+ /**
+ * Returns a new Color4 object from the current Color3 and the given alpha
+ * @param alpha defines the alpha component on the new Color4 object (default is 1)
+ * @returns a new Color4 object
+ */
+ toColor4(alpha = 1) {
+ return new Color4(this.r, this.g, this.b, alpha);
+ }
+ /**
+ * Returns a new array populated with 3 numeric elements : red, green and blue values
+ * @returns the new array
+ */
+ asArray() {
+ return [this.r, this.g, this.b];
+ }
+ /**
+ * Returns the luminance value
+ * @returns a float value
+ */
+ toLuminance() {
+ return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
+ }
+ /**
+ * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
+ * @param otherColor defines the second operand
+ * @returns the new Color3 object
+ */
+ multiply(otherColor) {
+ return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
+ }
+ /**
+ * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
+ * @param otherColor defines the second operand
+ * @param result defines the Color3 object where to store the result
+ * @returns the result Color3
+ */
+ multiplyToRef(otherColor, result) {
+ result.r = this.r * otherColor.r;
+ result.g = this.g * otherColor.g;
+ result.b = this.b * otherColor.b;
+ return result;
+ }
+ /**
+ * Multiplies the current Color3 coordinates by the given ones
+ * @param otherColor defines the second operand
+ * @returns the current updated Color3
+ */
+ multiplyInPlace(otherColor) {
+ this.r *= otherColor.r;
+ this.g *= otherColor.g;
+ this.b *= otherColor.b;
+ return this;
+ }
+ /**
+ * Returns a new Color3 set with the result of the multiplication of the current Color3 coordinates by the given floats
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @returns the new Color3
+ */
+ multiplyByFloats(r, g, b) {
+ return new Color3(this.r * r, this.g * g, this.b * b);
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divide(_other) {
+ throw new ReferenceError("Can not divide a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divideToRef(_other, _result) {
+ throw new ReferenceError("Can not divide a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divideInPlace(_other) {
+ throw new ReferenceError("Can not divide a color");
+ }
+ /**
+ * Updates the current Color3 with the minimal coordinate values between its and the given color ones
+ * @param other defines the second operand
+ * @returns the current updated Color3
+ */
+ minimizeInPlace(other) {
+ return this.minimizeInPlaceFromFloats(other.r, other.g, other.b);
+ }
+ /**
+ * Updates the current Color3 with the maximal coordinate values between its and the given color ones.
+ * @param other defines the second operand
+ * @returns the current updated Color3
+ */
+ maximizeInPlace(other) {
+ return this.maximizeInPlaceFromFloats(other.r, other.g, other.b);
+ }
+ /**
+ * Updates the current Color3 with the minimal coordinate values between its and the given coordinates
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @returns the current updated Color3
+ */
+ minimizeInPlaceFromFloats(r, g, b) {
+ this.r = Math.min(r, this.r);
+ this.g = Math.min(g, this.g);
+ this.b = Math.min(b, this.b);
+ return this;
+ }
+ /**
+ * Updates the current Color3 with the maximal coordinate values between its and the given coordinates.
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @returns the current updated Color3
+ */
+ maximizeInPlaceFromFloats(r, g, b) {
+ this.r = Math.max(r, this.r);
+ this.g = Math.max(g, this.g);
+ this.b = Math.max(b, this.b);
+ return this;
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ floorToRef(_result) {
+ throw new ReferenceError("Can not floor a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ floor() {
+ throw new ReferenceError("Can not floor a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ fractToRef(_result) {
+ throw new ReferenceError("Can not fract a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ fract() {
+ throw new ReferenceError("Can not fract a color");
+ }
+ /**
+ * Determines equality between Color3 objects
+ * @param otherColor defines the second operand
+ * @returns true if the rgb values are equal to the given ones
+ */
+ equals(otherColor) {
+ return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
+ }
+ /**
+ * Alias for equalsToFloats
+ * @param r red color component
+ * @param g green color component
+ * @param b blue color component
+ * @returns boolean
+ */
+ equalsFloats(r, g, b) {
+ return this.equalsToFloats(r, g, b);
+ }
+ /**
+ * Determines equality between the current Color3 object and a set of r,b,g values
+ * @param r defines the red component to check
+ * @param g defines the green component to check
+ * @param b defines the blue component to check
+ * @returns true if the rgb values are equal to the given ones
+ */
+ equalsToFloats(r, g, b) {
+ return this.r === r && this.g === g && this.b === b;
+ }
+ /**
+ * Returns true if the current Color3 and the given color coordinates are distant less than epsilon
+ * @param otherColor defines the second operand
+ * @param epsilon defines the minimal distance to define values as equals
+ * @returns true if both colors are distant less than epsilon
+ */
+ equalsWithEpsilon(otherColor, epsilon = Epsilon) {
+ return WithinEpsilon(this.r, otherColor.r, epsilon) && WithinEpsilon(this.g, otherColor.g, epsilon) && WithinEpsilon(this.b, otherColor.b, epsilon);
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ negate() {
+ throw new ReferenceError("Can not negate a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ negateInPlace() {
+ throw new ReferenceError("Can not negate a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ negateToRef(_result) {
+ throw new ReferenceError("Can not negate a color");
+ }
+ /**
+ * Creates a new Color3 with the current Color3 values multiplied by scale
+ * @param scale defines the scaling factor to apply
+ * @returns a new Color3 object
+ */
+ scale(scale) {
+ return new Color3(this.r * scale, this.g * scale, this.b * scale);
+ }
+ /**
+ * Multiplies the Color3 values by the float "scale"
+ * @param scale defines the scaling factor to apply
+ * @returns the current updated Color3
+ */
+ scaleInPlace(scale) {
+ this.r *= scale;
+ this.g *= scale;
+ this.b *= scale;
+ return this;
+ }
+ /**
+ * Multiplies the rgb values by scale and stores the result into "result"
+ * @param scale defines the scaling factor
+ * @param result defines the Color3 object where to store the result
+ * @returns the result Color3
+ */
+ scaleToRef(scale, result) {
+ result.r = this.r * scale;
+ result.g = this.g * scale;
+ result.b = this.b * scale;
+ return result;
+ }
+ /**
+ * Scale the current Color3 values by a factor and add the result to a given Color3
+ * @param scale defines the scale factor
+ * @param result defines color to store the result into
+ * @returns the result Color3
+ */
+ scaleAndAddToRef(scale, result) {
+ result.r += this.r * scale;
+ result.g += this.g * scale;
+ result.b += this.b * scale;
+ return result;
+ }
+ /**
+ * Clamps the rgb values by the min and max values and stores the result into "result"
+ * @param min defines minimum clamping value (default is 0)
+ * @param max defines maximum clamping value (default is 1)
+ * @param result defines color to store the result into
+ * @returns the result Color3
+ */
+ clampToRef(min = 0, max = 1, result) {
+ result.r = Clamp(this.r, min, max);
+ result.g = Clamp(this.g, min, max);
+ result.b = Clamp(this.b, min, max);
+ return result;
+ }
+ /**
+ * Creates a new Color3 set with the added values of the current Color3 and of the given one
+ * @param otherColor defines the second operand
+ * @returns the new Color3
+ */
+ add(otherColor) {
+ return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
+ }
+ /**
+ * Adds the given color to the current Color3
+ * @param otherColor defines the second operand
+ * @returns the current updated Color3
+ */
+ addInPlace(otherColor) {
+ this.r += otherColor.r;
+ this.g += otherColor.g;
+ this.b += otherColor.b;
+ return this;
+ }
+ /**
+ * Adds the given coordinates to the current Color3
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @returns the current updated Color3
+ */
+ addInPlaceFromFloats(r, g, b) {
+ this.r += r;
+ this.g += g;
+ this.b += b;
+ return this;
+ }
+ /**
+ * Stores the result of the addition of the current Color3 and given one rgb values into "result"
+ * @param otherColor defines the second operand
+ * @param result defines Color3 object to store the result into
+ * @returns the unmodified current Color3
+ */
+ addToRef(otherColor, result) {
+ result.r = this.r + otherColor.r;
+ result.g = this.g + otherColor.g;
+ result.b = this.b + otherColor.b;
+ return result;
+ }
+ /**
+ * Returns a new Color3 set with the subtracted values of the given one from the current Color3
+ * @param otherColor defines the second operand
+ * @returns the new Color3
+ */
+ subtract(otherColor) {
+ return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
+ }
+ /**
+ * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
+ * @param otherColor defines the second operand
+ * @param result defines Color3 object to store the result into
+ * @returns the unmodified current Color3
+ */
+ subtractToRef(otherColor, result) {
+ result.r = this.r - otherColor.r;
+ result.g = this.g - otherColor.g;
+ result.b = this.b - otherColor.b;
+ return result;
+ }
+ /**
+ * Subtract the given color from the current Color3
+ * @param otherColor defines the second operand
+ * @returns the current updated Color3
+ */
+ subtractInPlace(otherColor) {
+ this.r -= otherColor.r;
+ this.g -= otherColor.g;
+ this.b -= otherColor.b;
+ return this;
+ }
+ /**
+ * Returns a new Color3 set with the subtraction of the given floats from the current Color3 coordinates
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @returns the resulting Color3
+ */
+ subtractFromFloats(r, g, b) {
+ return new Color3(this.r - r, this.g - g, this.b - b);
+ }
+ /**
+ * Subtracts the given floats from the current Color3 coordinates and set the given color "result" with this result
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @param result defines the Color3 object where to store the result
+ * @returns the result
+ */
+ subtractFromFloatsToRef(r, g, b, result) {
+ result.r = this.r - r;
+ result.g = this.g - g;
+ result.b = this.b - b;
+ return result;
+ }
+ /**
+ * Copy the current object
+ * @returns a new Color3 copied the current one
+ */
+ clone() {
+ return new Color3(this.r, this.g, this.b);
+ }
+ /**
+ * Copies the rgb values from the source in the current Color3
+ * @param source defines the source Color3 object
+ * @returns the updated Color3 object
+ */
+ copyFrom(source) {
+ this.r = source.r;
+ this.g = source.g;
+ this.b = source.b;
+ return this;
+ }
+ /**
+ * Updates the Color3 rgb values from the given floats
+ * @param r defines the red component to read from
+ * @param g defines the green component to read from
+ * @param b defines the blue component to read from
+ * @returns the current Color3 object
+ */
+ copyFromFloats(r, g, b) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ return this;
+ }
+ /**
+ * Updates the Color3 rgb values from the given floats
+ * @param r defines the red component to read from
+ * @param g defines the green component to read from
+ * @param b defines the blue component to read from
+ * @returns the current Color3 object
+ */
+ set(r, g, b) {
+ return this.copyFromFloats(r, g, b);
+ }
+ /**
+ * Copies the given float to the current Color3 coordinates
+ * @param v defines the r, g and b coordinates of the operand
+ * @returns the current updated Color3
+ */
+ setAll(v) {
+ this.r = this.g = this.b = v;
+ return this;
+ }
+ /**
+ * Compute the Color3 hexadecimal code as a string
+ * @returns a string containing the hexadecimal representation of the Color3 object
+ */
+ toHexString() {
+ const intR = Math.round(this.r * 255);
+ const intG = Math.round(this.g * 255);
+ const intB = Math.round(this.b * 255);
+ return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB);
+ }
+ /**
+ * Updates the Color3 rgb values from the string containing valid hexadecimal values
+ * @param hex defines a string containing valid hexadecimal values
+ * @returns the current Color3 object
+ */
+ fromHexString(hex) {
+ if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
+ return this;
+ }
+ this.r = parseInt(hex.substring(1, 3), 16) / 255;
+ this.g = parseInt(hex.substring(3, 5), 16) / 255;
+ this.b = parseInt(hex.substring(5, 7), 16) / 255;
+ return this;
+ }
+ /**
+ * Converts current color in rgb space to HSV values
+ * @returns a new color3 representing the HSV values
+ */
+ toHSV() {
+ return this.toHSVToRef(new Color3());
+ }
+ /**
+ * Converts current color in rgb space to HSV values
+ * @param result defines the Color3 where to store the HSV values
+ * @returns the updated result
+ */
+ toHSVToRef(result) {
+ const r = this.r;
+ const g = this.g;
+ const b = this.b;
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ let h = 0;
+ let s = 0;
+ const v = max;
+ const dm = max - min;
+ if (max !== 0) {
+ s = dm / max;
+ }
+ if (max != min) {
+ if (max == r) {
+ h = (g - b) / dm;
+ if (g < b) {
+ h += 6;
+ }
+ }
+ else if (max == g) {
+ h = (b - r) / dm + 2;
+ }
+ else if (max == b) {
+ h = (r - g) / dm + 4;
+ }
+ h *= 60;
+ }
+ result.r = h;
+ result.g = s;
+ result.b = v;
+ return result;
+ }
+ /**
+ * Computes a new Color3 converted from the current one to linear space
+ * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)
+ * @returns a new Color3 object
+ */
+ toLinearSpace(exact = false) {
+ const convertedColor = new Color3();
+ this.toLinearSpaceToRef(convertedColor, exact);
+ return convertedColor;
+ }
+ /**
+ * Converts the Color3 values to linear space and stores the result in "convertedColor"
+ * @param convertedColor defines the Color3 object where to store the linear space version
+ * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)
+ * @returns the unmodified Color3
+ */
+ toLinearSpaceToRef(convertedColor, exact = false) {
+ if (exact) {
+ convertedColor.r = colorChannelToLinearSpaceExact(this.r);
+ convertedColor.g = colorChannelToLinearSpaceExact(this.g);
+ convertedColor.b = colorChannelToLinearSpaceExact(this.b);
+ }
+ else {
+ convertedColor.r = colorChannelToLinearSpace(this.r);
+ convertedColor.g = colorChannelToLinearSpace(this.g);
+ convertedColor.b = colorChannelToLinearSpace(this.b);
+ }
+ return this;
+ }
+ /**
+ * Computes a new Color3 converted from the current one to gamma space
+ * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)
+ * @returns a new Color3 object
+ */
+ toGammaSpace(exact = false) {
+ const convertedColor = new Color3();
+ this.toGammaSpaceToRef(convertedColor, exact);
+ return convertedColor;
+ }
+ /**
+ * Converts the Color3 values to gamma space and stores the result in "convertedColor"
+ * @param convertedColor defines the Color3 object where to store the gamma space version
+ * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)
+ * @returns the unmodified Color3
+ */
+ toGammaSpaceToRef(convertedColor, exact = false) {
+ if (exact) {
+ convertedColor.r = colorChannelToGammaSpaceExact(this.r);
+ convertedColor.g = colorChannelToGammaSpaceExact(this.g);
+ convertedColor.b = colorChannelToGammaSpaceExact(this.b);
+ }
+ else {
+ convertedColor.r = colorChannelToGammaSpace(this.r);
+ convertedColor.g = colorChannelToGammaSpace(this.g);
+ convertedColor.b = colorChannelToGammaSpace(this.b);
+ }
+ return this;
+ }
+ /**
+ * Converts Hue, saturation and value to a Color3 (RGB)
+ * @param hue defines the hue (value between 0 and 360)
+ * @param saturation defines the saturation (value between 0 and 1)
+ * @param value defines the value (value between 0 and 1)
+ * @param result defines the Color3 where to store the RGB values
+ * @returns the updated result
+ */
+ static HSVtoRGBToRef(hue, saturation, value, result) {
+ const chroma = value * saturation;
+ const h = hue / 60;
+ const x = chroma * (1 - Math.abs((h % 2) - 1));
+ let r = 0;
+ let g = 0;
+ let b = 0;
+ if (h >= 0 && h <= 1) {
+ r = chroma;
+ g = x;
+ }
+ else if (h >= 1 && h <= 2) {
+ r = x;
+ g = chroma;
+ }
+ else if (h >= 2 && h <= 3) {
+ g = chroma;
+ b = x;
+ }
+ else if (h >= 3 && h <= 4) {
+ g = x;
+ b = chroma;
+ }
+ else if (h >= 4 && h <= 5) {
+ r = x;
+ b = chroma;
+ }
+ else if (h >= 5 && h <= 6) {
+ r = chroma;
+ b = x;
+ }
+ const m = value - chroma;
+ result.r = r + m;
+ result.g = g + m;
+ result.b = b + m;
+ return result;
+ }
+ /**
+ * Converts Hue, saturation and value to a new Color3 (RGB)
+ * @param hue defines the hue (value between 0 and 360)
+ * @param saturation defines the saturation (value between 0 and 1)
+ * @param value defines the value (value between 0 and 1)
+ * @returns a new Color3 object
+ */
+ static FromHSV(hue, saturation, value) {
+ const result = new Color3(0, 0, 0);
+ Color3.HSVtoRGBToRef(hue, saturation, value, result);
+ return result;
+ }
+ /**
+ * Creates a new Color3 from the string containing valid hexadecimal values
+ * @param hex defines a string containing valid hexadecimal values
+ * @returns a new Color3 object
+ */
+ static FromHexString(hex) {
+ return new Color3(0, 0, 0).fromHexString(hex);
+ }
+ /**
+ * Creates a new Color3 from the starting index of the given array
+ * @param array defines the source array
+ * @param offset defines an offset in the source array
+ * @returns a new Color3 object
+ */
+ static FromArray(array, offset = 0) {
+ return new Color3(array[offset], array[offset + 1], array[offset + 2]);
+ }
+ /**
+ * Creates a new Color3 from the starting index element of the given array
+ * @param array defines the source array to read from
+ * @param offset defines the offset in the source array
+ * @param result defines the target Color3 object
+ */
+ static FromArrayToRef(array, offset = 0, result) {
+ result.r = array[offset];
+ result.g = array[offset + 1];
+ result.b = array[offset + 2];
+ }
+ /**
+ * Creates a new Color3 from integer values (\< 256)
+ * @param r defines the red component to read from (value between 0 and 255)
+ * @param g defines the green component to read from (value between 0 and 255)
+ * @param b defines the blue component to read from (value between 0 and 255)
+ * @returns a new Color3 object
+ */
+ static FromInts(r, g, b) {
+ return new Color3(r / 255.0, g / 255.0, b / 255.0);
+ }
+ /**
+ * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
+ * @param start defines the start Color3 value
+ * @param end defines the end Color3 value
+ * @param amount defines the gradient value between start and end
+ * @returns a new Color3 object
+ */
+ static Lerp(start, end, amount) {
+ const result = new Color3(0.0, 0.0, 0.0);
+ Color3.LerpToRef(start, end, amount, result);
+ return result;
+ }
+ /**
+ * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
+ * @param left defines the start value
+ * @param right defines the end value
+ * @param amount defines the gradient factor
+ * @param result defines the Color3 object where to store the result
+ */
+ static LerpToRef(left, right, amount, result) {
+ result.r = left.r + (right.r - left.r) * amount;
+ result.g = left.g + (right.g - left.g) * amount;
+ result.b = left.b + (right.b - left.b) * amount;
+ }
+ /**
+ * Returns a new Color3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent Color3
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent Color3
+ * @param amount defines the amount on the interpolation spline (between 0 and 1)
+ * @returns the new Color3
+ */
+ static Hermite(value1, tangent1, value2, tangent2, amount) {
+ const squared = amount * amount;
+ const cubed = amount * squared;
+ const part1 = 2.0 * cubed - 3.0 * squared + 1.0;
+ const part2 = -2 * cubed + 3.0 * squared;
+ const part3 = cubed - 2.0 * squared + amount;
+ const part4 = cubed - squared;
+ const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4;
+ const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4;
+ const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4;
+ return new Color3(r, g, b);
+ }
+ /**
+ * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2".
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @returns 1st derivative
+ */
+ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
+ const result = Color3.Black();
+ this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
+ return result;
+ }
+ /**
+ * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2".
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @param result define where to store the derivative
+ */
+ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {
+ const t2 = time * time;
+ result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r;
+ result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g;
+ result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b;
+ }
+ /**
+ * Returns a Color3 value containing a red color
+ * @returns a new Color3 object
+ */
+ static Red() {
+ return new Color3(1, 0, 0);
+ }
+ /**
+ * Returns a Color3 value containing a green color
+ * @returns a new Color3 object
+ */
+ static Green() {
+ return new Color3(0, 1, 0);
+ }
+ /**
+ * Returns a Color3 value containing a blue color
+ * @returns a new Color3 object
+ */
+ static Blue() {
+ return new Color3(0, 0, 1);
+ }
+ /**
+ * Returns a Color3 value containing a black color
+ * @returns a new Color3 object
+ */
+ static Black() {
+ return new Color3(0, 0, 0);
+ }
+ /**
+ * Gets a Color3 value containing a black color that must not be updated
+ */
+ static get BlackReadOnly() {
+ return Color3._BlackReadOnly;
+ }
+ /**
+ * Returns a Color3 value containing a white color
+ * @returns a new Color3 object
+ */
+ static White() {
+ return new Color3(1, 1, 1);
+ }
+ /**
+ * Returns a Color3 value containing a purple color
+ * @returns a new Color3 object
+ */
+ static Purple() {
+ return new Color3(0.5, 0, 0.5);
+ }
+ /**
+ * Returns a Color3 value containing a magenta color
+ * @returns a new Color3 object
+ */
+ static Magenta() {
+ return new Color3(1, 0, 1);
+ }
+ /**
+ * Returns a Color3 value containing a yellow color
+ * @returns a new Color3 object
+ */
+ static Yellow() {
+ return new Color3(1, 1, 0);
+ }
+ /**
+ * Returns a Color3 value containing a gray color
+ * @returns a new Color3 object
+ */
+ static Gray() {
+ return new Color3(0.5, 0.5, 0.5);
+ }
+ /**
+ * Returns a Color3 value containing a teal color
+ * @returns a new Color3 object
+ */
+ static Teal() {
+ return new Color3(0, 1.0, 1.0);
+ }
+ /**
+ * Returns a Color3 value containing a random color
+ * @returns a new Color3 object
+ */
+ static Random() {
+ return new Color3(Math.random(), Math.random(), Math.random());
+ }
+}
+/**
+ * If the first color is flagged with integers (as everything is 0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet.
+ * If subsequent colors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers,
+ * and henceforth it will use floating-point representation for all color instances that it creates.
+ * But the original color instances are unchanged and has a "deprecated map".
+ * If we keep using the color instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches.
+ */
+Color3._V8PerformanceHack = new Color3(0.5, 0.5, 0.5);
+// Statics
+Color3._BlackReadOnly = Color3.Black();
+Object.defineProperties(Color3.prototype, {
+ dimension: { value: [3] },
+ rank: { value: 1 },
+});
+/**
+ * Class used to hold a RBGA color
+ */
+class Color4 {
+ /**
+ * Creates a new Color4 object from red, green, blue values, all between 0 and 1
+ * @param r defines the red component (between 0 and 1, default is 0)
+ * @param g defines the green component (between 0 and 1, default is 0)
+ * @param b defines the blue component (between 0 and 1, default is 0)
+ * @param a defines the alpha component (between 0 and 1, default is 1)
+ */
+ constructor(
+ /**
+ * [0] Defines the red component (between 0 and 1, default is 0)
+ */
+ r = 0,
+ /**
+ * [0] Defines the green component (between 0 and 1, default is 0)
+ */
+ g = 0,
+ /**
+ * [0] Defines the blue component (between 0 and 1, default is 0)
+ */
+ b = 0,
+ /**
+ * [1] Defines the alpha component (between 0 and 1, default is 1)
+ */
+ a = 1) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ this.a = a;
+ }
+ // Operators
+ /**
+ * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
+ * @returns the new array
+ */
+ asArray() {
+ return [this.r, this.g, this.b, this.a];
+ }
+ /**
+ * Stores from the starting index in the given array the Color4 successive values
+ * @param array defines the array where to store the r,g,b components
+ * @param index defines an optional index in the target array to define where to start storing values
+ * @returns the current Color4 object
+ */
+ toArray(array, index = 0) {
+ array[index] = this.r;
+ array[index + 1] = this.g;
+ array[index + 2] = this.b;
+ array[index + 3] = this.a;
+ return this;
+ }
+ /**
+ * Update the current color with values stored in an array from the starting index of the given array
+ * @param array defines the source array
+ * @param offset defines an offset in the source array
+ * @returns the current Color4 object
+ */
+ fromArray(array, offset = 0) {
+ this.r = array[offset];
+ this.g = array[offset + 1];
+ this.b = array[offset + 2];
+ this.a = array[offset + 3];
+ return this;
+ }
+ /**
+ * Determines equality between Color4 objects
+ * @param otherColor defines the second operand
+ * @returns true if the rgba values are equal to the given ones
+ */
+ equals(otherColor) {
+ return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b && this.a === otherColor.a;
+ }
+ /**
+ * Creates a new Color4 set with the added values of the current Color4 and of the given one
+ * @param otherColor defines the second operand
+ * @returns a new Color4 object
+ */
+ add(otherColor) {
+ return new Color4(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b, this.a + otherColor.a);
+ }
+ /**
+ * Updates the given color "result" with the result of the addition of the current Color4 and the given one.
+ * @param otherColor the color to add
+ * @param result the color to store the result
+ * @returns result input
+ */
+ addToRef(otherColor, result) {
+ result.r = this.r + otherColor.r;
+ result.g = this.g + otherColor.g;
+ result.b = this.b + otherColor.b;
+ result.a = this.a + otherColor.a;
+ return result;
+ }
+ /**
+ * Adds in place the given Color4 values to the current Color4 object
+ * @param otherColor defines the second operand
+ * @returns the current updated Color4 object
+ */
+ addInPlace(otherColor) {
+ this.r += otherColor.r;
+ this.g += otherColor.g;
+ this.b += otherColor.b;
+ this.a += otherColor.a;
+ return this;
+ }
+ /**
+ * Adds the given coordinates to the current Color4
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @param a defines the a coordinate of the operand
+ * @returns the current updated Color4
+ */
+ addInPlaceFromFloats(r, g, b, a) {
+ this.r += r;
+ this.g += g;
+ this.b += b;
+ this.a += a;
+ return this;
+ }
+ /**
+ * Creates a new Color4 set with the subtracted values of the given one from the current Color4
+ * @param otherColor defines the second operand
+ * @returns a new Color4 object
+ */
+ subtract(otherColor) {
+ return new Color4(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b, this.a - otherColor.a);
+ }
+ /**
+ * Subtracts the given ones from the current Color4 values and stores the results in "result"
+ * @param otherColor defines the second operand
+ * @param result defines the Color4 object where to store the result
+ * @returns the result Color4 object
+ */
+ subtractToRef(otherColor, result) {
+ result.r = this.r - otherColor.r;
+ result.g = this.g - otherColor.g;
+ result.b = this.b - otherColor.b;
+ result.a = this.a - otherColor.a;
+ return result;
+ }
+ /**
+ * Subtract in place the given color from the current Color4.
+ * @param otherColor the color to subtract
+ * @returns the updated Color4.
+ */
+ subtractInPlace(otherColor) {
+ this.r -= otherColor.r;
+ this.g -= otherColor.g;
+ this.b -= otherColor.b;
+ this.a -= otherColor.a;
+ return this;
+ }
+ /**
+ * Returns a new Color4 set with the result of the subtraction of the given floats from the current Color4 coordinates.
+ * @param r value to subtract
+ * @param g value to subtract
+ * @param b value to subtract
+ * @param a value to subtract
+ * @returns new color containing the result
+ */
+ subtractFromFloats(r, g, b, a) {
+ return new Color4(this.r - r, this.g - g, this.b - b, this.a - a);
+ }
+ /**
+ * Sets the given color "result" set with the result of the subtraction of the given floats from the current Color4 coordinates.
+ * @param r value to subtract
+ * @param g value to subtract
+ * @param b value to subtract
+ * @param a value to subtract
+ * @param result the color to store the result in
+ * @returns result input
+ */
+ subtractFromFloatsToRef(r, g, b, a, result) {
+ result.r = this.r - r;
+ result.g = this.g - g;
+ result.b = this.b - b;
+ result.a = this.a - a;
+ return result;
+ }
+ /**
+ * Creates a new Color4 with the current Color4 values multiplied by scale
+ * @param scale defines the scaling factor to apply
+ * @returns a new Color4 object
+ */
+ scale(scale) {
+ return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
+ }
+ /**
+ * Multiplies the Color4 values by the float "scale"
+ * @param scale defines the scaling factor to apply
+ * @returns the current updated Color4
+ */
+ scaleInPlace(scale) {
+ this.r *= scale;
+ this.g *= scale;
+ this.b *= scale;
+ this.a *= scale;
+ return this;
+ }
+ /**
+ * Multiplies the current Color4 values by scale and stores the result in "result"
+ * @param scale defines the scaling factor to apply
+ * @param result defines the Color4 object where to store the result
+ * @returns the result Color4
+ */
+ scaleToRef(scale, result) {
+ result.r = this.r * scale;
+ result.g = this.g * scale;
+ result.b = this.b * scale;
+ result.a = this.a * scale;
+ return result;
+ }
+ /**
+ * Scale the current Color4 values by a factor and add the result to a given Color4
+ * @param scale defines the scale factor
+ * @param result defines the Color4 object where to store the result
+ * @returns the result Color4
+ */
+ scaleAndAddToRef(scale, result) {
+ result.r += this.r * scale;
+ result.g += this.g * scale;
+ result.b += this.b * scale;
+ result.a += this.a * scale;
+ return result;
+ }
+ /**
+ * Clamps the rgb values by the min and max values and stores the result into "result"
+ * @param min defines minimum clamping value (default is 0)
+ * @param max defines maximum clamping value (default is 1)
+ * @param result defines color to store the result into.
+ * @returns the result Color4
+ */
+ clampToRef(min = 0, max = 1, result) {
+ result.r = Clamp(this.r, min, max);
+ result.g = Clamp(this.g, min, max);
+ result.b = Clamp(this.b, min, max);
+ result.a = Clamp(this.a, min, max);
+ return result;
+ }
+ /**
+ * Multiply an Color4 value by another and return a new Color4 object
+ * @param color defines the Color4 value to multiply by
+ * @returns a new Color4 object
+ */
+ multiply(color) {
+ return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
+ }
+ /**
+ * Multiply a Color4 value by another and push the result in a reference value
+ * @param color defines the Color4 value to multiply by
+ * @param result defines the Color4 to fill the result in
+ * @returns the result Color4
+ */
+ multiplyToRef(color, result) {
+ result.r = this.r * color.r;
+ result.g = this.g * color.g;
+ result.b = this.b * color.b;
+ result.a = this.a * color.a;
+ return result;
+ }
+ /**
+ * Multiplies in place the current Color4 by the given one.
+ * @param otherColor color to multiple with
+ * @returns the updated Color4.
+ */
+ multiplyInPlace(otherColor) {
+ this.r *= otherColor.r;
+ this.g *= otherColor.g;
+ this.b *= otherColor.b;
+ this.a *= otherColor.a;
+ return this;
+ }
+ /**
+ * Returns a new Color4 set with the multiplication result of the given floats and the current Color4 coordinates.
+ * @param r value multiply with
+ * @param g value multiply with
+ * @param b value multiply with
+ * @param a value multiply with
+ * @returns resulting new color
+ */
+ multiplyByFloats(r, g, b, a) {
+ return new Color4(this.r * r, this.g * g, this.b * b, this.a * a);
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divide(_other) {
+ throw new ReferenceError("Can not divide a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divideToRef(_other, _result) {
+ throw new ReferenceError("Can not divide a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ divideInPlace(_other) {
+ throw new ReferenceError("Can not divide a color");
+ }
+ /**
+ * Updates the Color4 coordinates with the minimum values between its own and the given color ones
+ * @param other defines the second operand
+ * @returns the current updated Color4
+ */
+ minimizeInPlace(other) {
+ this.r = Math.min(this.r, other.r);
+ this.g = Math.min(this.g, other.g);
+ this.b = Math.min(this.b, other.b);
+ this.a = Math.min(this.a, other.a);
+ return this;
+ }
+ /**
+ * Updates the Color4 coordinates with the maximum values between its own and the given color ones
+ * @param other defines the second operand
+ * @returns the current updated Color4
+ */
+ maximizeInPlace(other) {
+ this.r = Math.max(this.r, other.r);
+ this.g = Math.max(this.g, other.g);
+ this.b = Math.max(this.b, other.b);
+ this.a = Math.max(this.a, other.a);
+ return this;
+ }
+ /**
+ * Updates the current Color4 with the minimal coordinate values between its and the given coordinates
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @param a defines the a coordinate of the operand
+ * @returns the current updated Color4
+ */
+ minimizeInPlaceFromFloats(r, g, b, a) {
+ this.r = Math.min(r, this.r);
+ this.g = Math.min(g, this.g);
+ this.b = Math.min(b, this.b);
+ this.a = Math.min(a, this.a);
+ return this;
+ }
+ /**
+ * Updates the current Color4 with the maximal coordinate values between its and the given coordinates.
+ * @param r defines the r coordinate of the operand
+ * @param g defines the g coordinate of the operand
+ * @param b defines the b coordinate of the operand
+ * @param a defines the a coordinate of the operand
+ * @returns the current updated Color4
+ */
+ maximizeInPlaceFromFloats(r, g, b, a) {
+ this.r = Math.max(r, this.r);
+ this.g = Math.max(g, this.g);
+ this.b = Math.max(b, this.b);
+ this.a = Math.max(a, this.a);
+ return this;
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ floorToRef(_result) {
+ throw new ReferenceError("Can not floor a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ floor() {
+ throw new ReferenceError("Can not floor a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ fractToRef(_result) {
+ throw new ReferenceError("Can not fract a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ fract() {
+ throw new ReferenceError("Can not fract a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ negate() {
+ throw new ReferenceError("Can not negate a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ negateInPlace() {
+ throw new ReferenceError("Can not negate a color");
+ }
+ /**
+ * @internal
+ * Do not use
+ */
+ negateToRef(_result) {
+ throw new ReferenceError("Can not negate a color");
+ }
+ /**
+ * Boolean : True if the current Color4 coordinates are each beneath the distance "epsilon" from the given color ones.
+ * @param otherColor color to compare against
+ * @param epsilon (Default: very small number)
+ * @returns true if they are equal
+ */
+ equalsWithEpsilon(otherColor, epsilon = Epsilon) {
+ return (WithinEpsilon(this.r, otherColor.r, epsilon) &&
+ WithinEpsilon(this.g, otherColor.g, epsilon) &&
+ WithinEpsilon(this.b, otherColor.b, epsilon) &&
+ WithinEpsilon(this.a, otherColor.a, epsilon));
+ }
+ /**
+ * Boolean : True if the given floats are strictly equal to the current Color4 coordinates.
+ * @param x x value to compare against
+ * @param y y value to compare against
+ * @param z z value to compare against
+ * @param w w value to compare against
+ * @returns true if equal
+ */
+ equalsToFloats(x, y, z, w) {
+ return this.r === x && this.g === y && this.b === z && this.a === w;
+ }
+ /**
+ * Creates a string with the Color4 current values
+ * @returns the string representation of the Color4 object
+ */
+ toString() {
+ return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
+ }
+ /**
+ * Returns the string "Color4"
+ * @returns "Color4"
+ */
+ getClassName() {
+ return "Color4";
+ }
+ /**
+ * Compute the Color4 hash code
+ * @returns an unique number that can be used to hash Color4 objects
+ */
+ getHashCode() {
+ let hash = (this.r * 255) | 0;
+ hash = (hash * 397) ^ ((this.g * 255) | 0);
+ hash = (hash * 397) ^ ((this.b * 255) | 0);
+ hash = (hash * 397) ^ ((this.a * 255) | 0);
+ return hash;
+ }
+ /**
+ * Creates a new Color4 copied from the current one
+ * @returns a new Color4 object
+ */
+ clone() {
+ const result = new Color4();
+ return result.copyFrom(this);
+ }
+ /**
+ * Copies the given Color4 values into the current one
+ * @param source defines the source Color4 object
+ * @returns the current updated Color4 object
+ */
+ copyFrom(source) {
+ this.r = source.r;
+ this.g = source.g;
+ this.b = source.b;
+ this.a = source.a;
+ return this;
+ }
+ /**
+ * Copies the given float values into the current one
+ * @param r defines the red component to read from
+ * @param g defines the green component to read from
+ * @param b defines the blue component to read from
+ * @param a defines the alpha component to read from
+ * @returns the current updated Color4 object
+ */
+ copyFromFloats(r, g, b, a) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ this.a = a;
+ return this;
+ }
+ /**
+ * Copies the given float values into the current one
+ * @param r defines the red component to read from
+ * @param g defines the green component to read from
+ * @param b defines the blue component to read from
+ * @param a defines the alpha component to read from
+ * @returns the current updated Color4 object
+ */
+ set(r, g, b, a) {
+ return this.copyFromFloats(r, g, b, a);
+ }
+ /**
+ * Copies the given float to the current Vector4 coordinates
+ * @param v defines the r, g, b, and a coordinates of the operand
+ * @returns the current updated Vector4
+ */
+ setAll(v) {
+ this.r = this.g = this.b = this.a = v;
+ return this;
+ }
+ /**
+ * Compute the Color4 hexadecimal code as a string
+ * @param returnAsColor3 defines if the string should only contains RGB values (off by default)
+ * @returns a string containing the hexadecimal representation of the Color4 object
+ */
+ toHexString(returnAsColor3 = false) {
+ const intR = Math.round(this.r * 255);
+ const intG = Math.round(this.g * 255);
+ const intB = Math.round(this.b * 255);
+ if (returnAsColor3) {
+ return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB);
+ }
+ const intA = Math.round(this.a * 255);
+ return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB) + ToHex(intA);
+ }
+ /**
+ * Updates the Color4 rgba values from the string containing valid hexadecimal values.
+ *
+ * A valid hex string is either in the format #RRGGBB or #RRGGBBAA.
+ *
+ * When a hex string without alpha is passed, the resulting Color4 keeps
+ * its previous alpha value.
+ *
+ * An invalid string does not modify this object
+ *
+ * @param hex defines a string containing valid hexadecimal values
+ * @returns the current updated Color4 object
+ */
+ fromHexString(hex) {
+ if (hex.substring(0, 1) !== "#" || (hex.length !== 9 && hex.length !== 7)) {
+ return this;
+ }
+ this.r = parseInt(hex.substring(1, 3), 16) / 255;
+ this.g = parseInt(hex.substring(3, 5), 16) / 255;
+ this.b = parseInt(hex.substring(5, 7), 16) / 255;
+ if (hex.length === 9) {
+ this.a = parseInt(hex.substring(7, 9), 16) / 255;
+ }
+ return this;
+ }
+ /**
+ * Computes a new Color4 converted from the current one to linear space
+ * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)
+ * @returns a new Color4 object
+ */
+ toLinearSpace(exact = false) {
+ const convertedColor = new Color4();
+ this.toLinearSpaceToRef(convertedColor, exact);
+ return convertedColor;
+ }
+ /**
+ * Converts the Color4 values to linear space and stores the result in "convertedColor"
+ * @param convertedColor defines the Color4 object where to store the linear space version
+ * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)
+ * @returns the unmodified Color4
+ */
+ toLinearSpaceToRef(convertedColor, exact = false) {
+ if (exact) {
+ convertedColor.r = colorChannelToLinearSpaceExact(this.r);
+ convertedColor.g = colorChannelToLinearSpaceExact(this.g);
+ convertedColor.b = colorChannelToLinearSpaceExact(this.b);
+ }
+ else {
+ convertedColor.r = colorChannelToLinearSpace(this.r);
+ convertedColor.g = colorChannelToLinearSpace(this.g);
+ convertedColor.b = colorChannelToLinearSpace(this.b);
+ }
+ convertedColor.a = this.a;
+ return this;
+ }
+ /**
+ * Computes a new Color4 converted from the current one to gamma space
+ * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)
+ * @returns a new Color4 object
+ */
+ toGammaSpace(exact = false) {
+ const convertedColor = new Color4();
+ this.toGammaSpaceToRef(convertedColor, exact);
+ return convertedColor;
+ }
+ /**
+ * Converts the Color4 values to gamma space and stores the result in "convertedColor"
+ * @param convertedColor defines the Color4 object where to store the gamma space version
+ * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)
+ * @returns the unmodified Color4
+ */
+ toGammaSpaceToRef(convertedColor, exact = false) {
+ if (exact) {
+ convertedColor.r = colorChannelToGammaSpaceExact(this.r);
+ convertedColor.g = colorChannelToGammaSpaceExact(this.g);
+ convertedColor.b = colorChannelToGammaSpaceExact(this.b);
+ }
+ else {
+ convertedColor.r = colorChannelToGammaSpace(this.r);
+ convertedColor.g = colorChannelToGammaSpace(this.g);
+ convertedColor.b = colorChannelToGammaSpace(this.b);
+ }
+ convertedColor.a = this.a;
+ return this;
+ }
+ // Statics
+ /**
+ * Creates a new Color4 from the string containing valid hexadecimal values.
+ *
+ * A valid hex string is either in the format #RRGGBB or #RRGGBBAA.
+ *
+ * When a hex string without alpha is passed, the resulting Color4 has
+ * its alpha value set to 1.0.
+ *
+ * An invalid string results in a Color with all its channels set to 0.0,
+ * i.e. "transparent black".
+ *
+ * @param hex defines a string containing valid hexadecimal values
+ * @returns a new Color4 object
+ */
+ static FromHexString(hex) {
+ if (hex.substring(0, 1) !== "#" || (hex.length !== 9 && hex.length !== 7)) {
+ return new Color4(0.0, 0.0, 0.0, 0.0);
+ }
+ return new Color4(0.0, 0.0, 0.0, 1.0).fromHexString(hex);
+ }
+ /**
+ * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
+ * @param left defines the start value
+ * @param right defines the end value
+ * @param amount defines the gradient factor
+ * @returns a new Color4 object
+ */
+ static Lerp(left, right, amount) {
+ return Color4.LerpToRef(left, right, amount, new Color4());
+ }
+ /**
+ * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
+ * @param left defines the start value
+ * @param right defines the end value
+ * @param amount defines the gradient factor
+ * @param result defines the Color4 object where to store data
+ * @returns the updated result
+ */
+ static LerpToRef(left, right, amount, result) {
+ result.r = left.r + (right.r - left.r) * amount;
+ result.g = left.g + (right.g - left.g) * amount;
+ result.b = left.b + (right.b - left.b) * amount;
+ result.a = left.a + (right.a - left.a) * amount;
+ return result;
+ }
+ /**
+ * Interpolate between two Color4 using Hermite interpolation
+ * @param value1 defines first Color4
+ * @param tangent1 defines the incoming tangent
+ * @param value2 defines second Color4
+ * @param tangent2 defines the outgoing tangent
+ * @param amount defines the target Color4
+ * @returns the new interpolated Color4
+ */
+ static Hermite(value1, tangent1, value2, tangent2, amount) {
+ const squared = amount * amount;
+ const cubed = amount * squared;
+ const part1 = 2.0 * cubed - 3.0 * squared + 1.0;
+ const part2 = -2 * cubed + 3.0 * squared;
+ const part3 = cubed - 2.0 * squared + amount;
+ const part4 = cubed - squared;
+ const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4;
+ const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4;
+ const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4;
+ const a = value1.a * part1 + value2.a * part2 + tangent1.a * part3 + tangent2.a * part4;
+ return new Color4(r, g, b, a);
+ }
+ /**
+ * Returns a new Color4 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2".
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @returns 1st derivative
+ */
+ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
+ const result = new Color4();
+ this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
+ return result;
+ }
+ /**
+ * Update a Color4 with the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2".
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @param result define where to store the derivative
+ */
+ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {
+ const t2 = time * time;
+ result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r;
+ result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g;
+ result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b;
+ result.a = (t2 - time) * 6 * value1.a + (3 * t2 - 4 * time + 1) * tangent1.a + (-t2 + time) * 6 * value2.a + (3 * t2 - 2 * time) * tangent2.a;
+ }
+ /**
+ * Creates a new Color4 from a Color3 and an alpha value
+ * @param color3 defines the source Color3 to read from
+ * @param alpha defines the alpha component (1.0 by default)
+ * @returns a new Color4 object
+ */
+ static FromColor3(color3, alpha = 1.0) {
+ return new Color4(color3.r, color3.g, color3.b, alpha);
+ }
+ /**
+ * Creates a new Color4 from the starting index element of the given array
+ * @param array defines the source array to read from
+ * @param offset defines the offset in the source array
+ * @returns a new Color4 object
+ */
+ static FromArray(array, offset = 0) {
+ return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
+ }
+ /**
+ * Creates a new Color4 from the starting index element of the given array
+ * @param array defines the source array to read from
+ * @param offset defines the offset in the source array
+ * @param result defines the target Color4 object
+ */
+ static FromArrayToRef(array, offset = 0, result) {
+ result.r = array[offset];
+ result.g = array[offset + 1];
+ result.b = array[offset + 2];
+ result.a = array[offset + 3];
+ }
+ /**
+ * Creates a new Color3 from integer values (less than 256)
+ * @param r defines the red component to read from (value between 0 and 255)
+ * @param g defines the green component to read from (value between 0 and 255)
+ * @param b defines the blue component to read from (value between 0 and 255)
+ * @param a defines the alpha component to read from (value between 0 and 255)
+ * @returns a new Color3 object
+ */
+ static FromInts(r, g, b, a) {
+ return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
+ }
+ /**
+ * Check the content of a given array and convert it to an array containing RGBA data
+ * If the original array was already containing count * 4 values then it is returned directly
+ * @param colors defines the array to check
+ * @param count defines the number of RGBA data to expect
+ * @returns an array containing count * 4 values (RGBA)
+ */
+ static CheckColors4(colors, count) {
+ // Check if color3 was used
+ if (colors.length === count * 3) {
+ const colors4 = [];
+ for (let index = 0; index < colors.length; index += 3) {
+ const newIndex = (index / 3) * 4;
+ colors4[newIndex] = colors[index];
+ colors4[newIndex + 1] = colors[index + 1];
+ colors4[newIndex + 2] = colors[index + 2];
+ colors4[newIndex + 3] = 1.0;
+ }
+ return colors4;
+ }
+ return colors;
+ }
+}
+/**
+ * If the first color is flagged with integers (as everything is 0,0,0,0), V8 stores all of the properties as integers internally because it doesn't know any better yet.
+ * If subsequent colors are created with non-integer values, V8 determines that it would be best to represent these properties as doubles instead of integers,
+ * and henceforth it will use floating-point representation for all color instances that it creates.
+ * But the original color instances are unchanged and has a "deprecated map".
+ * If we keep using the color instances from step 1, it will now be a poison pill which will mess up optimizations in any code it touches.
+ */
+Color4._V8PerformanceHack = new Color4(0.5, 0.5, 0.5, 0.5);
+Object.defineProperties(Color4.prototype, {
+ dimension: { value: [4] },
+ rank: { value: 1 },
+});
+/**
+ * @internal
+ */
+class TmpColors {
+}
+TmpColors.Color3 = BuildArray(3, Color3.Black);
+TmpColors.Color4 = BuildArray(3, () => new Color4(0, 0, 0, 0));
+RegisterClass("BABYLON.Color3", Color3);
+RegisterClass("BABYLON.Color4", Color4);
+
+/**
+ * Represents a plane by the equation ax + by + cz + d = 0
+ */
+class Plane {
+ /**
+ * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
+ * @param a a component of the plane
+ * @param b b component of the plane
+ * @param c c component of the plane
+ * @param d d component of the plane
+ */
+ constructor(a, b, c, d) {
+ this.normal = new Vector3(a, b, c);
+ this.d = d;
+ }
+ /**
+ * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
+ */
+ asArray() {
+ return [this.normal.x, this.normal.y, this.normal.z, this.d];
+ }
+ // Methods
+ /**
+ * @returns a new plane copied from the current Plane.
+ */
+ clone() {
+ return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
+ }
+ /**
+ * @returns the string "Plane".
+ */
+ getClassName() {
+ return "Plane";
+ }
+ /**
+ * @returns the Plane hash code.
+ */
+ getHashCode() {
+ let hash = this.normal.getHashCode();
+ hash = (hash * 397) ^ (this.d | 0);
+ return hash;
+ }
+ /**
+ * Normalize the current Plane in place.
+ * @returns the updated Plane.
+ */
+ normalize() {
+ const norm = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z);
+ let magnitude = 0.0;
+ if (norm !== 0) {
+ magnitude = 1.0 / norm;
+ }
+ this.normal.x *= magnitude;
+ this.normal.y *= magnitude;
+ this.normal.z *= magnitude;
+ this.d *= magnitude;
+ return this;
+ }
+ /**
+ * Applies a transformation the plane and returns the result
+ * @param transformation the transformation matrix to be applied to the plane
+ * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
+ */
+ transform(transformation) {
+ const invertedMatrix = Plane._TmpMatrix;
+ transformation.invertToRef(invertedMatrix);
+ const m = invertedMatrix.m;
+ const x = this.normal.x;
+ const y = this.normal.y;
+ const z = this.normal.z;
+ const d = this.d;
+ const normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];
+ const normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];
+ const normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];
+ const finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];
+ return new Plane(normalX, normalY, normalZ, finalD);
+ }
+ /**
+ * Compute the dot product between the point and the plane normal
+ * @param point point to calculate the dot product with
+ * @returns the dot product (float) of the point coordinates and the plane normal.
+ */
+ dotCoordinate(point) {
+ return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.d;
+ }
+ /**
+ * Updates the current Plane from the plane defined by the three given points.
+ * @param point1 one of the points used to construct the plane
+ * @param point2 one of the points used to construct the plane
+ * @param point3 one of the points used to construct the plane
+ * @returns the updated Plane.
+ */
+ copyFromPoints(point1, point2, point3) {
+ const x1 = point2.x - point1.x;
+ const y1 = point2.y - point1.y;
+ const z1 = point2.z - point1.z;
+ const x2 = point3.x - point1.x;
+ const y2 = point3.y - point1.y;
+ const z2 = point3.z - point1.z;
+ const yz = y1 * z2 - z1 * y2;
+ const xz = z1 * x2 - x1 * z2;
+ const xy = x1 * y2 - y1 * x2;
+ const pyth = Math.sqrt(yz * yz + xz * xz + xy * xy);
+ let invPyth;
+ if (pyth !== 0) {
+ invPyth = 1.0 / pyth;
+ }
+ else {
+ invPyth = 0.0;
+ }
+ this.normal.x = yz * invPyth;
+ this.normal.y = xz * invPyth;
+ this.normal.z = xy * invPyth;
+ this.d = -(this.normal.x * point1.x + this.normal.y * point1.y + this.normal.z * point1.z);
+ return this;
+ }
+ /**
+ * Checks if the plane is facing a given direction (meaning if the plane's normal is pointing in the opposite direction of the given vector).
+ * Note that for this function to work as expected you should make sure that:
+ * - direction and the plane normal are normalized
+ * - epsilon is a number just bigger than -1, something like -0.99 for eg
+ * @param direction the direction to check if the plane is facing
+ * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
+ * @returns True if the plane is facing the given direction
+ */
+ isFrontFacingTo(direction, epsilon) {
+ const dot = Vector3.Dot(this.normal, direction);
+ return dot <= epsilon;
+ }
+ /**
+ * Calculates the distance to a point
+ * @param point point to calculate distance to
+ * @returns the signed distance (float) from the given point to the Plane.
+ */
+ signedDistanceTo(point) {
+ return Vector3.Dot(point, this.normal) + this.d;
+ }
+ // Statics
+ /**
+ * Creates a plane from an array
+ * @param array the array to create a plane from
+ * @returns a new Plane from the given array.
+ */
+ static FromArray(array) {
+ return new Plane(array[0], array[1], array[2], array[3]);
+ }
+ /**
+ * Creates a plane from three points
+ * @param point1 point used to create the plane
+ * @param point2 point used to create the plane
+ * @param point3 point used to create the plane
+ * @returns a new Plane defined by the three given points.
+ */
+ static FromPoints(point1, point2, point3) {
+ const result = new Plane(0.0, 0.0, 0.0, 0.0);
+ result.copyFromPoints(point1, point2, point3);
+ return result;
+ }
+ /**
+ * Creates a plane from an origin point and a normal
+ * @param origin origin of the plane to be constructed
+ * @param normal normal of the plane to be constructed
+ * @returns a new Plane the normal vector to this plane at the given origin point.
+ */
+ static FromPositionAndNormal(origin, normal) {
+ const plane = new Plane(0.0, 0.0, 0.0, 0.0);
+ return this.FromPositionAndNormalToRef(origin, normal, plane);
+ }
+ /**
+ * Updates the given Plane "result" from an origin point and a normal.
+ * @param origin origin of the plane to be constructed
+ * @param normal the normalized normals of the plane to be constructed
+ * @param result defines the Plane where to store the result
+ * @returns result input
+ */
+ static FromPositionAndNormalToRef(origin, normal, result) {
+ result.normal.copyFrom(normal);
+ result.normal.normalize();
+ result.d = -origin.dot(result.normal);
+ return result;
+ }
+ /**
+ * Calculates the distance from a plane and a point
+ * @param origin origin of the plane to be constructed
+ * @param normal normal of the plane to be constructed
+ * @param point point to calculate distance to
+ * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
+ */
+ static SignedDistanceToPlaneFromPositionAndNormal(origin, normal, point) {
+ const d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
+ return Vector3.Dot(point, normal) + d;
+ }
+}
+Plane._TmpMatrix = Matrix.Identity();
+
+/**
+ * Represents a camera frustum
+ */
+class Frustum {
+ /**
+ * Gets the planes representing the frustum
+ * @param transform matrix to be applied to the returned planes
+ * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
+ */
+ static GetPlanes(transform) {
+ const frustumPlanes = [];
+ for (let index = 0; index < 6; index++) {
+ frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
+ }
+ Frustum.GetPlanesToRef(transform, frustumPlanes);
+ return frustumPlanes;
+ }
+ /**
+ * Gets the near frustum plane transformed by the transform matrix
+ * @param transform transformation matrix to be applied to the resulting frustum plane
+ * @param frustumPlane the resulting frustum plane
+ */
+ static GetNearPlaneToRef(transform, frustumPlane) {
+ const m = transform.m;
+ frustumPlane.normal.x = m[3] + m[2];
+ frustumPlane.normal.y = m[7] + m[6];
+ frustumPlane.normal.z = m[11] + m[10];
+ frustumPlane.d = m[15] + m[14];
+ frustumPlane.normalize();
+ }
+ /**
+ * Gets the far frustum plane transformed by the transform matrix
+ * @param transform transformation matrix to be applied to the resulting frustum plane
+ * @param frustumPlane the resulting frustum plane
+ */
+ static GetFarPlaneToRef(transform, frustumPlane) {
+ const m = transform.m;
+ frustumPlane.normal.x = m[3] - m[2];
+ frustumPlane.normal.y = m[7] - m[6];
+ frustumPlane.normal.z = m[11] - m[10];
+ frustumPlane.d = m[15] - m[14];
+ frustumPlane.normalize();
+ }
+ /**
+ * Gets the left frustum plane transformed by the transform matrix
+ * @param transform transformation matrix to be applied to the resulting frustum plane
+ * @param frustumPlane the resulting frustum plane
+ */
+ static GetLeftPlaneToRef(transform, frustumPlane) {
+ const m = transform.m;
+ frustumPlane.normal.x = m[3] + m[0];
+ frustumPlane.normal.y = m[7] + m[4];
+ frustumPlane.normal.z = m[11] + m[8];
+ frustumPlane.d = m[15] + m[12];
+ frustumPlane.normalize();
+ }
+ /**
+ * Gets the right frustum plane transformed by the transform matrix
+ * @param transform transformation matrix to be applied to the resulting frustum plane
+ * @param frustumPlane the resulting frustum plane
+ */
+ static GetRightPlaneToRef(transform, frustumPlane) {
+ const m = transform.m;
+ frustumPlane.normal.x = m[3] - m[0];
+ frustumPlane.normal.y = m[7] - m[4];
+ frustumPlane.normal.z = m[11] - m[8];
+ frustumPlane.d = m[15] - m[12];
+ frustumPlane.normalize();
+ }
+ /**
+ * Gets the top frustum plane transformed by the transform matrix
+ * @param transform transformation matrix to be applied to the resulting frustum plane
+ * @param frustumPlane the resulting frustum plane
+ */
+ static GetTopPlaneToRef(transform, frustumPlane) {
+ const m = transform.m;
+ frustumPlane.normal.x = m[3] - m[1];
+ frustumPlane.normal.y = m[7] - m[5];
+ frustumPlane.normal.z = m[11] - m[9];
+ frustumPlane.d = m[15] - m[13];
+ frustumPlane.normalize();
+ }
+ /**
+ * Gets the bottom frustum plane transformed by the transform matrix
+ * @param transform transformation matrix to be applied to the resulting frustum plane
+ * @param frustumPlane the resulting frustum plane
+ */
+ static GetBottomPlaneToRef(transform, frustumPlane) {
+ const m = transform.m;
+ frustumPlane.normal.x = m[3] + m[1];
+ frustumPlane.normal.y = m[7] + m[5];
+ frustumPlane.normal.z = m[11] + m[9];
+ frustumPlane.d = m[15] + m[13];
+ frustumPlane.normalize();
+ }
+ /**
+ * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
+ * @param transform transformation matrix to be applied to the resulting frustum planes
+ * @param frustumPlanes the resulting frustum planes
+ */
+ static GetPlanesToRef(transform, frustumPlanes) {
+ // Near
+ Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
+ // Far
+ Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
+ // Left
+ Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
+ // Right
+ Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
+ // Top
+ Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
+ // Bottom
+ Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
+ }
+ /**
+ * Tests if a point is located between the frustum planes.
+ * @param point defines the point to test
+ * @param frustumPlanes defines the frustum planes to test
+ * @returns true if the point is located between the frustum planes
+ */
+ static IsPointInFrustum(point, frustumPlanes) {
+ for (let i = 0; i < 6; i++) {
+ if (frustumPlanes[i].dotCoordinate(point) < 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
+
+/**
+ * Defines potential orientation for back face culling
+ */
+var Orientation;
+(function (Orientation) {
+ /**
+ * Clockwise
+ */
+ Orientation[Orientation["CW"] = 0] = "CW";
+ /** Counter clockwise */
+ Orientation[Orientation["CCW"] = 1] = "CCW";
+})(Orientation || (Orientation = {}));
+/** Class used to represent a Bezier curve */
+class BezierCurve {
+ /**
+ * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
+ * @param t defines the time
+ * @param x1 defines the left coordinate on X axis
+ * @param y1 defines the left coordinate on Y axis
+ * @param x2 defines the right coordinate on X axis
+ * @param y2 defines the right coordinate on Y axis
+ * @returns the interpolated value
+ */
+ static Interpolate(t, x1, y1, x2, y2) {
+ if (t === 0) {
+ return 0;
+ }
+ // Extract X (which is equal to time here)
+ const f0 = 1 - 3 * x2 + 3 * x1;
+ const f1 = 3 * x2 - 6 * x1;
+ const f2 = 3 * x1;
+ let refinedT = t;
+ for (let i = 0; i < 5; i++) {
+ const refinedT2 = refinedT * refinedT;
+ const refinedT3 = refinedT2 * refinedT;
+ const x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
+ const slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
+ refinedT -= (x - t) * slope;
+ refinedT = Math.min(1, Math.max(0, refinedT));
+ }
+ // Resolve cubic bezier for the given x
+ return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
+ }
+}
+/**
+ * Defines angle representation
+ */
+class Angle {
+ /**
+ * Creates an Angle object of "radians" radians (float).
+ * @param radians the angle in radians
+ */
+ constructor(radians) {
+ this._radians = radians;
+ if (this._radians < 0.0) {
+ this._radians += 2.0 * Math.PI;
+ }
+ }
+ /**
+ * Get value in degrees
+ * @returns the Angle value in degrees (float)
+ */
+ degrees() {
+ return (this._radians * 180.0) / Math.PI;
+ }
+ /**
+ * Get value in radians
+ * @returns the Angle value in radians (float)
+ */
+ radians() {
+ return this._radians;
+ }
+ /**
+ * Gets a new Angle object with a value of the angle (in radians) between the line connecting the two points and the x-axis
+ * @param a defines first point as the origin
+ * @param b defines point
+ * @returns a new Angle
+ */
+ static BetweenTwoPoints(a, b) {
+ const delta = b.subtract(a);
+ const theta = Math.atan2(delta.y, delta.x);
+ return new Angle(theta);
+ }
+ /**
+ * Gets the angle between the two vectors
+ * @param a defines first vector
+ * @param b defines vector
+ * @returns Returns an new Angle between 0 and PI
+ */
+ static BetweenTwoVectors(a, b) {
+ let product = a.lengthSquared() * b.lengthSquared();
+ if (product === 0)
+ return new Angle(Math.PI / 2);
+ product = Math.sqrt(product);
+ let cosVal = a.dot(b) / product;
+ cosVal = Clamp(cosVal, -1, 1);
+ const angle = Math.acos(cosVal);
+ return new Angle(angle);
+ }
+ /**
+ * Gets a new Angle object from the given float in radians
+ * @param radians defines the angle value in radians
+ * @returns a new Angle
+ */
+ static FromRadians(radians) {
+ return new Angle(radians);
+ }
+ /**
+ * Gets a new Angle object from the given float in degrees
+ * @param degrees defines the angle value in degrees
+ * @returns a new Angle
+ */
+ static FromDegrees(degrees) {
+ return new Angle((degrees * Math.PI) / 180.0);
+ }
+}
+/**
+ * This represents an arc in a 2d space.
+ */
+class Arc2 {
+ /**
+ * Creates an Arc object from the three given points : start, middle and end.
+ * @param startPoint Defines the start point of the arc
+ * @param midPoint Defines the middle point of the arc
+ * @param endPoint Defines the end point of the arc
+ */
+ constructor(
+ /** Defines the start point of the arc */
+ startPoint,
+ /** Defines the mid point of the arc */
+ midPoint,
+ /** Defines the end point of the arc */
+ endPoint) {
+ this.startPoint = startPoint;
+ this.midPoint = midPoint;
+ this.endPoint = endPoint;
+ const temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
+ const startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2;
+ const midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2;
+ const det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
+ this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
+ this.radius = this.centerPoint.subtract(this.startPoint).length();
+ this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
+ const a1 = this.startAngle.degrees();
+ let a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
+ let a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
+ // angles correction
+ if (a2 - a1 > 180) {
+ a2 -= 360.0;
+ }
+ if (a2 - a1 < -180) {
+ a2 += 360.0;
+ }
+ if (a3 - a2 > 180) {
+ a3 -= 360.0;
+ }
+ if (a3 - a2 < -180) {
+ a3 += 360.0;
+ }
+ this.orientation = a2 - a1 < 0 ? 0 /* Orientation.CW */ : 1 /* Orientation.CCW */;
+ this.angle = Angle.FromDegrees(this.orientation === 0 /* Orientation.CW */ ? a1 - a3 : a3 - a1);
+ }
+}
+/**
+ * Represents a 2D path made up of multiple 2D points
+ */
+class Path2 {
+ /**
+ * Creates a Path2 object from the starting 2D coordinates x and y.
+ * @param x the starting points x value
+ * @param y the starting points y value
+ */
+ constructor(x, y) {
+ this._points = new Array();
+ this._length = 0.0;
+ /**
+ * If the path start and end point are the same
+ */
+ this.closed = false;
+ this._points.push(new Vector2(x, y));
+ }
+ /**
+ * Adds a new segment until the given coordinates (x, y) to the current Path2.
+ * @param x the added points x value
+ * @param y the added points y value
+ * @returns the updated Path2.
+ */
+ addLineTo(x, y) {
+ if (this.closed) {
+ return this;
+ }
+ const newPoint = new Vector2(x, y);
+ const previousPoint = this._points[this._points.length - 1];
+ this._points.push(newPoint);
+ this._length += newPoint.subtract(previousPoint).length();
+ return this;
+ }
+ /**
+ * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
+ * @param midX middle point x value
+ * @param midY middle point y value
+ * @param endX end point x value
+ * @param endY end point y value
+ * @param numberOfSegments (default: 36)
+ * @returns the updated Path2.
+ */
+ addArcTo(midX, midY, endX, endY, numberOfSegments = 36) {
+ if (this.closed) {
+ return this;
+ }
+ const startPoint = this._points[this._points.length - 1];
+ const midPoint = new Vector2(midX, midY);
+ const endPoint = new Vector2(endX, endY);
+ const arc = new Arc2(startPoint, midPoint, endPoint);
+ let increment = arc.angle.radians() / numberOfSegments;
+ if (arc.orientation === 0 /* Orientation.CW */) {
+ increment *= -1;
+ }
+ let currentAngle = arc.startAngle.radians() + increment;
+ for (let i = 0; i < numberOfSegments; i++) {
+ const x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
+ const y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
+ this.addLineTo(x, y);
+ currentAngle += increment;
+ }
+ return this;
+ }
+ /**
+ * Adds _numberOfSegments_ segments according to the quadratic curve definition to the current Path2.
+ * @param controlX control point x value
+ * @param controlY control point y value
+ * @param endX end point x value
+ * @param endY end point y value
+ * @param numberOfSegments (default: 36)
+ * @returns the updated Path2.
+ */
+ addQuadraticCurveTo(controlX, controlY, endX, endY, numberOfSegments = 36) {
+ if (this.closed) {
+ return this;
+ }
+ const equation = (t, val0, val1, val2) => {
+ const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
+ return res;
+ };
+ const startPoint = this._points[this._points.length - 1];
+ for (let i = 0; i <= numberOfSegments; i++) {
+ const step = i / numberOfSegments;
+ const x = equation(step, startPoint.x, controlX, endX);
+ const y = equation(step, startPoint.y, controlY, endY);
+ this.addLineTo(x, y);
+ }
+ return this;
+ }
+ /**
+ * Adds _numberOfSegments_ segments according to the bezier curve definition to the current Path2.
+ * @param originTangentX tangent vector at the origin point x value
+ * @param originTangentY tangent vector at the origin point y value
+ * @param destinationTangentX tangent vector at the destination point x value
+ * @param destinationTangentY tangent vector at the destination point y value
+ * @param endX end point x value
+ * @param endY end point y value
+ * @param numberOfSegments (default: 36)
+ * @returns the updated Path2.
+ */
+ addBezierCurveTo(originTangentX, originTangentY, destinationTangentX, destinationTangentY, endX, endY, numberOfSegments = 36) {
+ if (this.closed) {
+ return this;
+ }
+ const equation = (t, val0, val1, val2, val3) => {
+ const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
+ return res;
+ };
+ const startPoint = this._points[this._points.length - 1];
+ for (let i = 0; i <= numberOfSegments; i++) {
+ const step = i / numberOfSegments;
+ const x = equation(step, startPoint.x, originTangentX, destinationTangentX, endX);
+ const y = equation(step, startPoint.y, originTangentY, destinationTangentY, endY);
+ this.addLineTo(x, y);
+ }
+ return this;
+ }
+ /**
+ * Defines if a given point is inside the polygon defines by the path
+ * @param point defines the point to test
+ * @returns true if the point is inside
+ */
+ isPointInside(point) {
+ let isInside = false;
+ const count = this._points.length;
+ for (let p = count - 1, q = 0; q < count; p = q++) {
+ let edgeLow = this._points[p];
+ let edgeHigh = this._points[q];
+ let edgeDx = edgeHigh.x - edgeLow.x;
+ let edgeDy = edgeHigh.y - edgeLow.y;
+ if (Math.abs(edgeDy) > Number.EPSILON) {
+ // Not parallel
+ if (edgeDy < 0) {
+ edgeLow = this._points[q];
+ edgeDx = -edgeDx;
+ edgeHigh = this._points[p];
+ edgeDy = -edgeDy;
+ }
+ if (point.y < edgeLow.y || point.y > edgeHigh.y) {
+ continue;
+ }
+ if (point.y === edgeLow.y && point.x === edgeLow.x) {
+ return true;
+ }
+ else {
+ const perpEdge = edgeDy * (point.x - edgeLow.x) - edgeDx * (point.y - edgeLow.y);
+ if (perpEdge === 0) {
+ return true;
+ }
+ if (perpEdge < 0) {
+ continue;
+ }
+ isInside = !isInside;
+ }
+ }
+ else {
+ // parallel or collinear
+ if (point.y !== edgeLow.y) {
+ continue;
+ }
+ if ((edgeHigh.x <= point.x && point.x <= edgeLow.x) || (edgeLow.x <= point.x && point.x <= edgeHigh.x)) {
+ return true;
+ }
+ }
+ }
+ return isInside;
+ }
+ /**
+ * Closes the Path2.
+ * @returns the Path2.
+ */
+ close() {
+ this.closed = true;
+ return this;
+ }
+ /**
+ * Gets the sum of the distance between each sequential point in the path
+ * @returns the Path2 total length (float).
+ */
+ length() {
+ let result = this._length;
+ if (this.closed) {
+ const lastPoint = this._points[this._points.length - 1];
+ const firstPoint = this._points[0];
+ result += firstPoint.subtract(lastPoint).length();
+ }
+ return result;
+ }
+ /**
+ * Gets the area of the polygon defined by the path
+ * @returns area value
+ */
+ area() {
+ const n = this._points.length;
+ let value = 0.0;
+ for (let p = n - 1, q = 0; q < n; p = q++) {
+ value += this._points[p].x * this._points[q].y - this._points[q].x * this._points[p].y;
+ }
+ return value * 0.5;
+ }
+ /**
+ * Gets the points which construct the path
+ * @returns the Path2 internal array of points.
+ */
+ getPoints() {
+ return this._points;
+ }
+ /**
+ * Retrieves the point at the distance aways from the starting point
+ * @param normalizedLengthPosition the length along the path to retrieve the point from
+ * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
+ */
+ getPointAtLengthPosition(normalizedLengthPosition) {
+ if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
+ return Vector2.Zero();
+ }
+ const lengthPosition = normalizedLengthPosition * this.length();
+ let previousOffset = 0;
+ for (let i = 0; i < this._points.length; i++) {
+ const j = (i + 1) % this._points.length;
+ const a = this._points[i];
+ const b = this._points[j];
+ const bToA = b.subtract(a);
+ const nextOffset = bToA.length() + previousOffset;
+ if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
+ const dir = bToA.normalize();
+ const localOffset = lengthPosition - previousOffset;
+ return new Vector2(a.x + dir.x * localOffset, a.y + dir.y * localOffset);
+ }
+ previousOffset = nextOffset;
+ }
+ return Vector2.Zero();
+ }
+ /**
+ * Creates a new path starting from an x and y position
+ * @param x starting x value
+ * @param y starting y value
+ * @returns a new Path2 starting at the coordinates (x, y).
+ */
+ static StartingAt(x, y) {
+ return new Path2(x, y);
+ }
+}
+/**
+ * Represents a 3D path made up of multiple 3D points
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D
+ */
+class Path3D {
+ /**
+ * new Path3D(path, normal, raw)
+ * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
+ * please read the description in the tutorial : https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D
+ * @param path an array of Vector3, the curve axis of the Path3D
+ * @param firstNormal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
+ * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
+ * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path.
+ */
+ constructor(
+ /**
+ * an array of Vector3, the curve axis of the Path3D
+ */
+ path, firstNormal = null, raw, alignTangentsWithPath = false) {
+ this.path = path;
+ this._curve = new Array();
+ this._distances = new Array();
+ this._tangents = new Array();
+ this._normals = new Array();
+ this._binormals = new Array();
+ // holds interpolated point data
+ this._pointAtData = {
+ id: 0,
+ point: Vector3.Zero(),
+ previousPointArrayIndex: 0,
+ position: 0,
+ subPosition: 0,
+ interpolateReady: false,
+ interpolationMatrix: Matrix.Identity(),
+ };
+ for (let p = 0; p < path.length; p++) {
+ this._curve[p] = path[p].clone(); // hard copy
+ }
+ this._raw = raw || false;
+ this._alignTangentsWithPath = alignTangentsWithPath;
+ this._compute(firstNormal, alignTangentsWithPath);
+ }
+ /**
+ * Returns the Path3D array of successive Vector3 designing its curve.
+ * @returns the Path3D array of successive Vector3 designing its curve.
+ */
+ getCurve() {
+ return this._curve;
+ }
+ /**
+ * Returns the Path3D array of successive Vector3 designing its curve.
+ * @returns the Path3D array of successive Vector3 designing its curve.
+ */
+ getPoints() {
+ return this._curve;
+ }
+ /**
+ * @returns the computed length (float) of the path.
+ */
+ length() {
+ return this._distances[this._distances.length - 1];
+ }
+ /**
+ * Returns an array populated with tangent vectors on each Path3D curve point.
+ * @returns an array populated with tangent vectors on each Path3D curve point.
+ */
+ getTangents() {
+ return this._tangents;
+ }
+ /**
+ * Returns an array populated with normal vectors on each Path3D curve point.
+ * @returns an array populated with normal vectors on each Path3D curve point.
+ */
+ getNormals() {
+ return this._normals;
+ }
+ /**
+ * Returns an array populated with binormal vectors on each Path3D curve point.
+ * @returns an array populated with binormal vectors on each Path3D curve point.
+ */
+ getBinormals() {
+ return this._binormals;
+ }
+ /**
+ * Returns an array populated with distances (float) of the i-th point from the first curve point.
+ * @returns an array populated with distances (float) of the i-th point from the first curve point.
+ */
+ getDistances() {
+ return this._distances;
+ }
+ /**
+ * Returns an interpolated point along this path
+ * @param position the position of the point along this path, from 0.0 to 1.0
+ * @returns a new Vector3 as the point
+ */
+ getPointAt(position) {
+ return this._updatePointAtData(position).point;
+ }
+ /**
+ * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path.
+ * @param position the position of the point along this path, from 0.0 to 1.0
+ * @param interpolated (optional, default false) : boolean, if true returns an interpolated tangent instead of the tangent of the previous path point.
+ * @returns a tangent vector corresponding to the interpolated Path3D curve point, if not interpolated, the tangent is taken from the precomputed tangents array.
+ */
+ getTangentAt(position, interpolated = false) {
+ this._updatePointAtData(position, interpolated);
+ return interpolated ? Vector3.TransformCoordinates(Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex];
+ }
+ /**
+ * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path.
+ * @param position the position of the point along this path, from 0.0 to 1.0
+ * @param interpolated (optional, default false) : boolean, if true returns an interpolated normal instead of the normal of the previous path point.
+ * @returns a normal vector corresponding to the interpolated Path3D curve point, if not interpolated, the normal is taken from the precomputed normals array.
+ */
+ getNormalAt(position, interpolated = false) {
+ this._updatePointAtData(position, interpolated);
+ return interpolated ? Vector3.TransformCoordinates(Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex];
+ }
+ /**
+ * Returns the binormal vector of an interpolated Path3D curve point at the specified position along this path.
+ * @param position the position of the point along this path, from 0.0 to 1.0
+ * @param interpolated (optional, default false) : boolean, if true returns an interpolated binormal instead of the binormal of the previous path point.
+ * @returns a binormal vector corresponding to the interpolated Path3D curve point, if not interpolated, the binormal is taken from the precomputed binormals array.
+ */
+ getBinormalAt(position, interpolated = false) {
+ this._updatePointAtData(position, interpolated);
+ return interpolated ? Vector3.TransformCoordinates(Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex];
+ }
+ /**
+ * Returns the distance (float) of an interpolated Path3D curve point at the specified position along this path.
+ * @param position the position of the point along this path, from 0.0 to 1.0
+ * @returns the distance of the interpolated Path3D curve point at the specified position along this path.
+ */
+ getDistanceAt(position) {
+ return this.length() * position;
+ }
+ /**
+ * Returns the array index of the previous point of an interpolated point along this path
+ * @param position the position of the point to interpolate along this path, from 0.0 to 1.0
+ * @returns the array index
+ */
+ getPreviousPointIndexAt(position) {
+ this._updatePointAtData(position);
+ return this._pointAtData.previousPointArrayIndex;
+ }
+ /**
+ * Returns the position of an interpolated point relative to the two path points it lies between, from 0.0 (point A) to 1.0 (point B)
+ * @param position the position of the point to interpolate along this path, from 0.0 to 1.0
+ * @returns the sub position
+ */
+ getSubPositionAt(position) {
+ this._updatePointAtData(position);
+ return this._pointAtData.subPosition;
+ }
+ /**
+ * Returns the position of the closest virtual point on this path to an arbitrary Vector3, from 0.0 to 1.0
+ * @param target the vector of which to get the closest position to
+ * @returns the position of the closest virtual point on this path to the target vector
+ */
+ getClosestPositionTo(target) {
+ let smallestDistance = Number.MAX_VALUE;
+ let closestPosition = 0.0;
+ for (let i = 0; i < this._curve.length - 1; i++) {
+ const point = this._curve[i + 0];
+ const tangent = this._curve[i + 1].subtract(point).normalize();
+ const subLength = this._distances[i + 1] - this._distances[i + 0];
+ const subPosition = Math.min((Math.max(Vector3.Dot(tangent, target.subtract(point).normalize()), 0.0) * Vector3.Distance(point, target)) / subLength, 1.0);
+ const distance = Vector3.Distance(point.add(tangent.scale(subPosition * subLength)), target);
+ if (distance < smallestDistance) {
+ smallestDistance = distance;
+ closestPosition = (this._distances[i + 0] + subLength * subPosition) / this.length();
+ }
+ }
+ return closestPosition;
+ }
+ /**
+ * Returns a sub path (slice) of this path
+ * @param start the position of the fist path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values
+ * @param end the position of the last path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values
+ * @returns a sub path (slice) of this path
+ */
+ slice(start = 0.0, end = 1.0) {
+ if (start < 0.0) {
+ start = 1 - ((start * -1) % 1.0);
+ }
+ if (end < 0.0) {
+ end = 1 - ((end * -1) % 1.0);
+ }
+ if (start > end) {
+ const _start = start;
+ start = end;
+ end = _start;
+ }
+ const curvePoints = this.getCurve();
+ const startPoint = this.getPointAt(start);
+ let startIndex = this.getPreviousPointIndexAt(start);
+ const endPoint = this.getPointAt(end);
+ const endIndex = this.getPreviousPointIndexAt(end) + 1;
+ const slicePoints = [];
+ if (start !== 0.0) {
+ startIndex++;
+ slicePoints.push(startPoint);
+ }
+ slicePoints.push(...curvePoints.slice(startIndex, endIndex));
+ if (end !== 1.0 || start === 1.0) {
+ slicePoints.push(endPoint);
+ }
+ return new Path3D(slicePoints, this.getNormalAt(start), this._raw, this._alignTangentsWithPath);
+ }
+ /**
+ * Forces the Path3D tangent, normal, binormal and distance recomputation.
+ * @param path path which all values are copied into the curves points
+ * @param firstNormal which should be projected onto the curve
+ * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path
+ * @returns the same object updated.
+ */
+ update(path, firstNormal = null, alignTangentsWithPath = false) {
+ for (let p = 0; p < path.length; p++) {
+ this._curve[p].x = path[p].x;
+ this._curve[p].y = path[p].y;
+ this._curve[p].z = path[p].z;
+ }
+ this._compute(firstNormal, alignTangentsWithPath);
+ return this;
+ }
+ // private function compute() : computes tangents, normals and binormals
+ _compute(firstNormal, alignTangentsWithPath = false) {
+ const l = this._curve.length;
+ if (l < 2) {
+ return;
+ }
+ // first and last tangents
+ this._tangents[0] = this._getFirstNonNullVector(0);
+ if (!this._raw) {
+ this._tangents[0].normalize();
+ }
+ this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
+ if (!this._raw) {
+ this._tangents[l - 1].normalize();
+ }
+ // normals and binormals at first point : arbitrary vector with _normalVector()
+ const tg0 = this._tangents[0];
+ const pp0 = this._normalVector(tg0, firstNormal);
+ this._normals[0] = pp0;
+ if (!this._raw) {
+ this._normals[0].normalize();
+ }
+ this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
+ if (!this._raw) {
+ this._binormals[0].normalize();
+ }
+ this._distances[0] = 0.0;
+ // normals and binormals : next points
+ let prev; // previous vector (segment)
+ let cur; // current vector (segment)
+ let curTang; // current tangent
+ // previous normal
+ let prevNor; // previous normal
+ let prevBinor; // previous binormal
+ for (let i = 1; i < l; i++) {
+ // tangents
+ prev = this._getLastNonNullVector(i);
+ if (i < l - 1) {
+ cur = this._getFirstNonNullVector(i);
+ this._tangents[i] = alignTangentsWithPath ? cur : prev.add(cur);
+ this._tangents[i].normalize();
+ }
+ this._distances[i] = this._distances[i - 1] + this._curve[i].subtract(this._curve[i - 1]).length();
+ // normals and binormals
+ // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
+ curTang = this._tangents[i];
+ prevBinor = this._binormals[i - 1];
+ this._normals[i] = Vector3.Cross(prevBinor, curTang);
+ if (!this._raw) {
+ if (this._normals[i].length() === 0) {
+ prevNor = this._normals[i - 1];
+ this._normals[i] = prevNor.clone();
+ }
+ else {
+ this._normals[i].normalize();
+ }
+ }
+ this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
+ if (!this._raw) {
+ this._binormals[i].normalize();
+ }
+ }
+ this._pointAtData.id = NaN;
+ }
+ // private function getFirstNonNullVector(index)
+ // returns the first non null vector from index : curve[index + N].subtract(curve[index])
+ _getFirstNonNullVector(index) {
+ let i = 1;
+ let nNVector = this._curve[index + i].subtract(this._curve[index]);
+ while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
+ i++;
+ nNVector = this._curve[index + i].subtract(this._curve[index]);
+ }
+ return nNVector;
+ }
+ // private function getLastNonNullVector(index)
+ // returns the last non null vector from index : curve[index].subtract(curve[index - N])
+ _getLastNonNullVector(index) {
+ let i = 1;
+ let nLVector = this._curve[index].subtract(this._curve[index - i]);
+ while (nLVector.length() === 0 && index > i + 1) {
+ i++;
+ nLVector = this._curve[index].subtract(this._curve[index - i]);
+ }
+ return nLVector;
+ }
+ // private function normalVector(v0, vt, va) :
+ // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
+ // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
+ _normalVector(vt, va) {
+ let normal0;
+ let tgl = vt.length();
+ if (tgl === 0.0) {
+ tgl = 1.0;
+ }
+ if (va === undefined || va === null) {
+ let point;
+ if (!WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, Epsilon)) {
+ // search for a point in the plane
+ point = new Vector3(0.0, -1, 0.0);
+ }
+ else if (!WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, Epsilon)) {
+ point = new Vector3(1.0, 0.0, 0.0);
+ }
+ else if (!WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, Epsilon)) {
+ point = new Vector3(0.0, 0.0, 1.0);
+ }
+ else {
+ point = Vector3.Zero();
+ }
+ normal0 = Vector3.Cross(vt, point);
+ }
+ else {
+ normal0 = Vector3.Cross(vt, va);
+ Vector3.CrossToRef(normal0, vt, normal0);
+ }
+ normal0.normalize();
+ return normal0;
+ }
+ /**
+ * Updates the point at data for an interpolated point along this curve
+ * @param position the position of the point along this curve, from 0.0 to 1.0
+ * @param interpolateTNB
+ * @interpolateTNB whether to compute the interpolated tangent, normal and binormal
+ * @returns the (updated) point at data
+ */
+ _updatePointAtData(position, interpolateTNB = false) {
+ // set an id for caching the result
+ if (this._pointAtData.id === position) {
+ if (!this._pointAtData.interpolateReady) {
+ this._updateInterpolationMatrix();
+ }
+ return this._pointAtData;
+ }
+ else {
+ this._pointAtData.id = position;
+ }
+ const curvePoints = this.getPoints();
+ // clamp position between 0.0 and 1.0
+ if (position <= 0.0) {
+ return this._setPointAtData(0.0, 0.0, curvePoints[0], 0, interpolateTNB);
+ }
+ else if (position >= 1.0) {
+ return this._setPointAtData(1.0, 1.0, curvePoints[curvePoints.length - 1], curvePoints.length - 1, interpolateTNB);
+ }
+ let previousPoint = curvePoints[0];
+ let currentPoint;
+ let currentLength = 0.0;
+ const targetLength = position * this.length();
+ for (let i = 1; i < curvePoints.length; i++) {
+ currentPoint = curvePoints[i];
+ const distance = Vector3.Distance(previousPoint, currentPoint);
+ currentLength += distance;
+ if (currentLength === targetLength) {
+ return this._setPointAtData(position, 1.0, currentPoint, i, interpolateTNB);
+ }
+ else if (currentLength > targetLength) {
+ const toLength = currentLength - targetLength;
+ const diff = toLength / distance;
+ const dir = previousPoint.subtract(currentPoint);
+ const point = currentPoint.add(dir.scaleInPlace(diff));
+ return this._setPointAtData(position, 1 - diff, point, i - 1, interpolateTNB);
+ }
+ previousPoint = currentPoint;
+ }
+ return this._pointAtData;
+ }
+ /**
+ * Updates the point at data from the specified parameters
+ * @param position where along the path the interpolated point is, from 0.0 to 1.0
+ * @param subPosition
+ * @param point the interpolated point
+ * @param parentIndex the index of an existing curve point that is on, or else positionally the first behind, the interpolated point
+ * @param interpolateTNB whether to compute the interpolated tangent, normal and binormal
+ * @returns the (updated) point at data
+ */
+ _setPointAtData(position, subPosition, point, parentIndex, interpolateTNB) {
+ this._pointAtData.point = point;
+ this._pointAtData.position = position;
+ this._pointAtData.subPosition = subPosition;
+ this._pointAtData.previousPointArrayIndex = parentIndex;
+ this._pointAtData.interpolateReady = interpolateTNB;
+ if (interpolateTNB) {
+ this._updateInterpolationMatrix();
+ }
+ return this._pointAtData;
+ }
+ /**
+ * Updates the point at interpolation matrix for the tangents, normals and binormals
+ */
+ _updateInterpolationMatrix() {
+ this._pointAtData.interpolationMatrix = Matrix.Identity();
+ const parentIndex = this._pointAtData.previousPointArrayIndex;
+ if (parentIndex !== this._tangents.length - 1) {
+ const index = parentIndex + 1;
+ const tangentFrom = this._tangents[parentIndex].clone();
+ const normalFrom = this._normals[parentIndex].clone();
+ const binormalFrom = this._binormals[parentIndex].clone();
+ const tangentTo = this._tangents[index].clone();
+ const normalTo = this._normals[index].clone();
+ const binormalTo = this._binormals[index].clone();
+ const quatFrom = Quaternion.RotationQuaternionFromAxis(normalFrom, binormalFrom, tangentFrom);
+ const quatTo = Quaternion.RotationQuaternionFromAxis(normalTo, binormalTo, tangentTo);
+ const quatAt = Quaternion.Slerp(quatFrom, quatTo, this._pointAtData.subPosition);
+ quatAt.toRotationMatrix(this._pointAtData.interpolationMatrix);
+ }
+ }
+}
+/**
+ * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
+ * A Curve3 is designed from a series of successive Vector3.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves
+ */
+class Curve3 {
+ /**
+ * Returns a Curve3 object along a Quadratic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#quadratic-bezier-curve
+ * @param v0 (Vector3) the origin point of the Quadratic Bezier
+ * @param v1 (Vector3) the control point
+ * @param v2 (Vector3) the end point of the Quadratic Bezier
+ * @param nbPoints (integer) the wanted number of points in the curve
+ * @returns the created Curve3
+ */
+ static CreateQuadraticBezier(v0, v1, v2, nbPoints) {
+ nbPoints = nbPoints > 2 ? nbPoints : 3;
+ const bez = [];
+ const equation = (t, val0, val1, val2) => {
+ const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
+ return res;
+ };
+ for (let i = 0; i <= nbPoints; i++) {
+ bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
+ }
+ return new Curve3(bez);
+ }
+ /**
+ * Returns a Curve3 object along a Cubic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#cubic-bezier-curve
+ * @param v0 (Vector3) the origin point of the Cubic Bezier
+ * @param v1 (Vector3) the first control point
+ * @param v2 (Vector3) the second control point
+ * @param v3 (Vector3) the end point of the Cubic Bezier
+ * @param nbPoints (integer) the wanted number of points in the curve
+ * @returns the created Curve3
+ */
+ static CreateCubicBezier(v0, v1, v2, v3, nbPoints) {
+ nbPoints = nbPoints > 3 ? nbPoints : 4;
+ const bez = [];
+ const equation = (t, val0, val1, val2, val3) => {
+ const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
+ return res;
+ };
+ for (let i = 0; i <= nbPoints; i++) {
+ bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
+ }
+ return new Curve3(bez);
+ }
+ /**
+ * Returns a Curve3 object along a Hermite Spline curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-spline
+ * @param p1 (Vector3) the origin point of the Hermite Spline
+ * @param t1 (Vector3) the tangent vector at the origin point
+ * @param p2 (Vector3) the end point of the Hermite Spline
+ * @param t2 (Vector3) the tangent vector at the end point
+ * @param nSeg (integer) the number of curve segments or nSeg + 1 points in the array
+ * @returns the created Curve3
+ */
+ static CreateHermiteSpline(p1, t1, p2, t2, nSeg) {
+ const hermite = [];
+ const step = 1.0 / nSeg;
+ for (let i = 0; i <= nSeg; i++) {
+ hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
+ }
+ return new Curve3(hermite);
+ }
+ /**
+ * Returns a Curve3 object along a CatmullRom Spline curve :
+ * @param points (array of Vector3) the points the spline must pass through. At least, four points required
+ * @param nbPoints (integer) the wanted number of points between each curve control points
+ * @param closed (boolean) optional with default false, when true forms a closed loop from the points
+ * @returns the created Curve3
+ */
+ static CreateCatmullRomSpline(points, nbPoints, closed) {
+ const catmullRom = [];
+ const step = 1.0 / nbPoints;
+ let amount = 0.0;
+ if (closed) {
+ const pointsCount = points.length;
+ for (let i = 0; i < pointsCount; i++) {
+ amount = 0;
+ for (let c = 0; c < nbPoints; c++) {
+ catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
+ amount += step;
+ }
+ }
+ catmullRom.push(catmullRom[0]);
+ }
+ else {
+ const totalPoints = [];
+ totalPoints.push(points[0].clone());
+ Array.prototype.push.apply(totalPoints, points);
+ totalPoints.push(points[points.length - 1].clone());
+ let i = 0;
+ for (; i < totalPoints.length - 3; i++) {
+ amount = 0;
+ for (let c = 0; c < nbPoints; c++) {
+ catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
+ amount += step;
+ }
+ }
+ i--;
+ catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
+ }
+ return new Curve3(catmullRom);
+ }
+ /**
+ * Returns a Curve3 object along an arc through three vector3 points:
+ * The three points should not be colinear. When they are the Curve3 is empty.
+ * @param first (Vector3) the first point the arc must pass through.
+ * @param second (Vector3) the second point the arc must pass through.
+ * @param third (Vector3) the third point the arc must pass through.
+ * @param steps (number) the larger the number of steps the more detailed the arc.
+ * @param closed (boolean) optional with default false, when true forms the chord from the first and third point
+ * @param fullCircle Circle (boolean) optional with default false, when true forms the complete circle through the three points
+ * @returns the created Curve3
+ */
+ static ArcThru3Points(first, second, third, steps = 32, closed = false, fullCircle = false) {
+ const arc = [];
+ const vec1 = second.subtract(first);
+ const vec2 = third.subtract(second);
+ const vec3 = first.subtract(third);
+ const zAxis = Vector3.Cross(vec1, vec2);
+ const len4 = zAxis.length();
+ if (len4 < Math.pow(10, -8)) {
+ return new Curve3(arc); // colinear points arc is empty
+ }
+ const len1_sq = vec1.lengthSquared();
+ const len2_sq = vec2.lengthSquared();
+ const len3_sq = vec3.lengthSquared();
+ const len4_sq = zAxis.lengthSquared();
+ const len1 = vec1.length();
+ const len2 = vec2.length();
+ const len3 = vec3.length();
+ const radius = (0.5 * len1 * len2 * len3) / len4;
+ const dot1 = Vector3.Dot(vec1, vec3);
+ const dot2 = Vector3.Dot(vec1, vec2);
+ const dot3 = Vector3.Dot(vec2, vec3);
+ const a = (-0.5 * len2_sq * dot1) / len4_sq;
+ const b = (-0.5 * len3_sq * dot2) / len4_sq;
+ const c = (-0.5 * len1_sq * dot3) / len4_sq;
+ const center = first.scale(a).add(second.scale(b)).add(third.scale(c));
+ const radiusVec = first.subtract(center);
+ const xAxis = radiusVec.normalize();
+ const yAxis = Vector3.Cross(zAxis, xAxis).normalize();
+ if (fullCircle) {
+ const dStep = (2 * Math.PI) / steps;
+ for (let theta = 0; theta <= 2 * Math.PI; theta += dStep) {
+ arc.push(center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta)))));
+ }
+ arc.push(first);
+ }
+ else {
+ const dStep = 1 / steps;
+ let theta = 0;
+ let point = Vector3.Zero();
+ do {
+ point = center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta))));
+ arc.push(point);
+ theta += dStep;
+ } while (!point.equalsWithEpsilon(third, radius * dStep * 1.1));
+ arc.push(third);
+ if (closed) {
+ arc.push(first);
+ }
+ }
+ return new Curve3(arc);
+ }
+ /**
+ * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
+ * A Curve3 is designed from a series of successive Vector3.
+ * Tuto : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#curve3-object
+ * @param points points which make up the curve
+ */
+ constructor(points) {
+ this._length = 0.0;
+ this._points = points;
+ this._length = this._computeLength(points);
+ }
+ /**
+ * @returns the Curve3 stored array of successive Vector3
+ */
+ getPoints() {
+ return this._points;
+ }
+ /**
+ * @returns the computed length (float) of the curve.
+ */
+ length() {
+ return this._length;
+ }
+ /**
+ * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
+ * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
+ * curveA and curveB keep unchanged.
+ * @param curve the curve to continue from this curve
+ * @returns the newly constructed curve
+ */
+ continue(curve) {
+ const lastPoint = this._points[this._points.length - 1];
+ const continuedPoints = this._points.slice();
+ const curvePoints = curve.getPoints();
+ for (let i = 1; i < curvePoints.length; i++) {
+ continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
+ }
+ const continuedCurve = new Curve3(continuedPoints);
+ return continuedCurve;
+ }
+ _computeLength(path) {
+ let l = 0;
+ for (let i = 1; i < path.length; i++) {
+ l += path[i].subtract(path[i - 1]).length();
+ }
+ return l;
+ }
+}
+
+/**
+ * Size containing width and height
+ */
+class Size {
+ /**
+ * Creates a Size object from the given width and height (floats).
+ * @param width width of the new size
+ * @param height height of the new size
+ */
+ constructor(width, height) {
+ this.width = width;
+ this.height = height;
+ }
+ /**
+ * Returns a string with the Size width and height
+ * @returns a string with the Size width and height
+ */
+ toString() {
+ return `{W: ${this.width}, H: ${this.height}}`;
+ }
+ /**
+ * "Size"
+ * @returns the string "Size"
+ */
+ getClassName() {
+ return "Size";
+ }
+ /**
+ * Returns the Size hash code.
+ * @returns a hash code for a unique width and height
+ */
+ getHashCode() {
+ let hash = this.width | 0;
+ hash = (hash * 397) ^ (this.height | 0);
+ return hash;
+ }
+ /**
+ * Updates the current size from the given one.
+ * @param src the given size
+ */
+ copyFrom(src) {
+ this.width = src.width;
+ this.height = src.height;
+ }
+ /**
+ * Updates in place the current Size from the given floats.
+ * @param width width of the new size
+ * @param height height of the new size
+ * @returns the updated Size.
+ */
+ copyFromFloats(width, height) {
+ this.width = width;
+ this.height = height;
+ return this;
+ }
+ /**
+ * Updates in place the current Size from the given floats.
+ * @param width width to set
+ * @param height height to set
+ * @returns the updated Size.
+ */
+ set(width, height) {
+ return this.copyFromFloats(width, height);
+ }
+ /**
+ * Multiplies the width and height by numbers
+ * @param w factor to multiple the width by
+ * @param h factor to multiple the height by
+ * @returns a new Size set with the multiplication result of the current Size and the given floats.
+ */
+ multiplyByFloats(w, h) {
+ return new Size(this.width * w, this.height * h);
+ }
+ /**
+ * Clones the size
+ * @returns a new Size copied from the given one.
+ */
+ clone() {
+ return new Size(this.width, this.height);
+ }
+ /**
+ * True if the current Size and the given one width and height are strictly equal.
+ * @param other the other size to compare against
+ * @returns True if the current Size and the given one width and height are strictly equal.
+ */
+ equals(other) {
+ if (!other) {
+ return false;
+ }
+ return this.width === other.width && this.height === other.height;
+ }
+ /**
+ * The surface of the Size : width * height (float).
+ */
+ get surface() {
+ return this.width * this.height;
+ }
+ /**
+ * Create a new size of zero
+ * @returns a new Size set to (0.0, 0.0)
+ */
+ static Zero() {
+ return new Size(0.0, 0.0);
+ }
+ /**
+ * Sums the width and height of two sizes
+ * @param otherSize size to add to this size
+ * @returns a new Size set as the addition result of the current Size and the given one.
+ */
+ add(otherSize) {
+ const r = new Size(this.width + otherSize.width, this.height + otherSize.height);
+ return r;
+ }
+ /**
+ * Subtracts the width and height of two
+ * @param otherSize size to subtract to this size
+ * @returns a new Size set as the subtraction result of the given one from the current Size.
+ */
+ subtract(otherSize) {
+ const r = new Size(this.width - otherSize.width, this.height - otherSize.height);
+ return r;
+ }
+ /**
+ * Scales the width and height
+ * @param scale the scale to multiply the width and height by
+ * @returns a new Size set with the multiplication result of the current Size and the given floats.
+ */
+ scale(scale) {
+ return new Size(this.width * scale, this.height * scale);
+ }
+ /**
+ * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
+ * @param start starting size to lerp between
+ * @param end end size to lerp between
+ * @param amount amount to lerp between the start and end values
+ * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
+ */
+ static Lerp(start, end, amount) {
+ const w = start.width + (end.width - start.width) * amount;
+ const h = start.height + (end.height - start.height) * amount;
+ return new Size(w, h);
+ }
+}
+
+/**
+ * Class used to represent a viewport on screen
+ */
+class Viewport {
+ /**
+ * Creates a Viewport object located at (x, y) and sized (width, height)
+ * @param x defines viewport left coordinate
+ * @param y defines viewport top coordinate
+ * @param width defines the viewport width
+ * @param height defines the viewport height
+ */
+ constructor(
+ /** viewport left coordinate */
+ x,
+ /** viewport top coordinate */
+ y,
+ /**viewport width */
+ width,
+ /** viewport height */
+ height) {
+ this.x = x;
+ this.y = y;
+ this.width = width;
+ this.height = height;
+ }
+ /**
+ * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
+ * @param renderWidth defines the rendering width
+ * @param renderHeight defines the rendering height
+ * @returns a new Viewport
+ */
+ toGlobal(renderWidth, renderHeight) {
+ return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
+ }
+ /**
+ * Stores absolute viewport value into a target viewport (from 0-> width, 0-> height instead of 0->1)
+ * @param renderWidth defines the rendering width
+ * @param renderHeight defines the rendering height
+ * @param ref defines the target viewport
+ * @returns the current viewport
+ */
+ toGlobalToRef(renderWidth, renderHeight, ref) {
+ ref.x = this.x * renderWidth;
+ ref.y = this.y * renderHeight;
+ ref.width = this.width * renderWidth;
+ ref.height = this.height * renderHeight;
+ return this;
+ }
+ /**
+ * Returns a new Viewport copied from the current one
+ * @returns a new Viewport
+ */
+ clone() {
+ return new Viewport(this.x, this.y, this.width, this.height);
+ }
+}
+
+/* eslint-disable @typescript-eslint/naming-convention */
+// https://dickyjim.wordpress.com/2013/09/04/spherical-harmonics-for-beginners/
+// http://silviojemma.com/public/papers/lighting/spherical-harmonic-lighting.pdf
+// https://www.ppsloan.org/publications/StupidSH36.pdf
+// http://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf
+// https://www.ppsloan.org/publications/SHJCGT.pdf
+// https://www.ppsloan.org/publications/shdering.pdf
+// https://google.github.io/filament/Filament.md.html#annex/sphericalharmonics
+// https://patapom.com/blog/SHPortal/
+// https://imdoingitwrong.wordpress.com/2011/04/14/spherical-harmonics-wtf/
+// Using real SH basis:
+// m>0 m m
+// y = sqrt(2) * K * P * cos(m*phi) * cos(theta)
+// l l l
+//
+// m<0 m |m|
+// y = sqrt(2) * K * P * sin(m*phi) * cos(theta)
+// l l l
+//
+// m=0 0 0
+// y = K * P * trigono terms
+// l l l
+//
+// m (2l + 1)(l - |m|)!
+// K = sqrt(------------------)
+// l 4pi(l + |m|)!
+//
+// and P by recursion:
+//
+// P00(x) = 1
+// P01(x) = x
+// Pll(x) = (-1^l)(2l - 1)!!(1-x*x)^(1/2)
+// ((2l - 1)x[Pl-1/m]-(l + m - 1)[Pl-2/m])
+// Plm(x) = ---------------------------------------
+// l - m
+// Leaving the trigonometric terms aside we can precompute the constants to :
+const SH3ylmBasisConstants = [
+ Math.sqrt(1 / (4 * Math.PI)), // l00
+ -Math.sqrt(3 / (4 * Math.PI)), // l1_1
+ Math.sqrt(3 / (4 * Math.PI)), // l10
+ -Math.sqrt(3 / (4 * Math.PI)), // l11
+ Math.sqrt(15 / (4 * Math.PI)), // l2_2
+ -Math.sqrt(15 / (4 * Math.PI)), // l2_1
+ Math.sqrt(5 / (16 * Math.PI)), // l20
+ -Math.sqrt(15 / (4 * Math.PI)), // l21
+ Math.sqrt(15 / (16 * Math.PI)), // l22
+];
+// cm = cos(m * phi)
+// sm = sin(m * phi)
+// {x,y,z} = {cos(phi)sin(theta), sin(phi)sin(theta), cos(theta)}
+// By recursion on using trigo identities:
+const SH3ylmBasisTrigonometricTerms = [
+ () => 1, // l00
+ (direction) => direction.y, // l1_1
+ (direction) => direction.z, // l10
+ (direction) => direction.x, // l11
+ (direction) => direction.x * direction.y, // l2_2
+ (direction) => direction.y * direction.z, // l2_1
+ (direction) => 3 * direction.z * direction.z - 1, // l20
+ (direction) => direction.x * direction.z, // l21
+ (direction) => direction.x * direction.x - direction.y * direction.y, // l22
+];
+// Wrap the full compute
+const applySH3 = (lm, direction) => {
+ return SH3ylmBasisConstants[lm] * SH3ylmBasisTrigonometricTerms[lm](direction);
+};
+// Derived from the integration of the a kernel convolution to SH.
+// Great explanation here: https://patapom.com/blog/SHPortal/#about-distant-radiance-and-irradiance-environments
+const SHCosKernelConvolution = [Math.PI, (2 * Math.PI) / 3, (2 * Math.PI) / 3, (2 * Math.PI) / 3, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4];
+/**
+ * Class representing spherical harmonics coefficients to the 3rd degree
+ */
+class SphericalHarmonics {
+ constructor() {
+ /**
+ * Defines whether or not the harmonics have been prescaled for rendering.
+ */
+ this.preScaled = false;
+ /**
+ * The l0,0 coefficients of the spherical harmonics
+ */
+ this.l00 = Vector3.Zero();
+ /**
+ * The l1,-1 coefficients of the spherical harmonics
+ */
+ this.l1_1 = Vector3.Zero();
+ /**
+ * The l1,0 coefficients of the spherical harmonics
+ */
+ this.l10 = Vector3.Zero();
+ /**
+ * The l1,1 coefficients of the spherical harmonics
+ */
+ this.l11 = Vector3.Zero();
+ /**
+ * The l2,-2 coefficients of the spherical harmonics
+ */
+ this.l2_2 = Vector3.Zero();
+ /**
+ * The l2,-1 coefficients of the spherical harmonics
+ */
+ this.l2_1 = Vector3.Zero();
+ /**
+ * The l2,0 coefficients of the spherical harmonics
+ */
+ this.l20 = Vector3.Zero();
+ /**
+ * The l2,1 coefficients of the spherical harmonics
+ */
+ this.l21 = Vector3.Zero();
+ /**
+ * The l2,2 coefficients of the spherical harmonics
+ */
+ this.l22 = Vector3.Zero();
+ }
+ /**
+ * Adds a light to the spherical harmonics
+ * @param direction the direction of the light
+ * @param color the color of the light
+ * @param deltaSolidAngle the delta solid angle of the light
+ */
+ addLight(direction, color, deltaSolidAngle) {
+ TmpVectors.Vector3[0].set(color.r, color.g, color.b);
+ const colorVector = TmpVectors.Vector3[0];
+ const c = TmpVectors.Vector3[1];
+ colorVector.scaleToRef(deltaSolidAngle, c);
+ c.scaleToRef(applySH3(0, direction), TmpVectors.Vector3[2]);
+ this.l00.addInPlace(TmpVectors.Vector3[2]);
+ c.scaleToRef(applySH3(1, direction), TmpVectors.Vector3[2]);
+ this.l1_1.addInPlace(TmpVectors.Vector3[2]);
+ c.scaleToRef(applySH3(2, direction), TmpVectors.Vector3[2]);
+ this.l10.addInPlace(TmpVectors.Vector3[2]);
+ c.scaleToRef(applySH3(3, direction), TmpVectors.Vector3[2]);
+ this.l11.addInPlace(TmpVectors.Vector3[2]);
+ c.scaleToRef(applySH3(4, direction), TmpVectors.Vector3[2]);
+ this.l2_2.addInPlace(TmpVectors.Vector3[2]);
+ c.scaleToRef(applySH3(5, direction), TmpVectors.Vector3[2]);
+ this.l2_1.addInPlace(TmpVectors.Vector3[2]);
+ c.scaleToRef(applySH3(6, direction), TmpVectors.Vector3[2]);
+ this.l20.addInPlace(TmpVectors.Vector3[2]);
+ c.scaleToRef(applySH3(7, direction), TmpVectors.Vector3[2]);
+ this.l21.addInPlace(TmpVectors.Vector3[2]);
+ c.scaleToRef(applySH3(8, direction), TmpVectors.Vector3[2]);
+ this.l22.addInPlace(TmpVectors.Vector3[2]);
+ }
+ /**
+ * Scales the spherical harmonics by the given amount
+ * @param scale the amount to scale
+ */
+ scaleInPlace(scale) {
+ this.l00.scaleInPlace(scale);
+ this.l1_1.scaleInPlace(scale);
+ this.l10.scaleInPlace(scale);
+ this.l11.scaleInPlace(scale);
+ this.l2_2.scaleInPlace(scale);
+ this.l2_1.scaleInPlace(scale);
+ this.l20.scaleInPlace(scale);
+ this.l21.scaleInPlace(scale);
+ this.l22.scaleInPlace(scale);
+ }
+ /**
+ * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
+ *
+ * ```
+ * E_lm = A_l * L_lm
+ * ```
+ *
+ * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
+ * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
+ * the scaling factors are given in equation 9.
+ */
+ convertIncidentRadianceToIrradiance() {
+ // Constant (Band 0)
+ this.l00.scaleInPlace(SHCosKernelConvolution[0]);
+ // Linear (Band 1)
+ this.l1_1.scaleInPlace(SHCosKernelConvolution[1]);
+ this.l10.scaleInPlace(SHCosKernelConvolution[2]);
+ this.l11.scaleInPlace(SHCosKernelConvolution[3]);
+ // Quadratic (Band 2)
+ this.l2_2.scaleInPlace(SHCosKernelConvolution[4]);
+ this.l2_1.scaleInPlace(SHCosKernelConvolution[5]);
+ this.l20.scaleInPlace(SHCosKernelConvolution[6]);
+ this.l21.scaleInPlace(SHCosKernelConvolution[7]);
+ this.l22.scaleInPlace(SHCosKernelConvolution[8]);
+ }
+ /**
+ * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
+ *
+ * ```
+ * L = (1/pi) * E * rho
+ * ```
+ *
+ * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
+ */
+ convertIrradianceToLambertianRadiance() {
+ this.scaleInPlace(1.0 / Math.PI);
+ // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
+ // (The pixel shader must apply albedo after texture fetches, etc).
+ }
+ /**
+ * Integrates the reconstruction coefficients directly in to the SH preventing further
+ * required operations at run time.
+ *
+ * This is simply done by scaling back the SH with Ylm constants parameter.
+ * The trigonometric part being applied by the shader at run time.
+ */
+ preScaleForRendering() {
+ this.preScaled = true;
+ this.l00.scaleInPlace(SH3ylmBasisConstants[0]);
+ this.l1_1.scaleInPlace(SH3ylmBasisConstants[1]);
+ this.l10.scaleInPlace(SH3ylmBasisConstants[2]);
+ this.l11.scaleInPlace(SH3ylmBasisConstants[3]);
+ this.l2_2.scaleInPlace(SH3ylmBasisConstants[4]);
+ this.l2_1.scaleInPlace(SH3ylmBasisConstants[5]);
+ this.l20.scaleInPlace(SH3ylmBasisConstants[6]);
+ this.l21.scaleInPlace(SH3ylmBasisConstants[7]);
+ this.l22.scaleInPlace(SH3ylmBasisConstants[8]);
+ }
+ /**
+ * update the spherical harmonics coefficients from the given array
+ * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
+ * @returns the spherical harmonics (this)
+ */
+ updateFromArray(data) {
+ Vector3.FromArrayToRef(data[0], 0, this.l00);
+ Vector3.FromArrayToRef(data[1], 0, this.l1_1);
+ Vector3.FromArrayToRef(data[2], 0, this.l10);
+ Vector3.FromArrayToRef(data[3], 0, this.l11);
+ Vector3.FromArrayToRef(data[4], 0, this.l2_2);
+ Vector3.FromArrayToRef(data[5], 0, this.l2_1);
+ Vector3.FromArrayToRef(data[6], 0, this.l20);
+ Vector3.FromArrayToRef(data[7], 0, this.l21);
+ Vector3.FromArrayToRef(data[8], 0, this.l22);
+ return this;
+ }
+ /**
+ * update the spherical harmonics coefficients from the given floats array
+ * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
+ * @returns the spherical harmonics (this)
+ */
+ updateFromFloatsArray(data) {
+ Vector3.FromFloatsToRef(data[0], data[1], data[2], this.l00);
+ Vector3.FromFloatsToRef(data[3], data[4], data[5], this.l1_1);
+ Vector3.FromFloatsToRef(data[6], data[7], data[8], this.l10);
+ Vector3.FromFloatsToRef(data[9], data[10], data[11], this.l11);
+ Vector3.FromFloatsToRef(data[12], data[13], data[14], this.l2_2);
+ Vector3.FromFloatsToRef(data[15], data[16], data[17], this.l2_1);
+ Vector3.FromFloatsToRef(data[18], data[19], data[20], this.l20);
+ Vector3.FromFloatsToRef(data[21], data[22], data[23], this.l21);
+ Vector3.FromFloatsToRef(data[24], data[25], data[26], this.l22);
+ return this;
+ }
+ /**
+ * Constructs a spherical harmonics from an array.
+ * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
+ * @returns the spherical harmonics
+ */
+ static FromArray(data) {
+ const sh = new SphericalHarmonics();
+ return sh.updateFromArray(data);
+ }
+ // Keep for references.
+ /**
+ * Gets the spherical harmonics from polynomial
+ * @param polynomial the spherical polynomial
+ * @returns the spherical harmonics
+ */
+ static FromPolynomial(polynomial) {
+ const result = new SphericalHarmonics();
+ result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
+ result.l1_1 = polynomial.y.scale(0.977204);
+ result.l10 = polynomial.z.scale(0.977204);
+ result.l11 = polynomial.x.scale(0.977204);
+ result.l2_2 = polynomial.xy.scale(1.16538);
+ result.l2_1 = polynomial.yz.scale(1.16538);
+ result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
+ result.l21 = polynomial.zx.scale(1.16538);
+ result.l22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
+ result.l1_1.scaleInPlace(-1);
+ result.l11.scaleInPlace(-1);
+ result.l2_1.scaleInPlace(-1);
+ result.l21.scaleInPlace(-1);
+ result.scaleInPlace(Math.PI);
+ return result;
+ }
+}
+/**
+ * Class representing spherical polynomial coefficients to the 3rd degree
+ */
+class SphericalPolynomial {
+ constructor() {
+ /**
+ * The x coefficients of the spherical polynomial
+ */
+ this.x = Vector3.Zero();
+ /**
+ * The y coefficients of the spherical polynomial
+ */
+ this.y = Vector3.Zero();
+ /**
+ * The z coefficients of the spherical polynomial
+ */
+ this.z = Vector3.Zero();
+ /**
+ * The xx coefficients of the spherical polynomial
+ */
+ this.xx = Vector3.Zero();
+ /**
+ * The yy coefficients of the spherical polynomial
+ */
+ this.yy = Vector3.Zero();
+ /**
+ * The zz coefficients of the spherical polynomial
+ */
+ this.zz = Vector3.Zero();
+ /**
+ * The xy coefficients of the spherical polynomial
+ */
+ this.xy = Vector3.Zero();
+ /**
+ * The yz coefficients of the spherical polynomial
+ */
+ this.yz = Vector3.Zero();
+ /**
+ * The zx coefficients of the spherical polynomial
+ */
+ this.zx = Vector3.Zero();
+ }
+ /**
+ * The spherical harmonics used to create the polynomials.
+ */
+ get preScaledHarmonics() {
+ if (!this._harmonics) {
+ this._harmonics = SphericalHarmonics.FromPolynomial(this);
+ }
+ if (!this._harmonics.preScaled) {
+ this._harmonics.preScaleForRendering();
+ }
+ return this._harmonics;
+ }
+ /**
+ * Adds an ambient color to the spherical polynomial
+ * @param color the color to add
+ */
+ addAmbient(color) {
+ TmpVectors.Vector3[0].copyFromFloats(color.r, color.g, color.b);
+ const colorVector = TmpVectors.Vector3[0];
+ this.xx.addInPlace(colorVector);
+ this.yy.addInPlace(colorVector);
+ this.zz.addInPlace(colorVector);
+ }
+ /**
+ * Scales the spherical polynomial by the given amount
+ * @param scale the amount to scale
+ */
+ scaleInPlace(scale) {
+ this.x.scaleInPlace(scale);
+ this.y.scaleInPlace(scale);
+ this.z.scaleInPlace(scale);
+ this.xx.scaleInPlace(scale);
+ this.yy.scaleInPlace(scale);
+ this.zz.scaleInPlace(scale);
+ this.yz.scaleInPlace(scale);
+ this.zx.scaleInPlace(scale);
+ this.xy.scaleInPlace(scale);
+ }
+ /**
+ * Updates the spherical polynomial from harmonics
+ * @param harmonics the spherical harmonics
+ * @returns the spherical polynomial
+ */
+ updateFromHarmonics(harmonics) {
+ this._harmonics = harmonics;
+ this.x.copyFrom(harmonics.l11);
+ this.x.scaleInPlace(1.02333).scaleInPlace(-1);
+ this.y.copyFrom(harmonics.l1_1);
+ this.y.scaleInPlace(1.02333).scaleInPlace(-1);
+ this.z.copyFrom(harmonics.l10);
+ this.z.scaleInPlace(1.02333);
+ this.xx.copyFrom(harmonics.l00);
+ TmpVectors.Vector3[0].copyFrom(harmonics.l20).scaleInPlace(0.247708);
+ TmpVectors.Vector3[1].copyFrom(harmonics.l22).scaleInPlace(0.429043);
+ this.xx.scaleInPlace(0.886277).subtractInPlace(TmpVectors.Vector3[0]).addInPlace(TmpVectors.Vector3[1]);
+ this.yy.copyFrom(harmonics.l00);
+ this.yy.scaleInPlace(0.886277).subtractInPlace(TmpVectors.Vector3[0]).subtractInPlace(TmpVectors.Vector3[1]);
+ this.zz.copyFrom(harmonics.l00);
+ TmpVectors.Vector3[0].copyFrom(harmonics.l20).scaleInPlace(0.495417);
+ this.zz.scaleInPlace(0.886277).addInPlace(TmpVectors.Vector3[0]);
+ this.yz.copyFrom(harmonics.l2_1);
+ this.yz.scaleInPlace(0.858086).scaleInPlace(-1);
+ this.zx.copyFrom(harmonics.l21);
+ this.zx.scaleInPlace(0.858086).scaleInPlace(-1);
+ this.xy.copyFrom(harmonics.l2_2);
+ this.xy.scaleInPlace(0.858086);
+ this.scaleInPlace(1.0 / Math.PI);
+ return this;
+ }
+ /**
+ * Gets the spherical polynomial from harmonics
+ * @param harmonics the spherical harmonics
+ * @returns the spherical polynomial
+ */
+ static FromHarmonics(harmonics) {
+ const result = new SphericalPolynomial();
+ return result.updateFromHarmonics(harmonics);
+ }
+ /**
+ * Constructs a spherical polynomial from an array.
+ * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
+ * @returns the spherical polynomial
+ */
+ static FromArray(data) {
+ const sp = new SphericalPolynomial();
+ Vector3.FromArrayToRef(data[0], 0, sp.x);
+ Vector3.FromArrayToRef(data[1], 0, sp.y);
+ Vector3.FromArrayToRef(data[2], 0, sp.z);
+ Vector3.FromArrayToRef(data[3], 0, sp.xx);
+ Vector3.FromArrayToRef(data[4], 0, sp.yy);
+ Vector3.FromArrayToRef(data[5], 0, sp.zz);
+ Vector3.FromArrayToRef(data[6], 0, sp.yz);
+ Vector3.FromArrayToRef(data[7], 0, sp.zx);
+ Vector3.FromArrayToRef(data[8], 0, sp.xy);
+ return sp;
+ }
+}
+
+function __decorate(decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+}
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const __mergedStore = {};
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const __decoratorInitialStore = {};
+/** @internal */
+function GetDirectStore(target) {
+ const classKey = target.getClassName();
+ if (!__decoratorInitialStore[classKey]) {
+ __decoratorInitialStore[classKey] = {};
+ }
+ return __decoratorInitialStore[classKey];
+}
+/**
+ * @returns the list of properties flagged as serializable
+ * @param target host object
+ */
+function GetMergedStore(target) {
+ const classKey = target.getClassName();
+ if (__mergedStore[classKey]) {
+ return __mergedStore[classKey];
+ }
+ __mergedStore[classKey] = {};
+ const store = __mergedStore[classKey];
+ let currentTarget = target;
+ let currentKey = classKey;
+ while (currentKey) {
+ const initialStore = __decoratorInitialStore[currentKey];
+ for (const property in initialStore) {
+ store[property] = initialStore[property];
+ }
+ let parent;
+ let done = false;
+ do {
+ parent = Object.getPrototypeOf(currentTarget);
+ if (!parent.getClassName) {
+ done = true;
+ break;
+ }
+ if (parent.getClassName() !== currentKey) {
+ break;
+ }
+ currentTarget = parent;
+ } while (parent);
+ if (done) {
+ break;
+ }
+ currentKey = parent.getClassName();
+ currentTarget = parent;
+ }
+ return store;
+}
+
+function generateSerializableMember(type, sourceName) {
+ return (target, propertyKey) => {
+ const classStore = GetDirectStore(target);
+ if (!classStore[propertyKey]) {
+ classStore[propertyKey] = { type: type, sourceName: sourceName };
+ }
+ };
+}
+function generateExpandMember(setCallback, targetKey = null) {
+ return (target, propertyKey) => {
+ const key = targetKey || "_" + propertyKey;
+ Object.defineProperty(target, propertyKey, {
+ get: function () {
+ return this[key];
+ },
+ set: function (value) {
+ // does this object (i.e. vector3) has an equals function? use it!
+ // Note - not using "with epsilon" here, it is expected te behave like the internal cache does.
+ if (typeof this[key]?.equals === "function") {
+ if (this[key].equals(value)) {
+ return;
+ }
+ }
+ if (this[key] === value) {
+ return;
+ }
+ this[key] = value;
+ target[setCallback].apply(this);
+ },
+ enumerable: true,
+ configurable: true,
+ });
+ };
+}
+function expandToProperty(callback, targetKey = null) {
+ return generateExpandMember(callback, targetKey);
+}
+function serialize(sourceName) {
+ return generateSerializableMember(0, sourceName); // value member
+}
+function serializeAsTexture(sourceName) {
+ return generateSerializableMember(1, sourceName); // texture member
+}
+function serializeAsColor3(sourceName) {
+ return generateSerializableMember(2, sourceName); // color3 member
+}
+function serializeAsFresnelParameters(sourceName) {
+ return generateSerializableMember(3, sourceName); // fresnel parameters member
+}
+function serializeAsVector2(sourceName) {
+ return generateSerializableMember(4, sourceName); // vector2 member
+}
+function serializeAsVector3(sourceName) {
+ return generateSerializableMember(5, sourceName); // vector3 member
+}
+function serializeAsMeshReference(sourceName) {
+ return generateSerializableMember(6, sourceName); // mesh reference member
+}
+function serializeAsColorCurves(sourceName) {
+ return generateSerializableMember(7, sourceName); // color curves
+}
+function serializeAsColor4(sourceName) {
+ return generateSerializableMember(8, sourceName); // color 4
+}
+function serializeAsImageProcessingConfiguration(sourceName) {
+ return generateSerializableMember(9, sourceName); // image processing
+}
+function serializeAsQuaternion(sourceName) {
+ return generateSerializableMember(10, sourceName); // quaternion member
+}
+function serializeAsMatrix(sourceName) {
+ return generateSerializableMember(12, sourceName); // matrix member
+}
+/**
+ * Decorator used to define property that can be serialized as reference to a camera
+ * @param sourceName defines the name of the property to decorate
+ * @returns Property Decorator
+ */
+function serializeAsCameraReference(sourceName) {
+ return generateSerializableMember(11, sourceName); // camera reference member
+}
+/**
+ * Decorator used to redirect a function to a native implementation if available.
+ * @internal
+ */
+function nativeOverride(target, propertyKey, descriptor, predicate) {
+ // Cache the original JS function for later.
+ const jsFunc = descriptor.value;
+ // Override the JS function to check for a native override on first invocation. Setting descriptor.value overrides the function at the early stage of code being loaded/imported.
+ descriptor.value = (...params) => {
+ // Assume the resolved function will be the original JS function, then we will check for the Babylon Native context.
+ let func = jsFunc;
+ // Check if we are executing in a Babylon Native context (e.g. check the presence of the _native global property) and if so also check if a function override is available.
+ if (typeof _native !== "undefined" && _native[propertyKey]) {
+ const nativeFunc = _native[propertyKey];
+ // If a predicate was provided, then we'll need to invoke the predicate on each invocation of the underlying function to determine whether to call the native function or the JS function.
+ if (predicate) {
+ // The resolved function will execute the predicate and then either execute the native function or the JS function.
+ func = (...params) => (predicate(...params) ? nativeFunc(...params) : jsFunc(...params));
+ }
+ else {
+ // The resolved function will directly execute the native function.
+ func = nativeFunc;
+ }
+ }
+ // Override the JS function again with the final resolved target function.
+ target[propertyKey] = func;
+ // The JS function has now been overridden based on whether we're executing in the context of Babylon Native, but we still need to invoke that function.
+ // Future invocations of the function will just directly invoke the final overridden function, not any of the decorator setup logic above.
+ return func(...params);
+ };
+}
+/**
+ * Decorator factory that applies the nativeOverride decorator, but determines whether to redirect to the native implementation based on a filter function that evaluates the function arguments.
+ * @param predicate
+ * @example @nativeOverride.filter((...[arg1]: Parameters) => arg1.length > 20)
+ * public someMethod(arg1: string, arg2: number): string {
+ * @internal
+ */
+nativeOverride.filter = function (predicate) {
+ return (target, propertyKey, descriptor) => nativeOverride(target, propertyKey, descriptor, predicate);
+};
+
+/**
+ * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
+ * Be aware Math.random() could cause collisions, but:
+ * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
+ * @returns a pseudo random id
+ */
+function RandomGUID() {
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
+ const r = (Math.random() * 16) | 0, v = c === "x" ? r : (r & 0x3) | 0x8;
+ return v.toString(16);
+ });
+}
+
+/** @internal */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function createXMLHttpRequest() {
+ // If running in Babylon Native, then defer to the native XMLHttpRequest, which has the same public contract
+ if (typeof _native !== "undefined" && _native.XMLHttpRequest) {
+ return new _native.XMLHttpRequest();
+ }
+ else {
+ return new XMLHttpRequest();
+ }
+}
+/**
+ * Extended version of XMLHttpRequest with support for customizations (headers, ...)
+ */
+class WebRequest {
+ constructor() {
+ this._xhr = createXMLHttpRequest();
+ this._requestURL = "";
+ }
+ /**
+ * This function can be called to check if there are request modifiers for network requests
+ * @returns true if there are any custom requests available
+ */
+ static get IsCustomRequestAvailable() {
+ return Object.keys(WebRequest.CustomRequestHeaders).length > 0 || WebRequest.CustomRequestModifiers.length > 0;
+ }
+ /**
+ * Returns the requested URL once open has been called
+ */
+ get requestURL() {
+ return this._requestURL;
+ }
+ _injectCustomRequestHeaders() {
+ if (this._shouldSkipRequestModifications(this._requestURL)) {
+ return;
+ }
+ for (const key in WebRequest.CustomRequestHeaders) {
+ const val = WebRequest.CustomRequestHeaders[key];
+ if (val) {
+ this._xhr.setRequestHeader(key, val);
+ }
+ }
+ }
+ _shouldSkipRequestModifications(url) {
+ return WebRequest.SkipRequestModificationForBabylonCDN && (url.includes("preview.babylonjs.com") || url.includes("cdn.babylonjs.com"));
+ }
+ /**
+ * Gets or sets a function to be called when loading progress changes
+ */
+ get onprogress() {
+ return this._xhr.onprogress;
+ }
+ set onprogress(value) {
+ this._xhr.onprogress = value;
+ }
+ /**
+ * Returns client's state
+ */
+ get readyState() {
+ return this._xhr.readyState;
+ }
+ /**
+ * Returns client's status
+ */
+ get status() {
+ return this._xhr.status;
+ }
+ /**
+ * Returns client's status as a text
+ */
+ get statusText() {
+ return this._xhr.statusText;
+ }
+ /**
+ * Returns client's response
+ */
+ get response() {
+ return this._xhr.response;
+ }
+ /**
+ * Returns client's response url
+ */
+ get responseURL() {
+ return this._xhr.responseURL;
+ }
+ /**
+ * Returns client's response as text
+ */
+ get responseText() {
+ return this._xhr.responseText;
+ }
+ /**
+ * Gets or sets the expected response type
+ */
+ get responseType() {
+ return this._xhr.responseType;
+ }
+ set responseType(value) {
+ this._xhr.responseType = value;
+ }
+ /**
+ * Gets or sets the timeout value in milliseconds
+ */
+ get timeout() {
+ return this._xhr.timeout;
+ }
+ set timeout(value) {
+ this._xhr.timeout = value;
+ }
+ addEventListener(type, listener, options) {
+ this._xhr.addEventListener(type, listener, options);
+ }
+ removeEventListener(type, listener, options) {
+ this._xhr.removeEventListener(type, listener, options);
+ }
+ /**
+ * Cancels any network activity
+ */
+ abort() {
+ this._xhr.abort();
+ }
+ /**
+ * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD
+ * @param body defines an optional request body
+ */
+ send(body) {
+ if (WebRequest.CustomRequestHeaders) {
+ this._injectCustomRequestHeaders();
+ }
+ this._xhr.send(body);
+ }
+ /**
+ * Sets the request method, request URL
+ * @param method defines the method to use (GET, POST, etc..)
+ * @param url defines the url to connect with
+ */
+ open(method, url) {
+ for (const update of WebRequest.CustomRequestModifiers) {
+ if (this._shouldSkipRequestModifications(url)) {
+ return;
+ }
+ url = update(this._xhr, url) || url;
+ }
+ // Clean url
+ url = url.replace("file:http:", "http:");
+ url = url.replace("file:https:", "https:");
+ this._requestURL = url;
+ this._xhr.open(method, url, true);
+ }
+ /**
+ * Sets the value of a request header.
+ * @param name The name of the header whose value is to be set
+ * @param value The value to set as the body of the header
+ */
+ setRequestHeader(name, value) {
+ this._xhr.setRequestHeader(name, value);
+ }
+ /**
+ * Get the string containing the text of a particular header's value.
+ * @param name The name of the header
+ * @returns The string containing the text of the given header name
+ */
+ getResponseHeader(name) {
+ return this._xhr.getResponseHeader(name);
+ }
+}
+/**
+ * Custom HTTP Request Headers to be sent with XMLHttpRequests
+ * i.e. when loading files, where the server/service expects an Authorization header
+ */
+WebRequest.CustomRequestHeaders = {};
+/**
+ * Add callback functions in this array to update all the requests before they get sent to the network
+ */
+WebRequest.CustomRequestModifiers = new Array();
+/**
+ * If set to true, requests to Babylon.js CDN requests will not be modified
+ */
+WebRequest.SkipRequestModificationForBabylonCDN = true;
+
+/**
+ * Class used to help managing file picking and drag'n'drop
+ * File Storage
+ */
+class FilesInputStore {
+}
+/**
+ * List of files ready to be loaded
+ */
+FilesInputStore.FilesToLoad = {};
+
+/**
+ * Class used to define a retry strategy when error happens while loading assets
+ */
+class RetryStrategy {
+ /**
+ * Function used to defines an exponential back off strategy
+ * @param maxRetries defines the maximum number of retries (3 by default)
+ * @param baseInterval defines the interval between retries
+ * @returns the strategy function to use
+ */
+ static ExponentialBackoff(maxRetries = 3, baseInterval = 500) {
+ return (url, request, retryIndex) => {
+ if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
+ return -1;
+ }
+ return Math.pow(2, retryIndex) * baseInterval;
+ };
+ }
+}
+
+/* eslint-disable @typescript-eslint/naming-convention */
+/**
+ * Base error. Due to limitations of typedoc-check and missing documentation
+ * in lib.es5.d.ts, cannot extend Error directly for RuntimeError.
+ * @ignore
+ */
+class BaseError extends Error {
+}
+// See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
+// and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
+// Polyfill for Object.setPrototypeOf if necessary.
+BaseError._setPrototypeOf = Object.setPrototypeOf ||
+ ((o, proto) => {
+ o.__proto__ = proto;
+ return o;
+ });
+/* IMP! DO NOT CHANGE THE NUMBERING OF EXISTING ERROR CODES */
+/**
+ * Error codes for BaseError
+ */
+const ErrorCodes = {
+ // Mesh errors 0-999
+ /** Invalid or empty mesh vertex positions. */
+ MeshInvalidPositionsError: 0,
+ // Texture errors 1000-1999
+ /** Unsupported texture found. */
+ UnsupportedTextureError: 1000,
+ // GLTFLoader errors 2000-2999
+ /** Unexpected magic number found in GLTF file header. */
+ GLTFLoaderUnexpectedMagicError: 2000,
+ // SceneLoader errors 3000-3999
+ /** SceneLoader generic error code. Ideally wraps the inner exception. */
+ SceneLoaderError: 3000,
+ // File related errors 4000-4999
+ /** Load file error */
+ LoadFileError: 4000,
+ /** Request file error */
+ RequestFileError: 4001,
+ /** Read file error */
+ ReadFileError: 4002,
+};
+/**
+ * Application runtime error
+ */
+class RuntimeError extends BaseError {
+ /**
+ * Creates a new RuntimeError
+ * @param message defines the message of the error
+ * @param errorCode the error code
+ * @param innerError the error that caused the outer error
+ */
+ constructor(message, errorCode, innerError) {
+ super(message);
+ this.errorCode = errorCode;
+ this.innerError = innerError;
+ this.name = "RuntimeError";
+ BaseError._setPrototypeOf(this, RuntimeError.prototype);
+ }
+}
+
+/* eslint-disable @typescript-eslint/naming-convention */
+/**
+ * Checks for a matching suffix at the end of a string (for ES5 and lower)
+ * @param str Source string
+ * @param suffix Suffix to search for in the source string
+ * @returns Boolean indicating whether the suffix was found (true) or not (false)
+ * @deprecated Please use native string function instead
+ */
+/**
+ * Decodes a buffer into a string
+ * @param buffer The buffer to decode
+ * @returns The decoded string
+ */
+const Decode = (buffer) => {
+ if (typeof TextDecoder !== "undefined") {
+ return new TextDecoder().decode(buffer);
+ }
+ let result = "";
+ for (let i = 0; i < buffer.byteLength; i++) {
+ result += String.fromCharCode(buffer[i]);
+ }
+ return result;
+};
+/**
+ * Encode a buffer to a base64 string
+ * @param buffer defines the buffer to encode
+ * @returns the encoded string
+ */
+const EncodeArrayBufferToBase64 = (buffer) => {
+ const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+ let output = "";
+ let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
+ let i = 0;
+ const bytes = ArrayBuffer.isView(buffer) ? new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) : new Uint8Array(buffer);
+ while (i < bytes.length) {
+ chr1 = bytes[i++];
+ chr2 = i < bytes.length ? bytes[i++] : Number.NaN;
+ chr3 = i < bytes.length ? bytes[i++] : Number.NaN;
+ enc1 = chr1 >> 2;
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+ enc4 = chr3 & 63;
+ if (isNaN(chr2)) {
+ enc3 = enc4 = 64;
+ }
+ else if (isNaN(chr3)) {
+ enc4 = 64;
+ }
+ output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
+ }
+ return output;
+};
+/**
+ * Converts a given base64 string as an ASCII encoded stream of data
+ * @param base64Data The base64 encoded string to decode
+ * @returns Decoded ASCII string
+ */
+const DecodeBase64ToString = (base64Data) => {
+ return atob(base64Data);
+};
+/**
+ * Converts a given base64 string into an ArrayBuffer of raw byte data
+ * @param base64Data The base64 encoded string to decode
+ * @returns ArrayBuffer of byte data
+ */
+const DecodeBase64ToBinary = (base64Data) => {
+ const decodedString = DecodeBase64ToString(base64Data);
+ const bufferLength = decodedString.length;
+ const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
+ for (let i = 0; i < bufferLength; i++) {
+ bufferView[i] = decodedString.charCodeAt(i);
+ }
+ return bufferView.buffer;
+};
+
+/* eslint-disable @typescript-eslint/naming-convention */
+const Base64DataUrlRegEx = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);
+/** @ignore */
+class LoadFileError extends RuntimeError {
+ /**
+ * Creates a new LoadFileError
+ * @param message defines the message of the error
+ * @param object defines the optional web request
+ */
+ constructor(message, object) {
+ super(message, ErrorCodes.LoadFileError);
+ this.name = "LoadFileError";
+ BaseError._setPrototypeOf(this, LoadFileError.prototype);
+ if (object instanceof WebRequest) {
+ this.request = object;
+ }
+ else {
+ this.file = object;
+ }
+ }
+}
+/** @ignore */
+class RequestFileError extends RuntimeError {
+ /**
+ * Creates a new LoadFileError
+ * @param message defines the message of the error
+ * @param request defines the optional web request
+ */
+ constructor(message, request) {
+ super(message, ErrorCodes.RequestFileError);
+ this.request = request;
+ this.name = "RequestFileError";
+ BaseError._setPrototypeOf(this, RequestFileError.prototype);
+ }
+}
+/** @ignore */
+class ReadFileError extends RuntimeError {
+ /**
+ * Creates a new ReadFileError
+ * @param message defines the message of the error
+ * @param file defines the optional file
+ */
+ constructor(message, file) {
+ super(message, ErrorCodes.ReadFileError);
+ this.file = file;
+ this.name = "ReadFileError";
+ BaseError._setPrototypeOf(this, ReadFileError.prototype);
+ }
+}
+/**
+ * Removes unwanted characters from an url
+ * @param url defines the url to clean
+ * @returns the cleaned url
+ */
+const CleanUrl = (url) => {
+ url = url.replace(/#/gm, "%23");
+ return url;
+};
+/**
+ * @internal
+ */
+const FileToolsOptions = {
+ /**
+ * Gets or sets the retry strategy to apply when an error happens while loading an asset.
+ * When defining this function, return the wait time before trying again or return -1 to
+ * stop retrying and error out.
+ */
+ DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(),
+ /**
+ * Gets or sets the base URL to use to load assets
+ */
+ BaseUrl: "",
+ /**
+ * Default behaviour for cors in the application.
+ * It can be a string if the expected behavior is identical in the entire app.
+ * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
+ */
+ CorsBehavior: "anonymous",
+ /**
+ * Gets or sets a function used to pre-process url before using them to load assets
+ * @param url
+ * @returns the processed url
+ */
+ PreprocessUrl: (url) => url,
+ /**
+ * Gets or sets the base URL to use to load scripts
+ * Used for both JS and WASM
+ */
+ ScriptBaseUrl: "",
+ /**
+ * Gets or sets a function used to pre-process script url before using them to load.
+ * Used for both JS and WASM
+ * @param url defines the url to process
+ * @returns the processed url
+ */
+ ScriptPreprocessUrl: (url) => url,
+ /**
+ * Gets or sets a function used to clean the url before using it to load assets
+ * @param url defines the url to clean
+ * @returns the cleaned url
+ */
+ CleanUrl,
+};
+/**
+ * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
+ * @param url define the url we are trying
+ * @param element define the dom element where to configure the cors policy
+ * @internal
+ */
+const SetCorsBehavior = (url, element) => {
+ if (url && url.indexOf("data:") === 0) {
+ return;
+ }
+ if (FileToolsOptions.CorsBehavior) {
+ if (typeof FileToolsOptions.CorsBehavior === "string" || FileToolsOptions.CorsBehavior instanceof String) {
+ element.crossOrigin = FileToolsOptions.CorsBehavior;
+ }
+ else {
+ const result = FileToolsOptions.CorsBehavior(url);
+ if (result) {
+ element.crossOrigin = result;
+ }
+ }
+ }
+};
+/**
+ * Loads an image as an HTMLImageElement.
+ * @param input url string, ArrayBuffer, or Blob to load
+ * @param onLoad callback called when the image successfully loads
+ * @param onError callback called when the image fails to load
+ * @param offlineProvider offline provider for caching
+ * @param mimeType optional mime type
+ * @param imageBitmapOptions
+ * @param engine the engine instance to use
+ * @returns the HTMLImageElement of the loaded image
+ * @internal
+ */
+const LoadImage = (input, onLoad, onError, offlineProvider, mimeType = "", imageBitmapOptions, engine = EngineStore.LastCreatedEngine) => {
+ if (typeof HTMLImageElement === "undefined" && !engine?._features.forceBitmapOverHTMLImageElement) {
+ onError("LoadImage is only supported in web or BabylonNative environments.");
+ return null;
+ }
+ let url;
+ let usingObjectURL = false;
+ if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {
+ if (typeof Blob !== "undefined" && typeof URL !== "undefined") {
+ url = URL.createObjectURL(new Blob([input], { type: mimeType }));
+ usingObjectURL = true;
+ }
+ else {
+ url = `data:${mimeType};base64,` + EncodeArrayBufferToBase64(input);
+ }
+ }
+ else if (input instanceof Blob) {
+ url = URL.createObjectURL(input);
+ usingObjectURL = true;
+ }
+ else {
+ url = FileToolsOptions.CleanUrl(input);
+ url = FileToolsOptions.PreprocessUrl(url);
+ }
+ const onErrorHandler = (exception) => {
+ if (onError) {
+ const inputText = url || input.toString();
+ onError(`Error while trying to load image: ${inputText.indexOf("http") === 0 || inputText.length <= 128 ? inputText : inputText.slice(0, 128) + "..."}`, exception);
+ }
+ };
+ if (engine?._features.forceBitmapOverHTMLImageElement) {
+ LoadFile(url, (data) => {
+ engine
+ .createImageBitmap(new Blob([data], { type: mimeType }), { premultiplyAlpha: "none", ...imageBitmapOptions })
+ .then((imgBmp) => {
+ onLoad(imgBmp);
+ if (usingObjectURL) {
+ URL.revokeObjectURL(url);
+ }
+ })
+ .catch((reason) => {
+ if (onError) {
+ onError("Error while trying to load image: " + input, reason);
+ }
+ });
+ }, undefined, offlineProvider || undefined, true, (request, exception) => {
+ onErrorHandler(exception);
+ });
+ return null;
+ }
+ const img = new Image();
+ SetCorsBehavior(url, img);
+ const handlersList = [];
+ const loadHandlersList = () => {
+ handlersList.forEach((handler) => {
+ handler.target.addEventListener(handler.name, handler.handler);
+ });
+ };
+ const unloadHandlersList = () => {
+ handlersList.forEach((handler) => {
+ handler.target.removeEventListener(handler.name, handler.handler);
+ });
+ handlersList.length = 0;
+ };
+ const loadHandler = () => {
+ unloadHandlersList();
+ onLoad(img);
+ // Must revoke the URL after calling onLoad to avoid security exceptions in
+ // certain scenarios (e.g. when hosted in vscode).
+ if (usingObjectURL && img.src) {
+ URL.revokeObjectURL(img.src);
+ }
+ };
+ const errorHandler = (err) => {
+ unloadHandlersList();
+ onErrorHandler(err);
+ if (usingObjectURL && img.src) {
+ URL.revokeObjectURL(img.src);
+ }
+ };
+ const cspHandler = (err) => {
+ if (err.blockedURI !== img.src || err.disposition === "report") {
+ return;
+ }
+ unloadHandlersList();
+ const cspException = new Error(`CSP violation of policy ${err.effectiveDirective} ${err.blockedURI}. Current policy is ${err.originalPolicy}`);
+ EngineStore.UseFallbackTexture = false;
+ onErrorHandler(cspException);
+ if (usingObjectURL && img.src) {
+ URL.revokeObjectURL(img.src);
+ }
+ img.src = "";
+ };
+ handlersList.push({ target: img, name: "load", handler: loadHandler });
+ handlersList.push({ target: img, name: "error", handler: errorHandler });
+ handlersList.push({ target: document, name: "securitypolicyviolation", handler: cspHandler });
+ loadHandlersList();
+ const fromBlob = url.substring(0, 5) === "blob:";
+ const fromData = url.substring(0, 5) === "data:";
+ const noOfflineSupport = () => {
+ if (fromBlob || fromData || !WebRequest.IsCustomRequestAvailable) {
+ img.src = url;
+ }
+ else {
+ LoadFile(url, (data, _, contentType) => {
+ const type = !mimeType && contentType ? contentType : mimeType;
+ const blob = new Blob([data], { type });
+ const url = URL.createObjectURL(blob);
+ usingObjectURL = true;
+ img.src = url;
+ }, undefined, offlineProvider || undefined, true, (_request, exception) => {
+ onErrorHandler(exception);
+ });
+ }
+ };
+ const loadFromOfflineSupport = () => {
+ if (offlineProvider) {
+ offlineProvider.loadImage(url, img);
+ }
+ };
+ if (!fromBlob && !fromData && offlineProvider && offlineProvider.enableTexturesOffline) {
+ offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
+ }
+ else {
+ if (url.indexOf("file:") !== -1) {
+ const textureName = decodeURIComponent(url.substring(5).toLowerCase());
+ if (FilesInputStore.FilesToLoad[textureName] && typeof URL !== "undefined") {
+ try {
+ let blobURL;
+ try {
+ blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);
+ }
+ catch (ex) {
+ // Chrome doesn't support oneTimeOnly parameter
+ blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);
+ }
+ img.src = blobURL;
+ usingObjectURL = true;
+ }
+ catch (e) {
+ img.src = "";
+ }
+ return img;
+ }
+ }
+ noOfflineSupport();
+ }
+ return img;
+};
+/**
+ * Reads a file from a File object
+ * @param file defines the file to load
+ * @param onSuccess defines the callback to call when data is loaded
+ * @param onProgress defines the callback to call during loading process
+ * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
+ * @param onError defines the callback to call when an error occurs
+ * @returns a file request object
+ * @internal
+ */
+const ReadFile = (file, onSuccess, onProgress, useArrayBuffer, onError) => {
+ const reader = new FileReader();
+ const fileRequest = {
+ onCompleteObservable: new Observable(),
+ abort: () => reader.abort(),
+ };
+ reader.onloadend = () => fileRequest.onCompleteObservable.notifyObservers(fileRequest);
+ if (onError) {
+ reader.onerror = () => {
+ onError(new ReadFileError(`Unable to read ${file.name}`, file));
+ };
+ }
+ reader.onload = (e) => {
+ //target doesn't have result from ts 1.3
+ onSuccess(e.target["result"]);
+ };
+ if (onProgress) {
+ reader.onprogress = onProgress;
+ }
+ if (!useArrayBuffer) {
+ // Asynchronous read
+ reader.readAsText(file);
+ }
+ else {
+ reader.readAsArrayBuffer(file);
+ }
+ return fileRequest;
+};
+/**
+ * Loads a file from a url, a data url, or a file url
+ * @param fileOrUrl file, url, data url, or file url to load
+ * @param onSuccess callback called when the file successfully loads
+ * @param onProgress callback called while file is loading (if the server supports this mode)
+ * @param offlineProvider defines the offline provider for caching
+ * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
+ * @param onError callback called when the file fails to load
+ * @param onOpened
+ * @returns a file request object
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const LoadFile = (fileOrUrl, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => {
+ if (fileOrUrl.name) {
+ return ReadFile(fileOrUrl, onSuccess, onProgress, useArrayBuffer, onError
+ ? (error) => {
+ onError(undefined, error);
+ }
+ : undefined);
+ }
+ const url = fileOrUrl;
+ // If file and file input are set
+ if (url.indexOf("file:") !== -1) {
+ let fileName = decodeURIComponent(url.substring(5).toLowerCase());
+ if (fileName.indexOf("./") === 0) {
+ fileName = fileName.substring(2);
+ }
+ const file = FilesInputStore.FilesToLoad[fileName];
+ if (file) {
+ return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError ? (error) => onError(undefined, new LoadFileError(error.message, error.file)) : undefined);
+ }
+ }
+ // For a Base64 Data URL
+ const { match, type } = TestBase64DataUrl(url);
+ if (match) {
+ const fileRequest = {
+ onCompleteObservable: new Observable(),
+ abort: () => () => { },
+ };
+ try {
+ const data = useArrayBuffer ? DecodeBase64UrlToBinary(url) : DecodeBase64UrlToString(url);
+ onSuccess(data, undefined, type);
+ }
+ catch (error) {
+ if (onError) {
+ onError(undefined, error);
+ }
+ else {
+ Logger.Error(error.message || "Failed to parse the Data URL");
+ }
+ }
+ TimingTools.SetImmediate(() => {
+ fileRequest.onCompleteObservable.notifyObservers(fileRequest);
+ });
+ return fileRequest;
+ }
+ return RequestFile(url, (data, request) => {
+ onSuccess(data, request?.responseURL, request?.getResponseHeader("content-type"));
+ }, onProgress, offlineProvider, useArrayBuffer, onError
+ ? (error) => {
+ onError(error.request, new LoadFileError(error.message, error.request));
+ }
+ : undefined, onOpened);
+};
+/**
+ * Loads a file from a url
+ * @param url url to load
+ * @param onSuccess callback called when the file successfully loads
+ * @param onProgress callback called while file is loading (if the server supports this mode)
+ * @param offlineProvider defines the offline provider for caching
+ * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
+ * @param onError callback called when the file fails to load
+ * @param onOpened callback called when the web request is opened
+ * @returns a file request object
+ * @internal
+ */
+const RequestFile = (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => {
+ url = FileToolsOptions.CleanUrl(url);
+ url = FileToolsOptions.PreprocessUrl(url);
+ const loadUrl = FileToolsOptions.BaseUrl + url;
+ let aborted = false;
+ const fileRequest = {
+ onCompleteObservable: new Observable(),
+ abort: () => (aborted = true),
+ };
+ const requestFile = () => {
+ let request = new WebRequest();
+ let retryHandle = null;
+ let onReadyStateChange;
+ const unbindEvents = () => {
+ if (!request) {
+ return;
+ }
+ if (onProgress) {
+ request.removeEventListener("progress", onProgress);
+ }
+ if (onReadyStateChange) {
+ request.removeEventListener("readystatechange", onReadyStateChange);
+ }
+ request.removeEventListener("loadend", onLoadEnd);
+ };
+ let onLoadEnd = () => {
+ unbindEvents();
+ fileRequest.onCompleteObservable.notifyObservers(fileRequest);
+ fileRequest.onCompleteObservable.clear();
+ onProgress = undefined;
+ onReadyStateChange = null;
+ onLoadEnd = null;
+ onError = undefined;
+ onOpened = undefined;
+ onSuccess = undefined;
+ };
+ fileRequest.abort = () => {
+ aborted = true;
+ if (onLoadEnd) {
+ onLoadEnd();
+ }
+ if (request && request.readyState !== (XMLHttpRequest.DONE || 4)) {
+ request.abort();
+ }
+ if (retryHandle !== null) {
+ clearTimeout(retryHandle);
+ retryHandle = null;
+ }
+ request = null;
+ };
+ const handleError = (error) => {
+ const message = error.message || "Unknown error";
+ if (onError && request) {
+ onError(new RequestFileError(message, request));
+ }
+ else {
+ Logger.Error(message);
+ }
+ };
+ const retryLoop = (retryIndex) => {
+ if (!request) {
+ return;
+ }
+ request.open("GET", loadUrl);
+ if (onOpened) {
+ try {
+ onOpened(request);
+ }
+ catch (e) {
+ handleError(e);
+ return;
+ }
+ }
+ if (useArrayBuffer) {
+ request.responseType = "arraybuffer";
+ }
+ if (onProgress) {
+ request.addEventListener("progress", onProgress);
+ }
+ if (onLoadEnd) {
+ request.addEventListener("loadend", onLoadEnd);
+ }
+ onReadyStateChange = () => {
+ if (aborted || !request) {
+ return;
+ }
+ // In case of undefined state in some browsers.
+ if (request.readyState === (XMLHttpRequest.DONE || 4)) {
+ // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
+ if (onReadyStateChange) {
+ request.removeEventListener("readystatechange", onReadyStateChange);
+ }
+ if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!IsWindowObjectExist() || IsFileURL()))) {
+ // It's possible for the request to have a success status code but null response if the underlying
+ // underlying HTTP connection was closed prematurely. See _onHttpResponseClose in xhr2.js. In this
+ // case we will throw an exception if we call the onSuccess handler because "data" will be null
+ // and that then bypasses the retry strategy.
+ const data = useArrayBuffer ? request.response : request.responseText;
+ if (data !== null) {
+ try {
+ if (onSuccess) {
+ onSuccess(data, request);
+ }
+ }
+ catch (e) {
+ handleError(e);
+ }
+ return;
+ }
+ }
+ const retryStrategy = FileToolsOptions.DefaultRetryStrategy;
+ if (retryStrategy) {
+ const waitTime = retryStrategy(loadUrl, request, retryIndex);
+ if (waitTime !== -1) {
+ // Prevent the request from completing for retry.
+ unbindEvents();
+ request = new WebRequest();
+ retryHandle = setTimeout(() => retryLoop(retryIndex + 1), waitTime);
+ return;
+ }
+ }
+ const error = new RequestFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
+ if (onError) {
+ onError(error);
+ }
+ }
+ };
+ request.addEventListener("readystatechange", onReadyStateChange);
+ request.send();
+ };
+ retryLoop(0);
+ };
+ // Caching all files
+ if (offlineProvider && offlineProvider.enableSceneOffline) {
+ const noOfflineSupport = (request) => {
+ if (request && request.status > 400) {
+ if (onError) {
+ onError(request);
+ }
+ }
+ else {
+ requestFile();
+ }
+ };
+ const loadFromOfflineSupport = () => {
+ // TODO: database needs to support aborting and should return a IFileRequest
+ if (offlineProvider) {
+ offlineProvider.loadFile(FileToolsOptions.BaseUrl + url, (data) => {
+ if (!aborted && onSuccess) {
+ onSuccess(data);
+ }
+ fileRequest.onCompleteObservable.notifyObservers(fileRequest);
+ }, onProgress
+ ? (event) => {
+ if (!aborted && onProgress) {
+ onProgress(event);
+ }
+ }
+ : undefined, noOfflineSupport, useArrayBuffer);
+ }
+ };
+ offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
+ }
+ else {
+ requestFile();
+ }
+ return fileRequest;
+};
+/**
+ * Checks if the loaded document was accessed via `file:`-Protocol.
+ * @returns boolean
+ * @internal
+ */
+const IsFileURL = () => {
+ return typeof location !== "undefined" && location.protocol === "file:";
+};
+/**
+ * Test if the given uri is a valid base64 data url
+ * @param uri The uri to test
+ * @returns True if the uri is a base64 data url or false otherwise
+ * @internal
+ */
+const IsBase64DataUrl = (uri) => {
+ return Base64DataUrlRegEx.test(uri);
+};
+const TestBase64DataUrl = (uri) => {
+ const results = Base64DataUrlRegEx.exec(uri);
+ if (results === null || results.length === 0) {
+ return { match: false, type: "" };
+ }
+ else {
+ const type = results[0].replace("data:", "").replace("base64,", "");
+ return { match: true, type };
+ }
+};
+/**
+ * Decode the given base64 uri.
+ * @param uri The uri to decode
+ * @returns The decoded base64 data.
+ * @internal
+ */
+function DecodeBase64UrlToBinary(uri) {
+ return DecodeBase64ToBinary(uri.split(",")[1]);
+}
+/**
+ * Decode the given base64 uri into a UTF-8 encoded string.
+ * @param uri The uri to decode
+ * @returns The decoded base64 data.
+ * @internal
+ */
+const DecodeBase64UrlToString = (uri) => {
+ return DecodeBase64ToString(uri.split(",")[1]);
+};
+/**
+ * This will be executed automatically for UMD and es5.
+ * If esm dev wants the side effects to execute they will have to run it manually
+ * Once we build native modules those need to be exported.
+ * @internal
+ */
+const initSideEffects$2 = () => {
+ AbstractEngine._FileToolsLoadImage = LoadImage;
+ EngineFunctionContext.loadFile = LoadFile;
+ _functionContainer.loadFile = LoadFile;
+};
+initSideEffects$2();
+// deprecated
+/**
+ * FileTools defined as any.
+ * This should not be imported or used in future releases or in any module in the framework
+ * @internal
+ * @deprecated import the needed function from fileTools.ts
+ */
+let FileTools;
+/**
+ * @internal
+ */
+const _injectLTSFileTools = (DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior) => {
+ /**
+ * Backwards compatibility.
+ * @internal
+ * @deprecated
+ */
+ FileTools = {
+ DecodeBase64UrlToBinary,
+ DecodeBase64UrlToString,
+ DefaultRetryStrategy: FileToolsOptions.DefaultRetryStrategy,
+ BaseUrl: FileToolsOptions.BaseUrl,
+ CorsBehavior: FileToolsOptions.CorsBehavior,
+ PreprocessUrl: FileToolsOptions.PreprocessUrl,
+ IsBase64DataUrl,
+ IsFileURL,
+ LoadFile,
+ LoadImage,
+ ReadFile,
+ RequestFile,
+ SetCorsBehavior,
+ };
+ Object.defineProperty(FileTools, "DefaultRetryStrategy", {
+ get: function () {
+ return FileToolsOptions.DefaultRetryStrategy;
+ },
+ set: function (value) {
+ FileToolsOptions.DefaultRetryStrategy = value;
+ },
+ });
+ Object.defineProperty(FileTools, "BaseUrl", {
+ get: function () {
+ return FileToolsOptions.BaseUrl;
+ },
+ set: function (value) {
+ FileToolsOptions.BaseUrl = value;
+ },
+ });
+ Object.defineProperty(FileTools, "PreprocessUrl", {
+ get: function () {
+ return FileToolsOptions.PreprocessUrl;
+ },
+ set: function (value) {
+ FileToolsOptions.PreprocessUrl = value;
+ },
+ });
+ Object.defineProperty(FileTools, "CorsBehavior", {
+ get: function () {
+ return FileToolsOptions.CorsBehavior;
+ },
+ set: function (value) {
+ FileToolsOptions.CorsBehavior = value;
+ },
+ });
+};
+_injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior);
+
+/**
+ * Base class of all the textures in babylon.
+ * It groups all the common properties required to work with Thin Engine.
+ */
+class ThinTexture {
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ get wrapU() {
+ return this._wrapU;
+ }
+ set wrapU(value) {
+ this._wrapU = value;
+ }
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ get wrapV() {
+ return this._wrapV;
+ }
+ set wrapV(value) {
+ this._wrapV = value;
+ }
+ /**
+ * How a texture is mapped.
+ * Unused in thin texture mode.
+ */
+ get coordinatesMode() {
+ return 0;
+ }
+ /**
+ * Define if the texture is a cube texture or if false a 2d texture.
+ */
+ get isCube() {
+ if (!this._texture) {
+ return false;
+ }
+ return this._texture.isCube;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ set isCube(value) {
+ if (!this._texture) {
+ return;
+ }
+ this._texture.isCube = value;
+ }
+ /**
+ * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
+ */
+ get is3D() {
+ if (!this._texture) {
+ return false;
+ }
+ return this._texture.is3D;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ set is3D(value) {
+ if (!this._texture) {
+ return;
+ }
+ this._texture.is3D = value;
+ }
+ /**
+ * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture.
+ */
+ get is2DArray() {
+ if (!this._texture) {
+ return false;
+ }
+ return this._texture.is2DArray;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ set is2DArray(value) {
+ if (!this._texture) {
+ return;
+ }
+ this._texture.is2DArray = value;
+ }
+ /**
+ * Get the class name of the texture.
+ * @returns "ThinTexture"
+ */
+ getClassName() {
+ return "ThinTexture";
+ }
+ static _IsRenderTargetWrapper(texture) {
+ return texture?.shareDepth !== undefined;
+ }
+ /**
+ * Instantiates a new ThinTexture.
+ * Base class of all the textures in babylon.
+ * This can be used as an internal texture wrapper in AbstractEngine to benefit from the cache
+ * @param internalTexture Define the internalTexture to wrap. You can also pass a RenderTargetWrapper, in which case the texture will be the render target's texture
+ */
+ constructor(internalTexture) {
+ this._wrapU = 1;
+ this._wrapV = 1;
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ this.wrapR = 1;
+ /**
+ * With compliant hardware and browser (supporting anisotropic filtering)
+ * this defines the level of anisotropic filtering in the texture.
+ * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
+ */
+ this.anisotropicFilteringLevel = 4;
+ /**
+ * Define the current state of the loading sequence when in delayed load mode.
+ */
+ this.delayLoadState = 0;
+ /** @internal */
+ this._texture = null;
+ this._engine = null;
+ this._cachedSize = Size.Zero();
+ this._cachedBaseSize = Size.Zero();
+ /** @internal */
+ this._initialSamplingMode = 2;
+ this._texture = ThinTexture._IsRenderTargetWrapper(internalTexture) ? internalTexture.texture : internalTexture;
+ if (this._texture) {
+ this._engine = this._texture.getEngine();
+ }
+ }
+ /**
+ * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
+ * @returns true if fully ready
+ */
+ isReady() {
+ if (this.delayLoadState === 4) {
+ this.delayLoad();
+ return false;
+ }
+ if (this._texture) {
+ return this._texture.isReady;
+ }
+ return false;
+ }
+ /**
+ * Triggers the load sequence in delayed load mode.
+ */
+ delayLoad() { }
+ /**
+ * Get the underlying lower level texture from Babylon.
+ * @returns the internal texture
+ */
+ getInternalTexture() {
+ return this._texture;
+ }
+ /**
+ * Get the size of the texture.
+ * @returns the texture size.
+ */
+ getSize() {
+ if (this._texture) {
+ if (this._texture.width) {
+ this._cachedSize.width = this._texture.width;
+ this._cachedSize.height = this._texture.height;
+ return this._cachedSize;
+ }
+ if (this._texture._size) {
+ this._cachedSize.width = this._texture._size;
+ this._cachedSize.height = this._texture._size;
+ return this._cachedSize;
+ }
+ }
+ return this._cachedSize;
+ }
+ /**
+ * Get the base size of the texture.
+ * It can be different from the size if the texture has been resized for POT for instance
+ * @returns the base size
+ */
+ getBaseSize() {
+ if (!this.isReady() || !this._texture) {
+ this._cachedBaseSize.width = 0;
+ this._cachedBaseSize.height = 0;
+ return this._cachedBaseSize;
+ }
+ if (this._texture._size) {
+ this._cachedBaseSize.width = this._texture._size;
+ this._cachedBaseSize.height = this._texture._size;
+ return this._cachedBaseSize;
+ }
+ this._cachedBaseSize.width = this._texture.baseWidth;
+ this._cachedBaseSize.height = this._texture.baseHeight;
+ return this._cachedBaseSize;
+ }
+ /**
+ * Get the current sampling mode associated with the texture.
+ */
+ get samplingMode() {
+ if (!this._texture) {
+ return this._initialSamplingMode;
+ }
+ return this._texture.samplingMode;
+ }
+ /**
+ * Update the sampling mode of the texture.
+ * Default is Trilinear mode.
+ *
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
+ * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
+ * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
+ * | 4 | NEAREST_NEAREST_MIPNEAREST | |
+ * | 5 | NEAREST_LINEAR_MIPNEAREST | |
+ * | 6 | NEAREST_LINEAR_MIPLINEAR | |
+ * | 7 | NEAREST_LINEAR | |
+ * | 8 | NEAREST_NEAREST | |
+ * | 9 | LINEAR_NEAREST_MIPNEAREST | |
+ * | 10 | LINEAR_NEAREST_MIPLINEAR | |
+ * | 11 | LINEAR_LINEAR | |
+ * | 12 | LINEAR_NEAREST | |
+ *
+ * > _mag_: magnification filter (close to the viewer)
+ * > _min_: minification filter (far from the viewer)
+ * > _mip_: filter used between mip map levels
+ *@param samplingMode Define the new sampling mode of the texture
+ */
+ updateSamplingMode(samplingMode) {
+ if (this._texture && this._engine) {
+ this._engine.updateTextureSamplingMode(samplingMode, this._texture);
+ }
+ }
+ /**
+ * Release and destroy the underlying lower level texture aka internalTexture.
+ */
+ releaseInternalTexture() {
+ if (this._texture) {
+ this._texture.dispose();
+ this._texture = null;
+ }
+ }
+ /**
+ * Dispose the texture and release its associated resources.
+ */
+ dispose() {
+ if (this._texture) {
+ this.releaseInternalTexture();
+ this._engine = null;
+ }
+ }
+}
+
+/**
+ * Class used to evaluate queries containing `and` and `or` operators
+ */
+class AndOrNotEvaluator {
+ /**
+ * Evaluate a query
+ * @param query defines the query to evaluate
+ * @param evaluateCallback defines the callback used to filter result
+ * @returns true if the query matches
+ */
+ static Eval(query, evaluateCallback) {
+ if (!query.match(/\([^()]*\)/g)) {
+ query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
+ }
+ else {
+ query = query.replace(/\([^()]*\)/g, (r) => {
+ // remove parenthesis
+ r = r.slice(1, r.length - 1);
+ return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
+ });
+ }
+ if (query === "true") {
+ return true;
+ }
+ if (query === "false") {
+ return false;
+ }
+ return AndOrNotEvaluator.Eval(query, evaluateCallback);
+ }
+ static _HandleParenthesisContent(parenthesisContent, evaluateCallback) {
+ evaluateCallback =
+ evaluateCallback ||
+ ((r) => {
+ return r === "true" ? true : false;
+ });
+ let result;
+ const or = parenthesisContent.split("||");
+ for (const i in or) {
+ if (Object.prototype.hasOwnProperty.call(or, i)) {
+ let ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
+ const and = ori.split("&&");
+ if (and.length > 1) {
+ for (let j = 0; j < and.length; ++j) {
+ const andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
+ if (andj !== "true" && andj !== "false") {
+ if (andj[0] === "!") {
+ result = !evaluateCallback(andj.substring(1));
+ }
+ else {
+ result = evaluateCallback(andj);
+ }
+ }
+ else {
+ result = andj === "true" ? true : false;
+ }
+ if (!result) {
+ // no need to continue since 'false && ... && ...' will always return false
+ ori = "false";
+ break;
+ }
+ }
+ }
+ if (result || ori === "true") {
+ // no need to continue since 'true || ... || ...' will always return true
+ result = true;
+ break;
+ }
+ // result equals false (or undefined)
+ if (ori !== "true" && ori !== "false") {
+ if (ori[0] === "!") {
+ result = !evaluateCallback(ori.substring(1));
+ }
+ else {
+ result = evaluateCallback(ori);
+ }
+ }
+ else {
+ result = ori === "true" ? true : false;
+ }
+ }
+ }
+ // the whole parenthesis scope is replaced by 'true' or 'false'
+ return result ? "true" : "false";
+ }
+ static _SimplifyNegation(booleanString) {
+ booleanString = booleanString.replace(/^[\s!]+/, (r) => {
+ // remove whitespaces
+ r = r.replace(/[\s]/g, () => "");
+ return r.length % 2 ? "!" : "";
+ });
+ booleanString = booleanString.trim();
+ if (booleanString === "!true") {
+ booleanString = "false";
+ }
+ else if (booleanString === "!false") {
+ booleanString = "true";
+ }
+ return booleanString;
+ }
+}
+
+/**
+ * Class used to store custom tags
+ */
+class Tags {
+ /**
+ * Adds support for tags on the given object
+ * @param obj defines the object to use
+ */
+ static EnableFor(obj) {
+ obj._tags = obj._tags || {};
+ obj.hasTags = () => {
+ return Tags.HasTags(obj);
+ };
+ obj.addTags = (tagsString) => {
+ return Tags.AddTagsTo(obj, tagsString);
+ };
+ obj.removeTags = (tagsString) => {
+ return Tags.RemoveTagsFrom(obj, tagsString);
+ };
+ obj.matchesTagsQuery = (tagsQuery) => {
+ return Tags.MatchesQuery(obj, tagsQuery);
+ };
+ }
+ /**
+ * Removes tags support
+ * @param obj defines the object to use
+ */
+ static DisableFor(obj) {
+ delete obj._tags;
+ delete obj.hasTags;
+ delete obj.addTags;
+ delete obj.removeTags;
+ delete obj.matchesTagsQuery;
+ }
+ /**
+ * Gets a boolean indicating if the given object has tags
+ * @param obj defines the object to use
+ * @returns a boolean
+ */
+ static HasTags(obj) {
+ if (!obj._tags) {
+ return false;
+ }
+ const tags = obj._tags;
+ for (const i in tags) {
+ if (Object.prototype.hasOwnProperty.call(tags, i)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * Gets the tags available on a given object
+ * @param obj defines the object to use
+ * @param asString defines if the tags must be returned as a string instead of an array of strings
+ * @returns the tags
+ */
+ static GetTags(obj, asString = true) {
+ if (!obj._tags) {
+ return null;
+ }
+ if (asString) {
+ const tagsArray = [];
+ for (const tag in obj._tags) {
+ if (Object.prototype.hasOwnProperty.call(obj._tags, tag) && obj._tags[tag] === true) {
+ tagsArray.push(tag);
+ }
+ }
+ return tagsArray.join(" ");
+ }
+ else {
+ return obj._tags;
+ }
+ }
+ /**
+ * Adds tags to an object
+ * @param obj defines the object to use
+ * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
+ * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
+ */
+ static AddTagsTo(obj, tagsString) {
+ if (!tagsString) {
+ return;
+ }
+ if (typeof tagsString !== "string") {
+ return;
+ }
+ const tags = tagsString.split(" ");
+ tags.forEach(function (tag) {
+ Tags._AddTagTo(obj, tag);
+ });
+ }
+ /**
+ * @internal
+ */
+ static _AddTagTo(obj, tag) {
+ tag = tag.trim();
+ if (tag === "" || tag === "true" || tag === "false") {
+ return;
+ }
+ if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
+ return;
+ }
+ Tags.EnableFor(obj);
+ obj._tags[tag] = true;
+ }
+ /**
+ * Removes specific tags from a specific object
+ * @param obj defines the object to use
+ * @param tagsString defines the tags to remove
+ */
+ static RemoveTagsFrom(obj, tagsString) {
+ if (!Tags.HasTags(obj)) {
+ return;
+ }
+ const tags = tagsString.split(" ");
+ for (const t in tags) {
+ Tags._RemoveTagFrom(obj, tags[t]);
+ }
+ }
+ /**
+ * @internal
+ */
+ static _RemoveTagFrom(obj, tag) {
+ delete obj._tags[tag];
+ }
+ /**
+ * Defines if tags hosted on an object match a given query
+ * @param obj defines the object to use
+ * @param tagsQuery defines the tag query
+ * @returns a boolean
+ */
+ static MatchesQuery(obj, tagsQuery) {
+ if (tagsQuery === undefined) {
+ return true;
+ }
+ if (tagsQuery === "") {
+ return Tags.HasTags(obj);
+ }
+ return AndOrNotEvaluator.Eval(tagsQuery, (r) => Tags.HasTags(obj) && obj._tags[r]);
+ }
+}
+
+const _copySource = function (creationFunction, source, instanciate, options = {}) {
+ const destination = creationFunction();
+ // Tags
+ if (Tags && Tags.HasTags(source)) {
+ Tags.AddTagsTo(destination, Tags.GetTags(source, true));
+ }
+ const classStore = GetMergedStore(destination);
+ // Map from source texture uniqueId to destination texture
+ const textureMap = {};
+ // Properties
+ for (const property in classStore) {
+ const propertyDescriptor = classStore[property];
+ const sourceProperty = source[property];
+ const propertyType = propertyDescriptor.type;
+ if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId)) {
+ switch (propertyType) {
+ case 0: // Value
+ case 6: // Mesh reference
+ case 9: // Image processing configuration reference
+ case 11: // Camera reference
+ destination[property] = sourceProperty;
+ break;
+ case 1: // Texture
+ if (options.cloneTexturesOnlyOnce && textureMap[sourceProperty.uniqueId]) {
+ destination[property] = textureMap[sourceProperty.uniqueId];
+ }
+ else {
+ destination[property] = instanciate || sourceProperty.isRenderTarget ? sourceProperty : sourceProperty.clone();
+ textureMap[sourceProperty.uniqueId] = destination[property];
+ }
+ break;
+ case 2: // Color3
+ case 3: // FresnelParameters
+ case 4: // Vector2
+ case 5: // Vector3
+ case 7: // Color Curves
+ case 8: // Color 4
+ case 10: // Quaternion
+ case 12: // Matrix
+ destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
+ break;
+ }
+ }
+ }
+ return destination;
+};
+/**
+ * Class used to help serialization objects
+ */
+class SerializationHelper {
+ /**
+ * Appends the serialized animations from the source animations
+ * @param source Source containing the animations
+ * @param destination Target to store the animations
+ */
+ static AppendSerializedAnimations(source, destination) {
+ if (source.animations) {
+ destination.animations = [];
+ for (let animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
+ const animation = source.animations[animationIndex];
+ destination.animations.push(animation.serialize());
+ }
+ }
+ }
+ /**
+ * Static function used to serialized a specific entity
+ * @param entity defines the entity to serialize
+ * @param serializationObject defines the optional target object where serialization data will be stored
+ * @returns a JSON compatible object representing the serialization of the entity
+ */
+ static Serialize(entity, serializationObject) {
+ if (!serializationObject) {
+ serializationObject = {};
+ }
+ // Tags
+ if (Tags) {
+ serializationObject.tags = Tags.GetTags(entity);
+ }
+ const serializedProperties = GetMergedStore(entity);
+ // Properties
+ for (const property in serializedProperties) {
+ const propertyDescriptor = serializedProperties[property];
+ const targetPropertyName = propertyDescriptor.sourceName || property;
+ const propertyType = propertyDescriptor.type;
+ const sourceProperty = entity[property];
+ if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId)) {
+ switch (propertyType) {
+ case 0: // Value
+ serializationObject[targetPropertyName] = sourceProperty;
+ break;
+ case 1: // Texture
+ serializationObject[targetPropertyName] = sourceProperty.serialize();
+ break;
+ case 2: // Color3
+ serializationObject[targetPropertyName] = sourceProperty.asArray();
+ break;
+ case 3: // FresnelParameters
+ serializationObject[targetPropertyName] = sourceProperty.serialize();
+ break;
+ case 4: // Vector2
+ serializationObject[targetPropertyName] = sourceProperty.asArray();
+ break;
+ case 5: // Vector3
+ serializationObject[targetPropertyName] = sourceProperty.asArray();
+ break;
+ case 6: // Mesh reference
+ serializationObject[targetPropertyName] = sourceProperty.id;
+ break;
+ case 7: // Color Curves
+ serializationObject[targetPropertyName] = sourceProperty.serialize();
+ break;
+ case 8: // Color 4
+ serializationObject[targetPropertyName] = sourceProperty.asArray();
+ break;
+ case 9: // Image Processing
+ serializationObject[targetPropertyName] = sourceProperty.serialize();
+ break;
+ case 10: // Quaternion
+ serializationObject[targetPropertyName] = sourceProperty.asArray();
+ break;
+ case 11: // Camera reference
+ serializationObject[targetPropertyName] = sourceProperty.id;
+ break;
+ case 12: // Matrix
+ serializationObject[targetPropertyName] = sourceProperty.asArray();
+ break;
+ }
+ }
+ }
+ return serializationObject;
+ }
+ /**
+ * Given a source json and a destination object in a scene, this function will parse the source and will try to apply its content to the destination object
+ * @param source the source json data
+ * @param destination the destination object
+ * @param scene the scene where the object is
+ * @param rootUrl root url to use to load assets
+ */
+ static ParseProperties(source, destination, scene, rootUrl) {
+ if (!rootUrl) {
+ rootUrl = "";
+ }
+ const classStore = GetMergedStore(destination);
+ // Properties
+ for (const property in classStore) {
+ const propertyDescriptor = classStore[property];
+ const sourceProperty = source[propertyDescriptor.sourceName || property];
+ const propertyType = propertyDescriptor.type;
+ if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId)) {
+ const dest = destination;
+ switch (propertyType) {
+ case 0: // Value
+ dest[property] = sourceProperty;
+ break;
+ case 1: // Texture
+ if (scene) {
+ dest[property] = SerializationHelper._TextureParser(sourceProperty, scene, rootUrl);
+ }
+ break;
+ case 2: // Color3
+ dest[property] = Color3.FromArray(sourceProperty);
+ break;
+ case 3: // FresnelParameters
+ dest[property] = SerializationHelper._FresnelParametersParser(sourceProperty);
+ break;
+ case 4: // Vector2
+ dest[property] = Vector2.FromArray(sourceProperty);
+ break;
+ case 5: // Vector3
+ dest[property] = Vector3.FromArray(sourceProperty);
+ break;
+ case 6: // Mesh reference
+ if (scene) {
+ dest[property] = scene.getLastMeshById(sourceProperty);
+ }
+ break;
+ case 7: // Color Curves
+ dest[property] = SerializationHelper._ColorCurvesParser(sourceProperty);
+ break;
+ case 8: // Color 4
+ dest[property] = Color4.FromArray(sourceProperty);
+ break;
+ case 9: // Image Processing
+ dest[property] = SerializationHelper._ImageProcessingConfigurationParser(sourceProperty);
+ break;
+ case 10: // Quaternion
+ dest[property] = Quaternion.FromArray(sourceProperty);
+ break;
+ case 11: // Camera reference
+ if (scene) {
+ dest[property] = scene.getCameraById(sourceProperty);
+ }
+ break;
+ case 12: // Matrix
+ dest[property] = Matrix.FromArray(sourceProperty);
+ break;
+ }
+ }
+ }
+ }
+ /**
+ * Creates a new entity from a serialization data object
+ * @param creationFunction defines a function used to instanciated the new entity
+ * @param source defines the source serialization data
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root url for resources
+ * @returns a new entity
+ */
+ static Parse(creationFunction, source, scene, rootUrl = null) {
+ const destination = creationFunction();
+ // Tags
+ if (Tags) {
+ Tags.AddTagsTo(destination, source.tags);
+ }
+ SerializationHelper.ParseProperties(source, destination, scene, rootUrl);
+ return destination;
+ }
+ /**
+ * Clones an object
+ * @param creationFunction defines the function used to instanciate the new object
+ * @param source defines the source object
+ * @param options defines the options to use
+ * @returns the cloned object
+ */
+ static Clone(creationFunction, source, options = {}) {
+ return _copySource(creationFunction, source, false, options);
+ }
+ /**
+ * Instanciates a new object based on a source one (some data will be shared between both object)
+ * @param creationFunction defines the function used to instanciate the new object
+ * @param source defines the source object
+ * @returns the new object
+ */
+ static Instanciate(creationFunction, source) {
+ return _copySource(creationFunction, source, true);
+ }
+}
+/**
+ * Gets or sets a boolean to indicate if the UniqueId property should be serialized
+ */
+SerializationHelper.AllowLoadingUniqueId = false;
+/**
+ * @internal
+ */
+SerializationHelper._ImageProcessingConfigurationParser = (sourceProperty) => {
+ throw _WarnImport("ImageProcessingConfiguration");
+};
+/**
+ * @internal
+ */
+SerializationHelper._FresnelParametersParser = (sourceProperty) => {
+ throw _WarnImport("FresnelParameters");
+};
+/**
+ * @internal
+ */
+SerializationHelper._ColorCurvesParser = (sourceProperty) => {
+ throw _WarnImport("ColorCurves");
+};
+/**
+ * @internal
+ */
+SerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => {
+ throw _WarnImport("Texture");
+};
+
+/**
+ * Base class of all the textures in babylon.
+ * It groups all the common properties the materials, post process, lights... might need
+ * in order to make a correct use of the texture.
+ */
+class BaseTexture extends ThinTexture {
+ /**
+ * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
+ */
+ set hasAlpha(value) {
+ if (this._hasAlpha === value) {
+ return;
+ }
+ this._hasAlpha = value;
+ if (this._scene) {
+ this._scene.markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ }
+ get hasAlpha() {
+ return this._hasAlpha;
+ }
+ /**
+ * Defines if the alpha value should be determined via the rgb values.
+ * If true the luminance of the pixel might be used to find the corresponding alpha value.
+ */
+ set getAlphaFromRGB(value) {
+ if (this._getAlphaFromRGB === value) {
+ return;
+ }
+ this._getAlphaFromRGB = value;
+ if (this._scene) {
+ this._scene.markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ }
+ get getAlphaFromRGB() {
+ return this._getAlphaFromRGB;
+ }
+ /**
+ * Define the UV channel to use starting from 0 and defaulting to 0.
+ * This is part of the texture as textures usually maps to one uv set.
+ */
+ set coordinatesIndex(value) {
+ if (this._coordinatesIndex === value) {
+ return;
+ }
+ this._coordinatesIndex = value;
+ if (this._scene) {
+ this._scene.markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ }
+ get coordinatesIndex() {
+ return this._coordinatesIndex;
+ }
+ /**
+ * How a texture is mapped.
+ *
+ * | Value | Type | Description |
+ * | ----- | ----------------------------------- | ----------- |
+ * | 0 | EXPLICIT_MODE | |
+ * | 1 | SPHERICAL_MODE | |
+ * | 2 | PLANAR_MODE | |
+ * | 3 | CUBIC_MODE | |
+ * | 4 | PROJECTION_MODE | |
+ * | 5 | SKYBOX_MODE | |
+ * | 6 | INVCUBIC_MODE | |
+ * | 7 | EQUIRECTANGULAR_MODE | |
+ * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
+ * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
+ */
+ set coordinatesMode(value) {
+ if (this._coordinatesMode === value) {
+ return;
+ }
+ this._coordinatesMode = value;
+ if (this._scene) {
+ this._scene.markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ }
+ get coordinatesMode() {
+ return this._coordinatesMode;
+ }
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ get wrapU() {
+ return this._wrapU;
+ }
+ set wrapU(value) {
+ this._wrapU = value;
+ }
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ get wrapV() {
+ return this._wrapV;
+ }
+ set wrapV(value) {
+ this._wrapV = value;
+ }
+ /**
+ * Define if the texture is a cube texture or if false a 2d texture.
+ */
+ get isCube() {
+ if (!this._texture) {
+ return this._isCube;
+ }
+ return this._texture.isCube;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ set isCube(value) {
+ if (!this._texture) {
+ this._isCube = value;
+ }
+ else {
+ this._texture.isCube = value;
+ }
+ }
+ /**
+ * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
+ */
+ get is3D() {
+ if (!this._texture) {
+ return false;
+ }
+ return this._texture.is3D;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ set is3D(value) {
+ if (!this._texture) {
+ return;
+ }
+ this._texture.is3D = value;
+ }
+ /**
+ * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture.
+ */
+ get is2DArray() {
+ if (!this._texture) {
+ return false;
+ }
+ return this._texture.is2DArray;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ set is2DArray(value) {
+ if (!this._texture) {
+ return;
+ }
+ this._texture.is2DArray = value;
+ }
+ /**
+ * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
+ * HDR texture are usually stored in linear space.
+ * This only impacts the PBR and Background materials
+ */
+ get gammaSpace() {
+ if (!this._texture) {
+ return this._gammaSpace;
+ }
+ else {
+ if (this._texture._gammaSpace === null) {
+ this._texture._gammaSpace = this._gammaSpace;
+ }
+ }
+ return this._texture._gammaSpace && !this._texture._useSRGBBuffer;
+ }
+ set gammaSpace(gamma) {
+ if (!this._texture) {
+ if (this._gammaSpace === gamma) {
+ return;
+ }
+ this._gammaSpace = gamma;
+ }
+ else {
+ if (this._texture._gammaSpace === gamma) {
+ return;
+ }
+ this._texture._gammaSpace = gamma;
+ }
+ this.getScene()?.markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ /**
+ * Gets or sets whether or not the texture contains RGBD data.
+ */
+ get isRGBD() {
+ return this._texture != null && this._texture._isRGBD;
+ }
+ set isRGBD(value) {
+ if (value === this.isRGBD) {
+ return;
+ }
+ if (this._texture) {
+ this._texture._isRGBD = value;
+ }
+ this.getScene()?.markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ /**
+ * Are mip maps generated for this texture or not.
+ */
+ get noMipmap() {
+ return false;
+ }
+ /**
+ * With prefiltered texture, defined the offset used during the prefiltering steps.
+ */
+ get lodGenerationOffset() {
+ if (this._texture) {
+ return this._texture._lodGenerationOffset;
+ }
+ return 0.0;
+ }
+ set lodGenerationOffset(value) {
+ if (this._texture) {
+ this._texture._lodGenerationOffset = value;
+ }
+ }
+ /**
+ * With prefiltered texture, defined the scale used during the prefiltering steps.
+ */
+ get lodGenerationScale() {
+ if (this._texture) {
+ return this._texture._lodGenerationScale;
+ }
+ return 0.0;
+ }
+ set lodGenerationScale(value) {
+ if (this._texture) {
+ this._texture._lodGenerationScale = value;
+ }
+ }
+ /**
+ * With prefiltered texture, defined if the specular generation is based on a linear ramp.
+ * By default we are using a log2 of the linear roughness helping to keep a better resolution for
+ * average roughness values.
+ */
+ get linearSpecularLOD() {
+ if (this._texture) {
+ return this._texture._linearSpecularLOD;
+ }
+ return false;
+ }
+ set linearSpecularLOD(value) {
+ if (this._texture) {
+ this._texture._linearSpecularLOD = value;
+ }
+ }
+ /**
+ * In case a better definition than spherical harmonics is required for the diffuse part of the environment.
+ * You can set the irradiance texture to rely on a texture instead of the spherical approach.
+ * This texture need to have the same characteristics than its parent (Cube vs 2d, coordinates mode, Gamma/Linear, RGBD).
+ */
+ get irradianceTexture() {
+ if (this._texture) {
+ return this._texture._irradianceTexture;
+ }
+ return null;
+ }
+ set irradianceTexture(value) {
+ if (this._texture) {
+ this._texture._irradianceTexture = value;
+ }
+ }
+ /**
+ * Define the unique id of the texture in the scene.
+ */
+ get uid() {
+ if (!this._uid) {
+ this._uid = RandomGUID();
+ }
+ return this._uid;
+ }
+ /**
+ * Return a string representation of the texture.
+ * @returns the texture as a string
+ */
+ toString() {
+ return this.name;
+ }
+ /**
+ * Get the class name of the texture.
+ * @returns "BaseTexture"
+ */
+ getClassName() {
+ return "BaseTexture";
+ }
+ /**
+ * Callback triggered when the texture has been disposed.
+ * Kept for back compatibility, you can use the onDisposeObservable instead.
+ */
+ set onDispose(callback) {
+ if (this._onDisposeObserver) {
+ this.onDisposeObservable.remove(this._onDisposeObserver);
+ }
+ this._onDisposeObserver = this.onDisposeObservable.add(callback);
+ }
+ /**
+ * Define if the texture is preventing a material to render or not.
+ * If not and the texture is not ready, the engine will use a default black texture instead.
+ */
+ get isBlocking() {
+ return true;
+ }
+ /**
+ * Was there any loading error?
+ */
+ get loadingError() {
+ return this._loadingError;
+ }
+ /**
+ * If a loading error occurred this object will be populated with information about the error.
+ */
+ get errorObject() {
+ return this._errorObject;
+ }
+ /**
+ * Instantiates a new BaseTexture.
+ * Base class of all the textures in babylon.
+ * It groups all the common properties the materials, post process, lights... might need
+ * in order to make a correct use of the texture.
+ * @param sceneOrEngine Define the scene or engine the texture belongs to
+ * @param internalTexture Define the internal texture associated with the texture
+ */
+ constructor(sceneOrEngine, internalTexture = null) {
+ super(null);
+ /**
+ * Gets or sets an object used to store user defined information.
+ */
+ this.metadata = null;
+ /**
+ * For internal use only. Please do not use.
+ */
+ this.reservedDataStore = null;
+ this._hasAlpha = false;
+ this._getAlphaFromRGB = false;
+ /**
+ * Intensity or strength of the texture.
+ * It is commonly used by materials to fine tune the intensity of the texture
+ */
+ this.level = 1;
+ this._coordinatesIndex = 0;
+ /**
+ * Gets or sets a boolean indicating that the texture should try to reduce shader code if there is no UV manipulation.
+ * (ie. when texture.getTextureMatrix().isIdentityAs3x2() returns true)
+ */
+ this.optimizeUVAllocation = true;
+ this._coordinatesMode = 0;
+ /**
+ * | Value | Type | Description |
+ * | ----- | ------------------ | ----------- |
+ * | 0 | CLAMP_ADDRESSMODE | |
+ * | 1 | WRAP_ADDRESSMODE | |
+ * | 2 | MIRROR_ADDRESSMODE | |
+ */
+ this.wrapR = 1;
+ /**
+ * With compliant hardware and browser (supporting anisotropic filtering)
+ * this defines the level of anisotropic filtering in the texture.
+ * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
+ */
+ this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
+ /** @internal */
+ this._isCube = false;
+ /** @internal */
+ this._gammaSpace = true;
+ /**
+ * Is Z inverted in the texture (useful in a cube texture).
+ */
+ this.invertZ = false;
+ /**
+ * @internal
+ */
+ this.lodLevelInAlpha = false;
+ /**
+ * Define if the texture is a render target.
+ */
+ this.isRenderTarget = false;
+ /** @internal */
+ this._prefiltered = false;
+ /** @internal */
+ this._forceSerialize = false;
+ /**
+ * Define the list of animation attached to the texture.
+ */
+ this.animations = [];
+ /**
+ * An event triggered when the texture is disposed.
+ */
+ this.onDisposeObservable = new Observable();
+ this._onDisposeObserver = null;
+ this._scene = null;
+ /** @internal */
+ this._uid = null;
+ /** @internal */
+ this._parentContainer = null;
+ this._loadingError = false;
+ if (sceneOrEngine) {
+ if (BaseTexture._IsScene(sceneOrEngine)) {
+ this._scene = sceneOrEngine;
+ }
+ else {
+ this._engine = sceneOrEngine;
+ }
+ }
+ else {
+ this._scene = EngineStore.LastCreatedScene;
+ }
+ if (this._scene) {
+ this.uniqueId = this._scene.getUniqueId();
+ this._scene.addTexture(this);
+ this._engine = this._scene.getEngine();
+ }
+ this._texture = internalTexture;
+ this._uid = null;
+ }
+ /**
+ * Get the scene the texture belongs to.
+ * @returns the scene or null if undefined
+ */
+ getScene() {
+ return this._scene;
+ }
+ /** @internal */
+ _getEngine() {
+ return this._engine;
+ }
+ /**
+ * Get the texture transform matrix used to offset tile the texture for instance.
+ * @returns the transformation matrix
+ */
+ getTextureMatrix() {
+ return Matrix.IdentityReadOnly;
+ }
+ /**
+ * Get the texture reflection matrix used to rotate/transform the reflection.
+ * @returns the reflection matrix
+ */
+ getReflectionTextureMatrix() {
+ return Matrix.IdentityReadOnly;
+ }
+ /**
+ * Gets a suitable rotate/transform matrix when the texture is used for refraction.
+ * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode.
+ * @returns The refraction matrix
+ */
+ getRefractionTextureMatrix() {
+ return this.getReflectionTextureMatrix();
+ }
+ /**
+ * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
+ * @returns true if ready, not blocking or if there was an error loading the texture
+ */
+ isReadyOrNotBlocking() {
+ return !this.isBlocking || this.isReady() || this.loadingError;
+ }
+ /**
+ * Scales the texture if is `canRescale()`
+ * @param ratio the resize factor we want to use to rescale
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ scale(ratio) { }
+ /**
+ * Get if the texture can rescale.
+ */
+ get canRescale() {
+ return false;
+ }
+ /**
+ * @internal
+ */
+ _getFromCache(url, noMipmap, sampling, invertY, useSRGBBuffer, isCube) {
+ const engine = this._getEngine();
+ if (!engine) {
+ return null;
+ }
+ const correctedUseSRGBBuffer = engine._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap);
+ const texturesCache = engine.getLoadedTexturesCache();
+ for (let index = 0; index < texturesCache.length; index++) {
+ const texturesCacheEntry = texturesCache[index];
+ if (useSRGBBuffer === undefined || correctedUseSRGBBuffer === texturesCacheEntry._useSRGBBuffer) {
+ if (invertY === undefined || invertY === texturesCacheEntry.invertY) {
+ if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
+ if (!sampling || sampling === texturesCacheEntry.samplingMode) {
+ if (isCube === undefined || isCube === texturesCacheEntry.isCube) {
+ texturesCacheEntry.incrementReferences();
+ return texturesCacheEntry;
+ }
+ }
+ }
+ }
+ }
+ }
+ return null;
+ }
+ /** @internal */
+ _rebuild(_fromContextLost = false) { }
+ /**
+ * Clones the texture.
+ * @returns the cloned texture
+ */
+ clone() {
+ return null;
+ }
+ /**
+ * Get the texture underlying type (INT, FLOAT...)
+ */
+ get textureType() {
+ if (!this._texture) {
+ return 0;
+ }
+ return this._texture.type !== undefined ? this._texture.type : 0;
+ }
+ /**
+ * Get the texture underlying format (RGB, RGBA...)
+ */
+ get textureFormat() {
+ if (!this._texture) {
+ return 5;
+ }
+ return this._texture.format !== undefined ? this._texture.format : 5;
+ }
+ /**
+ * Indicates that textures need to be re-calculated for all materials
+ */
+ _markAllSubMeshesAsTexturesDirty() {
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ scene.markAllMaterialsAsDirty(1);
+ }
+ /**
+ * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
+ * This will returns an RGBA array buffer containing either in values (0-255) or
+ * float values (0-1) depending of the underlying buffer type.
+ * @param faceIndex defines the face of the texture to read (in case of cube texture)
+ * @param level defines the LOD level of the texture to read (in case of Mip Maps)
+ * @param buffer defines a user defined buffer to fill with data (can be null)
+ * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels
+ * @param noDataConversion false to convert the data to Uint8Array (if texture type is UNSIGNED_BYTE) or to Float32Array (if texture type is anything but UNSIGNED_BYTE). If true, the type of the generated buffer (if buffer==null) will depend on the type of the texture
+ * @param x defines the region x coordinates to start reading from (default to 0)
+ * @param y defines the region y coordinates to start reading from (default to 0)
+ * @param width defines the region width to read from (default to the texture size at level)
+ * @param height defines the region width to read from (default to the texture size at level)
+ * @returns The Array buffer promise containing the pixels data.
+ */
+ readPixels(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0, width = Number.MAX_VALUE, height = Number.MAX_VALUE) {
+ if (!this._texture) {
+ return null;
+ }
+ const engine = this._getEngine();
+ if (!engine) {
+ return null;
+ }
+ const size = this.getSize();
+ let maxWidth = size.width;
+ let maxHeight = size.height;
+ if (level !== 0) {
+ maxWidth = maxWidth / Math.pow(2, level);
+ maxHeight = maxHeight / Math.pow(2, level);
+ maxWidth = Math.round(maxWidth);
+ maxHeight = Math.round(maxHeight);
+ }
+ width = Math.min(maxWidth, width);
+ height = Math.min(maxHeight, height);
+ try {
+ if (this._texture.isCube) {
+ return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y);
+ }
+ return engine._readTexturePixels(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion, x, y);
+ }
+ catch (e) {
+ return null;
+ }
+ }
+ /**
+ * @internal
+ */
+ _readPixelsSync(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false) {
+ if (!this._texture) {
+ return null;
+ }
+ const size = this.getSize();
+ let width = size.width;
+ let height = size.height;
+ const engine = this._getEngine();
+ if (!engine) {
+ return null;
+ }
+ if (level != 0) {
+ width = width / Math.pow(2, level);
+ height = height / Math.pow(2, level);
+ width = Math.round(width);
+ height = Math.round(height);
+ }
+ try {
+ if (this._texture.isCube) {
+ return engine._readTexturePixelsSync(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion);
+ }
+ return engine._readTexturePixelsSync(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion);
+ }
+ catch (e) {
+ return null;
+ }
+ }
+ /** @internal */
+ get _lodTextureHigh() {
+ if (this._texture) {
+ return this._texture._lodTextureHigh;
+ }
+ return null;
+ }
+ /** @internal */
+ get _lodTextureMid() {
+ if (this._texture) {
+ return this._texture._lodTextureMid;
+ }
+ return null;
+ }
+ /** @internal */
+ get _lodTextureLow() {
+ if (this._texture) {
+ return this._texture._lodTextureLow;
+ }
+ return null;
+ }
+ /**
+ * Dispose the texture and release its associated resources.
+ */
+ dispose() {
+ if (this._scene) {
+ // Animations
+ if (this._scene.stopAnimation) {
+ this._scene.stopAnimation(this);
+ }
+ // Remove from scene
+ this._scene.removePendingData(this);
+ const index = this._scene.textures.indexOf(this);
+ if (index >= 0) {
+ this._scene.textures.splice(index, 1);
+ }
+ this._scene.onTextureRemovedObservable.notifyObservers(this);
+ this._scene = null;
+ if (this._parentContainer) {
+ const index = this._parentContainer.textures.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.textures.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ }
+ // Callback
+ this.onDisposeObservable.notifyObservers(this);
+ this.onDisposeObservable.clear();
+ this.metadata = null;
+ super.dispose();
+ }
+ /**
+ * Serialize the texture into a JSON representation that can be parsed later on.
+ * @param allowEmptyName True to force serialization even if name is empty. Default: false
+ * @returns the JSON representation of the texture
+ */
+ serialize(allowEmptyName = false) {
+ if (!this.name && !allowEmptyName) {
+ return null;
+ }
+ const serializationObject = SerializationHelper.Serialize(this);
+ // Animations
+ SerializationHelper.AppendSerializedAnimations(this, serializationObject);
+ return serializationObject;
+ }
+ /**
+ * Helper function to be called back once a list of texture contains only ready textures.
+ * @param textures Define the list of textures to wait for
+ * @param callback Define the callback triggered once the entire list will be ready
+ */
+ static WhenAllReady(textures, callback) {
+ let numRemaining = textures.length;
+ if (numRemaining === 0) {
+ callback();
+ return;
+ }
+ for (let i = 0; i < textures.length; i++) {
+ const texture = textures[i];
+ if (texture.isReady()) {
+ if (--numRemaining === 0) {
+ callback();
+ }
+ }
+ else {
+ const onLoadObservable = texture.onLoadObservable;
+ if (onLoadObservable) {
+ onLoadObservable.addOnce(() => {
+ if (--numRemaining === 0) {
+ callback();
+ }
+ });
+ }
+ else {
+ if (--numRemaining === 0) {
+ callback();
+ }
+ }
+ }
+ }
+ }
+ static _IsScene(sceneOrEngine) {
+ return sceneOrEngine.getClassName() === "Scene";
+ }
+}
+/**
+ * Default anisotropic filtering level for the application.
+ * It is set to 4 as a good tradeoff between perf and quality.
+ */
+BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
+__decorate([
+ serialize()
+], BaseTexture.prototype, "uniqueId", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "name", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "displayName", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "metadata", void 0);
+__decorate([
+ serialize("hasAlpha")
+], BaseTexture.prototype, "_hasAlpha", void 0);
+__decorate([
+ serialize("getAlphaFromRGB")
+], BaseTexture.prototype, "_getAlphaFromRGB", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "level", void 0);
+__decorate([
+ serialize("coordinatesIndex")
+], BaseTexture.prototype, "_coordinatesIndex", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "optimizeUVAllocation", void 0);
+__decorate([
+ serialize("coordinatesMode")
+], BaseTexture.prototype, "_coordinatesMode", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "wrapU", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "wrapV", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "wrapR", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "isCube", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "is3D", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "is2DArray", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "gammaSpace", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "invertZ", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "lodLevelInAlpha", void 0);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "lodGenerationOffset", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "lodGenerationScale", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "linearSpecularLOD", null);
+__decorate([
+ serializeAsTexture()
+], BaseTexture.prototype, "irradianceTexture", null);
+__decorate([
+ serialize()
+], BaseTexture.prototype, "isRenderTarget", void 0);
+
+ThinEngine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) {
+ const callback = async (loadData) => {
+ if (!loadData) {
+ if (onLoad) {
+ onLoad(null);
+ }
+ return;
+ }
+ const texture = loadData.texture;
+ if (!createPolynomials) {
+ texture._sphericalPolynomial = new SphericalPolynomial();
+ }
+ else if (loadData.info.sphericalPolynomial) {
+ texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
+ }
+ texture._source = 9 /* InternalTextureSource.CubePrefiltered */;
+ if (this.getCaps().textureLOD) {
+ // Do not add extra process if texture lod is supported.
+ if (onLoad) {
+ onLoad(texture);
+ }
+ return;
+ }
+ const mipSlices = 3;
+ const gl = this._gl;
+ const width = loadData.width;
+ if (!width) {
+ return;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const { DDSTools } = await Promise.resolve().then(() => dds);
+ const textures = [];
+ for (let i = 0; i < mipSlices; i++) {
+ //compute LOD from even spacing in smoothness (matching shader calculation)
+ const smoothness = i / (mipSlices - 1);
+ const roughness = 1 - smoothness;
+ const minLODIndex = lodOffset; // roughness = 0
+ const maxLODIndex = Math.log2(width) * lodScale + lodOffset; // roughness = 1
+ const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
+ const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
+ const glTextureFromLod = new InternalTexture(this, 2 /* InternalTextureSource.Temp */);
+ glTextureFromLod.type = texture.type;
+ glTextureFromLod.format = texture.format;
+ glTextureFromLod.width = Math.pow(2, Math.max(Math.log2(width) - mipmapIndex, 0));
+ glTextureFromLod.height = glTextureFromLod.width;
+ glTextureFromLod.isCube = true;
+ glTextureFromLod._cachedWrapU = 0;
+ glTextureFromLod._cachedWrapV = 0;
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
+ glTextureFromLod.samplingMode = 2;
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ if (loadData.isDDS) {
+ const info = loadData.info;
+ const data = loadData.data;
+ this._unpackFlipY(info.isCompressed);
+ DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex);
+ }
+ else {
+ Logger.Warn("DDS is the only prefiltered cube map supported so far.");
+ }
+ this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
+ // Wrap in a base texture for easy binding.
+ const lodTexture = new BaseTexture(scene);
+ lodTexture._isCube = true;
+ lodTexture._texture = glTextureFromLod;
+ glTextureFromLod.isReady = true;
+ textures.push(lodTexture);
+ }
+ texture._lodTextureHigh = textures[2];
+ texture._lodTextureMid = textures[1];
+ texture._lodTextureLow = textures[0];
+ if (onLoad) {
+ onLoad(texture);
+ }
+ };
+ return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
+};
+
+ThinEngine.prototype.createUniformBuffer = function (elements, _label) {
+ const ubo = this._gl.createBuffer();
+ if (!ubo) {
+ throw new Error("Unable to create uniform buffer");
+ }
+ const result = new WebGLDataBuffer(ubo);
+ this.bindUniformBuffer(result);
+ if (elements instanceof Float32Array) {
+ this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
+ }
+ else {
+ this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
+ }
+ this.bindUniformBuffer(null);
+ result.references = 1;
+ return result;
+};
+ThinEngine.prototype.createDynamicUniformBuffer = function (elements, _label) {
+ const ubo = this._gl.createBuffer();
+ if (!ubo) {
+ throw new Error("Unable to create dynamic uniform buffer");
+ }
+ const result = new WebGLDataBuffer(ubo);
+ this.bindUniformBuffer(result);
+ if (elements instanceof Float32Array) {
+ this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
+ }
+ else {
+ this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
+ }
+ this.bindUniformBuffer(null);
+ result.references = 1;
+ return result;
+};
+ThinEngine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
+ this.bindUniformBuffer(uniformBuffer);
+ if (offset === undefined) {
+ offset = 0;
+ }
+ if (count === undefined) {
+ if (elements instanceof Float32Array) {
+ this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
+ }
+ else {
+ this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
+ }
+ }
+ else {
+ if (elements instanceof Float32Array) {
+ this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
+ }
+ else {
+ this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
+ }
+ }
+ this.bindUniformBuffer(null);
+};
+ThinEngine.prototype.bindUniformBuffer = function (buffer) {
+ this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer ? buffer.underlyingResource : null);
+};
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+ThinEngine.prototype.bindUniformBufferBase = function (buffer, location, name) {
+ this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer ? buffer.underlyingResource : null);
+};
+ThinEngine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) {
+ const program = pipelineContext.program;
+ const uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
+ if (uniformLocation !== 0xffffffff) {
+ this._gl.uniformBlockBinding(program, uniformLocation, index);
+ }
+};
+
+AbstractEngine.prototype.displayLoadingUI = function () {
+ if (!IsWindowObjectExist()) {
+ return;
+ }
+ const loadingScreen = this.loadingScreen;
+ if (loadingScreen) {
+ loadingScreen.displayLoadingUI();
+ }
+};
+AbstractEngine.prototype.hideLoadingUI = function () {
+ if (!IsWindowObjectExist()) {
+ return;
+ }
+ const loadingScreen = this._loadingScreen;
+ if (loadingScreen) {
+ loadingScreen.hideLoadingUI();
+ }
+};
+Object.defineProperty(AbstractEngine.prototype, "loadingScreen", {
+ get: function () {
+ if (!this._loadingScreen && this._renderingCanvas) {
+ this._loadingScreen = AbstractEngine.DefaultLoadingScreenFactory(this._renderingCanvas);
+ }
+ return this._loadingScreen;
+ },
+ set: function (value) {
+ this._loadingScreen = value;
+ },
+ enumerable: true,
+ configurable: true,
+});
+Object.defineProperty(AbstractEngine.prototype, "loadingUIText", {
+ set: function (value) {
+ this.loadingScreen.loadingUIText = value;
+ },
+ enumerable: true,
+ configurable: true,
+});
+Object.defineProperty(AbstractEngine.prototype, "loadingUIBackgroundColor", {
+ set: function (value) {
+ this.loadingScreen.loadingUIBackgroundColor = value;
+ },
+ enumerable: true,
+ configurable: true,
+});
+
+AbstractEngine.prototype.getInputElement = function () {
+ return this._renderingCanvas;
+};
+AbstractEngine.prototype.getRenderingCanvasClientRect = function () {
+ if (!this._renderingCanvas) {
+ return null;
+ }
+ return this._renderingCanvas.getBoundingClientRect();
+};
+AbstractEngine.prototype.getInputElementClientRect = function () {
+ if (!this._renderingCanvas) {
+ return null;
+ }
+ return this.getInputElement().getBoundingClientRect();
+};
+AbstractEngine.prototype.getAspectRatio = function (viewportOwner, useScreen = false) {
+ const viewport = viewportOwner.viewport;
+ return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
+};
+AbstractEngine.prototype.getScreenAspectRatio = function () {
+ return this.getRenderWidth(true) / this.getRenderHeight(true);
+};
+AbstractEngine.prototype._verifyPointerLock = function () {
+ this._onPointerLockChange?.();
+};
+
+AbstractEngine.prototype.setAlphaEquation = function (equation) {
+ if (this._alphaEquation === equation) {
+ return;
+ }
+ switch (equation) {
+ case 0:
+ this._alphaState.setAlphaEquationParameters(32774, 32774);
+ break;
+ case 1:
+ this._alphaState.setAlphaEquationParameters(32778, 32778);
+ break;
+ case 2:
+ this._alphaState.setAlphaEquationParameters(32779, 32779);
+ break;
+ case 3:
+ this._alphaState.setAlphaEquationParameters(32776, 32776);
+ break;
+ case 4:
+ this._alphaState.setAlphaEquationParameters(32775, 32775);
+ break;
+ case 5:
+ this._alphaState.setAlphaEquationParameters(32775, 32774);
+ break;
+ }
+ this._alphaEquation = equation;
+};
+
+AbstractEngine.prototype.getInputElement = function () {
+ return this._renderingCanvas;
+};
+AbstractEngine.prototype.getDepthFunction = function () {
+ return this._depthCullingState.depthFunc;
+};
+AbstractEngine.prototype.setDepthFunction = function (depthFunc) {
+ this._depthCullingState.depthFunc = depthFunc;
+};
+AbstractEngine.prototype.setDepthFunctionToGreater = function () {
+ this.setDepthFunction(516);
+};
+AbstractEngine.prototype.setDepthFunctionToGreaterOrEqual = function () {
+ this.setDepthFunction(518);
+};
+AbstractEngine.prototype.setDepthFunctionToLess = function () {
+ this.setDepthFunction(513);
+};
+AbstractEngine.prototype.setDepthFunctionToLessOrEqual = function () {
+ this.setDepthFunction(515);
+};
+AbstractEngine.prototype.getDepthWrite = function () {
+ return this._depthCullingState.depthMask;
+};
+AbstractEngine.prototype.setDepthWrite = function (enable) {
+ this._depthCullingState.depthMask = enable;
+};
+AbstractEngine.prototype.getStencilBuffer = function () {
+ return this._stencilState.stencilTest;
+};
+AbstractEngine.prototype.setStencilBuffer = function (enable) {
+ this._stencilState.stencilTest = enable;
+};
+AbstractEngine.prototype.getStencilMask = function () {
+ return this._stencilState.stencilMask;
+};
+AbstractEngine.prototype.setStencilMask = function (mask) {
+ this._stencilState.stencilMask = mask;
+};
+AbstractEngine.prototype.getStencilFunction = function () {
+ return this._stencilState.stencilFunc;
+};
+AbstractEngine.prototype.getStencilFunctionReference = function () {
+ return this._stencilState.stencilFuncRef;
+};
+AbstractEngine.prototype.getStencilFunctionMask = function () {
+ return this._stencilState.stencilFuncMask;
+};
+AbstractEngine.prototype.setStencilFunction = function (stencilFunc) {
+ this._stencilState.stencilFunc = stencilFunc;
+};
+AbstractEngine.prototype.setStencilFunctionReference = function (reference) {
+ this._stencilState.stencilFuncRef = reference;
+};
+AbstractEngine.prototype.setStencilFunctionMask = function (mask) {
+ this._stencilState.stencilFuncMask = mask;
+};
+AbstractEngine.prototype.getStencilOperationFail = function () {
+ return this._stencilState.stencilOpStencilFail;
+};
+AbstractEngine.prototype.getStencilOperationDepthFail = function () {
+ return this._stencilState.stencilOpDepthFail;
+};
+AbstractEngine.prototype.getStencilOperationPass = function () {
+ return this._stencilState.stencilOpStencilDepthPass;
+};
+AbstractEngine.prototype.setStencilOperationFail = function (operation) {
+ this._stencilState.stencilOpStencilFail = operation;
+};
+AbstractEngine.prototype.setStencilOperationDepthFail = function (operation) {
+ this._stencilState.stencilOpDepthFail = operation;
+};
+AbstractEngine.prototype.setStencilOperationPass = function (operation) {
+ this._stencilState.stencilOpStencilDepthPass = operation;
+};
+AbstractEngine.prototype.cacheStencilState = function () {
+ this._cachedStencilBuffer = this.getStencilBuffer();
+ this._cachedStencilFunction = this.getStencilFunction();
+ this._cachedStencilMask = this.getStencilMask();
+ this._cachedStencilOperationPass = this.getStencilOperationPass();
+ this._cachedStencilOperationFail = this.getStencilOperationFail();
+ this._cachedStencilOperationDepthFail = this.getStencilOperationDepthFail();
+ this._cachedStencilReference = this.getStencilFunctionReference();
+};
+AbstractEngine.prototype.restoreStencilState = function () {
+ this.setStencilFunction(this._cachedStencilFunction);
+ this.setStencilMask(this._cachedStencilMask);
+ this.setStencilBuffer(this._cachedStencilBuffer);
+ this.setStencilOperationPass(this._cachedStencilOperationPass);
+ this.setStencilOperationFail(this._cachedStencilOperationFail);
+ this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail);
+ this.setStencilFunctionReference(this._cachedStencilReference);
+};
+AbstractEngine.prototype.setAlphaConstants = function (r, g, b, a) {
+ this._alphaState.setAlphaBlendConstants(r, g, b, a);
+};
+AbstractEngine.prototype.getAlphaMode = function () {
+ return this._alphaMode;
+};
+AbstractEngine.prototype.getAlphaEquation = function () {
+ return this._alphaEquation;
+};
+
+AbstractEngine.prototype.getRenderPassNames = function () {
+ return this._renderPassNames;
+};
+AbstractEngine.prototype.getCurrentRenderPassName = function () {
+ return this._renderPassNames[this.currentRenderPassId];
+};
+AbstractEngine.prototype.createRenderPassId = function (name) {
+ // Note: render pass id == 0 is always for the main render pass
+ const id = ++AbstractEngine._RenderPassIdCounter;
+ this._renderPassNames[id] = name ?? "NONAME";
+ return id;
+};
+AbstractEngine.prototype.releaseRenderPassId = function (id) {
+ this._renderPassNames[id] = undefined;
+ for (let s = 0; s < this.scenes.length; ++s) {
+ const scene = this.scenes[s];
+ for (let m = 0; m < scene.meshes.length; ++m) {
+ const mesh = scene.meshes[m];
+ if (mesh.subMeshes) {
+ for (let b = 0; b < mesh.subMeshes.length; ++b) {
+ const subMesh = mesh.subMeshes[b];
+ subMesh._removeDrawWrapper(id);
+ }
+ }
+ }
+ }
+};
+
+/** @internal */
+function _DisableTouchAction(canvas) {
+ if (!canvas || !canvas.setAttribute) {
+ return;
+ }
+ canvas.setAttribute("touch-action", "none");
+ canvas.style.touchAction = "none";
+ canvas.style.webkitTapHighlightColor = "transparent";
+}
+/** @internal */
+function _CommonInit(commonEngine, canvas, creationOptions) {
+ commonEngine._onCanvasFocus = () => {
+ commonEngine.onCanvasFocusObservable.notifyObservers(commonEngine);
+ };
+ commonEngine._onCanvasBlur = () => {
+ commonEngine.onCanvasBlurObservable.notifyObservers(commonEngine);
+ };
+ commonEngine._onCanvasContextMenu = (evt) => {
+ if (commonEngine.disableContextMenu) {
+ evt.preventDefault();
+ }
+ };
+ canvas.addEventListener("focus", commonEngine._onCanvasFocus);
+ canvas.addEventListener("blur", commonEngine._onCanvasBlur);
+ canvas.addEventListener("contextmenu", commonEngine._onCanvasContextMenu);
+ commonEngine._onBlur = () => {
+ if (commonEngine.disablePerformanceMonitorInBackground) {
+ commonEngine.performanceMonitor.disable();
+ }
+ commonEngine._windowIsBackground = true;
+ };
+ commonEngine._onFocus = () => {
+ if (commonEngine.disablePerformanceMonitorInBackground) {
+ commonEngine.performanceMonitor.enable();
+ }
+ commonEngine._windowIsBackground = false;
+ };
+ commonEngine._onCanvasPointerOut = (ev) => {
+ // Check that the element at the point of the pointer out isn't the canvas and if it isn't, notify observers
+ // Note: This is a workaround for a bug with Safari
+ if (document.elementFromPoint(ev.clientX, ev.clientY) !== canvas) {
+ commonEngine.onCanvasPointerOutObservable.notifyObservers(ev);
+ }
+ };
+ const hostWindow = commonEngine.getHostWindow(); // it calls IsWindowObjectExist()
+ if (hostWindow && typeof hostWindow.addEventListener === "function") {
+ hostWindow.addEventListener("blur", commonEngine._onBlur);
+ hostWindow.addEventListener("focus", commonEngine._onFocus);
+ }
+ canvas.addEventListener("pointerout", commonEngine._onCanvasPointerOut);
+ if (!creationOptions.doNotHandleTouchAction) {
+ _DisableTouchAction(canvas);
+ }
+ // Create Audio Engine if needed.
+ if (!AbstractEngine.audioEngine && creationOptions.audioEngine && AbstractEngine.AudioEngineFactory) {
+ AbstractEngine.audioEngine = AbstractEngine.AudioEngineFactory(commonEngine.getRenderingCanvas(), commonEngine.getAudioContext(), commonEngine.getAudioDestination());
+ }
+ if (IsDocumentAvailable()) {
+ // Fullscreen
+ commonEngine._onFullscreenChange = () => {
+ commonEngine.isFullscreen = !!document.fullscreenElement;
+ // Pointer lock
+ if (commonEngine.isFullscreen && commonEngine._pointerLockRequested && canvas) {
+ RequestPointerlock(canvas);
+ }
+ };
+ document.addEventListener("fullscreenchange", commonEngine._onFullscreenChange, false);
+ document.addEventListener("webkitfullscreenchange", commonEngine._onFullscreenChange, false);
+ // Pointer lock
+ commonEngine._onPointerLockChange = () => {
+ commonEngine.isPointerLock = document.pointerLockElement === canvas;
+ };
+ document.addEventListener("pointerlockchange", commonEngine._onPointerLockChange, false);
+ document.addEventListener("webkitpointerlockchange", commonEngine._onPointerLockChange, false);
+ }
+ commonEngine.enableOfflineSupport = AbstractEngine.OfflineProviderFactory !== undefined;
+ commonEngine._deterministicLockstep = !!creationOptions.deterministicLockstep;
+ commonEngine._lockstepMaxSteps = creationOptions.lockstepMaxSteps || 0;
+ commonEngine._timeStep = creationOptions.timeStep || 1 / 60;
+}
+/** @internal */
+function _CommonDispose(commonEngine, canvas) {
+ // Release audio engine
+ if (EngineStore.Instances.length === 1 && AbstractEngine.audioEngine) {
+ AbstractEngine.audioEngine.dispose();
+ AbstractEngine.audioEngine = null;
+ }
+ // Events
+ const hostWindow = commonEngine.getHostWindow(); // it calls IsWindowObjectExist()
+ if (hostWindow && typeof hostWindow.removeEventListener === "function") {
+ hostWindow.removeEventListener("blur", commonEngine._onBlur);
+ hostWindow.removeEventListener("focus", commonEngine._onFocus);
+ }
+ if (canvas) {
+ canvas.removeEventListener("focus", commonEngine._onCanvasFocus);
+ canvas.removeEventListener("blur", commonEngine._onCanvasBlur);
+ canvas.removeEventListener("pointerout", commonEngine._onCanvasPointerOut);
+ canvas.removeEventListener("contextmenu", commonEngine._onCanvasContextMenu);
+ }
+ if (IsDocumentAvailable()) {
+ document.removeEventListener("fullscreenchange", commonEngine._onFullscreenChange);
+ document.removeEventListener("mozfullscreenchange", commonEngine._onFullscreenChange);
+ document.removeEventListener("webkitfullscreenchange", commonEngine._onFullscreenChange);
+ document.removeEventListener("msfullscreenchange", commonEngine._onFullscreenChange);
+ document.removeEventListener("pointerlockchange", commonEngine._onPointerLockChange);
+ document.removeEventListener("mspointerlockchange", commonEngine._onPointerLockChange);
+ document.removeEventListener("mozpointerlockchange", commonEngine._onPointerLockChange);
+ document.removeEventListener("webkitpointerlockchange", commonEngine._onPointerLockChange);
+ }
+}
+/**
+ * Get Font size information
+ * @param font font name
+ * @returns an object containing ascent, height and descent
+ */
+function GetFontOffset(font) {
+ const text = document.createElement("span");
+ text.textContent = "Hg";
+ text.style.font = font;
+ const block = document.createElement("div");
+ block.style.display = "inline-block";
+ block.style.width = "1px";
+ block.style.height = "0px";
+ block.style.verticalAlign = "bottom";
+ const div = document.createElement("div");
+ div.style.whiteSpace = "nowrap";
+ div.appendChild(text);
+ div.appendChild(block);
+ document.body.appendChild(div);
+ let fontAscent = 0;
+ let fontHeight = 0;
+ try {
+ fontHeight = block.getBoundingClientRect().top - text.getBoundingClientRect().top;
+ block.style.verticalAlign = "baseline";
+ fontAscent = block.getBoundingClientRect().top - text.getBoundingClientRect().top;
+ }
+ finally {
+ document.body.removeChild(div);
+ }
+ return { ascent: fontAscent, height: fontHeight, descent: fontHeight - fontAscent };
+}
+/** @internal */
+function CreateImageBitmapFromSource(engine, imageSource, options) {
+ const promise = new Promise((resolve, reject) => {
+ const image = new Image();
+ image.onload = () => {
+ image.decode().then(() => {
+ engine.createImageBitmap(image, options).then((imageBitmap) => {
+ resolve(imageBitmap);
+ });
+ });
+ };
+ image.onerror = () => {
+ reject(`Error loading image ${image.src}`);
+ };
+ image.src = imageSource;
+ });
+ return promise;
+}
+/** @internal */
+function ResizeImageBitmap(engine, image, bufferWidth, bufferHeight) {
+ const canvas = engine.createCanvas(bufferWidth, bufferHeight);
+ const context = canvas.getContext("2d");
+ if (!context) {
+ throw new Error("Unable to get 2d context for resizeImageBitmap");
+ }
+ context.drawImage(image, 0, 0);
+ // Create VertexData from map data
+ // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
+ const buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
+ return buffer;
+}
+/**
+ * Ask the browser to promote the current element to fullscreen rendering mode
+ * @param element defines the DOM element to promote
+ */
+function RequestFullscreen(element) {
+ const requestFunction = element.requestFullscreen || element.webkitRequestFullscreen;
+ if (!requestFunction) {
+ return;
+ }
+ requestFunction.call(element);
+}
+/**
+ * Asks the browser to exit fullscreen mode
+ */
+function ExitFullscreen() {
+ const anyDoc = document;
+ if (document.exitFullscreen) {
+ document.exitFullscreen();
+ }
+ else if (anyDoc.webkitCancelFullScreen) {
+ anyDoc.webkitCancelFullScreen();
+ }
+}
+/**
+ * Ask the browser to promote the current element to pointerlock mode
+ * @param element defines the DOM element to promote
+ */
+function RequestPointerlock(element) {
+ if (element.requestPointerLock) {
+ // In some browsers, requestPointerLock returns a promise.
+ // Handle possible rejections to avoid an unhandled top-level exception.
+ const promise = element.requestPointerLock();
+ if (promise instanceof Promise)
+ promise
+ .then(() => {
+ element.focus();
+ })
+ .catch(() => { });
+ else
+ element.focus();
+ }
+}
+/**
+ * Asks the browser to exit pointerlock mode
+ */
+function ExitPointerlock() {
+ if (document.exitPointerLock) {
+ document.exitPointerLock();
+ }
+}
+
+/**
+ * This class is used to track a performance counter which is number based.
+ * The user has access to many properties which give statistics of different nature.
+ *
+ * The implementer can track two kinds of Performance Counter: time and count.
+ * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
+ * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
+ */
+class PerfCounter {
+ /**
+ * Returns the smallest value ever
+ */
+ get min() {
+ return this._min;
+ }
+ /**
+ * Returns the biggest value ever
+ */
+ get max() {
+ return this._max;
+ }
+ /**
+ * Returns the average value since the performance counter is running
+ */
+ get average() {
+ return this._average;
+ }
+ /**
+ * Returns the average value of the last second the counter was monitored
+ */
+ get lastSecAverage() {
+ return this._lastSecAverage;
+ }
+ /**
+ * Returns the current value
+ */
+ get current() {
+ return this._current;
+ }
+ /**
+ * Gets the accumulated total
+ */
+ get total() {
+ return this._totalAccumulated;
+ }
+ /**
+ * Gets the total value count
+ */
+ get count() {
+ return this._totalValueCount;
+ }
+ /**
+ * Creates a new counter
+ */
+ constructor() {
+ this._startMonitoringTime = 0;
+ this._min = 0;
+ this._max = 0;
+ this._average = 0;
+ this._lastSecAverage = 0;
+ this._current = 0;
+ this._totalValueCount = 0;
+ this._totalAccumulated = 0;
+ this._lastSecAccumulated = 0;
+ this._lastSecTime = 0;
+ this._lastSecValueCount = 0;
+ }
+ /**
+ * Call this method to start monitoring a new frame.
+ * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
+ */
+ fetchNewFrame() {
+ this._totalValueCount++;
+ this._current = 0;
+ this._lastSecValueCount++;
+ }
+ /**
+ * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
+ * @param newCount the count value to add to the monitored count
+ * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
+ */
+ addCount(newCount, fetchResult) {
+ if (!PerfCounter.Enabled) {
+ return;
+ }
+ this._current += newCount;
+ if (fetchResult) {
+ this._fetchResult();
+ }
+ }
+ /**
+ * Start monitoring this performance counter
+ */
+ beginMonitoring() {
+ if (!PerfCounter.Enabled) {
+ return;
+ }
+ this._startMonitoringTime = PrecisionDate.Now;
+ }
+ /**
+ * Compute the time lapsed since the previous beginMonitoring() call.
+ * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
+ */
+ endMonitoring(newFrame = true) {
+ if (!PerfCounter.Enabled) {
+ return;
+ }
+ if (newFrame) {
+ this.fetchNewFrame();
+ }
+ const currentTime = PrecisionDate.Now;
+ this._current = currentTime - this._startMonitoringTime;
+ if (newFrame) {
+ this._fetchResult();
+ }
+ }
+ /**
+ * Call this method to end the monitoring of a frame.
+ * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the end of the frame, after beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
+ */
+ endFrame() {
+ this._fetchResult();
+ }
+ /** @internal */
+ _fetchResult() {
+ this._totalAccumulated += this._current;
+ this._lastSecAccumulated += this._current;
+ // Min/Max update
+ this._min = Math.min(this._min, this._current);
+ this._max = Math.max(this._max, this._current);
+ this._average = this._totalAccumulated / this._totalValueCount;
+ // Reset last sec?
+ const now = PrecisionDate.Now;
+ if (now - this._lastSecTime > 1000) {
+ this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
+ this._lastSecTime = now;
+ this._lastSecAccumulated = 0;
+ this._lastSecValueCount = 0;
+ }
+ }
+}
+/**
+ * Gets or sets a global boolean to turn on and off all the counters
+ */
+PerfCounter.Enabled = true;
+
+/**
+ * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
+ */
+class Engine extends ThinEngine {
+ /**
+ * Returns the current npm package of the sdk
+ */
+ // Not mixed with Version for tooling purpose.
+ static get NpmPackage() {
+ return AbstractEngine.NpmPackage;
+ }
+ /**
+ * Returns the current version of the framework
+ */
+ static get Version() {
+ return AbstractEngine.Version;
+ }
+ /** Gets the list of created engines */
+ static get Instances() {
+ return EngineStore.Instances;
+ }
+ /**
+ * Gets the latest created engine
+ */
+ static get LastCreatedEngine() {
+ return EngineStore.LastCreatedEngine;
+ }
+ /**
+ * Gets the latest created scene
+ */
+ static get LastCreatedScene() {
+ return EngineStore.LastCreatedScene;
+ }
+ /** @internal */
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Method called to create the default loading screen.
+ * This can be overridden in your own app.
+ * @param canvas The rendering canvas element
+ * @returns The loading screen
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static DefaultLoadingScreenFactory(canvas) {
+ return AbstractEngine.DefaultLoadingScreenFactory(canvas);
+ }
+ get _supportsHardwareTextureRescaling() {
+ return !!Engine._RescalePostProcessFactory;
+ }
+ _measureFps() {
+ this._performanceMonitor.sampleFrame();
+ this._fps = this._performanceMonitor.averageFPS;
+ this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
+ }
+ /**
+ * Gets the performance monitor attached to this engine
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation
+ */
+ get performanceMonitor() {
+ return this._performanceMonitor;
+ }
+ // Events
+ /**
+ * Creates a new engine
+ * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which already used the WebGL context
+ * @param antialias defines enable antialiasing (default: false)
+ * @param options defines further options to be sent to the getContext() function
+ * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
+ */
+ constructor(canvasOrContext, antialias, options, adaptToDeviceRatio = false) {
+ super(canvasOrContext, antialias, options, adaptToDeviceRatio);
+ // Members
+ /**
+ * If set, will be used to request the next animation frame for the render loop
+ */
+ this.customAnimationFrameRequester = null;
+ this._performanceMonitor = new PerformanceMonitor();
+ this._drawCalls = new PerfCounter();
+ if (!canvasOrContext) {
+ return;
+ }
+ this._features.supportRenderPasses = true;
+ options = this._creationOptions;
+ }
+ _initGLContext() {
+ super._initGLContext();
+ this._rescalePostProcess = null;
+ }
+ /**
+ * Shared initialization across engines types.
+ * @param canvas The canvas associated with this instance of the engine.
+ */
+ _sharedInit(canvas) {
+ super._sharedInit(canvas);
+ _CommonInit(this, canvas, this._creationOptions);
+ }
+ /**
+ * Resize an image and returns the image data as an uint8array
+ * @param image image to resize
+ * @param bufferWidth destination buffer width
+ * @param bufferHeight destination buffer height
+ * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size
+ */
+ resizeImageBitmap(image, bufferWidth, bufferHeight) {
+ return ResizeImageBitmap(this, image, bufferWidth, bufferHeight);
+ }
+ /**
+ * Engine abstraction for loading and creating an image bitmap from a given source string.
+ * @param imageSource source to load the image from.
+ * @param options An object that sets options for the image's extraction.
+ * @returns ImageBitmap
+ */
+ _createImageBitmapFromSource(imageSource, options) {
+ return CreateImageBitmapFromSource(this, imageSource, options);
+ }
+ /**
+ * Toggle full screen mode
+ * @param requestPointerLock defines if a pointer lock should be requested from the user
+ */
+ switchFullscreen(requestPointerLock) {
+ if (this.isFullscreen) {
+ this.exitFullscreen();
+ }
+ else {
+ this.enterFullscreen(requestPointerLock);
+ }
+ }
+ /**
+ * Enters full screen mode
+ * @param requestPointerLock defines if a pointer lock should be requested from the user
+ */
+ enterFullscreen(requestPointerLock) {
+ if (!this.isFullscreen) {
+ this._pointerLockRequested = requestPointerLock;
+ if (this._renderingCanvas) {
+ RequestFullscreen(this._renderingCanvas);
+ }
+ }
+ }
+ /**
+ * Exits full screen mode
+ */
+ exitFullscreen() {
+ if (this.isFullscreen) {
+ ExitFullscreen();
+ }
+ }
+ /** States */
+ /**
+ * Sets a boolean indicating if the dithering state is enabled or disabled
+ * @param value defines the dithering state
+ */
+ setDitheringState(value) {
+ if (value) {
+ this._gl.enable(this._gl.DITHER);
+ }
+ else {
+ this._gl.disable(this._gl.DITHER);
+ }
+ }
+ /**
+ * Sets a boolean indicating if the rasterizer state is enabled or disabled
+ * @param value defines the rasterizer state
+ */
+ setRasterizerState(value) {
+ if (value) {
+ this._gl.disable(this._gl.RASTERIZER_DISCARD);
+ }
+ else {
+ this._gl.enable(this._gl.RASTERIZER_DISCARD);
+ }
+ }
+ /**
+ * Directly set the WebGL Viewport
+ * @param x defines the x coordinate of the viewport (in screen space)
+ * @param y defines the y coordinate of the viewport (in screen space)
+ * @param width defines the width of the viewport (in screen space)
+ * @param height defines the height of the viewport (in screen space)
+ * @returns the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
+ */
+ setDirectViewport(x, y, width, height) {
+ const currentViewport = this._cachedViewport;
+ this._cachedViewport = null;
+ this._viewport(x, y, width, height);
+ return currentViewport;
+ }
+ /**
+ * Executes a scissor clear (ie. a clear on a specific portion of the screen)
+ * @param x defines the x-coordinate of the bottom left corner of the clear rectangle
+ * @param y defines the y-coordinate of the corner of the clear rectangle
+ * @param width defines the width of the clear rectangle
+ * @param height defines the height of the clear rectangle
+ * @param clearColor defines the clear color
+ */
+ scissorClear(x, y, width, height, clearColor) {
+ this.enableScissor(x, y, width, height);
+ this.clear(clearColor, true, true, true);
+ this.disableScissor();
+ }
+ /**
+ * Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen)
+ * @param x defines the x-coordinate of the bottom left corner of the clear rectangle
+ * @param y defines the y-coordinate of the corner of the clear rectangle
+ * @param width defines the width of the clear rectangle
+ * @param height defines the height of the clear rectangle
+ */
+ enableScissor(x, y, width, height) {
+ const gl = this._gl;
+ // Change state
+ gl.enable(gl.SCISSOR_TEST);
+ gl.scissor(x, y, width, height);
+ }
+ /**
+ * Disable previously set scissor test rectangle
+ */
+ disableScissor() {
+ const gl = this._gl;
+ gl.disable(gl.SCISSOR_TEST);
+ }
+ /**
+ * @internal
+ */
+ _loadFileAsync(url, offlineProvider, useArrayBuffer) {
+ return new Promise((resolve, reject) => {
+ this._loadFile(url, (data) => {
+ resolve(data);
+ }, undefined, offlineProvider, useArrayBuffer, (request, exception) => {
+ reject(exception);
+ });
+ });
+ }
+ /**
+ * Gets the source code of the vertex shader associated with a specific webGL program
+ * @param program defines the program to use
+ * @returns a string containing the source code of the vertex shader associated with the program
+ */
+ getVertexShaderSource(program) {
+ const shaders = this._gl.getAttachedShaders(program);
+ if (!shaders) {
+ return null;
+ }
+ return this._gl.getShaderSource(shaders[0]);
+ }
+ /**
+ * Gets the source code of the fragment shader associated with a specific webGL program
+ * @param program defines the program to use
+ * @returns a string containing the source code of the fragment shader associated with the program
+ */
+ getFragmentShaderSource(program) {
+ const shaders = this._gl.getAttachedShaders(program);
+ if (!shaders) {
+ return null;
+ }
+ return this._gl.getShaderSource(shaders[1]);
+ }
+ /**
+ * sets the object from which width and height will be taken from when getting render width and height
+ * Will fallback to the gl object
+ * @param dimensions the framebuffer width and height that will be used.
+ */
+ set framebufferDimensionsObject(dimensions) {
+ this._framebufferDimensionsObject = dimensions;
+ if (this._framebufferDimensionsObject) {
+ this.onResizeObservable.notifyObservers(this);
+ }
+ }
+ _rebuildBuffers() {
+ // Index / Vertex
+ for (const scene of this.scenes) {
+ scene.resetCachedMaterial();
+ scene._rebuildGeometries();
+ }
+ for (const scene of this._virtualScenes) {
+ scene.resetCachedMaterial();
+ scene._rebuildGeometries();
+ }
+ super._rebuildBuffers();
+ }
+ /**
+ * Get Font size information
+ * @param font font name
+ * @returns an object containing ascent, height and descent
+ */
+ getFontOffset(font) {
+ return GetFontOffset(font);
+ }
+ _cancelFrame() {
+ if (this.customAnimationFrameRequester) {
+ if (this._frameHandler !== 0) {
+ this._frameHandler = 0;
+ const { cancelAnimationFrame } = this.customAnimationFrameRequester;
+ if (cancelAnimationFrame) {
+ cancelAnimationFrame(this.customAnimationFrameRequester.requestID);
+ }
+ }
+ }
+ else {
+ super._cancelFrame();
+ }
+ }
+ _renderLoop(timestamp) {
+ this._processFrame(timestamp);
+ // The first condition prevents queuing another frame if we no longer have active render loops (e.g., if
+ // `stopRenderLoop` is called mid frame). The second condition prevents queuing another frame if one has
+ // already been queued (e.g., if `stopRenderLoop` and `runRenderLoop` is called mid frame).
+ if (this._activeRenderLoops.length > 0 && this._frameHandler === 0) {
+ if (this.customAnimationFrameRequester) {
+ this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester);
+ this._frameHandler = this.customAnimationFrameRequester.requestID;
+ }
+ else {
+ this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
+ }
+ }
+ }
+ /**
+ * Enters Pointerlock mode
+ */
+ enterPointerlock() {
+ if (this._renderingCanvas) {
+ RequestPointerlock(this._renderingCanvas);
+ }
+ }
+ /**
+ * Exits Pointerlock mode
+ */
+ exitPointerlock() {
+ ExitPointerlock();
+ }
+ /**
+ * Begin a new frame
+ */
+ beginFrame() {
+ this._measureFps();
+ super.beginFrame();
+ }
+ _deletePipelineContext(pipelineContext) {
+ const webGLPipelineContext = pipelineContext;
+ if (webGLPipelineContext && webGLPipelineContext.program) {
+ if (webGLPipelineContext.transformFeedback) {
+ this.deleteTransformFeedback(webGLPipelineContext.transformFeedback);
+ webGLPipelineContext.transformFeedback = null;
+ }
+ }
+ super._deletePipelineContext(pipelineContext);
+ }
+ createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) {
+ context = context || this._gl;
+ this.onBeforeShaderCompilationObservable.notifyObservers(this);
+ const program = super.createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings);
+ this.onAfterShaderCompilationObservable.notifyObservers(this);
+ return program;
+ }
+ _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) {
+ const shaderProgram = context.createProgram();
+ pipelineContext.program = shaderProgram;
+ if (!shaderProgram) {
+ throw new Error("Unable to create program");
+ }
+ context.attachShader(shaderProgram, vertexShader);
+ context.attachShader(shaderProgram, fragmentShader);
+ if (this.webGLVersion > 1 && transformFeedbackVaryings) {
+ const transformFeedback = this.createTransformFeedback();
+ this.bindTransformFeedback(transformFeedback);
+ this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
+ pipelineContext.transformFeedback = transformFeedback;
+ }
+ context.linkProgram(shaderProgram);
+ if (this.webGLVersion > 1 && transformFeedbackVaryings) {
+ this.bindTransformFeedback(null);
+ }
+ pipelineContext.context = context;
+ pipelineContext.vertexShader = vertexShader;
+ pipelineContext.fragmentShader = fragmentShader;
+ if (!pipelineContext.isParallelCompiled) {
+ this._finalizePipelineContext(pipelineContext);
+ }
+ return shaderProgram;
+ }
+ /**
+ * @internal
+ */
+ _releaseTexture(texture) {
+ super._releaseTexture(texture);
+ }
+ /**
+ * @internal
+ */
+ _releaseRenderTargetWrapper(rtWrapper) {
+ super._releaseRenderTargetWrapper(rtWrapper);
+ // Set output texture of post process to null if the framebuffer has been released/disposed
+ this.scenes.forEach((scene) => {
+ scene.postProcesses.forEach((postProcess) => {
+ if (postProcess._outputTexture === rtWrapper) {
+ postProcess._outputTexture = null;
+ }
+ });
+ scene.cameras.forEach((camera) => {
+ camera._postProcesses.forEach((postProcess) => {
+ if (postProcess) {
+ if (postProcess._outputTexture === rtWrapper) {
+ postProcess._outputTexture = null;
+ }
+ }
+ });
+ });
+ });
+ }
+ /**
+ * @internal
+ * Rescales a texture
+ * @param source input texture
+ * @param destination destination texture
+ * @param scene scene to use to render the resize
+ * @param internalFormat format to use when resizing
+ * @param onComplete callback to be called when resize has completed
+ */
+ _rescaleTexture(source, destination, scene, internalFormat, onComplete) {
+ this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
+ this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
+ this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
+ this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
+ const rtt = this.createRenderTargetTexture({
+ width: destination.width,
+ height: destination.height,
+ }, {
+ generateMipMaps: false,
+ type: 0,
+ samplingMode: 2,
+ generateDepthBuffer: false,
+ generateStencilBuffer: false,
+ });
+ if (!this._rescalePostProcess && Engine._RescalePostProcessFactory) {
+ this._rescalePostProcess = Engine._RescalePostProcessFactory(this);
+ }
+ if (this._rescalePostProcess) {
+ this._rescalePostProcess.externalTextureSamplerBinding = true;
+ const onCompiled = () => {
+ this._rescalePostProcess.onApply = function (effect) {
+ effect._bindTexture("textureSampler", source);
+ };
+ let hostingScene = scene;
+ if (!hostingScene) {
+ hostingScene = this.scenes[this.scenes.length - 1];
+ }
+ hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
+ this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
+ this.unBindFramebuffer(rtt);
+ rtt.dispose();
+ if (onComplete) {
+ onComplete();
+ }
+ };
+ const effect = this._rescalePostProcess.getEffect();
+ if (effect) {
+ effect.executeWhenCompiled(onCompiled);
+ }
+ else {
+ this._rescalePostProcess.onEffectCreatedObservable.addOnce((effect) => {
+ effect.executeWhenCompiled(onCompiled);
+ });
+ }
+ }
+ }
+ /**
+ * Wraps an external web gl texture in a Babylon texture.
+ * @param texture defines the external texture
+ * @param hasMipMaps defines whether the external texture has mip maps (default: false)
+ * @param samplingMode defines the sampling mode for the external texture (default: 3)
+ * @param width defines the width for the external texture (default: 0)
+ * @param height defines the height for the external texture (default: 0)
+ * @returns the babylon internal texture
+ */
+ wrapWebGLTexture(texture, hasMipMaps = false, samplingMode = 3, width = 0, height = 0) {
+ const hardwareTexture = new WebGLHardwareTexture(texture, this._gl);
+ const internalTexture = new InternalTexture(this, 0 /* InternalTextureSource.Unknown */, true);
+ internalTexture._hardwareTexture = hardwareTexture;
+ internalTexture.baseWidth = width;
+ internalTexture.baseHeight = height;
+ internalTexture.width = width;
+ internalTexture.height = height;
+ internalTexture.isReady = true;
+ internalTexture.useMipMaps = hasMipMaps;
+ this.updateTextureSamplingMode(samplingMode, internalTexture);
+ return internalTexture;
+ }
+ /**
+ * @internal
+ */
+ _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {
+ const gl = this._gl;
+ const textureType = this._getWebGLTextureType(texture.type);
+ const format = this._getInternalFormat(texture.format);
+ const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
+ const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
+ this._bindTextureDirectly(bindTarget, texture, true);
+ this._unpackFlipY(texture.invertY);
+ let target = gl.TEXTURE_2D;
+ if (texture.isCube) {
+ target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
+ }
+ gl.texImage2D(target, lod, internalFormat, format, textureType, image);
+ this._bindTextureDirectly(bindTarget, null, true);
+ }
+ /**
+ * Updates a depth texture Comparison Mode and Function.
+ * If the comparison Function is equal to 0, the mode will be set to none.
+ * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
+ * @param texture The texture to set the comparison function for
+ * @param comparisonFunction The comparison function to set, 0 if no comparison required
+ */
+ updateTextureComparisonFunction(texture, comparisonFunction) {
+ if (this.webGLVersion === 1) {
+ Logger.Error("WebGL 1 does not support texture comparison.");
+ return;
+ }
+ const gl = this._gl;
+ if (texture.isCube) {
+ this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
+ if (comparisonFunction === 0) {
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, 515);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
+ }
+ else {
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
+ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
+ }
+ this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
+ }
+ else {
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
+ if (comparisonFunction === 0) {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, 515);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
+ }
+ else {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
+ }
+ this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
+ }
+ texture._comparisonFunction = comparisonFunction;
+ }
+ /**
+ * Creates a webGL buffer to use with instantiation
+ * @param capacity defines the size of the buffer
+ * @returns the webGL buffer
+ */
+ createInstancesBuffer(capacity) {
+ const buffer = this._gl.createBuffer();
+ if (!buffer) {
+ throw new Error("Unable to create instance buffer");
+ }
+ const result = new WebGLDataBuffer(buffer);
+ result.capacity = capacity;
+ this.bindArrayBuffer(result);
+ this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
+ result.references = 1;
+ return result;
+ }
+ /**
+ * Delete a webGL buffer used with instantiation
+ * @param buffer defines the webGL buffer to delete
+ */
+ deleteInstancesBuffer(buffer) {
+ this._gl.deleteBuffer(buffer);
+ }
+ _clientWaitAsync(sync, flags = 0, intervalms = 10) {
+ const gl = this._gl;
+ return new Promise((resolve, reject) => {
+ _retryWithInterval(() => {
+ const res = gl.clientWaitSync(sync, flags, 0);
+ if (res == gl.WAIT_FAILED) {
+ throw new Error("clientWaitSync failed");
+ }
+ if (res == gl.TIMEOUT_EXPIRED) {
+ return false;
+ }
+ return true;
+ }, resolve, reject, intervalms);
+ });
+ }
+ /**
+ * @internal
+ */
+ _readPixelsAsync(x, y, w, h, format, type, outputBuffer) {
+ if (this._webGLVersion < 2) {
+ throw new Error("_readPixelsAsync only work on WebGL2+");
+ }
+ const gl = this._gl;
+ const buf = gl.createBuffer();
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);
+ gl.bufferData(gl.PIXEL_PACK_BUFFER, outputBuffer.byteLength, gl.STREAM_READ);
+ gl.readPixels(x, y, w, h, format, type, 0);
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
+ const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
+ if (!sync) {
+ return null;
+ }
+ gl.flush();
+ return this._clientWaitAsync(sync, 0, 10).then(() => {
+ gl.deleteSync(sync);
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);
+ gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, outputBuffer);
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
+ gl.deleteBuffer(buf);
+ return outputBuffer;
+ });
+ }
+ dispose() {
+ this.hideLoadingUI();
+ // Rescale PP
+ if (this._rescalePostProcess) {
+ this._rescalePostProcess.dispose();
+ }
+ _CommonDispose(this, this._renderingCanvas);
+ super.dispose();
+ }
+}
+// Const statics
+/** Defines that alpha blending is disabled */
+Engine.ALPHA_DISABLE = 0;
+/** Defines that alpha blending to SRC ALPHA * SRC + DEST */
+Engine.ALPHA_ADD = 1;
+/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
+Engine.ALPHA_COMBINE = 2;
+/** Defines that alpha blending to DEST - SRC * DEST */
+Engine.ALPHA_SUBTRACT = 3;
+/** Defines that alpha blending to SRC * DEST */
+Engine.ALPHA_MULTIPLY = 4;
+/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
+Engine.ALPHA_MAXIMIZED = 5;
+/** Defines that alpha blending to SRC + DEST */
+Engine.ALPHA_ONEONE = 6;
+/** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
+Engine.ALPHA_PREMULTIPLIED = 7;
+/**
+ * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
+ * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
+ */
+Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
+/** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
+Engine.ALPHA_INTERPOLATE = 9;
+/**
+ * Defines that alpha blending to SRC + (1 - SRC) * DEST
+ * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
+ */
+Engine.ALPHA_SCREENMODE = 10;
+/** Defines that the resource is not delayed*/
+Engine.DELAYLOADSTATE_NONE = 0;
+/** Defines that the resource was successfully delay loaded */
+Engine.DELAYLOADSTATE_LOADED = 1;
+/** Defines that the resource is currently delay loading */
+Engine.DELAYLOADSTATE_LOADING = 2;
+/** Defines that the resource is delayed and has not started loading */
+Engine.DELAYLOADSTATE_NOTLOADED = 4;
+// Depht or Stencil test Constants.
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
+Engine.NEVER = 512;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
+Engine.ALWAYS = 519;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
+Engine.LESS = 513;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
+Engine.EQUAL = 514;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
+Engine.LEQUAL = 515;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
+Engine.GREATER = 516;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
+Engine.GEQUAL = 518;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
+Engine.NOTEQUAL = 517;
+// Stencil Actions Constants.
+/** Passed to stencilOperation to specify that stencil value must be kept */
+Engine.KEEP = 7680;
+/** Passed to stencilOperation to specify that stencil value must be replaced */
+Engine.REPLACE = 7681;
+/** Passed to stencilOperation to specify that stencil value must be incremented */
+Engine.INCR = 7682;
+/** Passed to stencilOperation to specify that stencil value must be decremented */
+Engine.DECR = 7683;
+/** Passed to stencilOperation to specify that stencil value must be inverted */
+Engine.INVERT = 5386;
+/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
+Engine.INCR_WRAP = 34055;
+/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
+Engine.DECR_WRAP = 34056;
+/** Texture is not repeating outside of 0..1 UVs */
+Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
+/** Texture is repeating outside of 0..1 UVs */
+Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
+/** Texture is repeating and mirrored */
+Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
+/** ALPHA */
+Engine.TEXTUREFORMAT_ALPHA = 0;
+/** LUMINANCE */
+Engine.TEXTUREFORMAT_LUMINANCE = 1;
+/** LUMINANCE_ALPHA */
+Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
+/** RGB */
+Engine.TEXTUREFORMAT_RGB = 4;
+/** RGBA */
+Engine.TEXTUREFORMAT_RGBA = 5;
+/** RED */
+Engine.TEXTUREFORMAT_RED = 6;
+/** RED (2nd reference) */
+Engine.TEXTUREFORMAT_R = 6;
+/** RED unsigned short normed to [0, 1] **/
+Engine.TEXTUREFORMAT_R16_UNORM = 33322;
+/** RG unsigned short normed to [0, 1] **/
+Engine.TEXTUREFORMAT_RG16_UNORM = 33324;
+/** RGB unsigned short normed to [0, 1] **/
+Engine.TEXTUREFORMAT_RGB16_UNORM = 32852;
+/** RGBA unsigned short normed to [0, 1] **/
+Engine.TEXTUREFORMAT_RGBA16_UNORM = 32859;
+/** RED signed short normed to [-1, 1] **/
+Engine.TEXTUREFORMAT_R16_SNORM = 36760;
+/** RG signed short normed to [-1, 1] **/
+Engine.TEXTUREFORMAT_RG16_SNORM = 36761;
+/** RGB signed short normed to [-1, 1] **/
+Engine.TEXTUREFORMAT_RGB16_SNORM = 36762;
+/** RGBA signed short normed to [-1, 1] **/
+Engine.TEXTUREFORMAT_RGBA16_SNORM = 36763;
+/** RG */
+Engine.TEXTUREFORMAT_RG = 7;
+/** RED_INTEGER */
+Engine.TEXTUREFORMAT_RED_INTEGER = 8;
+/** RED_INTEGER (2nd reference) */
+Engine.TEXTUREFORMAT_R_INTEGER = 8;
+/** RG_INTEGER */
+Engine.TEXTUREFORMAT_RG_INTEGER = 9;
+/** RGB_INTEGER */
+Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
+/** RGBA_INTEGER */
+Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
+/** UNSIGNED_BYTE */
+Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
+/** @deprecated use more explicit TEXTURETYPE_UNSIGNED_BYTE instead. Use TEXTURETYPE_UNSIGNED_INTEGER for 32bits values.*/
+Engine.TEXTURETYPE_UNSIGNED_INT = 0;
+/** FLOAT */
+Engine.TEXTURETYPE_FLOAT = 1;
+/** HALF_FLOAT */
+Engine.TEXTURETYPE_HALF_FLOAT = 2;
+/** BYTE */
+Engine.TEXTURETYPE_BYTE = 3;
+/** SHORT */
+Engine.TEXTURETYPE_SHORT = 4;
+/** UNSIGNED_SHORT */
+Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
+/** INT */
+Engine.TEXTURETYPE_INT = 6;
+/** UNSIGNED_INT */
+Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
+/** UNSIGNED_SHORT_4_4_4_4 */
+Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
+/** UNSIGNED_SHORT_5_5_5_1 */
+Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
+/** UNSIGNED_SHORT_5_6_5 */
+Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
+/** UNSIGNED_INT_2_10_10_10_REV */
+Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
+/** UNSIGNED_INT_24_8 */
+Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
+/** UNSIGNED_INT_10F_11F_11F_REV */
+Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
+/** UNSIGNED_INT_5_9_9_9_REV */
+Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
+/** FLOAT_32_UNSIGNED_INT_24_8_REV */
+Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
+/** nearest is mag = nearest and min = nearest and mip = none */
+Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
+/** Bilinear is mag = linear and min = linear and mip = nearest */
+Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
+/** Trilinear is mag = linear and min = linear and mip = linear */
+Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
+/** nearest is mag = nearest and min = nearest and mip = linear */
+Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;
+/** Bilinear is mag = linear and min = linear and mip = nearest */
+Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;
+/** Trilinear is mag = linear and min = linear and mip = linear */
+Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
+/** mag = nearest and min = nearest and mip = nearest */
+Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
+/** mag = nearest and min = linear and mip = nearest */
+Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
+/** mag = nearest and min = linear and mip = linear */
+Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
+/** mag = nearest and min = linear and mip = none */
+Engine.TEXTURE_NEAREST_LINEAR = 7;
+/** mag = nearest and min = nearest and mip = none */
+Engine.TEXTURE_NEAREST_NEAREST = 1;
+/** mag = linear and min = nearest and mip = nearest */
+Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
+/** mag = linear and min = nearest and mip = linear */
+Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
+/** mag = linear and min = linear and mip = none */
+Engine.TEXTURE_LINEAR_LINEAR = 2;
+/** mag = linear and min = nearest and mip = none */
+Engine.TEXTURE_LINEAR_NEAREST = 12;
+/** Explicit coordinates mode */
+Engine.TEXTURE_EXPLICIT_MODE = 0;
+/** Spherical coordinates mode */
+Engine.TEXTURE_SPHERICAL_MODE = 1;
+/** Planar coordinates mode */
+Engine.TEXTURE_PLANAR_MODE = 2;
+/** Cubic coordinates mode */
+Engine.TEXTURE_CUBIC_MODE = 3;
+/** Projection coordinates mode */
+Engine.TEXTURE_PROJECTION_MODE = 4;
+/** Skybox coordinates mode */
+Engine.TEXTURE_SKYBOX_MODE = 5;
+/** Inverse Cubic coordinates mode */
+Engine.TEXTURE_INVCUBIC_MODE = 6;
+/** Equirectangular coordinates mode */
+Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
+/** Equirectangular Fixed coordinates mode */
+Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
+/** Equirectangular Fixed Mirrored coordinates mode */
+Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
+// Texture rescaling mode
+/** Defines that texture rescaling will use a floor to find the closer power of 2 size */
+Engine.SCALEMODE_FLOOR = 1;
+/** Defines that texture rescaling will look for the nearest power of 2 size */
+Engine.SCALEMODE_NEAREST = 2;
+/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
+Engine.SCALEMODE_CEILING = 3;
+
+class Monobehiver {
+ mainApp;
+ constructor(mainApp) {
+ this.mainApp = mainApp;
+ }
+ /** 醒来/初始化,子类可重写 */
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
+ Awake() {
+ }
+}
+
+const AppConfig = {
+ container: document.querySelector("#renderDom"),
+ modelUrlList: [],
+ env: {
+ envPath: "/hdr/sanGiuseppeBridge.env",
+ intensity: 1.5,
+ rotationY: 0,
+ background: true
+ }
+};
+
+class AppEngin extends Monobehiver {
+ object;
+ canvas;
+ constructor(mainApp) {
+ super(mainApp);
+ this.object = null;
+ this.canvas = null;
+ }
+ Awake() {
+ this.canvas = AppConfig.container;
+ if (!this.canvas) {
+ throw new Error("Render canvas not found");
+ }
+ this.object = new Engine(this.canvas, true, {
+ preserveDrawingBuffer: false,
+ // 不保留绘图缓冲区
+ stencil: true,
+ // 启用模板缓冲
+ alpha: true
+ // 启用透明背景
+ });
+ this.object.setSize(window.innerWidth, window.innerHeight);
+ this.object.setHardwareScalingLevel(1);
+ }
+ /** 处理窗口大小变化 */
+ handleResize() {
+ if (this.object) {
+ this.object.setSize(window.innerWidth, window.innerHeight);
+ this.object.resize();
+ }
+ }
+}
+
+const CloneValue = (source, destinationObject, shallowCopyValues) => {
+ if (!source) {
+ return null;
+ }
+ if (source.getClassName && source.getClassName() === "Mesh") {
+ return null;
+ }
+ if (source.getClassName && (source.getClassName() === "SubMesh" || source.getClassName() === "PhysicsBody")) {
+ return source.clone(destinationObject);
+ }
+ else if (source.clone) {
+ return source.clone();
+ }
+ else if (Array.isArray(source)) {
+ return source.slice();
+ }
+ else if (shallowCopyValues && typeof source === "object") {
+ return { ...source };
+ }
+ return null;
+};
+function GetAllPropertyNames(obj) {
+ const props = [];
+ do {
+ Object.getOwnPropertyNames(obj).forEach(function (prop) {
+ if (props.indexOf(prop) === -1) {
+ props.push(prop);
+ }
+ });
+ } while ((obj = Object.getPrototypeOf(obj)));
+ return props;
+}
+/**
+ * Class containing a set of static utilities functions for deep copy.
+ */
+class DeepCopier {
+ /**
+ * Tries to copy an object by duplicating every property
+ * @param source defines the source object
+ * @param destination defines the target object
+ * @param doNotCopyList defines a list of properties to avoid
+ * @param mustCopyList defines a list of properties to copy (even if they start with _)
+ * @param shallowCopyValues defines wether properties referencing objects (none cloneable) must be shallow copied (false by default)
+ * @remarks shallowCopyValues will not instantite the copied values which makes it only usable for "JSON objects"
+ */
+ static DeepCopy(source, destination, doNotCopyList, mustCopyList, shallowCopyValues = false) {
+ const properties = GetAllPropertyNames(source);
+ for (const prop of properties) {
+ if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
+ continue;
+ }
+ if (prop.endsWith("Observable")) {
+ continue;
+ }
+ if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
+ continue;
+ }
+ const sourceValue = source[prop];
+ const typeOfSourceValue = typeof sourceValue;
+ if (typeOfSourceValue === "function") {
+ continue;
+ }
+ try {
+ if (typeOfSourceValue === "object") {
+ if (sourceValue instanceof Uint8Array) {
+ destination[prop] = Uint8Array.from(sourceValue);
+ }
+ else if (sourceValue instanceof Array) {
+ destination[prop] = [];
+ if (sourceValue.length > 0) {
+ if (typeof sourceValue[0] == "object") {
+ for (let index = 0; index < sourceValue.length; index++) {
+ const clonedValue = CloneValue(sourceValue[index], destination, shallowCopyValues);
+ if (destination[prop].indexOf(clonedValue) === -1) {
+ // Test if auto inject was not done
+ destination[prop].push(clonedValue);
+ }
+ }
+ }
+ else {
+ destination[prop] = sourceValue.slice(0);
+ }
+ }
+ }
+ else {
+ destination[prop] = CloneValue(sourceValue, destination, shallowCopyValues);
+ }
+ }
+ else {
+ destination[prop] = sourceValue;
+ }
+ }
+ catch (e) {
+ // Log a warning (it could be because of a read-only property)
+ Logger.Warn(e.message);
+ }
+ }
+ }
+}
+
+/**
+ * Class used to enable instantiation of objects by class name
+ */
+class InstantiationTools {
+ /**
+ * Tries to instantiate a new object from a given class name
+ * @param className defines the class name to instantiate
+ * @returns the new object or null if the system was not able to do the instantiation
+ */
+ static Instantiate(className) {
+ if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[className]) {
+ return this.RegisteredExternalClasses[className];
+ }
+ const internalClass = GetClass(className);
+ if (internalClass) {
+ return internalClass;
+ }
+ Logger.Warn(className + " not found, you may have missed an import.");
+ const arr = className.split(".");
+ let fn = window || this;
+ for (let i = 0, len = arr.length; i < len; i++) {
+ fn = fn[arr[i]];
+ }
+ if (typeof fn !== "function") {
+ return null;
+ }
+ return fn;
+ }
+}
+/**
+ * Use this object to register external classes like custom textures or material
+ * to allow the loaders to instantiate them
+ */
+InstantiationTools.RegisteredExternalClasses = {};
+
+/**
+ * Class containing a set of static utilities functions
+ */
+class Tools {
+ /**
+ * Gets or sets the base URL to use to load assets
+ */
+ static get BaseUrl() {
+ return FileToolsOptions.BaseUrl;
+ }
+ static set BaseUrl(value) {
+ FileToolsOptions.BaseUrl = value;
+ }
+ /**
+ * Gets or sets the clean URL function to use to load assets
+ */
+ static get CleanUrl() {
+ return FileToolsOptions.CleanUrl;
+ }
+ static set CleanUrl(value) {
+ FileToolsOptions.CleanUrl = value;
+ }
+ /**
+ * This function checks whether a URL is absolute or not.
+ * It will also detect data and blob URLs
+ * @param url the url to check
+ * @returns is the url absolute or relative
+ */
+ static IsAbsoluteUrl(url) {
+ // See https://stackoverflow.com/a/38979205.
+ // URL is protocol-relative (= absolute)
+ if (url.indexOf("//") === 0) {
+ return true;
+ }
+ // URL has no protocol (= relative)
+ if (url.indexOf("://") === -1) {
+ return false;
+ }
+ // URL does not contain a dot, i.e. no TLD (= relative, possibly REST)
+ if (url.indexOf(".") === -1) {
+ return false;
+ }
+ // URL does not contain a single slash (= relative)
+ if (url.indexOf("/") === -1) {
+ return false;
+ }
+ // The first colon comes after the first slash (= relative)
+ if (url.indexOf(":") > url.indexOf("/")) {
+ return false;
+ }
+ // Protocol is defined before first dot (= absolute)
+ if (url.indexOf("://") < url.indexOf(".")) {
+ return true;
+ }
+ if (url.indexOf("data:") === 0 || url.indexOf("blob:") === 0) {
+ return true;
+ }
+ // Anything else must be relative
+ return false;
+ }
+ /**
+ * Sets the base URL to use to load scripts
+ */
+ static set ScriptBaseUrl(value) {
+ FileToolsOptions.ScriptBaseUrl = value;
+ }
+ static get ScriptBaseUrl() {
+ return FileToolsOptions.ScriptBaseUrl;
+ }
+ /**
+ * Sets both the script base URL and the assets base URL to the same value.
+ * Setter only!
+ */
+ static set CDNBaseUrl(value) {
+ Tools.ScriptBaseUrl = value;
+ Tools.AssetBaseUrl = value;
+ }
+ /**
+ * Sets a preprocessing function to run on a source URL before importing it
+ * Note that this function will execute AFTER the base URL is appended to the URL
+ */
+ static set ScriptPreprocessUrl(func) {
+ FileToolsOptions.ScriptPreprocessUrl = func;
+ }
+ static get ScriptPreprocessUrl() {
+ return FileToolsOptions.ScriptPreprocessUrl;
+ }
+ /**
+ * Gets or sets the retry strategy to apply when an error happens while loading an asset
+ */
+ static get DefaultRetryStrategy() {
+ return FileToolsOptions.DefaultRetryStrategy;
+ }
+ static set DefaultRetryStrategy(strategy) {
+ FileToolsOptions.DefaultRetryStrategy = strategy;
+ }
+ /**
+ * Default behavior for cors in the application.
+ * It can be a string if the expected behavior is identical in the entire app.
+ * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
+ */
+ static get CorsBehavior() {
+ return FileToolsOptions.CorsBehavior;
+ }
+ static set CorsBehavior(value) {
+ FileToolsOptions.CorsBehavior = value;
+ }
+ /**
+ * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
+ * @ignorenaming
+ */
+ static get UseFallbackTexture() {
+ return EngineStore.UseFallbackTexture;
+ }
+ static set UseFallbackTexture(value) {
+ EngineStore.UseFallbackTexture = value;
+ }
+ /**
+ * Use this object to register external classes like custom textures or material
+ * to allow the loaders to instantiate them
+ */
+ static get RegisteredExternalClasses() {
+ return InstantiationTools.RegisteredExternalClasses;
+ }
+ static set RegisteredExternalClasses(classes) {
+ InstantiationTools.RegisteredExternalClasses = classes;
+ }
+ /**
+ * Texture content used if a texture cannot loaded
+ * @ignorenaming
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static get fallbackTexture() {
+ return EngineStore.FallbackTexture;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static set fallbackTexture(value) {
+ EngineStore.FallbackTexture = value;
+ }
+ /**
+ * Read the content of a byte array at a specified coordinates (taking in account wrapping)
+ * @param u defines the coordinate on X axis
+ * @param v defines the coordinate on Y axis
+ * @param width defines the width of the source data
+ * @param height defines the height of the source data
+ * @param pixels defines the source byte array
+ * @param color defines the output color
+ */
+ static FetchToRef(u, v, width, height, pixels, color) {
+ const wrappedU = (Math.abs(u) * width) % width | 0;
+ const wrappedV = (Math.abs(v) * height) % height | 0;
+ const position = (wrappedU + wrappedV * width) * 4;
+ color.r = pixels[position] / 255;
+ color.g = pixels[position + 1] / 255;
+ color.b = pixels[position + 2] / 255;
+ color.a = pixels[position + 3] / 255;
+ }
+ /**
+ * Interpolates between a and b via alpha
+ * @param a The lower value (returned when alpha = 0)
+ * @param b The upper value (returned when alpha = 1)
+ * @param alpha The interpolation-factor
+ * @returns The mixed value
+ */
+ static Mix(a, b, alpha) {
+ return 0;
+ }
+ /**
+ * Tries to instantiate a new object from a given class name
+ * @param className defines the class name to instantiate
+ * @returns the new object or null if the system was not able to do the instantiation
+ */
+ static Instantiate(className) {
+ return InstantiationTools.Instantiate(className);
+ }
+ /**
+ * Polyfill for setImmediate
+ * @param action defines the action to execute after the current execution block
+ */
+ static SetImmediate(action) {
+ TimingTools.SetImmediate(action);
+ }
+ /**
+ * Function indicating if a number is an exponent of 2
+ * @param value defines the value to test
+ * @returns true if the value is an exponent of 2
+ */
+ static IsExponentOfTwo(value) {
+ return true;
+ }
+ /**
+ * Returns the nearest 32-bit single precision float representation of a Number
+ * @param value A Number. If the parameter is of a different type, it will get converted
+ * to a number or to NaN if it cannot be converted
+ * @returns number
+ */
+ static FloatRound(value) {
+ return Math.fround(value);
+ }
+ /**
+ * Extracts the filename from a path
+ * @param path defines the path to use
+ * @returns the filename
+ */
+ static GetFilename(path) {
+ const index = path.lastIndexOf("/");
+ if (index < 0) {
+ return path;
+ }
+ return path.substring(index + 1);
+ }
+ /**
+ * Extracts the "folder" part of a path (everything before the filename).
+ * @param uri The URI to extract the info from
+ * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
+ * @returns The "folder" part of the path
+ */
+ static GetFolderPath(uri, returnUnchangedIfNoSlash = false) {
+ const index = uri.lastIndexOf("/");
+ if (index < 0) {
+ if (returnUnchangedIfNoSlash) {
+ return uri;
+ }
+ return "";
+ }
+ return uri.substring(0, index + 1);
+ }
+ /**
+ * Convert an angle in radians to degrees
+ * @param angle defines the angle to convert
+ * @returns the angle in degrees
+ */
+ static ToDegrees(angle) {
+ return (angle * 180) / Math.PI;
+ }
+ /**
+ * Convert an angle in degrees to radians
+ * @param angle defines the angle to convert
+ * @returns the angle in radians
+ */
+ static ToRadians(angle) {
+ return (angle * Math.PI) / 180;
+ }
+ /**
+ * Smooth angle changes (kind of low-pass filter), in particular for device orientation "shaking"
+ * Use trigonometric functions to avoid discontinuity (0/360, -180/180)
+ * @param previousAngle defines last angle value, in degrees
+ * @param newAngle defines new angle value, in degrees
+ * @param smoothFactor defines smoothing sensitivity; min 0: no smoothing, max 1: new data ignored
+ * @returns the angle in degrees
+ */
+ static SmoothAngleChange(previousAngle, newAngle, smoothFactor = 0.9) {
+ const previousAngleRad = this.ToRadians(previousAngle);
+ const newAngleRad = this.ToRadians(newAngle);
+ return this.ToDegrees(Math.atan2((1 - smoothFactor) * Math.sin(newAngleRad) + smoothFactor * Math.sin(previousAngleRad), (1 - smoothFactor) * Math.cos(newAngleRad) + smoothFactor * Math.cos(previousAngleRad)));
+ }
+ /**
+ * Returns an array if obj is not an array
+ * @param obj defines the object to evaluate as an array
+ * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
+ * @returns either obj directly if obj is an array or a new array containing obj
+ */
+ static MakeArray(obj, allowsNullUndefined) {
+ if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
+ return null;
+ }
+ return Array.isArray(obj) ? obj : [obj];
+ }
+ /**
+ * Gets the pointer prefix to use
+ * @param engine defines the engine we are finding the prefix for
+ * @returns "pointer" if touch is enabled. Else returns "mouse"
+ */
+ static GetPointerPrefix(engine) {
+ return IsWindowObjectExist() && !window.PointerEvent ? "mouse" : "pointer";
+ }
+ /**
+ * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
+ * @param url define the url we are trying
+ * @param element define the dom element where to configure the cors policy
+ * @param element.crossOrigin
+ */
+ static SetCorsBehavior(url, element) {
+ SetCorsBehavior(url, element);
+ }
+ /**
+ * Sets the referrerPolicy behavior on a dom element.
+ * @param referrerPolicy define the referrer policy to use
+ * @param element define the dom element where to configure the referrer policy
+ * @param element.referrerPolicy
+ */
+ static SetReferrerPolicyBehavior(referrerPolicy, element) {
+ element.referrerPolicy = referrerPolicy;
+ }
+ // External files
+ /**
+ * Gets or sets a function used to pre-process url before using them to load assets
+ */
+ static get PreprocessUrl() {
+ return FileToolsOptions.PreprocessUrl;
+ }
+ static set PreprocessUrl(processor) {
+ FileToolsOptions.PreprocessUrl = processor;
+ }
+ /**
+ * Loads an image as an HTMLImageElement.
+ * @param input url string, ArrayBuffer, or Blob to load
+ * @param onLoad callback called when the image successfully loads
+ * @param onError callback called when the image fails to load
+ * @param offlineProvider offline provider for caching
+ * @param mimeType optional mime type
+ * @param imageBitmapOptions optional the options to use when creating an ImageBitmap
+ * @returns the HTMLImageElement of the loaded image
+ */
+ static LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions) {
+ return LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions);
+ }
+ /**
+ * Loads a file from a url
+ * @param url url string, ArrayBuffer, or Blob to load
+ * @param onSuccess callback called when the file successfully loads
+ * @param onProgress callback called while file is loading (if the server supports this mode)
+ * @param offlineProvider defines the offline provider for caching
+ * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
+ * @param onError callback called when the file fails to load
+ * @returns a file request object
+ */
+ static LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
+ return LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
+ }
+ /**
+ * Loads a file from a url
+ * @param url the file url to load
+ * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
+ * @returns a promise containing an ArrayBuffer corresponding to the loaded file
+ */
+ static LoadFileAsync(url, useArrayBuffer = true) {
+ return new Promise((resolve, reject) => {
+ LoadFile(url, (data) => {
+ resolve(data);
+ }, undefined, undefined, useArrayBuffer, (request, exception) => {
+ reject(exception);
+ });
+ });
+ }
+ /**
+ * This function will convert asset URLs if the AssetBaseUrl parameter is set.
+ * Any URL with `assets.babylonjs.com/core` will be replaced with the value of AssetBaseUrl.
+ * @param url the URL to convert
+ * @returns a new URL
+ */
+ static GetAssetUrl(url) {
+ if (!url) {
+ return "";
+ }
+ if (Tools.AssetBaseUrl && url.startsWith(Tools._DefaultAssetsUrl)) {
+ // normalize the baseUrl
+ const baseUrl = Tools.AssetBaseUrl[Tools.AssetBaseUrl.length - 1] === "/" ? Tools.AssetBaseUrl.substring(0, Tools.AssetBaseUrl.length - 1) : Tools.AssetBaseUrl;
+ return url.replace(Tools._DefaultAssetsUrl, baseUrl);
+ }
+ return url;
+ }
+ /**
+ * Get a script URL including preprocessing
+ * @param scriptUrl the script Url to process
+ * @param forceAbsoluteUrl force the script to be an absolute url (adding the current base url if necessary)
+ * @returns a modified URL to use
+ */
+ static GetBabylonScriptURL(scriptUrl, forceAbsoluteUrl) {
+ if (!scriptUrl) {
+ return "";
+ }
+ // if the base URL was set, and the script Url is an absolute path change the default path
+ if (Tools.ScriptBaseUrl && scriptUrl.startsWith(Tools._DefaultCdnUrl)) {
+ // change the default host, which is https://cdn.babylonjs.com with the one defined
+ // make sure no trailing slash is present
+ const baseUrl = Tools.ScriptBaseUrl[Tools.ScriptBaseUrl.length - 1] === "/" ? Tools.ScriptBaseUrl.substring(0, Tools.ScriptBaseUrl.length - 1) : Tools.ScriptBaseUrl;
+ scriptUrl = scriptUrl.replace(Tools._DefaultCdnUrl, baseUrl);
+ }
+ // run the preprocessor
+ scriptUrl = Tools.ScriptPreprocessUrl(scriptUrl);
+ if (forceAbsoluteUrl) {
+ scriptUrl = Tools.GetAbsoluteUrl(scriptUrl);
+ }
+ return scriptUrl;
+ }
+ /**
+ * This function is used internally by babylon components to load a script (identified by an url). When the url returns, the
+ * content of this file is added into a new script element, attached to the DOM (body element)
+ * @param scriptUrl defines the url of the script to load
+ * @param onSuccess defines the callback called when the script is loaded
+ * @param onError defines the callback to call if an error occurs
+ * @param scriptId defines the id of the script element
+ */
+ static LoadBabylonScript(scriptUrl, onSuccess, onError, scriptId) {
+ scriptUrl = Tools.GetBabylonScriptURL(scriptUrl);
+ Tools.LoadScript(scriptUrl, onSuccess, onError);
+ }
+ /**
+ * Load an asynchronous script (identified by an url). When the url returns, the
+ * content of this file is added into a new script element, attached to the DOM (body element)
+ * @param scriptUrl defines the url of the script to laod
+ * @returns a promise request object
+ */
+ static LoadBabylonScriptAsync(scriptUrl) {
+ scriptUrl = Tools.GetBabylonScriptURL(scriptUrl);
+ return Tools.LoadScriptAsync(scriptUrl);
+ }
+ /**
+ * This function is used internally by babylon components to load a script (identified by an url). When the url returns, the
+ * content of this file is added into a new script element, attached to the DOM (body element)
+ * @param scriptUrl defines the url of the script to load
+ * @param onSuccess defines the callback called when the script is loaded
+ * @param onError defines the callback to call if an error occurs
+ * @param scriptId defines the id of the script element
+ * @param useModule defines if we should use the module strategy to load the script
+ */
+ static LoadScript(scriptUrl, onSuccess, onError, scriptId, useModule = false) {
+ if (typeof importScripts === "function") {
+ try {
+ importScripts(scriptUrl);
+ if (onSuccess) {
+ onSuccess();
+ }
+ }
+ catch (e) {
+ onError?.(`Unable to load script '${scriptUrl}' in worker`, e);
+ }
+ return;
+ }
+ else if (!IsWindowObjectExist()) {
+ onError?.(`Cannot load script '${scriptUrl}' outside of a window or a worker`);
+ return;
+ }
+ const head = document.getElementsByTagName("head")[0];
+ const script = document.createElement("script");
+ if (useModule) {
+ script.setAttribute("type", "module");
+ script.innerText = scriptUrl;
+ }
+ else {
+ script.setAttribute("type", "text/javascript");
+ script.setAttribute("src", scriptUrl);
+ }
+ if (scriptId) {
+ script.id = scriptId;
+ }
+ script.onload = () => {
+ if (onSuccess) {
+ onSuccess();
+ }
+ };
+ script.onerror = (e) => {
+ if (onError) {
+ onError(`Unable to load script '${scriptUrl}'`, e);
+ }
+ };
+ head.appendChild(script);
+ }
+ /**
+ * Load an asynchronous script (identified by an url). When the url returns, the
+ * content of this file is added into a new script element, attached to the DOM (body element)
+ * @param scriptUrl defines the url of the script to load
+ * @param scriptId defines the id of the script element
+ * @returns a promise request object
+ */
+ static LoadScriptAsync(scriptUrl, scriptId) {
+ return new Promise((resolve, reject) => {
+ this.LoadScript(scriptUrl, () => {
+ resolve();
+ }, (message, exception) => {
+ reject(exception || new Error(message));
+ }, scriptId);
+ });
+ }
+ /**
+ * Loads a file from a blob
+ * @param fileToLoad defines the blob to use
+ * @param callback defines the callback to call when data is loaded
+ * @param progressCallback defines the callback to call during loading process
+ * @returns a file request object
+ */
+ static ReadFileAsDataURL(fileToLoad, callback, progressCallback) {
+ const reader = new FileReader();
+ const request = {
+ onCompleteObservable: new Observable(),
+ abort: () => reader.abort(),
+ };
+ reader.onloadend = () => {
+ request.onCompleteObservable.notifyObservers(request);
+ };
+ reader.onload = (e) => {
+ //target doesn't have result from ts 1.3
+ callback(e.target["result"]);
+ };
+ reader.onprogress = progressCallback;
+ reader.readAsDataURL(fileToLoad);
+ return request;
+ }
+ /**
+ * Reads a file from a File object
+ * @param file defines the file to load
+ * @param onSuccess defines the callback to call when data is loaded
+ * @param onProgress defines the callback to call during loading process
+ * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
+ * @param onError defines the callback to call when an error occurs
+ * @returns a file request object
+ */
+ static ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError) {
+ return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError);
+ }
+ /**
+ * Creates a data url from a given string content
+ * @param content defines the content to convert
+ * @returns the new data url link
+ */
+ static FileAsURL(content) {
+ const fileBlob = new Blob([content]);
+ const url = window.URL;
+ const link = url.createObjectURL(fileBlob);
+ return link;
+ }
+ /**
+ * Format the given number to a specific decimal format
+ * @param value defines the number to format
+ * @param decimals defines the number of decimals to use
+ * @returns the formatted string
+ */
+ static Format(value, decimals = 2) {
+ return value.toFixed(decimals);
+ }
+ /**
+ * Tries to copy an object by duplicating every property
+ * @param source defines the source object
+ * @param destination defines the target object
+ * @param doNotCopyList defines a list of properties to avoid
+ * @param mustCopyList defines a list of properties to copy (even if they start with _)
+ */
+ static DeepCopy(source, destination, doNotCopyList, mustCopyList) {
+ DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);
+ }
+ /**
+ * Gets a boolean indicating if the given object has no own property
+ * @param obj defines the object to test
+ * @returns true if object has no own property
+ */
+ static IsEmpty(obj) {
+ for (const i in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, i)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Function used to register events at window level
+ * @param windowElement defines the Window object to use
+ * @param events defines the events to register
+ */
+ static RegisterTopRootEvents(windowElement, events) {
+ for (let index = 0; index < events.length; index++) {
+ const event = events[index];
+ windowElement.addEventListener(event.name, event.handler, false);
+ try {
+ if (window.parent) {
+ window.parent.addEventListener(event.name, event.handler, false);
+ }
+ }
+ catch (e) {
+ // Silently fails...
+ }
+ }
+ }
+ /**
+ * Function used to unregister events from window level
+ * @param windowElement defines the Window object to use
+ * @param events defines the events to unregister
+ */
+ static UnregisterTopRootEvents(windowElement, events) {
+ for (let index = 0; index < events.length; index++) {
+ const event = events[index];
+ windowElement.removeEventListener(event.name, event.handler);
+ try {
+ if (windowElement.parent) {
+ windowElement.parent.removeEventListener(event.name, event.handler);
+ }
+ }
+ catch (e) {
+ // Silently fails...
+ }
+ }
+ }
+ /**
+ * Dumps the current bound framebuffer
+ * @param width defines the rendering width
+ * @param height defines the rendering height
+ * @param engine defines the hosting engine
+ * @param successCallback defines the callback triggered once the data are available
+ * @param mimeType defines the mime type of the result
+ * @param fileName defines the filename to download. If present, the result will automatically be downloaded
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ * @returns a void promise
+ */
+ static async DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) {
+ throw _WarnImport("DumpTools");
+ }
+ /**
+ * Dumps an array buffer
+ * @param width defines the rendering width
+ * @param height defines the rendering height
+ * @param data the data array
+ * @param successCallback defines the callback triggered once the data are available
+ * @param mimeType defines the mime type of the result
+ * @param fileName defines the filename to download. If present, the result will automatically be downloaded
+ * @param invertY true to invert the picture in the Y dimension
+ * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ */
+ static DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) {
+ throw _WarnImport("DumpTools");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Dumps an array buffer
+ * @param width defines the rendering width
+ * @param height defines the rendering height
+ * @param data the data array
+ * @param mimeType defines the mime type of the result
+ * @param fileName defines the filename to download. If present, the result will automatically be downloaded
+ * @param invertY true to invert the picture in the Y dimension
+ * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ * @returns a promise that resolve to the final data
+ */
+ static DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) {
+ throw _WarnImport("DumpTools");
+ }
+ static _IsOffScreenCanvas(canvas) {
+ return canvas.convertToBlob !== undefined;
+ }
+ /**
+ * Converts the canvas data to blob.
+ * This acts as a polyfill for browsers not supporting the to blob function.
+ * @param canvas Defines the canvas to extract the data from (can be an offscreen canvas)
+ * @param successCallback Defines the callback triggered once the data are available
+ * @param mimeType Defines the mime type of the result
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ */
+ static ToBlob(canvas, successCallback, mimeType = "image/png", quality) {
+ // We need HTMLCanvasElement.toBlob for HD screenshots
+ if (!Tools._IsOffScreenCanvas(canvas) && !canvas.toBlob) {
+ // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
+ canvas.toBlob = function (callback, type, quality) {
+ setTimeout(() => {
+ const binStr = atob(this.toDataURL(type, quality).split(",")[1]), len = binStr.length, arr = new Uint8Array(len);
+ for (let i = 0; i < len; i++) {
+ arr[i] = binStr.charCodeAt(i);
+ }
+ callback(new Blob([arr]));
+ });
+ };
+ }
+ if (Tools._IsOffScreenCanvas(canvas)) {
+ canvas
+ .convertToBlob({
+ type: mimeType,
+ quality,
+ })
+ .then((blob) => successCallback(blob));
+ }
+ else {
+ canvas.toBlob(function (blob) {
+ successCallback(blob);
+ }, mimeType, quality);
+ }
+ }
+ /**
+ * Download a Blob object
+ * @param blob the Blob object
+ * @param fileName the file name to download
+ */
+ static DownloadBlob(blob, fileName) {
+ //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
+ if ("download" in document.createElement("a")) {
+ if (!fileName) {
+ const date = new Date();
+ const stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ("0" + date.getMinutes()).slice(-2);
+ fileName = "screenshot_" + stringDate + ".png";
+ }
+ Tools.Download(blob, fileName);
+ }
+ else {
+ if (blob && typeof URL !== "undefined") {
+ const url = URL.createObjectURL(blob);
+ const newWindow = window.open("");
+ if (!newWindow) {
+ return;
+ }
+ const img = newWindow.document.createElement("img");
+ img.onload = function () {
+ // no longer need to read the blob so it's revoked
+ URL.revokeObjectURL(url);
+ };
+ img.src = url;
+ newWindow.document.body.appendChild(img);
+ }
+ }
+ }
+ /**
+ * Encodes the canvas data to base 64, or automatically downloads the result if `fileName` is defined.
+ * @param canvas The canvas to get the data from, which can be an offscreen canvas.
+ * @param successCallback The callback which is triggered once the data is available. If `fileName` is defined, the callback will be invoked after the download occurs, and the `data` argument will be an empty string.
+ * @param mimeType The mime type of the result.
+ * @param fileName The name of the file to download. If defined, the result will automatically be downloaded. If not defined, and `successCallback` is also not defined, the result will automatically be downloaded with an auto-generated file name.
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ */
+ static EncodeScreenshotCanvasData(canvas, successCallback, mimeType = "image/png", fileName, quality) {
+ if (typeof fileName === "string" || !successCallback) {
+ this.ToBlob(canvas, function (blob) {
+ if (blob) {
+ Tools.DownloadBlob(blob, fileName);
+ }
+ if (successCallback) {
+ successCallback("");
+ }
+ }, mimeType, quality);
+ }
+ else if (successCallback) {
+ if (Tools._IsOffScreenCanvas(canvas)) {
+ canvas
+ .convertToBlob({
+ type: mimeType,
+ quality,
+ })
+ .then((blob) => {
+ const reader = new FileReader();
+ reader.readAsDataURL(blob);
+ reader.onloadend = () => {
+ const base64data = reader.result;
+ successCallback(base64data);
+ };
+ });
+ return;
+ }
+ const base64Image = canvas.toDataURL(mimeType, quality);
+ successCallback(base64Image);
+ }
+ }
+ /**
+ * Downloads a blob in the browser
+ * @param blob defines the blob to download
+ * @param fileName defines the name of the downloaded file
+ */
+ static Download(blob, fileName) {
+ if (typeof URL === "undefined") {
+ return;
+ }
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ document.body.appendChild(a);
+ a.style.display = "none";
+ a.href = url;
+ a.download = fileName;
+ a.addEventListener("click", () => {
+ if (a.parentElement) {
+ a.parentElement.removeChild(a);
+ }
+ });
+ a.click();
+ window.URL.revokeObjectURL(url);
+ }
+ /**
+ * Will return the right value of the noPreventDefault variable
+ * Needed to keep backwards compatibility to the old API.
+ *
+ * @param args arguments passed to the attachControl function
+ * @returns the correct value for noPreventDefault
+ */
+ static BackCompatCameraNoPreventDefault(args) {
+ // is it used correctly?
+ if (typeof args[0] === "boolean") {
+ return args[0];
+ }
+ else if (typeof args[1] === "boolean") {
+ return args[1];
+ }
+ return false;
+ }
+ /**
+ * Captures a screenshot of the current rendering
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG
+ * @param engine defines the rendering engine
+ * @param camera defines the source camera
+ * @param size This parameter can be set to a single number or to an object with the
+ * following (optional) properties: precision, width, height. If a single number is passed,
+ * it will be used for both width and height. If an object is passed, the screenshot size
+ * will be derived from the parameters. The precision property is a multiplier allowing
+ * rendering at a higher or lower resolution
+ * @param successCallback defines the callback receives a single parameter which contains the
+ * screenshot as a string of base64-encoded characters. This string can be assigned to the
+ * src parameter of an
to display it
+ * @param mimeType defines the MIME type of the screenshot image (default: image/png).
+ * Check your browser for supported MIME types
+ * @param forceDownload force the system to download the image even if a successCallback is provided
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static CreateScreenshot(engine, camera, size, successCallback, mimeType = "image/png", forceDownload = false, quality) {
+ throw _WarnImport("ScreenshotTools");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Captures a screenshot of the current rendering
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG
+ * @param engine defines the rendering engine
+ * @param camera defines the source camera
+ * @param size This parameter can be set to a single number or to an object with the
+ * following (optional) properties: precision, width, height. If a single number is passed,
+ * it will be used for both width and height. If an object is passed, the screenshot size
+ * will be derived from the parameters. The precision property is a multiplier allowing
+ * rendering at a higher or lower resolution
+ * @param mimeType defines the MIME type of the screenshot image (default: image/png).
+ * Check your browser for supported MIME types
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ * @returns screenshot as a string of base64-encoded characters. This string can be assigned
+ * to the src parameter of an
to display it
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static CreateScreenshotAsync(engine, camera, size, mimeType = "image/png", quality) {
+ throw _WarnImport("ScreenshotTools");
+ }
+ /**
+ * Generates an image screenshot from the specified camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG
+ * @param engine The engine to use for rendering
+ * @param camera The camera to use for rendering
+ * @param size This parameter can be set to a single number or to an object with the
+ * following (optional) properties: precision, width, height. If a single number is passed,
+ * it will be used for both width and height. If an object is passed, the screenshot size
+ * will be derived from the parameters. The precision property is a multiplier allowing
+ * rendering at a higher or lower resolution
+ * @param successCallback The callback receives a single parameter which contains the
+ * screenshot as a string of base64-encoded characters. This string can be assigned to the
+ * src parameter of an
to display it
+ * @param mimeType The MIME type of the screenshot image (default: image/png).
+ * Check your browser for supported MIME types
+ * @param samples Texture samples (default: 1)
+ * @param antialiasing Whether antialiasing should be turned on or not (default: false)
+ * @param fileName A name for for the downloaded file.
+ * @param renderSprites Whether the sprites should be rendered or not (default: false)
+ * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)
+ * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ * @param customizeTexture An optional callback that can be used to modify the render target texture before taking the screenshot. This can be used, for instance, to enable camera post-processes before taking the screenshot.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture) {
+ throw _WarnImport("ScreenshotTools");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Generates an image screenshot from the specified camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG
+ * @param engine The engine to use for rendering
+ * @param camera The camera to use for rendering
+ * @param size This parameter can be set to a single number or to an object with the
+ * following (optional) properties: precision, width, height. If a single number is passed,
+ * it will be used for both width and height. If an object is passed, the screenshot size
+ * will be derived from the parameters. The precision property is a multiplier allowing
+ * rendering at a higher or lower resolution
+ * @param mimeType The MIME type of the screenshot image (default: image/png).
+ * Check your browser for supported MIME types
+ * @param samples Texture samples (default: 1)
+ * @param antialiasing Whether antialiasing should be turned on or not (default: false)
+ * @param fileName A name for for the downloaded file.
+ * @param renderSprites Whether the sprites should be rendered or not (default: false)
+ * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)
+ * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)
+ * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.
+ * @param customizeTexture An optional callback that can be used to modify the render target texture before taking the screenshot. This can be used, for instance, to enable camera post-processes before taking the screenshot.
+ * @returns screenshot as a string of base64-encoded characters. This string can be assigned
+ * to the src parameter of an
to display it
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture) {
+ throw _WarnImport("ScreenshotTools");
+ }
+ /**
+ * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
+ * Be aware Math.random() could cause collisions, but:
+ * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
+ * @returns a pseudo random id
+ */
+ static RandomId() {
+ return RandomGUID();
+ }
+ /**
+ * Test if the given uri is a base64 string
+ * @deprecated Please use FileTools.IsBase64DataUrl instead.
+ * @param uri The uri to test
+ * @returns True if the uri is a base64 string or false otherwise
+ */
+ static IsBase64(uri) {
+ return IsBase64DataUrl(uri);
+ }
+ /**
+ * Decode the given base64 uri.
+ * @deprecated Please use FileTools.DecodeBase64UrlToBinary instead.
+ * @param uri The uri to decode
+ * @returns The decoded base64 data.
+ */
+ static DecodeBase64(uri) {
+ return DecodeBase64UrlToBinary(uri);
+ }
+ /**
+ * Gets a value indicating the number of loading errors
+ * @ignorenaming
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static get errorsCount() {
+ return Logger.errorsCount;
+ }
+ /**
+ * Log a message to the console
+ * @param message defines the message to log
+ */
+ static Log(message) {
+ Logger.Log(message);
+ }
+ /**
+ * Write a warning message to the console
+ * @param message defines the message to log
+ */
+ static Warn(message) {
+ Logger.Warn(message);
+ }
+ /**
+ * Write an error message to the console
+ * @param message defines the message to log
+ */
+ static Error(message) {
+ Logger.Error(message);
+ }
+ /**
+ * Gets current log cache (list of logs)
+ */
+ static get LogCache() {
+ return Logger.LogCache;
+ }
+ /**
+ * Clears the log cache
+ */
+ static ClearLogCache() {
+ Logger.ClearLogCache();
+ }
+ /**
+ * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
+ */
+ static set LogLevels(level) {
+ Logger.LogLevels = level;
+ }
+ /**
+ * Sets the current performance log level
+ */
+ static set PerformanceLogLevel(level) {
+ if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
+ Tools.StartPerformanceCounter = Tools._StartUserMark;
+ Tools.EndPerformanceCounter = Tools._EndUserMark;
+ return;
+ }
+ if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
+ Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
+ Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
+ return;
+ }
+ Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
+ Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static _StartPerformanceCounterDisabled(counterName, condition) { }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static _EndPerformanceCounterDisabled(counterName, condition) { }
+ static _StartUserMark(counterName, condition = true) {
+ if (!Tools._Performance) {
+ if (!IsWindowObjectExist()) {
+ return;
+ }
+ Tools._Performance = window.performance;
+ }
+ if (!condition || !Tools._Performance.mark) {
+ return;
+ }
+ Tools._Performance.mark(counterName + "-Begin");
+ }
+ static _EndUserMark(counterName, condition = true) {
+ if (!condition || !Tools._Performance.mark) {
+ return;
+ }
+ Tools._Performance.mark(counterName + "-End");
+ Tools._Performance.measure(counterName, counterName + "-Begin", counterName + "-End");
+ }
+ static _StartPerformanceConsole(counterName, condition = true) {
+ if (!condition) {
+ return;
+ }
+ Tools._StartUserMark(counterName, condition);
+ if (console.time) {
+ console.time(counterName);
+ }
+ }
+ static _EndPerformanceConsole(counterName, condition = true) {
+ if (!condition) {
+ return;
+ }
+ Tools._EndUserMark(counterName, condition);
+ console.timeEnd(counterName);
+ }
+ /**
+ * Gets either window.performance.now() if supported or Date.now() else
+ */
+ static get Now() {
+ return PrecisionDate.Now;
+ }
+ /**
+ * This method will return the name of the class used to create the instance of the given object.
+ * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
+ * @param object the object to get the class name from
+ * @param isType defines if the object is actually a type
+ * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
+ */
+ static GetClassName(object, isType = false) {
+ let name = null;
+ if (!isType && object.getClassName) {
+ name = object.getClassName();
+ }
+ else {
+ if (object instanceof Object) {
+ const classObj = isType ? object : Object.getPrototypeOf(object);
+ name = classObj.constructor["__bjsclassName__"];
+ }
+ if (!name) {
+ name = typeof object;
+ }
+ }
+ return name;
+ }
+ /**
+ * Gets the first element of an array satisfying a given predicate
+ * @param array defines the array to browse
+ * @param predicate defines the predicate to use
+ * @returns null if not found or the element
+ */
+ static First(array, predicate) {
+ for (const el of array) {
+ if (predicate(el)) {
+ return el;
+ }
+ }
+ return null;
+ }
+ /**
+ * This method will return the name of the full name of the class, including its owning module (if any).
+ * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
+ * @param object the object to get the class name from
+ * @param isType defines if the object is actually a type
+ * @returns a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
+ * @ignorenaming
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static getFullClassName(object, isType = false) {
+ let className = null;
+ let moduleName = null;
+ if (!isType && object.getClassName) {
+ className = object.getClassName();
+ }
+ else {
+ if (object instanceof Object) {
+ const classObj = isType ? object : Object.getPrototypeOf(object);
+ className = classObj.constructor["__bjsclassName__"];
+ moduleName = classObj.constructor["__bjsmoduleName__"];
+ }
+ if (!className) {
+ className = typeof object;
+ }
+ }
+ if (!className) {
+ return null;
+ }
+ return (moduleName != null ? moduleName + "." : "") + className;
+ }
+ /**
+ * Returns a promise that resolves after the given amount of time.
+ * @param delay Number of milliseconds to delay
+ * @returns Promise that resolves after the given amount of time
+ */
+ static DelayAsync(delay) {
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ resolve();
+ }, delay);
+ });
+ }
+ /**
+ * Utility function to detect if the current user agent is Safari
+ * @returns whether or not the current user agent is safari
+ */
+ static IsSafari() {
+ if (!IsNavigatorAvailable()) {
+ return false;
+ }
+ return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
+ }
+}
+/**
+ * The base URL to use to load assets. If empty the default base url is used.
+ */
+Tools.AssetBaseUrl = "";
+/**
+ * Enable/Disable Custom HTTP Request Headers globally.
+ * default = false
+ * @see CustomRequestHeaders
+ */
+Tools.UseCustomRequestHeaders = false;
+/**
+ * Custom HTTP Request Headers to be sent with XMLHttpRequests
+ * i.e. when loading files, where the server/service expects an Authorization header
+ */
+Tools.CustomRequestHeaders = WebRequest.CustomRequestHeaders;
+/**
+ * Extracts text content from a DOM element hierarchy
+ * Back Compat only, please use GetDOMTextContent instead.
+ */
+Tools.GetDOMTextContent = GetDOMTextContent;
+/**
+ * @internal
+ */
+Tools._DefaultCdnUrl = "https://cdn.babylonjs.com";
+/**
+ * @internal
+ */
+Tools._DefaultAssetsUrl = "https://assets.babylonjs.com/core";
+// eslint-disable-next-line jsdoc/require-returns-check, jsdoc/require-param
+/**
+ * @returns the absolute URL of a given (relative) url
+ */
+Tools.GetAbsoluteUrl = typeof document === "object"
+ ? (url) => {
+ const a = document.createElement("a");
+ a.href = url;
+ return a.href;
+ }
+ : typeof URL === "function" && typeof location === "object"
+ ? (url) => new URL(url, location.origin).href
+ : () => {
+ throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.");
+ };
+// Logs
+/**
+ * No log
+ */
+Tools.NoneLogLevel = Logger.NoneLogLevel;
+/**
+ * Only message logs
+ */
+Tools.MessageLogLevel = Logger.MessageLogLevel;
+/**
+ * Only warning logs
+ */
+Tools.WarningLogLevel = Logger.WarningLogLevel;
+/**
+ * Only error logs
+ */
+Tools.ErrorLogLevel = Logger.ErrorLogLevel;
+/**
+ * All logs
+ */
+Tools.AllLogLevel = Logger.AllLogLevel;
+/**
+ * Checks if the window object exists
+ * Back Compat only, please use IsWindowObjectExist instead.
+ */
+Tools.IsWindowObjectExist = IsWindowObjectExist;
+// Performances
+/**
+ * No performance log
+ */
+Tools.PerformanceNoneLogLevel = 0;
+/**
+ * Use user marks to log performance
+ */
+Tools.PerformanceUserMarkLogLevel = 1;
+/**
+ * Log performance to the console
+ */
+Tools.PerformanceConsoleLogLevel = 2;
+/**
+ * Starts a performance counter
+ */
+Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
+/**
+ * Ends a specific performance counter
+ */
+Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
+/**
+ * An implementation of a loop for asynchronous functions.
+ */
+class AsyncLoop {
+ /**
+ * Constructor.
+ * @param iterations the number of iterations.
+ * @param func the function to run each iteration
+ * @param successCallback the callback that will be called upon successful execution
+ * @param offset starting offset.
+ */
+ constructor(
+ /**
+ * Defines the number of iterations for the loop
+ */
+ iterations, func, successCallback, offset = 0) {
+ this.iterations = iterations;
+ this.index = offset - 1;
+ this._done = false;
+ this._fn = func;
+ this._successCallback = successCallback;
+ }
+ /**
+ * Execute the next iteration. Must be called after the last iteration was finished.
+ */
+ executeNext() {
+ if (!this._done) {
+ if (this.index + 1 < this.iterations) {
+ ++this.index;
+ this._fn(this);
+ }
+ else {
+ this.breakLoop();
+ }
+ }
+ }
+ /**
+ * Break the loop and run the success callback.
+ */
+ breakLoop() {
+ this._done = true;
+ this._successCallback();
+ }
+ /**
+ * Create and run an async loop.
+ * @param iterations the number of iterations.
+ * @param fn the function to run each iteration
+ * @param successCallback the callback that will be called upon successful execution
+ * @param offset starting offset.
+ * @returns the created async loop object
+ */
+ static Run(iterations, fn, successCallback, offset = 0) {
+ const loop = new AsyncLoop(iterations, fn, successCallback, offset);
+ loop.executeNext();
+ return loop;
+ }
+ /**
+ * A for-loop that will run a given number of iterations synchronous and the rest async.
+ * @param iterations total number of iterations
+ * @param syncedIterations number of synchronous iterations in each async iteration.
+ * @param fn the function to call each iteration.
+ * @param callback a success call back that will be called when iterating stops.
+ * @param breakFunction a break condition (optional)
+ * @param timeout timeout settings for the setTimeout function. default - 0.
+ * @returns the created async loop object
+ */
+ static SyncAsyncForLoop(iterations, syncedIterations, fn, callback, breakFunction, timeout = 0) {
+ return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop) => {
+ if (breakFunction && breakFunction()) {
+ loop.breakLoop();
+ }
+ else {
+ setTimeout(() => {
+ for (let i = 0; i < syncedIterations; ++i) {
+ const iteration = loop.index * syncedIterations + i;
+ if (iteration >= iterations) {
+ break;
+ }
+ fn(iteration);
+ if (breakFunction && breakFunction()) {
+ loop.breakLoop();
+ break;
+ }
+ }
+ loop.executeNext();
+ }, timeout);
+ }
+ }, callback);
+ }
+}
+Tools.Mix = Mix;
+Tools.IsExponentOfTwo = IsExponentOfTwo;
+// Will only be define if Tools is imported freeing up some space when only engine is required
+EngineStore.FallbackTexture =
+ "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
+
+/**
+ * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
+ */
+class SmartArray {
+ /**
+ * Instantiates a Smart Array.
+ * @param capacity defines the default capacity of the array.
+ */
+ constructor(capacity) {
+ /**
+ * The active length of the array.
+ */
+ this.length = 0;
+ this.data = new Array(capacity);
+ this._id = SmartArray._GlobalId++;
+ }
+ /**
+ * Pushes a value at the end of the active data.
+ * @param value defines the object to push in the array.
+ */
+ push(value) {
+ this.data[this.length++] = value;
+ if (this.length > this.data.length) {
+ this.data.length *= 2;
+ }
+ }
+ /**
+ * Iterates over the active data and apply the lambda to them.
+ * @param func defines the action to apply on each value.
+ */
+ forEach(func) {
+ for (let index = 0; index < this.length; index++) {
+ func(this.data[index]);
+ }
+ }
+ /**
+ * Sorts the full sets of data.
+ * @param compareFn defines the comparison function to apply.
+ */
+ sort(compareFn) {
+ this.data.sort(compareFn);
+ }
+ /**
+ * Resets the active data to an empty array.
+ */
+ reset() {
+ this.length = 0;
+ }
+ /**
+ * Releases all the data from the array as well as the array.
+ */
+ dispose() {
+ this.reset();
+ if (this.data) {
+ this.data.length = 0;
+ }
+ }
+ /**
+ * Concats the active data with a given array.
+ * @param array defines the data to concatenate with.
+ */
+ concat(array) {
+ if (array.length === 0) {
+ return;
+ }
+ if (this.length + array.length > this.data.length) {
+ this.data.length = (this.length + array.length) * 2;
+ }
+ for (let index = 0; index < array.length; index++) {
+ this.data[this.length++] = (array.data || array)[index];
+ }
+ }
+ /**
+ * Returns the position of a value in the active data.
+ * @param value defines the value to find the index for
+ * @returns the index if found in the active data otherwise -1
+ */
+ indexOf(value) {
+ const position = this.data.indexOf(value);
+ if (position >= this.length) {
+ return -1;
+ }
+ return position;
+ }
+ /**
+ * Returns whether an element is part of the active data.
+ * @param value defines the value to look for
+ * @returns true if found in the active data otherwise false
+ */
+ contains(value) {
+ return this.indexOf(value) !== -1;
+ }
+}
+// Statics
+SmartArray._GlobalId = 0;
+/**
+ * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
+ * The data in this array can only be present once
+ */
+class SmartArrayNoDuplicate extends SmartArray {
+ constructor() {
+ super(...arguments);
+ this._duplicateId = 0;
+ }
+ /**
+ * Pushes a value at the end of the active data.
+ * THIS DOES NOT PREVENT DUPPLICATE DATA
+ * @param value defines the object to push in the array.
+ */
+ push(value) {
+ super.push(value);
+ if (!value.__smartArrayFlags) {
+ value.__smartArrayFlags = {};
+ }
+ value.__smartArrayFlags[this._id] = this._duplicateId;
+ }
+ /**
+ * Pushes a value at the end of the active data.
+ * If the data is already present, it won t be added again
+ * @param value defines the object to push in the array.
+ * @returns true if added false if it was already present
+ */
+ pushNoDuplicate(value) {
+ if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
+ return false;
+ }
+ this.push(value);
+ return true;
+ }
+ /**
+ * Resets the active data to an empty array.
+ */
+ reset() {
+ super.reset();
+ this._duplicateId++;
+ }
+ /**
+ * Concats the active data with a given array.
+ * This ensures no duplicate will be present in the result.
+ * @param array defines the data to concatenate with.
+ */
+ concatWithNoDuplicate(array) {
+ if (array.length === 0) {
+ return;
+ }
+ if (this.length + array.length > this.data.length) {
+ this.data.length = (this.length + array.length) * 2;
+ }
+ for (let index = 0; index < array.length; index++) {
+ const item = (array.data || array)[index];
+ this.pushNoDuplicate(item);
+ }
+ }
+}
+
+/**
+ * This class implement a typical dictionary using a string as key and the generic type T as value.
+ * The underlying implementation relies on an associative array to ensure the best performances.
+ * The value can be anything including 'null' but except 'undefined'
+ */
+class StringDictionary {
+ constructor() {
+ this._count = 0;
+ this._data = {};
+ }
+ /**
+ * This will clear this dictionary and copy the content from the 'source' one.
+ * If the T value is a custom object, it won't be copied/cloned, the same object will be used
+ * @param source the dictionary to take the content from and copy to this dictionary
+ */
+ copyFrom(source) {
+ this.clear();
+ source.forEach((t, v) => this.add(t, v));
+ }
+ /**
+ * Get a value based from its key
+ * @param key the given key to get the matching value from
+ * @returns the value if found, otherwise undefined is returned
+ */
+ get(key) {
+ const val = this._data[key];
+ if (val !== undefined) {
+ return val;
+ }
+ return undefined;
+ }
+ /**
+ * Get a value from its key or add it if it doesn't exist.
+ * This method will ensure you that a given key/data will be present in the dictionary.
+ * @param key the given key to get the matching value from
+ * @param factory the factory that will create the value if the key is not present in the dictionary.
+ * The factory will only be invoked if there's no data for the given key.
+ * @returns the value corresponding to the key.
+ */
+ getOrAddWithFactory(key, factory) {
+ let val = this.get(key);
+ if (val !== undefined) {
+ return val;
+ }
+ val = factory(key);
+ if (val) {
+ this.add(key, val);
+ }
+ return val;
+ }
+ /**
+ * Get a value from its key if present in the dictionary otherwise add it
+ * @param key the key to get the value from
+ * @param val if there's no such key/value pair in the dictionary add it with this value
+ * @returns the value corresponding to the key
+ */
+ getOrAdd(key, val) {
+ const curVal = this.get(key);
+ if (curVal !== undefined) {
+ return curVal;
+ }
+ this.add(key, val);
+ return val;
+ }
+ /**
+ * Check if there's a given key in the dictionary
+ * @param key the key to check for
+ * @returns true if the key is present, false otherwise
+ */
+ contains(key) {
+ return this._data[key] !== undefined;
+ }
+ /**
+ * Add a new key and its corresponding value
+ * @param key the key to add
+ * @param value the value corresponding to the key
+ * @returns true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
+ */
+ add(key, value) {
+ if (this._data[key] !== undefined) {
+ return false;
+ }
+ this._data[key] = value;
+ ++this._count;
+ return true;
+ }
+ /**
+ * Update a specific value associated to a key
+ * @param key defines the key to use
+ * @param value defines the value to store
+ * @returns true if the value was updated (or false if the key was not found)
+ */
+ set(key, value) {
+ if (this._data[key] === undefined) {
+ return false;
+ }
+ this._data[key] = value;
+ return true;
+ }
+ /**
+ * Get the element of the given key and remove it from the dictionary
+ * @param key defines the key to search
+ * @returns the value associated with the key or null if not found
+ */
+ getAndRemove(key) {
+ const val = this.get(key);
+ if (val !== undefined) {
+ delete this._data[key];
+ --this._count;
+ return val;
+ }
+ return null;
+ }
+ /**
+ * Remove a key/value from the dictionary.
+ * @param key the key to remove
+ * @returns true if the item was successfully deleted, false if no item with such key exist in the dictionary
+ */
+ remove(key) {
+ if (this.contains(key)) {
+ delete this._data[key];
+ --this._count;
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Clear the whole content of the dictionary
+ */
+ clear() {
+ this._data = {};
+ this._count = 0;
+ }
+ /**
+ * Gets the current count
+ */
+ get count() {
+ return this._count;
+ }
+ /**
+ * Execute a callback on each key/val of the dictionary.
+ * Note that you can remove any element in this dictionary in the callback implementation
+ * @param callback the callback to execute on a given key/value pair
+ */
+ forEach(callback) {
+ for (const cur in this._data) {
+ const val = this._data[cur];
+ callback(cur, val);
+ }
+ }
+ /**
+ * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
+ * If the callback returns null or undefined the method will iterate to the next key/value pair
+ * Note that you can remove any element in this dictionary in the callback implementation
+ * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
+ * @returns the first item
+ */
+ first(callback) {
+ for (const cur in this._data) {
+ const val = this._data[cur];
+ const res = callback(cur, val);
+ if (res) {
+ return res;
+ }
+ }
+ return null;
+ }
+}
+
+/**
+ * Prepare the list of uniforms associated with the ColorCurves effects.
+ * @param uniformsList The list of uniforms used in the effect
+ */
+function PrepareUniformsForColorCurves(uniformsList) {
+ uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
+}
+
+/**
+ * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).
+ * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
+ * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
+ * corresponding to low luminance, medium luminance, and high luminance areas respectively.
+ */
+class ColorCurves {
+ constructor() {
+ this._dirty = true;
+ this._tempColor = new Color4(0, 0, 0, 0);
+ this._globalCurve = new Color4(0, 0, 0, 0);
+ this._highlightsCurve = new Color4(0, 0, 0, 0);
+ this._midtonesCurve = new Color4(0, 0, 0, 0);
+ this._shadowsCurve = new Color4(0, 0, 0, 0);
+ this._positiveCurve = new Color4(0, 0, 0, 0);
+ this._negativeCurve = new Color4(0, 0, 0, 0);
+ this._globalHue = 30;
+ this._globalDensity = 0;
+ this._globalSaturation = 0;
+ this._globalExposure = 0;
+ this._highlightsHue = 30;
+ this._highlightsDensity = 0;
+ this._highlightsSaturation = 0;
+ this._highlightsExposure = 0;
+ this._midtonesHue = 30;
+ this._midtonesDensity = 0;
+ this._midtonesSaturation = 0;
+ this._midtonesExposure = 0;
+ this._shadowsHue = 30;
+ this._shadowsDensity = 0;
+ this._shadowsSaturation = 0;
+ this._shadowsExposure = 0;
+ }
+ /**
+ * Gets the global Hue value.
+ * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
+ */
+ get globalHue() {
+ return this._globalHue;
+ }
+ /**
+ * Sets the global Hue value.
+ * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
+ */
+ set globalHue(value) {
+ this._globalHue = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the global Density value.
+ * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
+ * Values less than zero provide a filter of opposite hue.
+ */
+ get globalDensity() {
+ return this._globalDensity;
+ }
+ /**
+ * Sets the global Density value.
+ * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
+ * Values less than zero provide a filter of opposite hue.
+ */
+ set globalDensity(value) {
+ this._globalDensity = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the global Saturation value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
+ */
+ get globalSaturation() {
+ return this._globalSaturation;
+ }
+ /**
+ * Sets the global Saturation value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
+ */
+ set globalSaturation(value) {
+ this._globalSaturation = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the global Exposure value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
+ */
+ get globalExposure() {
+ return this._globalExposure;
+ }
+ /**
+ * Sets the global Exposure value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
+ */
+ set globalExposure(value) {
+ this._globalExposure = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the highlights Hue value.
+ * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
+ */
+ get highlightsHue() {
+ return this._highlightsHue;
+ }
+ /**
+ * Sets the highlights Hue value.
+ * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
+ */
+ set highlightsHue(value) {
+ this._highlightsHue = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the highlights Density value.
+ * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
+ * Values less than zero provide a filter of opposite hue.
+ */
+ get highlightsDensity() {
+ return this._highlightsDensity;
+ }
+ /**
+ * Sets the highlights Density value.
+ * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
+ * Values less than zero provide a filter of opposite hue.
+ */
+ set highlightsDensity(value) {
+ this._highlightsDensity = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the highlights Saturation value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
+ */
+ get highlightsSaturation() {
+ return this._highlightsSaturation;
+ }
+ /**
+ * Sets the highlights Saturation value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
+ */
+ set highlightsSaturation(value) {
+ this._highlightsSaturation = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the highlights Exposure value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
+ */
+ get highlightsExposure() {
+ return this._highlightsExposure;
+ }
+ /**
+ * Sets the highlights Exposure value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
+ */
+ set highlightsExposure(value) {
+ this._highlightsExposure = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the midtones Hue value.
+ * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
+ */
+ get midtonesHue() {
+ return this._midtonesHue;
+ }
+ /**
+ * Sets the midtones Hue value.
+ * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
+ */
+ set midtonesHue(value) {
+ this._midtonesHue = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the midtones Density value.
+ * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
+ * Values less than zero provide a filter of opposite hue.
+ */
+ get midtonesDensity() {
+ return this._midtonesDensity;
+ }
+ /**
+ * Sets the midtones Density value.
+ * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
+ * Values less than zero provide a filter of opposite hue.
+ */
+ set midtonesDensity(value) {
+ this._midtonesDensity = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the midtones Saturation value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
+ */
+ get midtonesSaturation() {
+ return this._midtonesSaturation;
+ }
+ /**
+ * Sets the midtones Saturation value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
+ */
+ set midtonesSaturation(value) {
+ this._midtonesSaturation = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the midtones Exposure value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
+ */
+ get midtonesExposure() {
+ return this._midtonesExposure;
+ }
+ /**
+ * Sets the midtones Exposure value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
+ */
+ set midtonesExposure(value) {
+ this._midtonesExposure = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the shadows Hue value.
+ * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
+ */
+ get shadowsHue() {
+ return this._shadowsHue;
+ }
+ /**
+ * Sets the shadows Hue value.
+ * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
+ */
+ set shadowsHue(value) {
+ this._shadowsHue = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the shadows Density value.
+ * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
+ * Values less than zero provide a filter of opposite hue.
+ */
+ get shadowsDensity() {
+ return this._shadowsDensity;
+ }
+ /**
+ * Sets the shadows Density value.
+ * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
+ * Values less than zero provide a filter of opposite hue.
+ */
+ set shadowsDensity(value) {
+ this._shadowsDensity = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the shadows Saturation value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
+ */
+ get shadowsSaturation() {
+ return this._shadowsSaturation;
+ }
+ /**
+ * Sets the shadows Saturation value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
+ */
+ set shadowsSaturation(value) {
+ this._shadowsSaturation = value;
+ this._dirty = true;
+ }
+ /**
+ * Gets the shadows Exposure value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
+ */
+ get shadowsExposure() {
+ return this._shadowsExposure;
+ }
+ /**
+ * Sets the shadows Exposure value.
+ * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
+ */
+ set shadowsExposure(value) {
+ this._shadowsExposure = value;
+ this._dirty = true;
+ }
+ /**
+ * Returns the class name
+ * @returns The class name
+ */
+ getClassName() {
+ return "ColorCurves";
+ }
+ /**
+ * Binds the color curves to the shader.
+ * @param colorCurves The color curve to bind
+ * @param effect The effect to bind to
+ * @param positiveUniform The positive uniform shader parameter
+ * @param neutralUniform The neutral uniform shader parameter
+ * @param negativeUniform The negative uniform shader parameter
+ */
+ static Bind(colorCurves, effect, positiveUniform = "vCameraColorCurvePositive", neutralUniform = "vCameraColorCurveNeutral", negativeUniform = "vCameraColorCurveNegative") {
+ if (colorCurves._dirty) {
+ colorCurves._dirty = false;
+ // Fill in global info.
+ colorCurves._getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
+ // Compute highlights info.
+ colorCurves._getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
+ colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
+ // Compute midtones info.
+ colorCurves._getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
+ colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
+ // Compute shadows info.
+ colorCurves._getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
+ colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
+ // Compute deltas (neutral is midtones).
+ colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
+ colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
+ }
+ if (effect) {
+ effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
+ effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
+ effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
+ }
+ }
+ /**
+ * Returns color grading data based on a hue, density, saturation and exposure value.
+ * @param hue
+ * @param density
+ * @param saturation The saturation.
+ * @param exposure The exposure.
+ * @param result The result data container.
+ */
+ _getColorGradingDataToRef(hue, density, saturation, exposure, result) {
+ if (hue == null) {
+ return;
+ }
+ hue = ColorCurves._Clamp(hue, 0, 360);
+ density = ColorCurves._Clamp(density, -100, 100);
+ saturation = ColorCurves._Clamp(saturation, -100, 100);
+ exposure = ColorCurves._Clamp(exposure, -100, 100);
+ // Remap the slider/config filter density with non-linear mapping and also scale by half
+ // so that the maximum filter density is only 50% control. This provides fine control
+ // for small values and reasonable range.
+ density = ColorCurves._ApplyColorGradingSliderNonlinear(density);
+ density *= 0.5;
+ exposure = ColorCurves._ApplyColorGradingSliderNonlinear(exposure);
+ if (density < 0) {
+ density *= -1;
+ hue = (hue + 180) % 360;
+ }
+ ColorCurves._FromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
+ result.scaleToRef(2, result);
+ result.a = 1 + 0.01 * saturation;
+ }
+ /**
+ * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
+ * @param value The input slider value in range [-100,100].
+ * @returns Adjusted value.
+ */
+ static _ApplyColorGradingSliderNonlinear(value) {
+ value /= 100;
+ let x = Math.abs(value);
+ x = Math.pow(x, 2);
+ if (value < 0) {
+ x *= -1;
+ }
+ x *= 100;
+ return x;
+ }
+ /**
+ * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
+ * @param hue The hue (H) input.
+ * @param saturation The saturation (S) input.
+ * @param brightness The brightness (B) input.
+ * @param result
+ * @result An RGBA color represented as Vector4.
+ */
+ static _FromHSBToRef(hue, saturation, brightness, result) {
+ let h = ColorCurves._Clamp(hue, 0, 360);
+ const s = ColorCurves._Clamp(saturation / 100, 0, 1);
+ const v = ColorCurves._Clamp(brightness / 100, 0, 1);
+ if (s === 0) {
+ result.r = v;
+ result.g = v;
+ result.b = v;
+ }
+ else {
+ // sector 0 to 5
+ h /= 60;
+ const i = Math.floor(h);
+ // fractional part of h
+ const f = h - i;
+ const p = v * (1 - s);
+ const q = v * (1 - s * f);
+ const t = v * (1 - s * (1 - f));
+ switch (i) {
+ case 0:
+ result.r = v;
+ result.g = t;
+ result.b = p;
+ break;
+ case 1:
+ result.r = q;
+ result.g = v;
+ result.b = p;
+ break;
+ case 2:
+ result.r = p;
+ result.g = v;
+ result.b = t;
+ break;
+ case 3:
+ result.r = p;
+ result.g = q;
+ result.b = v;
+ break;
+ case 4:
+ result.r = t;
+ result.g = p;
+ result.b = v;
+ break;
+ default:
+ // case 5:
+ result.r = v;
+ result.g = p;
+ result.b = q;
+ break;
+ }
+ }
+ result.a = 1;
+ }
+ /**
+ * Returns a value clamped between min and max
+ * @param value The value to clamp
+ * @param min The minimum of value
+ * @param max The maximum of value
+ * @returns The clamped value.
+ */
+ static _Clamp(value, min, max) {
+ return Math.min(Math.max(value, min), max);
+ }
+ /**
+ * Clones the current color curve instance.
+ * @returns The cloned curves
+ */
+ clone() {
+ return SerializationHelper.Clone(() => new ColorCurves(), this);
+ }
+ /**
+ * Serializes the current color curve instance to a json representation.
+ * @returns a JSON representation
+ */
+ serialize() {
+ return SerializationHelper.Serialize(this);
+ }
+ /**
+ * Parses the color curve from a json representation.
+ * @param source the JSON source to parse
+ * @returns The parsed curves
+ */
+ static Parse(source) {
+ return SerializationHelper.Parse(() => new ColorCurves(), source, null, null);
+ }
+}
+/**
+ * Prepare the list of uniforms associated with the ColorCurves effects.
+ * @param uniformsList The list of uniforms used in the effect
+ */
+ColorCurves.PrepareUniforms = PrepareUniformsForColorCurves;
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_globalHue", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_globalDensity", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_globalSaturation", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_globalExposure", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_highlightsHue", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_highlightsDensity", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_highlightsSaturation", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_highlightsExposure", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_midtonesHue", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_midtonesDensity", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_midtonesSaturation", void 0);
+__decorate([
+ serialize()
+], ColorCurves.prototype, "_midtonesExposure", void 0);
+// References the dependencies.
+SerializationHelper._ColorCurvesParser = ColorCurves.Parse;
+
+/**
+ * Prepare the list of uniforms associated with the Image Processing effects.
+ * @param uniforms The list of uniforms used in the effect
+ * @param defines the list of defines currently in use
+ */
+function PrepareUniformsForImageProcessing(uniforms, defines) {
+ if (defines.EXPOSURE) {
+ uniforms.push("exposureLinear");
+ }
+ if (defines.CONTRAST) {
+ uniforms.push("contrast");
+ }
+ if (defines.COLORGRADING) {
+ uniforms.push("colorTransformSettings");
+ }
+ if (defines.VIGNETTE || defines.DITHER) {
+ uniforms.push("vInverseScreenSize");
+ }
+ if (defines.VIGNETTE) {
+ uniforms.push("vignetteSettings1");
+ uniforms.push("vignetteSettings2");
+ }
+ if (defines.COLORCURVES) {
+ PrepareUniformsForColorCurves(uniforms);
+ }
+ if (defines.DITHER) {
+ uniforms.push("ditherIntensity");
+ }
+}
+/**
+ * Prepare the list of samplers associated with the Image Processing effects.
+ * @param samplersList The list of uniforms used in the effect
+ * @param defines the list of defines currently in use
+ */
+function PrepareSamplersForImageProcessing(samplersList, defines) {
+ if (defines.COLORGRADING) {
+ samplersList.push("txColorTransform");
+ }
+}
+
+/**
+ * This groups together the common properties used for image processing either in direct forward pass
+ * or through post processing effect depending on the use of the image processing pipeline in your scene
+ * or not.
+ */
+class ImageProcessingConfiguration {
+ constructor() {
+ /**
+ * Color curves setup used in the effect if colorCurvesEnabled is set to true
+ */
+ this.colorCurves = new ColorCurves();
+ this._colorCurvesEnabled = false;
+ this._colorGradingEnabled = false;
+ this._colorGradingWithGreenDepth = true;
+ this._colorGradingBGR = true;
+ /** @internal */
+ this._exposure = 1.0;
+ this._toneMappingEnabled = false;
+ this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
+ this._contrast = 1.0;
+ /**
+ * Vignette stretch size.
+ */
+ this.vignetteStretch = 0;
+ /**
+ * Vignette center X Offset.
+ */
+ this.vignetteCenterX = 0;
+ /**
+ * Vignette center Y Offset.
+ */
+ this.vignetteCenterY = 0;
+ /**
+ * Vignette weight or intensity of the vignette effect.
+ */
+ this.vignetteWeight = 1.5;
+ /**
+ * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
+ * if vignetteEnabled is set to true.
+ */
+ this.vignetteColor = new Color4(0, 0, 0, 0);
+ /**
+ * Camera field of view used by the Vignette effect.
+ */
+ this.vignetteCameraFov = 0.5;
+ this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
+ this._vignetteEnabled = false;
+ this._ditheringEnabled = false;
+ this._ditheringIntensity = 1.0 / 255.0;
+ /** @internal */
+ this._skipFinalColorClamp = false;
+ /** @internal */
+ this._applyByPostProcess = false;
+ this._isEnabled = true;
+ /**
+ * An event triggered when the configuration changes and requires Shader to Update some parameters.
+ */
+ this.onUpdateParameters = new Observable();
+ }
+ /**
+ * Gets whether the color curves effect is enabled.
+ */
+ get colorCurvesEnabled() {
+ return this._colorCurvesEnabled;
+ }
+ /**
+ * Sets whether the color curves effect is enabled.
+ */
+ set colorCurvesEnabled(value) {
+ if (this._colorCurvesEnabled === value) {
+ return;
+ }
+ this._colorCurvesEnabled = value;
+ this._updateParameters();
+ }
+ /**
+ * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
+ */
+ get colorGradingTexture() {
+ return this._colorGradingTexture;
+ }
+ /**
+ * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
+ */
+ set colorGradingTexture(value) {
+ if (this._colorGradingTexture === value) {
+ return;
+ }
+ this._colorGradingTexture = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets whether the color grading effect is enabled.
+ */
+ get colorGradingEnabled() {
+ return this._colorGradingEnabled;
+ }
+ /**
+ * Sets whether the color grading effect is enabled.
+ */
+ set colorGradingEnabled(value) {
+ if (this._colorGradingEnabled === value) {
+ return;
+ }
+ this._colorGradingEnabled = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets whether the color grading effect is using a green depth for the 3d Texture.
+ */
+ get colorGradingWithGreenDepth() {
+ return this._colorGradingWithGreenDepth;
+ }
+ /**
+ * Sets whether the color grading effect is using a green depth for the 3d Texture.
+ */
+ set colorGradingWithGreenDepth(value) {
+ if (this._colorGradingWithGreenDepth === value) {
+ return;
+ }
+ this._colorGradingWithGreenDepth = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets whether the color grading texture contains BGR values.
+ */
+ get colorGradingBGR() {
+ return this._colorGradingBGR;
+ }
+ /**
+ * Sets whether the color grading texture contains BGR values.
+ */
+ set colorGradingBGR(value) {
+ if (this._colorGradingBGR === value) {
+ return;
+ }
+ this._colorGradingBGR = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets the Exposure used in the effect.
+ */
+ get exposure() {
+ return this._exposure;
+ }
+ /**
+ * Sets the Exposure used in the effect.
+ */
+ set exposure(value) {
+ if (this._exposure === value) {
+ return;
+ }
+ this._exposure = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets whether the tone mapping effect is enabled.
+ */
+ get toneMappingEnabled() {
+ return this._toneMappingEnabled;
+ }
+ /**
+ * Sets whether the tone mapping effect is enabled.
+ */
+ set toneMappingEnabled(value) {
+ if (this._toneMappingEnabled === value) {
+ return;
+ }
+ this._toneMappingEnabled = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets the type of tone mapping effect.
+ */
+ get toneMappingType() {
+ return this._toneMappingType;
+ }
+ /**
+ * Sets the type of tone mapping effect used in BabylonJS.
+ */
+ set toneMappingType(value) {
+ if (this._toneMappingType === value) {
+ return;
+ }
+ this._toneMappingType = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets the contrast used in the effect.
+ */
+ get contrast() {
+ return this._contrast;
+ }
+ /**
+ * Sets the contrast used in the effect.
+ */
+ set contrast(value) {
+ if (this._contrast === value) {
+ return;
+ }
+ this._contrast = value;
+ this._updateParameters();
+ }
+ /**
+ * Back Compat: Vignette center Y Offset.
+ * @deprecated use vignetteCenterY instead
+ */
+ get vignetteCentreY() {
+ return this.vignetteCenterY;
+ }
+ set vignetteCentreY(value) {
+ this.vignetteCenterY = value;
+ }
+ /**
+ * Back Compat: Vignette center X Offset.
+ * @deprecated use vignetteCenterX instead
+ */
+ get vignetteCentreX() {
+ return this.vignetteCenterX;
+ }
+ set vignetteCentreX(value) {
+ this.vignetteCenterX = value;
+ }
+ /**
+ * Gets the vignette blend mode allowing different kind of effect.
+ */
+ get vignetteBlendMode() {
+ return this._vignetteBlendMode;
+ }
+ /**
+ * Sets the vignette blend mode allowing different kind of effect.
+ */
+ set vignetteBlendMode(value) {
+ if (this._vignetteBlendMode === value) {
+ return;
+ }
+ this._vignetteBlendMode = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets whether the vignette effect is enabled.
+ */
+ get vignetteEnabled() {
+ return this._vignetteEnabled;
+ }
+ /**
+ * Sets whether the vignette effect is enabled.
+ */
+ set vignetteEnabled(value) {
+ if (this._vignetteEnabled === value) {
+ return;
+ }
+ this._vignetteEnabled = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets whether the dithering effect is enabled.
+ * The dithering effect can be used to reduce banding.
+ */
+ get ditheringEnabled() {
+ return this._ditheringEnabled;
+ }
+ /**
+ * Sets whether the dithering effect is enabled.
+ * The dithering effect can be used to reduce banding.
+ */
+ set ditheringEnabled(value) {
+ if (this._ditheringEnabled === value) {
+ return;
+ }
+ this._ditheringEnabled = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0.
+ */
+ get ditheringIntensity() {
+ return this._ditheringIntensity;
+ }
+ /**
+ * Sets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0.
+ */
+ set ditheringIntensity(value) {
+ if (this._ditheringIntensity === value) {
+ return;
+ }
+ this._ditheringIntensity = value;
+ this._updateParameters();
+ }
+ /**
+ * If apply by post process is set to true, setting this to true will skip the final color clamp step in the fragment shader
+ * Applies to PBR materials.
+ */
+ get skipFinalColorClamp() {
+ return this._skipFinalColorClamp;
+ }
+ /**
+ * If apply by post process is set to true, setting this to true will skip the final color clamp step in the fragment shader
+ * Applies to PBR materials.
+ */
+ set skipFinalColorClamp(value) {
+ if (this._skipFinalColorClamp === value) {
+ return;
+ }
+ this._skipFinalColorClamp = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets whether the image processing is applied through a post process or not.
+ */
+ get applyByPostProcess() {
+ return this._applyByPostProcess;
+ }
+ /**
+ * Sets whether the image processing is applied through a post process or not.
+ */
+ set applyByPostProcess(value) {
+ if (this._applyByPostProcess === value) {
+ return;
+ }
+ this._applyByPostProcess = value;
+ this._updateParameters();
+ }
+ /**
+ * Gets whether the image processing is enabled or not.
+ */
+ get isEnabled() {
+ return this._isEnabled;
+ }
+ /**
+ * Sets whether the image processing is enabled or not.
+ */
+ set isEnabled(value) {
+ if (this._isEnabled === value) {
+ return;
+ }
+ this._isEnabled = value;
+ this._updateParameters();
+ }
+ /**
+ * Method called each time the image processing information changes requires to recompile the effect.
+ */
+ _updateParameters() {
+ this.onUpdateParameters.notifyObservers(this);
+ }
+ /**
+ * Gets the current class name.
+ * @returns "ImageProcessingConfiguration"
+ */
+ getClassName() {
+ return "ImageProcessingConfiguration";
+ }
+ /**
+ * Prepare the list of defines associated to the shader.
+ * @param defines the list of defines to complete
+ * @param forPostProcess Define if we are currently in post process mode or not
+ */
+ prepareDefines(defines, forPostProcess = false) {
+ if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
+ defines.VIGNETTE = false;
+ defines.TONEMAPPING = 0;
+ defines.CONTRAST = false;
+ defines.EXPOSURE = false;
+ defines.COLORCURVES = false;
+ defines.COLORGRADING = false;
+ defines.COLORGRADING3D = false;
+ defines.DITHER = false;
+ defines.IMAGEPROCESSING = false;
+ defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp;
+ defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
+ return;
+ }
+ defines.VIGNETTE = this.vignetteEnabled;
+ defines.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY;
+ defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
+ if (!this._toneMappingEnabled) {
+ defines.TONEMAPPING = 0;
+ }
+ else {
+ switch (this._toneMappingType) {
+ case ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL:
+ defines.TONEMAPPING = 3;
+ break;
+ case ImageProcessingConfiguration.TONEMAPPING_ACES:
+ defines.TONEMAPPING = 2;
+ break;
+ default:
+ defines.TONEMAPPING = 1;
+ break;
+ }
+ }
+ defines.CONTRAST = this.contrast !== 1.0;
+ defines.EXPOSURE = this.exposure !== 1.0;
+ defines.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves;
+ defines.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture;
+ if (defines.COLORGRADING) {
+ defines.COLORGRADING3D = this.colorGradingTexture.is3D;
+ }
+ else {
+ defines.COLORGRADING3D = false;
+ }
+ defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
+ defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
+ defines.DITHER = this._ditheringEnabled;
+ defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
+ defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp;
+ defines.IMAGEPROCESSING =
+ defines.VIGNETTE || !!defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.DITHER;
+ }
+ /**
+ * Returns true if all the image processing information are ready.
+ * @returns True if ready, otherwise, false
+ */
+ isReady() {
+ // Color Grading texture can not be none blocking.
+ return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
+ }
+ /**
+ * Binds the image processing to the shader.
+ * @param effect The effect to bind to
+ * @param overrideAspectRatio Override the aspect ratio of the effect
+ */
+ bind(effect, overrideAspectRatio) {
+ // Color Curves
+ if (this._colorCurvesEnabled && this.colorCurves) {
+ ColorCurves.Bind(this.colorCurves, effect);
+ }
+ // Vignette and dither handled together due to common uniform.
+ if (this._vignetteEnabled || this._ditheringEnabled) {
+ const inverseWidth = 1 / effect.getEngine().getRenderWidth();
+ const inverseHeight = 1 / effect.getEngine().getRenderHeight();
+ effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
+ if (this._ditheringEnabled) {
+ effect.setFloat("ditherIntensity", 0.5 * this._ditheringIntensity);
+ }
+ if (this._vignetteEnabled) {
+ const aspectRatio = overrideAspectRatio != null ? overrideAspectRatio : inverseHeight / inverseWidth;
+ let vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
+ let vignetteScaleX = vignetteScaleY * aspectRatio;
+ const vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
+ vignetteScaleX = Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
+ vignetteScaleY = Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
+ effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCenterX, -vignetteScaleY * this.vignetteCenterY);
+ const vignettePower = -2 * this.vignetteWeight;
+ effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
+ }
+ }
+ // Exposure
+ effect.setFloat("exposureLinear", this.exposure);
+ // Contrast
+ effect.setFloat("contrast", this.contrast);
+ // Color transform settings
+ if (this.colorGradingTexture) {
+ effect.setTexture("txColorTransform", this.colorGradingTexture);
+ const textureSize = this.colorGradingTexture.getSize().height;
+ effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
+ 0.5 / textureSize, // textureOffset
+ textureSize, // textureSize
+ this.colorGradingTexture.level // weight
+ );
+ }
+ }
+ /**
+ * Clones the current image processing instance.
+ * @returns The cloned image processing
+ */
+ clone() {
+ return SerializationHelper.Clone(() => new ImageProcessingConfiguration(), this);
+ }
+ /**
+ * Serializes the current image processing instance to a json representation.
+ * @returns a JSON representation
+ */
+ serialize() {
+ return SerializationHelper.Serialize(this);
+ }
+ /**
+ * Parses the image processing from a json representation.
+ * @param source the JSON source to parse
+ * @returns The parsed image processing
+ */
+ static Parse(source) {
+ const parsed = SerializationHelper.Parse(() => new ImageProcessingConfiguration(), source, null, null);
+ // Backward compatibility
+ if (source.vignetteCentreX !== undefined) {
+ parsed.vignetteCenterX = source.vignetteCentreX;
+ }
+ if (source.vignetteCentreY !== undefined) {
+ parsed.vignetteCenterY = source.vignetteCentreY;
+ }
+ return parsed;
+ }
+ /**
+ * Used to apply the vignette as a mix with the pixel color.
+ */
+ static get VIGNETTEMODE_MULTIPLY() {
+ return this._VIGNETTEMODE_MULTIPLY;
+ }
+ /**
+ * Used to apply the vignette as a replacement of the pixel color.
+ */
+ static get VIGNETTEMODE_OPAQUE() {
+ return this._VIGNETTEMODE_OPAQUE;
+ }
+}
+/**
+ * Default tone mapping applied in BabylonJS.
+ */
+ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
+/**
+ * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
+ * to other engines rendering to increase portability.
+ */
+ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
+/**
+ * Neutral Tone mapping developped by the Khronos group in order to constrain
+ * values between 0 and 1 without shifting Hue.
+ */
+ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL = 2;
+/**
+ * Prepare the list of uniforms associated with the Image Processing effects.
+ * @param uniforms The list of uniforms used in the effect
+ * @param defines the list of defines currently in use
+ */
+ImageProcessingConfiguration.PrepareUniforms = PrepareUniformsForImageProcessing;
+/**
+ * Prepare the list of samplers associated with the Image Processing effects.
+ * @param samplersList The list of uniforms used in the effect
+ * @param defines the list of defines currently in use
+ */
+ImageProcessingConfiguration.PrepareSamplers = PrepareSamplersForImageProcessing;
+// Static constants associated to the image processing.
+ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
+ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
+__decorate([
+ serializeAsColorCurves()
+], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
+__decorate([
+ serializeAsTexture("colorGradingTexture")
+], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_exposure", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_contrast", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "vignetteCenterX", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "vignetteCenterY", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
+__decorate([
+ serializeAsColor4()
+], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_ditheringEnabled", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_ditheringIntensity", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_skipFinalColorClamp", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
+__decorate([
+ serialize()
+], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
+// References the dependencies.
+SerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse;
+// Register Class Name
+RegisterClass("BABYLON.ImageProcessingConfiguration", ImageProcessingConfiguration);
+
+/**
+ * Uniform buffer objects.
+ *
+ * Handles blocks of uniform on the GPU.
+ *
+ * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls.
+ *
+ * For more information, please refer to :
+ * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
+ */
+class UniformBuffer {
+ /**
+ * Instantiates a new Uniform buffer objects.
+ *
+ * Handles blocks of uniform on the GPU.
+ *
+ * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls.
+ *
+ * For more information, please refer to :
+ * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
+ * @param engine Define the engine the buffer is associated with
+ * @param data Define the data contained in the buffer
+ * @param dynamic Define if the buffer is updatable
+ * @param name to assign to the buffer (debugging purpose)
+ * @param forceNoUniformBuffer define that this object must not rely on UBO objects
+ */
+ constructor(engine, data, dynamic, name, forceNoUniformBuffer = false) {
+ // Matrix cache
+ this._valueCache = {};
+ this._engine = engine;
+ this._noUBO = !engine.supportsUniformBuffers || forceNoUniformBuffer;
+ this._dynamic = dynamic;
+ this._name = name ?? "no-name";
+ this._data = data || [];
+ this._uniformLocations = {};
+ this._uniformSizes = {};
+ this._uniformArraySizes = {};
+ this._uniformLocationPointer = 0;
+ this._needSync = false;
+ if (this._engine._features.trackUbosInFrame) {
+ this._buffers = [];
+ this._bufferIndex = -1;
+ this._createBufferOnWrite = false;
+ this._currentFrameId = 0;
+ }
+ if (this._noUBO) {
+ this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
+ this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
+ this.updateFloat = this._updateFloatForEffect;
+ this.updateFloat2 = this._updateFloat2ForEffect;
+ this.updateFloat3 = this._updateFloat3ForEffect;
+ this.updateFloat4 = this._updateFloat4ForEffect;
+ this.updateFloatArray = this._updateFloatArrayForEffect;
+ this.updateArray = this._updateArrayForEffect;
+ this.updateIntArray = this._updateIntArrayForEffect;
+ this.updateUIntArray = this._updateUIntArrayForEffect;
+ this.updateMatrix = this._updateMatrixForEffect;
+ this.updateMatrices = this._updateMatricesForEffect;
+ this.updateVector3 = this._updateVector3ForEffect;
+ this.updateVector4 = this._updateVector4ForEffect;
+ this.updateColor3 = this._updateColor3ForEffect;
+ this.updateColor4 = this._updateColor4ForEffect;
+ this.updateDirectColor4 = this._updateDirectColor4ForEffect;
+ this.updateInt = this._updateIntForEffect;
+ this.updateInt2 = this._updateInt2ForEffect;
+ this.updateInt3 = this._updateInt3ForEffect;
+ this.updateInt4 = this._updateInt4ForEffect;
+ this.updateUInt = this._updateUIntForEffect;
+ this.updateUInt2 = this._updateUInt2ForEffect;
+ this.updateUInt3 = this._updateUInt3ForEffect;
+ this.updateUInt4 = this._updateUInt4ForEffect;
+ }
+ else {
+ this._engine._uniformBuffers.push(this);
+ this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
+ this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
+ this.updateFloat = this._updateFloatForUniform;
+ this.updateFloat2 = this._updateFloat2ForUniform;
+ this.updateFloat3 = this._updateFloat3ForUniform;
+ this.updateFloat4 = this._updateFloat4ForUniform;
+ this.updateFloatArray = this._updateFloatArrayForUniform;
+ this.updateArray = this._updateArrayForUniform;
+ this.updateIntArray = this._updateIntArrayForUniform;
+ this.updateUIntArray = this._updateUIntArrayForUniform;
+ this.updateMatrix = this._updateMatrixForUniform;
+ this.updateMatrices = this._updateMatricesForUniform;
+ this.updateVector3 = this._updateVector3ForUniform;
+ this.updateVector4 = this._updateVector4ForUniform;
+ this.updateColor3 = this._updateColor3ForUniform;
+ this.updateColor4 = this._updateColor4ForUniform;
+ this.updateDirectColor4 = this._updateDirectColor4ForUniform;
+ this.updateInt = this._updateIntForUniform;
+ this.updateInt2 = this._updateInt2ForUniform;
+ this.updateInt3 = this._updateInt3ForUniform;
+ this.updateInt4 = this._updateInt4ForUniform;
+ this.updateUInt = this._updateUIntForUniform;
+ this.updateUInt2 = this._updateUInt2ForUniform;
+ this.updateUInt3 = this._updateUInt3ForUniform;
+ this.updateUInt4 = this._updateUInt4ForUniform;
+ }
+ }
+ /**
+ * Indicates if the buffer is using the WebGL2 UBO implementation,
+ * or just falling back on setUniformXXX calls.
+ */
+ get useUbo() {
+ return !this._noUBO;
+ }
+ /**
+ * Indicates if the WebGL underlying uniform buffer is in sync
+ * with the javascript cache data.
+ */
+ get isSync() {
+ return !this._needSync;
+ }
+ /**
+ * Indicates if the WebGL underlying uniform buffer is dynamic.
+ * Also, a dynamic UniformBuffer will disable cache verification and always
+ * update the underlying WebGL uniform buffer to the GPU.
+ * @returns if Dynamic, otherwise false
+ */
+ isDynamic() {
+ return this._dynamic !== undefined;
+ }
+ /**
+ * The data cache on JS side.
+ * @returns the underlying data as a float array
+ */
+ getData() {
+ return this._bufferData;
+ }
+ /**
+ * The underlying WebGL Uniform buffer.
+ * @returns the webgl buffer
+ */
+ getBuffer() {
+ return this._buffer;
+ }
+ /**
+ * std140 layout specifies how to align data within an UBO structure.
+ * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
+ * for specs.
+ * @param size
+ */
+ _fillAlignment(size) {
+ // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
+ // and 4x4 matrices
+ // TODO : change if other types are used
+ let alignment;
+ if (size <= 2) {
+ alignment = size;
+ }
+ else {
+ alignment = 4;
+ }
+ if (this._uniformLocationPointer % alignment !== 0) {
+ const oldPointer = this._uniformLocationPointer;
+ this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
+ const diff = this._uniformLocationPointer - oldPointer;
+ for (let i = 0; i < diff; i++) {
+ this._data.push(0);
+ }
+ }
+ }
+ /**
+ * Adds an uniform in the buffer.
+ * Warning : the subsequents calls of this function must be in the same order as declared in the shader
+ * for the layout to be correct ! The addUniform function only handles types like float, vec2, vec3, vec4, mat4,
+ * meaning size=1,2,3,4 or 16. It does not handle struct types.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ * @param size Data size, or data directly.
+ * @param arraySize The number of elements in the array, 0 if not an array.
+ */
+ addUniform(name, size, arraySize = 0) {
+ if (this._noUBO) {
+ return;
+ }
+ if (this._uniformLocations[name] !== undefined) {
+ // Already existing uniform
+ return;
+ }
+ // This function must be called in the order of the shader layout !
+ // size can be the size of the uniform, or data directly
+ let data;
+ // std140 FTW...
+ if (arraySize > 0) {
+ if (size instanceof Array) {
+ // eslint-disable-next-line no-throw-literal
+ throw "addUniform should not be use with Array in UBO: " + name;
+ }
+ this._fillAlignment(4);
+ this._uniformArraySizes[name] = { strideSize: size, arraySize };
+ if (size == 16) {
+ size = size * arraySize;
+ }
+ else {
+ const perElementPadding = 4 - size;
+ const totalPadding = perElementPadding * arraySize;
+ size = size * arraySize + totalPadding;
+ }
+ data = [];
+ // Fill with zeros
+ for (let i = 0; i < size; i++) {
+ data.push(0);
+ }
+ }
+ else {
+ if (size instanceof Array) {
+ data = size;
+ size = data.length;
+ }
+ else {
+ size = size;
+ data = [];
+ // Fill with zeros
+ for (let i = 0; i < size; i++) {
+ data.push(0);
+ }
+ }
+ this._fillAlignment(size);
+ }
+ this._uniformSizes[name] = size;
+ this._uniformLocations[name] = this._uniformLocationPointer;
+ this._uniformLocationPointer += size;
+ for (let i = 0; i < size; i++) {
+ this._data.push(data[i]);
+ }
+ this._needSync = true;
+ }
+ /**
+ * Adds a Matrix 4x4 to the uniform buffer.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ * @param mat A 4x4 matrix.
+ */
+ addMatrix(name, mat) {
+ this.addUniform(name, Array.prototype.slice.call(mat.asArray()));
+ }
+ /**
+ * Adds a vec2 to the uniform buffer.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ * @param x Define the x component value of the vec2
+ * @param y Define the y component value of the vec2
+ */
+ addFloat2(name, x, y) {
+ const temp = [x, y];
+ this.addUniform(name, temp);
+ }
+ /**
+ * Adds a vec3 to the uniform buffer.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ * @param x Define the x component value of the vec3
+ * @param y Define the y component value of the vec3
+ * @param z Define the z component value of the vec3
+ */
+ addFloat3(name, x, y, z) {
+ const temp = [x, y, z];
+ this.addUniform(name, temp);
+ }
+ /**
+ * Adds a vec3 to the uniform buffer.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ * @param color Define the vec3 from a Color
+ */
+ addColor3(name, color) {
+ const temp = [color.r, color.g, color.b];
+ this.addUniform(name, temp);
+ }
+ /**
+ * Adds a vec4 to the uniform buffer.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ * @param color Define the rgb components from a Color
+ * @param alpha Define the a component of the vec4
+ */
+ addColor4(name, color, alpha) {
+ const temp = [color.r, color.g, color.b, alpha];
+ this.addUniform(name, temp);
+ }
+ /**
+ * Adds a vec3 to the uniform buffer.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ * @param vector Define the vec3 components from a Vector
+ */
+ addVector3(name, vector) {
+ const temp = [vector.x, vector.y, vector.z];
+ this.addUniform(name, temp);
+ }
+ /**
+ * Adds a Matrix 3x3 to the uniform buffer.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ */
+ addMatrix3x3(name) {
+ this.addUniform(name, 12);
+ }
+ /**
+ * Adds a Matrix 2x2 to the uniform buffer.
+ * @param name Name of the uniform, as used in the uniform block in the shader.
+ */
+ addMatrix2x2(name) {
+ this.addUniform(name, 8);
+ }
+ /**
+ * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
+ */
+ create() {
+ if (this._noUBO) {
+ return;
+ }
+ if (this._buffer) {
+ return; // nothing to do
+ }
+ // See spec, alignment must be filled as a vec4
+ this._fillAlignment(4);
+ this._bufferData = new Float32Array(this._data);
+ this._rebuild();
+ this._needSync = true;
+ }
+ // The result of this method is used for debugging purpose, as part of the buffer name
+ // It is meant to more easily know what this buffer is about when debugging
+ // Some buffers can have a lot of uniforms (several dozens), so the method only returns the first 10 of them
+ // (should be enough to understand what the buffer is for)
+ _getNames() {
+ const names = [];
+ let i = 0;
+ for (const name in this._uniformLocations) {
+ names.push(name);
+ if (++i === 10) {
+ break;
+ }
+ }
+ return names.join(",");
+ }
+ /** @internal */
+ _rebuild() {
+ if (this._noUBO || !this._bufferData) {
+ return;
+ }
+ if (this._dynamic) {
+ this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData, this._name + "_UniformList:" + this._getNames());
+ }
+ else {
+ this._buffer = this._engine.createUniformBuffer(this._bufferData, this._name + "_UniformList:" + this._getNames());
+ }
+ if (this._engine._features.trackUbosInFrame) {
+ this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : undefined]);
+ this._bufferIndex = this._buffers.length - 1;
+ this._createBufferOnWrite = false;
+ }
+ }
+ /** @internal */
+ _rebuildAfterContextLost() {
+ if (this._engine._features.trackUbosInFrame) {
+ this._buffers = [];
+ this._currentFrameId = 0;
+ }
+ this._rebuild();
+ }
+ /** @internal */
+ get _numBuffers() {
+ return this._buffers.length;
+ }
+ /** @internal */
+ get _indexBuffer() {
+ return this._bufferIndex;
+ }
+ /** Gets the name of this buffer */
+ get name() {
+ return this._name;
+ }
+ /** Gets the current effect */
+ get currentEffect() {
+ return this._currentEffect;
+ }
+ _buffersEqual(buf1, buf2) {
+ for (let i = 0; i < buf1.length; ++i) {
+ if (buf1[i] !== buf2[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+ _copyBuffer(src, dst) {
+ for (let i = 0; i < src.length; ++i) {
+ dst[i] = src[i];
+ }
+ }
+ /**
+ * Updates the WebGL Uniform Buffer on the GPU.
+ * If the `dynamic` flag is set to true, no cache comparison is done.
+ * Otherwise, the buffer will be updated only if the cache differs.
+ */
+ update() {
+ if (this._noUBO) {
+ return;
+ }
+ this.bindUniformBuffer();
+ if (!this._buffer) {
+ this.create();
+ return;
+ }
+ if (!this._dynamic && !this._needSync) {
+ this._createBufferOnWrite = this._engine._features.trackUbosInFrame;
+ return;
+ }
+ if (this._buffers && this._buffers.length > 1 && this._buffers[this._bufferIndex][1]) {
+ if (this._buffersEqual(this._bufferData, this._buffers[this._bufferIndex][1])) {
+ this._needSync = false;
+ this._createBufferOnWrite = this._engine._features.trackUbosInFrame;
+ return;
+ }
+ else {
+ this._copyBuffer(this._bufferData, this._buffers[this._bufferIndex][1]);
+ }
+ }
+ this._engine.updateUniformBuffer(this._buffer, this._bufferData);
+ if (this._engine._features._collectUbosUpdatedInFrame) {
+ if (!UniformBuffer._UpdatedUbosInFrame[this._name]) {
+ UniformBuffer._UpdatedUbosInFrame[this._name] = 0;
+ }
+ UniformBuffer._UpdatedUbosInFrame[this._name]++;
+ }
+ this._needSync = false;
+ this._createBufferOnWrite = this._engine._features.trackUbosInFrame;
+ }
+ _createNewBuffer() {
+ if (this._bufferIndex + 1 < this._buffers.length) {
+ this._bufferIndex++;
+ this._buffer = this._buffers[this._bufferIndex][0];
+ this._createBufferOnWrite = false;
+ this._needSync = true;
+ }
+ else {
+ this._rebuild();
+ }
+ }
+ _checkNewFrame() {
+ if (this._engine._features.trackUbosInFrame && this._currentFrameId !== this._engine.frameId) {
+ this._currentFrameId = this._engine.frameId;
+ this._createBufferOnWrite = false;
+ if (this._buffers && this._buffers.length > 0) {
+ this._needSync = this._bufferIndex !== 0;
+ this._bufferIndex = 0;
+ this._buffer = this._buffers[this._bufferIndex][0];
+ }
+ else {
+ this._bufferIndex = -1;
+ }
+ }
+ }
+ /**
+ * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
+ * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
+ * @param data Define the flattened data
+ * @param size Define the size of the data.
+ */
+ updateUniform(uniformName, data, size) {
+ this._checkNewFrame();
+ let location = this._uniformLocations[uniformName];
+ if (location === undefined) {
+ if (this._buffer) {
+ // Cannot add an uniform if the buffer is already created
+ Logger.Error("Cannot add an uniform after UBO has been created. uniformName=" + uniformName);
+ return;
+ }
+ this.addUniform(uniformName, size);
+ location = this._uniformLocations[uniformName];
+ }
+ if (!this._buffer) {
+ this.create();
+ }
+ if (!this._dynamic) {
+ // Cache for static uniform buffers
+ let changed = false;
+ for (let i = 0; i < size; i++) {
+ // We are checking the matrix cache before calling updateUniform so we do not need to check it here
+ // Hence the test for size === 16 to simply commit the matrix values
+ if ((size === 16 && !this._engine._features.uniformBufferHardCheckMatrix) || this._bufferData[location + i] !== Math.fround(data[i])) {
+ changed = true;
+ if (this._createBufferOnWrite) {
+ this._createNewBuffer();
+ }
+ this._bufferData[location + i] = data[i];
+ }
+ }
+ this._needSync = this._needSync || changed;
+ }
+ else {
+ // No cache for dynamic
+ for (let i = 0; i < size; i++) {
+ this._bufferData[location + i] = data[i];
+ }
+ }
+ }
+ /**
+ * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
+ * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
+ * @param data Define the flattened data
+ * @param size Define the size of the data.
+ */
+ updateUniformArray(uniformName, data, size) {
+ this._checkNewFrame();
+ const location = this._uniformLocations[uniformName];
+ if (location === undefined) {
+ Logger.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");
+ return;
+ }
+ if (!this._buffer) {
+ this.create();
+ }
+ const arraySizes = this._uniformArraySizes[uniformName];
+ if (!this._dynamic) {
+ // Cache for static uniform buffers
+ let changed = false;
+ let countToFour = 0;
+ let baseStride = 0;
+ for (let i = 0; i < size; i++) {
+ if (this._bufferData[location + baseStride * 4 + countToFour] !== Tools.FloatRound(data[i])) {
+ changed = true;
+ if (this._createBufferOnWrite) {
+ this._createNewBuffer();
+ }
+ this._bufferData[location + baseStride * 4 + countToFour] = data[i];
+ }
+ countToFour++;
+ if (countToFour === arraySizes.strideSize) {
+ for (; countToFour < 4; countToFour++) {
+ this._bufferData[location + baseStride * 4 + countToFour] = 0;
+ }
+ countToFour = 0;
+ baseStride++;
+ }
+ }
+ this._needSync = this._needSync || changed;
+ }
+ else {
+ // No cache for dynamic
+ for (let i = 0; i < size; i++) {
+ this._bufferData[location + i] = data[i];
+ }
+ }
+ }
+ _cacheMatrix(name, matrix) {
+ this._checkNewFrame();
+ const cache = this._valueCache[name];
+ const flag = matrix.updateFlag;
+ if (cache !== undefined && cache === flag) {
+ return false;
+ }
+ this._valueCache[name] = flag;
+ return true;
+ }
+ // Update methods
+ _updateMatrix3x3ForUniform(name, matrix) {
+ // To match std140, matrix must be realigned
+ for (let i = 0; i < 3; i++) {
+ UniformBuffer._TempBuffer[i * 4] = matrix[i * 3];
+ UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
+ UniformBuffer._TempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
+ UniformBuffer._TempBuffer[i * 4 + 3] = 0.0;
+ }
+ this.updateUniform(name, UniformBuffer._TempBuffer, 12);
+ }
+ _updateMatrix3x3ForEffect(name, matrix) {
+ this._currentEffect.setMatrix3x3(name, matrix);
+ }
+ _updateMatrix2x2ForEffect(name, matrix) {
+ this._currentEffect.setMatrix2x2(name, matrix);
+ }
+ _updateMatrix2x2ForUniform(name, matrix) {
+ // To match std140, matrix must be realigned
+ for (let i = 0; i < 2; i++) {
+ UniformBuffer._TempBuffer[i * 4] = matrix[i * 2];
+ UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
+ UniformBuffer._TempBuffer[i * 4 + 2] = 0.0;
+ UniformBuffer._TempBuffer[i * 4 + 3] = 0.0;
+ }
+ this.updateUniform(name, UniformBuffer._TempBuffer, 8);
+ }
+ _updateFloatForEffect(name, x) {
+ this._currentEffect.setFloat(name, x);
+ }
+ _updateFloatForUniform(name, x) {
+ UniformBuffer._TempBuffer[0] = x;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 1);
+ }
+ _updateFloat2ForEffect(name, x, y, suffix = "") {
+ this._currentEffect.setFloat2(name + suffix, x, y);
+ }
+ _updateFloat2ForUniform(name, x, y) {
+ UniformBuffer._TempBuffer[0] = x;
+ UniformBuffer._TempBuffer[1] = y;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 2);
+ }
+ _updateFloat3ForEffect(name, x, y, z, suffix = "") {
+ this._currentEffect.setFloat3(name + suffix, x, y, z);
+ }
+ _updateFloat3ForUniform(name, x, y, z) {
+ UniformBuffer._TempBuffer[0] = x;
+ UniformBuffer._TempBuffer[1] = y;
+ UniformBuffer._TempBuffer[2] = z;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 3);
+ }
+ _updateFloat4ForEffect(name, x, y, z, w, suffix = "") {
+ this._currentEffect.setFloat4(name + suffix, x, y, z, w);
+ }
+ _updateFloat4ForUniform(name, x, y, z, w) {
+ UniformBuffer._TempBuffer[0] = x;
+ UniformBuffer._TempBuffer[1] = y;
+ UniformBuffer._TempBuffer[2] = z;
+ UniformBuffer._TempBuffer[3] = w;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 4);
+ }
+ _updateFloatArrayForEffect(name, array) {
+ this._currentEffect.setFloatArray(name, array);
+ }
+ _updateFloatArrayForUniform(name, array) {
+ this.updateUniformArray(name, array, array.length);
+ }
+ _updateArrayForEffect(name, array) {
+ this._currentEffect.setArray(name, array);
+ }
+ _updateArrayForUniform(name, array) {
+ this.updateUniformArray(name, array, array.length);
+ }
+ _updateIntArrayForEffect(name, array) {
+ this._currentEffect.setIntArray(name, array);
+ }
+ _updateIntArrayForUniform(name, array) {
+ UniformBuffer._TempBufferInt32View.set(array);
+ this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length);
+ }
+ _updateUIntArrayForEffect(name, array) {
+ this._currentEffect.setUIntArray(name, array);
+ }
+ _updateUIntArrayForUniform(name, array) {
+ UniformBuffer._TempBufferUInt32View.set(array);
+ this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length);
+ }
+ _updateMatrixForEffect(name, mat) {
+ this._currentEffect.setMatrix(name, mat);
+ }
+ _updateMatrixForUniform(name, mat) {
+ if (this._cacheMatrix(name, mat)) {
+ this.updateUniform(name, mat.asArray(), 16);
+ }
+ }
+ _updateMatricesForEffect(name, mat) {
+ this._currentEffect.setMatrices(name, mat);
+ }
+ _updateMatricesForUniform(name, mat) {
+ this.updateUniform(name, mat, mat.length);
+ }
+ _updateVector3ForEffect(name, vector) {
+ this._currentEffect.setVector3(name, vector);
+ }
+ _updateVector3ForUniform(name, vector) {
+ UniformBuffer._TempBuffer[0] = vector.x;
+ UniformBuffer._TempBuffer[1] = vector.y;
+ UniformBuffer._TempBuffer[2] = vector.z;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 3);
+ }
+ _updateVector4ForEffect(name, vector) {
+ this._currentEffect.setVector4(name, vector);
+ }
+ _updateVector4ForUniform(name, vector) {
+ UniformBuffer._TempBuffer[0] = vector.x;
+ UniformBuffer._TempBuffer[1] = vector.y;
+ UniformBuffer._TempBuffer[2] = vector.z;
+ UniformBuffer._TempBuffer[3] = vector.w;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 4);
+ }
+ _updateColor3ForEffect(name, color, suffix = "") {
+ this._currentEffect.setColor3(name + suffix, color);
+ }
+ _updateColor3ForUniform(name, color) {
+ UniformBuffer._TempBuffer[0] = color.r;
+ UniformBuffer._TempBuffer[1] = color.g;
+ UniformBuffer._TempBuffer[2] = color.b;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 3);
+ }
+ _updateColor4ForEffect(name, color, alpha, suffix = "") {
+ this._currentEffect.setColor4(name + suffix, color, alpha);
+ }
+ _updateDirectColor4ForEffect(name, color, suffix = "") {
+ this._currentEffect.setDirectColor4(name + suffix, color);
+ }
+ _updateColor4ForUniform(name, color, alpha) {
+ UniformBuffer._TempBuffer[0] = color.r;
+ UniformBuffer._TempBuffer[1] = color.g;
+ UniformBuffer._TempBuffer[2] = color.b;
+ UniformBuffer._TempBuffer[3] = alpha;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 4);
+ }
+ _updateDirectColor4ForUniform(name, color) {
+ UniformBuffer._TempBuffer[0] = color.r;
+ UniformBuffer._TempBuffer[1] = color.g;
+ UniformBuffer._TempBuffer[2] = color.b;
+ UniformBuffer._TempBuffer[3] = color.a;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 4);
+ }
+ _updateIntForEffect(name, x, suffix = "") {
+ this._currentEffect.setInt(name + suffix, x);
+ }
+ _updateIntForUniform(name, x) {
+ UniformBuffer._TempBufferInt32View[0] = x;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 1);
+ }
+ _updateInt2ForEffect(name, x, y, suffix = "") {
+ this._currentEffect.setInt2(name + suffix, x, y);
+ }
+ _updateInt2ForUniform(name, x, y) {
+ UniformBuffer._TempBufferInt32View[0] = x;
+ UniformBuffer._TempBufferInt32View[1] = y;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 2);
+ }
+ _updateInt3ForEffect(name, x, y, z, suffix = "") {
+ this._currentEffect.setInt3(name + suffix, x, y, z);
+ }
+ _updateInt3ForUniform(name, x, y, z) {
+ UniformBuffer._TempBufferInt32View[0] = x;
+ UniformBuffer._TempBufferInt32View[1] = y;
+ UniformBuffer._TempBufferInt32View[2] = z;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 3);
+ }
+ _updateInt4ForEffect(name, x, y, z, w, suffix = "") {
+ this._currentEffect.setInt4(name + suffix, x, y, z, w);
+ }
+ _updateInt4ForUniform(name, x, y, z, w) {
+ UniformBuffer._TempBufferInt32View[0] = x;
+ UniformBuffer._TempBufferInt32View[1] = y;
+ UniformBuffer._TempBufferInt32View[2] = z;
+ UniformBuffer._TempBufferInt32View[3] = w;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 4);
+ }
+ _updateUIntForEffect(name, x, suffix = "") {
+ this._currentEffect.setUInt(name + suffix, x);
+ }
+ _updateUIntForUniform(name, x) {
+ UniformBuffer._TempBufferUInt32View[0] = x;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 1);
+ }
+ _updateUInt2ForEffect(name, x, y, suffix = "") {
+ this._currentEffect.setUInt2(name + suffix, x, y);
+ }
+ _updateUInt2ForUniform(name, x, y) {
+ UniformBuffer._TempBufferUInt32View[0] = x;
+ UniformBuffer._TempBufferUInt32View[1] = y;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 2);
+ }
+ _updateUInt3ForEffect(name, x, y, z, suffix = "") {
+ this._currentEffect.setUInt3(name + suffix, x, y, z);
+ }
+ _updateUInt3ForUniform(name, x, y, z) {
+ UniformBuffer._TempBufferUInt32View[0] = x;
+ UniformBuffer._TempBufferUInt32View[1] = y;
+ UniformBuffer._TempBufferUInt32View[2] = z;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 3);
+ }
+ _updateUInt4ForEffect(name, x, y, z, w, suffix = "") {
+ this._currentEffect.setUInt4(name + suffix, x, y, z, w);
+ }
+ _updateUInt4ForUniform(name, x, y, z, w) {
+ UniformBuffer._TempBufferUInt32View[0] = x;
+ UniformBuffer._TempBufferUInt32View[1] = y;
+ UniformBuffer._TempBufferUInt32View[2] = z;
+ UniformBuffer._TempBufferUInt32View[3] = w;
+ this.updateUniform(name, UniformBuffer._TempBuffer, 4);
+ }
+ /**
+ * Sets a sampler uniform on the effect.
+ * @param name Define the name of the sampler.
+ * @param texture Define the texture to set in the sampler
+ */
+ setTexture(name, texture) {
+ this._currentEffect.setTexture(name, texture);
+ }
+ /**
+ * Sets an array of sampler uniforms on the effect.
+ * @param name Define the name of uniform.
+ * @param textures Define the textures to set in the array of samplers
+ */
+ setTextureArray(name, textures) {
+ this._currentEffect.setTextureArray(name, textures);
+ }
+ /**
+ * Sets a sampler uniform on the effect.
+ * @param name Define the name of the sampler.
+ * @param texture Define the (internal) texture to set in the sampler
+ */
+ bindTexture(name, texture) {
+ this._currentEffect._bindTexture(name, texture);
+ }
+ /**
+ * Directly updates the value of the uniform in the cache AND on the GPU.
+ * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
+ * @param data Define the flattened data
+ */
+ updateUniformDirectly(uniformName, data) {
+ this.updateUniform(uniformName, data, data.length);
+ this.update();
+ }
+ /**
+ * Associates an effect to this uniform buffer
+ * @param effect Define the effect to associate the buffer to
+ * @param name Name of the uniform block in the shader.
+ */
+ bindToEffect(effect, name) {
+ this._currentEffect = effect;
+ this._currentEffectName = name;
+ }
+ /**
+ * Binds the current (GPU) buffer to the effect
+ */
+ bindUniformBuffer() {
+ if (!this._noUBO && this._buffer && this._currentEffect) {
+ this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName);
+ }
+ }
+ /**
+ * Dissociates the current effect from this uniform buffer
+ */
+ unbindEffect() {
+ this._currentEffect = undefined;
+ this._currentEffectName = undefined;
+ }
+ /**
+ * Sets the current state of the class (_bufferIndex, _buffer) to point to the data buffer passed in parameter if this buffer is one of the buffers handled by the class (meaning if it can be found in the _buffers array)
+ * This method is meant to be able to update a buffer at any time: just call setDataBuffer to set the class in the right state, call some updateXXX methods and then call udpate() => that will update the GPU buffer on the graphic card
+ * @param dataBuffer buffer to look for
+ * @returns true if the buffer has been found and the class internal state points to it, else false
+ */
+ setDataBuffer(dataBuffer) {
+ if (!this._buffers) {
+ return this._buffer === dataBuffer;
+ }
+ for (let b = 0; b < this._buffers.length; ++b) {
+ const buffer = this._buffers[b];
+ if (buffer[0] === dataBuffer) {
+ this._bufferIndex = b;
+ this._buffer = dataBuffer;
+ this._createBufferOnWrite = false;
+ this._currentEffect = undefined;
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * Disposes the uniform buffer.
+ */
+ dispose() {
+ if (this._noUBO) {
+ return;
+ }
+ const uniformBuffers = this._engine._uniformBuffers;
+ const index = uniformBuffers.indexOf(this);
+ if (index !== -1) {
+ uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];
+ uniformBuffers.pop();
+ }
+ if (this._engine._features.trackUbosInFrame && this._buffers) {
+ for (let i = 0; i < this._buffers.length; ++i) {
+ const buffer = this._buffers[i][0];
+ this._engine._releaseBuffer(buffer);
+ }
+ }
+ else if (this._buffer && this._engine._releaseBuffer(this._buffer)) {
+ this._buffer = null;
+ }
+ }
+}
+/** @internal */
+UniformBuffer._UpdatedUbosInFrame = {};
+// Pool for avoiding memory leaks
+UniformBuffer._MAX_UNIFORM_SIZE = 256;
+UniformBuffer._TempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
+UniformBuffer._TempBufferInt32View = new Int32Array(UniformBuffer._TempBuffer.buffer);
+UniformBuffer._TempBufferUInt32View = new Uint32Array(UniformBuffer._TempBuffer.buffer);
+
+function GetFloatValue(dataView, type, byteOffset, normalized) {
+ switch (type) {
+ case 5120: {
+ let value = dataView.getInt8(byteOffset);
+ if (normalized) {
+ value = Math.max(value / 127, -1);
+ }
+ return value;
+ }
+ case 5121: {
+ let value = dataView.getUint8(byteOffset);
+ if (normalized) {
+ value = value / 255;
+ }
+ return value;
+ }
+ case 5122: {
+ let value = dataView.getInt16(byteOffset, true);
+ if (normalized) {
+ value = Math.max(value / 32767, -1);
+ }
+ return value;
+ }
+ case 5123: {
+ let value = dataView.getUint16(byteOffset, true);
+ if (normalized) {
+ value = value / 65535;
+ }
+ return value;
+ }
+ case 5124: {
+ return dataView.getInt32(byteOffset, true);
+ }
+ case 5125: {
+ return dataView.getUint32(byteOffset, true);
+ }
+ case 5126: {
+ return dataView.getFloat32(byteOffset, true);
+ }
+ default: {
+ throw new Error(`Invalid component type ${type}`);
+ }
+ }
+}
+function SetFloatValue(dataView, type, byteOffset, normalized, value) {
+ switch (type) {
+ case 5120: {
+ if (normalized) {
+ value = Math.round(value * 127.0);
+ }
+ dataView.setInt8(byteOffset, value);
+ break;
+ }
+ case 5121: {
+ if (normalized) {
+ value = Math.round(value * 255);
+ }
+ dataView.setUint8(byteOffset, value);
+ break;
+ }
+ case 5122: {
+ if (normalized) {
+ value = Math.round(value * 32767);
+ }
+ dataView.setInt16(byteOffset, value, true);
+ break;
+ }
+ case 5123: {
+ if (normalized) {
+ value = Math.round(value * 65535);
+ }
+ dataView.setUint16(byteOffset, value, true);
+ break;
+ }
+ case 5124: {
+ dataView.setInt32(byteOffset, value, true);
+ break;
+ }
+ case 5125: {
+ dataView.setUint32(byteOffset, value, true);
+ break;
+ }
+ case 5126: {
+ dataView.setFloat32(byteOffset, value, true);
+ break;
+ }
+ default: {
+ throw new Error(`Invalid component type ${type}`);
+ }
+ }
+}
+/**
+ * Gets the byte length of the given type.
+ * @param type the type
+ * @returns the number of bytes
+ */
+function GetTypeByteLength(type) {
+ switch (type) {
+ case 5120:
+ case 5121:
+ return 1;
+ case 5122:
+ case 5123:
+ return 2;
+ case 5124:
+ case 5125:
+ case 5126:
+ return 4;
+ default:
+ throw new Error(`Invalid type '${type}'`);
+ }
+}
+/**
+ * Gets the appropriate TypedArray constructor for the given component type.
+ * @param componentType the component type
+ * @returns the constructor object
+ */
+function GetTypedArrayConstructor(componentType) {
+ switch (componentType) {
+ case 5120:
+ return Int8Array;
+ case 5121:
+ return Uint8Array;
+ case 5122:
+ return Int16Array;
+ case 5123:
+ return Uint16Array;
+ case 5124:
+ return Int32Array;
+ case 5125:
+ return Uint32Array;
+ case 5126:
+ return Float32Array;
+ default:
+ throw new Error(`Invalid component type '${componentType}'`);
+ }
+}
+/**
+ * Enumerates each value of the data array and calls the given callback.
+ * @param data the data to enumerate
+ * @param byteOffset the byte offset of the data
+ * @param byteStride the byte stride of the data
+ * @param componentCount the number of components per element
+ * @param componentType the type of the component
+ * @param count the number of values to enumerate
+ * @param normalized whether the data is normalized
+ * @param callback the callback function called for each group of component values
+ */
+function EnumerateFloatValues(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
+ const oldValues = new Array(componentCount);
+ const newValues = new Array(componentCount);
+ if (data instanceof Array) {
+ let offset = byteOffset / 4;
+ const stride = byteStride / 4;
+ for (let index = 0; index < count; index += componentCount) {
+ for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {
+ oldValues[componentIndex] = newValues[componentIndex] = data[offset + componentIndex];
+ }
+ callback(newValues, index);
+ for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {
+ if (oldValues[componentIndex] !== newValues[componentIndex]) {
+ data[offset + componentIndex] = newValues[componentIndex];
+ }
+ }
+ offset += stride;
+ }
+ }
+ else {
+ const dataView = !ArrayBuffer.isView(data) ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
+ const componentByteLength = GetTypeByteLength(componentType);
+ for (let index = 0; index < count; index += componentCount) {
+ for (let componentIndex = 0, componentByteOffset = byteOffset; componentIndex < componentCount; componentIndex++, componentByteOffset += componentByteLength) {
+ oldValues[componentIndex] = newValues[componentIndex] = GetFloatValue(dataView, componentType, componentByteOffset, normalized);
+ }
+ callback(newValues, index);
+ for (let componentIndex = 0, componentByteOffset = byteOffset; componentIndex < componentCount; componentIndex++, componentByteOffset += componentByteLength) {
+ if (oldValues[componentIndex] !== newValues[componentIndex]) {
+ SetFloatValue(dataView, componentType, componentByteOffset, normalized, newValues[componentIndex]);
+ }
+ }
+ byteOffset += byteStride;
+ }
+ }
+}
+/**
+ * Gets the given data array as a float array. Float data is constructed if the data array cannot be returned directly.
+ * @param data the input data array
+ * @param size the number of components
+ * @param type the component type
+ * @param byteOffset the byte offset of the data
+ * @param byteStride the byte stride of the data
+ * @param normalized whether the data is normalized
+ * @param totalVertices number of vertices in the buffer to take into account
+ * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
+ * @returns a float array containing vertex data
+ */
+function GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) {
+ const tightlyPackedByteStride = size * GetTypeByteLength(type);
+ const count = totalVertices * size;
+ if (type !== 5126 || byteStride !== tightlyPackedByteStride) {
+ const copy = new Float32Array(count);
+ EnumerateFloatValues(data, byteOffset, byteStride, size, type, count, normalized, (values, index) => {
+ for (let i = 0; i < size; i++) {
+ copy[index + i] = values[i];
+ }
+ });
+ return copy;
+ }
+ if (!(data instanceof Array || data instanceof Float32Array) || byteOffset !== 0 || data.length !== count) {
+ if (data instanceof Array) {
+ const offset = byteOffset / 4;
+ return data.slice(offset, offset + count);
+ }
+ else if (data instanceof ArrayBuffer) {
+ return new Float32Array(data, byteOffset, count);
+ }
+ else {
+ const offset = data.byteOffset + byteOffset;
+ if ((offset & 3) !== 0) {
+ Logger.Warn("Float array must be aligned to 4-bytes border");
+ forceCopy = true;
+ }
+ if (forceCopy) {
+ return new Float32Array(data.buffer.slice(offset, offset + count * Float32Array.BYTES_PER_ELEMENT));
+ }
+ else {
+ return new Float32Array(data.buffer, offset, count);
+ }
+ }
+ }
+ if (forceCopy) {
+ return data.slice();
+ }
+ return data;
+}
+/**
+ * Gets the given data array as a typed array that matches the component type. If the data cannot be used directly, a copy is made to support the new typed array.
+ * If the data is number[], byteOffset and byteStride must be a multiple of 4, as data will be treated like a list of floats.
+ * @param data the input data array
+ * @param size the number of components
+ * @param type the component type
+ * @param byteOffset the byte offset of the data
+ * @param byteStride the byte stride of the data
+ * @param normalized whether the data is normalized
+ * @param totalVertices number of vertices in the buffer to take into account
+ * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
+ * @returns a typed array containing vertex data
+ */
+function GetTypedArrayData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) {
+ const typeByteLength = GetTypeByteLength(type);
+ const constructor = GetTypedArrayConstructor(type);
+ const count = totalVertices * size;
+ // Handle number[]
+ if (Array.isArray(data)) {
+ if ((byteOffset & 3) !== 0 || (byteStride & 3) !== 0) {
+ throw new Error("byteOffset and byteStride must be a multiple of 4 for number[] data.");
+ }
+ const offset = byteOffset / 4;
+ const stride = byteStride / 4;
+ const lastIndex = offset + (totalVertices - 1) * stride + size;
+ if (lastIndex > data.length) {
+ throw new Error("Last accessed index is out of bounds.");
+ }
+ if (stride < size) {
+ throw new Error("Data stride cannot be smaller than the component size.");
+ }
+ if (stride !== size) {
+ const copy = new constructor(count);
+ EnumerateFloatValues(data, byteOffset, byteStride, size, type, count, normalized, (values, index) => {
+ for (let i = 0; i < size; i++) {
+ copy[index + i] = values[i];
+ }
+ });
+ return copy;
+ }
+ return new constructor(data.slice(offset, offset + count));
+ }
+ // Handle ArrayBuffer and ArrayBufferView
+ let buffer;
+ let adjustedByteOffset = byteOffset;
+ if (data instanceof ArrayBuffer) {
+ buffer = data;
+ }
+ else {
+ buffer = data.buffer;
+ adjustedByteOffset += data.byteOffset;
+ }
+ const lastByteOffset = adjustedByteOffset + (totalVertices - 1) * byteStride + size * typeByteLength;
+ if (lastByteOffset > buffer.byteLength) {
+ throw new Error("Last accessed byte is out of bounds.");
+ }
+ const tightlyPackedByteStride = size * typeByteLength;
+ if (byteStride < tightlyPackedByteStride) {
+ throw new Error("Byte stride cannot be smaller than the component's byte size.");
+ }
+ if (byteStride !== tightlyPackedByteStride) {
+ const copy = new constructor(count);
+ EnumerateFloatValues(buffer, adjustedByteOffset, byteStride, size, type, count, normalized, (values, index) => {
+ for (let i = 0; i < size; i++) {
+ copy[index + i] = values[i];
+ }
+ });
+ return copy;
+ }
+ if (typeByteLength !== 1 && (adjustedByteOffset & (typeByteLength - 1)) !== 0) {
+ Logger.Warn("Array must be aligned to border of element size. Data will be copied.");
+ forceCopy = true;
+ }
+ if (forceCopy) {
+ return new constructor(buffer.slice(adjustedByteOffset, adjustedByteOffset + count * typeByteLength));
+ }
+ return new constructor(buffer, adjustedByteOffset, count);
+}
+/**
+ * Copies the given data array to the given float array.
+ * @param input the input data array
+ * @param size the number of components
+ * @param type the component type
+ * @param byteOffset the byte offset of the data
+ * @param byteStride the byte stride of the data
+ * @param normalized whether the data is normalized
+ * @param totalVertices number of vertices in the buffer to take into account
+ * @param output the output float array
+ */
+function CopyFloatData(input, size, type, byteOffset, byteStride, normalized, totalVertices, output) {
+ const tightlyPackedByteStride = size * GetTypeByteLength(type);
+ const count = totalVertices * size;
+ if (output.length !== count) {
+ throw new Error("Output length is not valid");
+ }
+ if (type !== 5126 || byteStride !== tightlyPackedByteStride) {
+ EnumerateFloatValues(input, byteOffset, byteStride, size, type, count, normalized, (values, index) => {
+ for (let i = 0; i < size; i++) {
+ output[index + i] = values[i];
+ }
+ });
+ return;
+ }
+ if (input instanceof Array) {
+ const offset = byteOffset / 4;
+ output.set(input, offset);
+ }
+ else if (input instanceof ArrayBuffer) {
+ const floatData = new Float32Array(input, byteOffset, count);
+ output.set(floatData);
+ }
+ else {
+ const offset = input.byteOffset + byteOffset;
+ if ((offset & 3) !== 0) {
+ Logger.Warn("Float array must be aligned to 4-bytes border");
+ output.set(new Float32Array(input.buffer.slice(offset, offset + count * Float32Array.BYTES_PER_ELEMENT)));
+ return;
+ }
+ const floatData = new Float32Array(input.buffer, offset, count);
+ output.set(floatData);
+ }
+}
+/**
+ * Utility function to determine if an IndicesArray is an Uint32Array. If indices is an Array, determines whether at least one index is 32 bits.
+ * @param indices The IndicesArray to check.
+ * @param count The number of indices. Only used if indices is an Array.
+ * @param start The offset to start at (default: 0). Only used if indices is an Array.
+ * @param offset The offset to substract from the indices before testing (default: 0). Only used if indices is an Array.
+ * @returns True if the indices use 32 bits
+ */
+function AreIndices32Bits(indices, count, start = 0, offset = 0) {
+ if (Array.isArray(indices)) {
+ for (let index = 0; index < count; index++) {
+ if (indices[start + index] - offset > 65535) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return indices.BYTES_PER_ELEMENT === 4;
+}
+
+/**
+ * Class used to store data that will be store in GPU memory
+ */
+class Buffer {
+ /**
+ * Gets a boolean indicating if the Buffer is disposed
+ */
+ get isDisposed() {
+ return this._isDisposed;
+ }
+ /**
+ * Constructor
+ * @param engine the engine
+ * @param data the data to use for this buffer
+ * @param updatable whether the data is updatable
+ * @param stride the stride (optional)
+ * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
+ * @param instanced whether the buffer is instanced (optional)
+ * @param useBytes set to true if the stride in in bytes (optional)
+ * @param divisor sets an optional divisor for instances (1 by default)
+ * @param label defines the label of the buffer (for debug purpose)
+ */
+ constructor(engine, data, updatable, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false, divisor, label) {
+ this._isAlreadyOwned = false;
+ this._isDisposed = false;
+ if (engine && engine.getScene) {
+ // old versions of VertexBuffer accepted 'mesh' instead of 'engine'
+ this._engine = engine.getScene().getEngine();
+ }
+ else {
+ this._engine = engine;
+ }
+ this._updatable = updatable;
+ this._instanced = instanced;
+ this._divisor = divisor || 1;
+ this._label = label;
+ if (data instanceof DataBuffer) {
+ this._data = null;
+ this._buffer = data;
+ }
+ else {
+ this._data = data;
+ this._buffer = null;
+ }
+ this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
+ if (!postponeInternalCreation) {
+ // by default
+ this.create();
+ }
+ }
+ /**
+ * Create a new VertexBuffer based on the current buffer
+ * @param kind defines the vertex buffer kind (position, normal, etc.)
+ * @param offset defines offset in the buffer (0 by default)
+ * @param size defines the size in floats of attributes (position is 3 for instance)
+ * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
+ * @param instanced defines if the vertex buffer contains indexed data
+ * @param useBytes defines if the offset and stride are in bytes *
+ * @param divisor sets an optional divisor for instances (1 by default)
+ * @returns the new vertex buffer
+ */
+ createVertexBuffer(kind, offset, size, stride, instanced, useBytes = false, divisor) {
+ const byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
+ const byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
+ // a lot of these parameters are ignored as they are overridden by the buffer
+ return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true, this._divisor || divisor);
+ }
+ // Properties
+ /**
+ * Gets a boolean indicating if the Buffer is updatable?
+ * @returns true if the buffer is updatable
+ */
+ isUpdatable() {
+ return this._updatable;
+ }
+ /**
+ * Gets current buffer's data
+ * @returns a DataArray or null
+ */
+ getData() {
+ return this._data;
+ }
+ /**
+ * Gets underlying native buffer
+ * @returns underlying native buffer
+ */
+ getBuffer() {
+ return this._buffer;
+ }
+ /**
+ * Gets the stride in float32 units (i.e. byte stride / 4).
+ * May not be an integer if the byte stride is not divisible by 4.
+ * @returns the stride in float32 units
+ * @deprecated Please use byteStride instead.
+ */
+ getStrideSize() {
+ return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
+ }
+ // Methods
+ /**
+ * Store data into the buffer. Creates the buffer if not used already.
+ * If the buffer was already used, it will be updated only if it is updatable, otherwise it will do nothing.
+ * @param data defines the data to store
+ */
+ create(data = null) {
+ if (!data && this._buffer) {
+ return; // nothing to do
+ }
+ data = data || this._data;
+ if (!data) {
+ return;
+ }
+ if (!this._buffer) {
+ // create buffer
+ if (this._updatable) {
+ this._buffer = this._engine.createDynamicVertexBuffer(data, this._label);
+ this._data = data;
+ }
+ else {
+ this._buffer = this._engine.createVertexBuffer(data, undefined, this._label);
+ }
+ }
+ else if (this._updatable) {
+ // update buffer
+ this._engine.updateDynamicVertexBuffer(this._buffer, data);
+ this._data = data;
+ }
+ }
+ /** @internal */
+ _rebuild() {
+ if (!this._data) {
+ if (!this._buffer) {
+ // Buffer was not yet created, nothing to do
+ return;
+ }
+ if (this._buffer.capacity > 0) {
+ // We can at least recreate the buffer with the right size, even if we don't have the data
+ if (this._updatable) {
+ this._buffer = this._engine.createDynamicVertexBuffer(this._buffer.capacity, this._label);
+ }
+ else {
+ this._buffer = this._engine.createVertexBuffer(this._buffer.capacity, undefined, this._label);
+ }
+ return;
+ }
+ Logger.Warn(`Missing data for buffer "${this._label}" ${this._buffer ? "(uniqueId: " + this._buffer.uniqueId + ")" : ""}. Buffer reconstruction failed.`);
+ this._buffer = null;
+ }
+ else {
+ this._buffer = null;
+ this.create(this._data);
+ }
+ }
+ /**
+ * Update current buffer data
+ * @param data defines the data to store
+ */
+ update(data) {
+ this.create(data);
+ }
+ /**
+ * Updates the data directly.
+ * @param data the new data
+ * @param offset the new offset
+ * @param vertexCount the vertex count (optional)
+ * @param useBytes set to true if the offset is in bytes
+ */
+ updateDirectly(data, offset, vertexCount, useBytes = false) {
+ if (!this._buffer) {
+ return;
+ }
+ if (this._updatable) {
+ // update buffer
+ this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : undefined);
+ if (offset === 0 && vertexCount === undefined) {
+ // Keep the data if we easily can
+ this._data = data;
+ }
+ else {
+ this._data = null;
+ }
+ }
+ }
+ /** @internal */
+ _increaseReferences() {
+ if (!this._buffer) {
+ return;
+ }
+ if (!this._isAlreadyOwned) {
+ this._isAlreadyOwned = true;
+ return;
+ }
+ this._buffer.references++;
+ }
+ /**
+ * Release all resources
+ */
+ dispose() {
+ if (!this._buffer) {
+ return;
+ }
+ // The data buffer has an internal counter as this buffer can be used by several VertexBuffer objects
+ // This means that we only flag it as disposed when all references are released (when _releaseBuffer will return true)
+ if (this._engine._releaseBuffer(this._buffer)) {
+ this._isDisposed = true;
+ this._data = null;
+ this._buffer = null;
+ }
+ }
+}
+/**
+ * Specialized buffer used to store vertex data
+ */
+class VertexBuffer {
+ /**
+ * Gets a boolean indicating if the Buffer is disposed
+ */
+ get isDisposed() {
+ return this._isDisposed;
+ }
+ /**
+ * Gets or sets the instance divisor when in instanced mode
+ */
+ get instanceDivisor() {
+ return this._instanceDivisor;
+ }
+ set instanceDivisor(value) {
+ const isInstanced = value != 0;
+ this._instanceDivisor = value;
+ if (isInstanced !== this._instanced) {
+ this._instanced = isInstanced;
+ this._computeHashCode();
+ }
+ }
+ /**
+ * Gets the max possible amount of vertices stored within the current vertex buffer.
+ * We do not have the end offset or count so this will be too big for concatenated vertex buffers.
+ * @internal
+ */
+ get _maxVerticesCount() {
+ const data = this.getData();
+ if (!data) {
+ return 0;
+ }
+ if (Array.isArray(data)) {
+ // data is a regular number[] with float values
+ return data.length / (this.byteStride / 4) - this.byteOffset / 4;
+ }
+ return (data.byteLength - this.byteOffset) / this.byteStride;
+ }
+ /** @internal */
+ constructor(engine, data, kind, updatableOrOptions, postponeInternalCreation, stride, instanced, offset, size, type, normalized = false, useBytes = false, divisor = 1, takeBufferOwnership = false) {
+ /** @internal */
+ this._isDisposed = false;
+ let updatable = false;
+ this.engine = engine;
+ if (typeof updatableOrOptions === "object" && updatableOrOptions !== null) {
+ updatable = updatableOrOptions.updatable ?? false;
+ postponeInternalCreation = updatableOrOptions.postponeInternalCreation;
+ stride = updatableOrOptions.stride;
+ instanced = updatableOrOptions.instanced;
+ offset = updatableOrOptions.offset;
+ size = updatableOrOptions.size;
+ type = updatableOrOptions.type;
+ normalized = updatableOrOptions.normalized ?? false;
+ useBytes = updatableOrOptions.useBytes ?? false;
+ divisor = updatableOrOptions.divisor ?? 1;
+ takeBufferOwnership = updatableOrOptions.takeBufferOwnership ?? false;
+ this._label = updatableOrOptions.label;
+ }
+ else {
+ updatable = !!updatableOrOptions;
+ }
+ if (data instanceof Buffer) {
+ this._buffer = data;
+ this._ownsBuffer = takeBufferOwnership;
+ }
+ else {
+ this._buffer = new Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes, divisor, this._label);
+ this._ownsBuffer = true;
+ }
+ this.uniqueId = VertexBuffer._Counter++;
+ this._kind = kind;
+ if (type === undefined) {
+ const vertexData = this.getData();
+ this.type = vertexData ? VertexBuffer.GetDataType(vertexData) : VertexBuffer.FLOAT;
+ }
+ else {
+ this.type = type;
+ }
+ const typeByteLength = GetTypeByteLength(this.type);
+ if (useBytes) {
+ this._size = size || (stride ? stride / typeByteLength : VertexBuffer.DeduceStride(kind));
+ this.byteStride = stride || this._buffer.byteStride || this._size * typeByteLength;
+ this.byteOffset = offset || 0;
+ }
+ else {
+ this._size = size || stride || VertexBuffer.DeduceStride(kind);
+ this.byteStride = stride ? stride * typeByteLength : this._buffer.byteStride || this._size * typeByteLength;
+ this.byteOffset = (offset || 0) * typeByteLength;
+ }
+ this.normalized = normalized;
+ this._instanced = instanced !== undefined ? instanced : false;
+ this._instanceDivisor = instanced ? divisor : 0;
+ this._alignBuffer();
+ this._computeHashCode();
+ }
+ _computeHashCode() {
+ // note: cast to any because the property is declared readonly
+ this.hashCode =
+ ((this.type - 5120) << 0) +
+ ((this.normalized ? 1 : 0) << 3) +
+ (this._size << 4) +
+ ((this._instanced ? 1 : 0) << 6) +
+ /* keep 5 bits free */
+ (this.byteStride << 12);
+ }
+ /** @internal */
+ _rebuild() {
+ this._buffer?._rebuild();
+ }
+ /**
+ * Returns the kind of the VertexBuffer (string)
+ * @returns a string
+ */
+ getKind() {
+ return this._kind;
+ }
+ // Properties
+ /**
+ * Gets a boolean indicating if the VertexBuffer is updatable?
+ * @returns true if the buffer is updatable
+ */
+ isUpdatable() {
+ return this._buffer.isUpdatable();
+ }
+ /**
+ * Gets current buffer's data
+ * @returns a DataArray or null
+ */
+ getData() {
+ return this._buffer.getData();
+ }
+ /**
+ * Gets current buffer's data as a float array. Float data is constructed if the vertex buffer data cannot be returned directly.
+ * @param totalVertices number of vertices in the buffer to take into account
+ * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
+ * @returns a float array containing vertex data
+ */
+ getFloatData(totalVertices, forceCopy) {
+ const data = this.getData();
+ if (!data) {
+ return null;
+ }
+ return GetFloatData(data, this._size, this.type, this.byteOffset, this.byteStride, this.normalized, totalVertices, forceCopy);
+ }
+ /**
+ * Gets underlying native buffer
+ * @returns underlying native buffer
+ */
+ getBuffer() {
+ return this._buffer.getBuffer();
+ }
+ /**
+ * Gets the Buffer instance that wraps the native GPU buffer
+ * @returns the wrapper buffer
+ */
+ getWrapperBuffer() {
+ return this._buffer;
+ }
+ /**
+ * Gets the stride in float32 units (i.e. byte stride / 4).
+ * May not be an integer if the byte stride is not divisible by 4.
+ * @returns the stride in float32 units
+ * @deprecated Please use byteStride instead.
+ */
+ getStrideSize() {
+ return this.byteStride / GetTypeByteLength(this.type);
+ }
+ /**
+ * Returns the offset as a multiple of the type byte length.
+ * @returns the offset in bytes
+ * @deprecated Please use byteOffset instead.
+ */
+ getOffset() {
+ return this.byteOffset / GetTypeByteLength(this.type);
+ }
+ /**
+ * Returns the number of components or the byte size per vertex attribute
+ * @param sizeInBytes If true, returns the size in bytes or else the size in number of components of the vertex attribute (default: false)
+ * @returns the number of components
+ */
+ getSize(sizeInBytes = false) {
+ return sizeInBytes ? this._size * GetTypeByteLength(this.type) : this._size;
+ }
+ /**
+ * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
+ * @returns true if this buffer is instanced
+ */
+ getIsInstanced() {
+ return this._instanced;
+ }
+ /**
+ * Returns the instancing divisor, zero for non-instanced (integer).
+ * @returns a number
+ */
+ getInstanceDivisor() {
+ return this._instanceDivisor;
+ }
+ // Methods
+ /**
+ * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
+ * @param data defines the data to store
+ */
+ create(data) {
+ this._buffer.create(data);
+ this._alignBuffer();
+ }
+ /**
+ * Updates the underlying buffer according to the passed numeric array or Float32Array.
+ * This function will create a new buffer if the current one is not updatable
+ * @param data defines the data to store
+ */
+ update(data) {
+ this._buffer.update(data);
+ this._alignBuffer();
+ }
+ /**
+ * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
+ * Returns the directly updated WebGLBuffer.
+ * @param data the new data
+ * @param offset the new offset
+ * @param useBytes set to true if the offset is in bytes
+ */
+ updateDirectly(data, offset, useBytes = false) {
+ this._buffer.updateDirectly(data, offset, undefined, useBytes);
+ this._alignBuffer();
+ }
+ /**
+ * Disposes the VertexBuffer and the underlying WebGLBuffer.
+ */
+ dispose() {
+ if (this._ownsBuffer) {
+ this._buffer.dispose();
+ }
+ this._isDisposed = true;
+ }
+ /**
+ * Enumerates each value of this vertex buffer as numbers.
+ * @param count the number of values to enumerate
+ * @param callback the callback function called for each value
+ */
+ forEach(count, callback) {
+ EnumerateFloatValues(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, (values, index) => {
+ for (let i = 0; i < this._size; i++) {
+ callback(values[i], index + i);
+ }
+ });
+ }
+ /** @internal */
+ _alignBuffer() { }
+ /**
+ * Deduces the stride given a kind.
+ * @param kind The kind string to deduce
+ * @returns The deduced stride
+ */
+ static DeduceStride(kind) {
+ switch (kind) {
+ case VertexBuffer.UVKind:
+ case VertexBuffer.UV2Kind:
+ case VertexBuffer.UV3Kind:
+ case VertexBuffer.UV4Kind:
+ case VertexBuffer.UV5Kind:
+ case VertexBuffer.UV6Kind:
+ return 2;
+ case VertexBuffer.NormalKind:
+ case VertexBuffer.PositionKind:
+ return 3;
+ case VertexBuffer.ColorKind:
+ case VertexBuffer.ColorInstanceKind:
+ case VertexBuffer.MatricesIndicesKind:
+ case VertexBuffer.MatricesIndicesExtraKind:
+ case VertexBuffer.MatricesWeightsKind:
+ case VertexBuffer.MatricesWeightsExtraKind:
+ case VertexBuffer.TangentKind:
+ return 4;
+ default:
+ throw new Error("Invalid kind '" + kind + "'");
+ }
+ }
+ /**
+ * Gets the vertex buffer type of the given data array.
+ * @param data the data array
+ * @returns the vertex buffer type
+ */
+ static GetDataType(data) {
+ if (data instanceof Int8Array) {
+ return VertexBuffer.BYTE;
+ }
+ else if (data instanceof Uint8Array) {
+ return VertexBuffer.UNSIGNED_BYTE;
+ }
+ else if (data instanceof Int16Array) {
+ return VertexBuffer.SHORT;
+ }
+ else if (data instanceof Uint16Array) {
+ return VertexBuffer.UNSIGNED_SHORT;
+ }
+ else if (data instanceof Int32Array) {
+ return VertexBuffer.INT;
+ }
+ else if (data instanceof Uint32Array) {
+ return VertexBuffer.UNSIGNED_INT;
+ }
+ else {
+ return VertexBuffer.FLOAT;
+ }
+ }
+ /**
+ * Gets the byte length of the given type.
+ * @param type the type
+ * @returns the number of bytes
+ * @deprecated Use `getTypeByteLength` from `bufferUtils` instead
+ */
+ static GetTypeByteLength(type) {
+ return GetTypeByteLength(type);
+ }
+ /**
+ * Enumerates each value of the given parameters as numbers.
+ * @param data the data to enumerate
+ * @param byteOffset the byte offset of the data
+ * @param byteStride the byte stride of the data
+ * @param componentCount the number of components per element
+ * @param componentType the type of the component
+ * @param count the number of values to enumerate
+ * @param normalized whether the data is normalized
+ * @param callback the callback function called for each value
+ * @deprecated Use `EnumerateFloatValues` from `bufferUtils` instead
+ */
+ static ForEach(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
+ EnumerateFloatValues(data, byteOffset, byteStride, componentCount, componentType, count, normalized, (values, index) => {
+ for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {
+ callback(values[componentIndex], index + componentIndex);
+ }
+ });
+ }
+ /**
+ * Gets the given data array as a float array. Float data is constructed if the data array cannot be returned directly.
+ * @param data the input data array
+ * @param size the number of components
+ * @param type the component type
+ * @param byteOffset the byte offset of the data
+ * @param byteStride the byte stride of the data
+ * @param normalized whether the data is normalized
+ * @param totalVertices number of vertices in the buffer to take into account
+ * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
+ * @returns a float array containing vertex data
+ * @deprecated Use `GetFloatData` from `bufferUtils` instead
+ */
+ static GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) {
+ return GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy);
+ }
+}
+VertexBuffer._Counter = 0;
+/**
+ * The byte type.
+ */
+VertexBuffer.BYTE = 5120;
+/**
+ * The unsigned byte type.
+ */
+VertexBuffer.UNSIGNED_BYTE = 5121;
+/**
+ * The short type.
+ */
+VertexBuffer.SHORT = 5122;
+/**
+ * The unsigned short type.
+ */
+VertexBuffer.UNSIGNED_SHORT = 5123;
+/**
+ * The integer type.
+ */
+VertexBuffer.INT = 5124;
+/**
+ * The unsigned integer type.
+ */
+VertexBuffer.UNSIGNED_INT = 5125;
+/**
+ * The float type.
+ */
+VertexBuffer.FLOAT = 5126;
+// Enums
+/**
+ * Positions
+ */
+VertexBuffer.PositionKind = `position`;
+/**
+ * Normals
+ */
+VertexBuffer.NormalKind = `normal`;
+/**
+ * Tangents
+ */
+VertexBuffer.TangentKind = `tangent`;
+/**
+ * Texture coordinates
+ */
+VertexBuffer.UVKind = `uv`;
+/**
+ * Texture coordinates 2
+ */
+VertexBuffer.UV2Kind = `uv2`;
+/**
+ * Texture coordinates 3
+ */
+VertexBuffer.UV3Kind = `uv3`;
+/**
+ * Texture coordinates 4
+ */
+VertexBuffer.UV4Kind = `uv4`;
+/**
+ * Texture coordinates 5
+ */
+VertexBuffer.UV5Kind = `uv5`;
+/**
+ * Texture coordinates 6
+ */
+VertexBuffer.UV6Kind = `uv6`;
+/**
+ * Colors
+ */
+VertexBuffer.ColorKind = `color`;
+/**
+ * Instance Colors
+ */
+VertexBuffer.ColorInstanceKind = `instanceColor`;
+/**
+ * Matrix indices (for bones)
+ */
+VertexBuffer.MatricesIndicesKind = `matricesIndices`;
+/**
+ * Matrix weights (for bones)
+ */
+VertexBuffer.MatricesWeightsKind = `matricesWeights`;
+/**
+ * Additional matrix indices (for bones)
+ */
+VertexBuffer.MatricesIndicesExtraKind = `matricesIndicesExtra`;
+/**
+ * Additional matrix weights (for bones)
+ */
+VertexBuffer.MatricesWeightsExtraKind = `matricesWeightsExtra`;
+
+/**
+ * Information about the result of picking within a scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions
+ */
+class PickingInfo {
+ constructor() {
+ /**
+ * If the pick collided with an object
+ */
+ this.hit = false;
+ /**
+ * Distance away where the pick collided
+ */
+ this.distance = 0;
+ /**
+ * The location of pick collision
+ */
+ this.pickedPoint = null;
+ /**
+ * The mesh corresponding the pick collision
+ */
+ this.pickedMesh = null;
+ /** (See getTextureCoordinates) The barycentric U coordinate that is used when calculating the texture coordinates of the collision.*/
+ this.bu = 0;
+ /** (See getTextureCoordinates) The barycentric V coordinate that is used when calculating the texture coordinates of the collision.*/
+ this.bv = 0;
+ /** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */
+ this.faceId = -1;
+ /** The index of the face on the subMesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */
+ this.subMeshFaceId = -1;
+ /** Id of the submesh that was picked */
+ this.subMeshId = 0;
+ /** If a sprite was picked, this will be the sprite the pick collided with */
+ this.pickedSprite = null;
+ /** If we are picking a mesh with thin instance, this will give you the picked thin instance */
+ this.thinInstanceIndex = -1;
+ /**
+ * The ray that was used to perform the picking.
+ */
+ this.ray = null;
+ /**
+ * If a mesh was used to do the picking (eg. 6dof controller) as a "near interaction", this will be populated.
+ */
+ this.originMesh = null;
+ /**
+ * The aim-space transform of the input used for picking, if it is an XR input source.
+ */
+ this.aimTransform = null;
+ /**
+ * The grip-space transform of the input used for picking, if it is an XR input source.
+ * Some XR sources, such as input coming from head mounted displays, do not have this.
+ */
+ this.gripTransform = null;
+ }
+ /**
+ * Gets the normal corresponding to the face the pick collided with
+ * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
+ * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map (default: true)
+ * @returns The normal corresponding to the face the pick collided with
+ * @remarks Note that the returned normal will always point towards the picking ray.
+ */
+ getNormal(useWorldCoordinates = false, useVerticesNormals = true) {
+ if (!this.pickedMesh || (useVerticesNormals && !this.pickedMesh.isVerticesDataPresent(VertexBuffer.NormalKind))) {
+ return null;
+ }
+ let indices = this.pickedMesh.getIndices();
+ if (indices?.length === 0) {
+ indices = null;
+ }
+ let result;
+ const tmp0 = TmpVectors.Vector3[0];
+ const tmp1 = TmpVectors.Vector3[1];
+ const tmp2 = TmpVectors.Vector3[2];
+ if (useVerticesNormals) {
+ const normals = this.pickedMesh.getVerticesData(VertexBuffer.NormalKind);
+ let normal0 = indices
+ ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3] * 3, tmp0)
+ : tmp0.copyFromFloats(normals[this.faceId * 3 * 3], normals[this.faceId * 3 * 3 + 1], normals[this.faceId * 3 * 3 + 2]);
+ let normal1 = indices
+ ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 1] * 3, tmp1)
+ : tmp1.copyFromFloats(normals[(this.faceId * 3 + 1) * 3], normals[(this.faceId * 3 + 1) * 3 + 1], normals[(this.faceId * 3 + 1) * 3 + 2]);
+ let normal2 = indices
+ ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 2] * 3, tmp2)
+ : tmp2.copyFromFloats(normals[(this.faceId * 3 + 2) * 3], normals[(this.faceId * 3 + 2) * 3 + 1], normals[(this.faceId * 3 + 2) * 3 + 2]);
+ normal0 = normal0.scale(this.bu);
+ normal1 = normal1.scale(this.bv);
+ normal2 = normal2.scale(1.0 - this.bu - this.bv);
+ result = new Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
+ }
+ else {
+ const positions = this.pickedMesh.getVerticesData(VertexBuffer.PositionKind);
+ const vertex1 = indices
+ ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3] * 3, tmp0)
+ : tmp0.copyFromFloats(positions[this.faceId * 3 * 3], positions[this.faceId * 3 * 3 + 1], positions[this.faceId * 3 * 3 + 2]);
+ const vertex2 = indices
+ ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 1] * 3, tmp1)
+ : tmp1.copyFromFloats(positions[(this.faceId * 3 + 1) * 3], positions[(this.faceId * 3 + 1) * 3 + 1], positions[(this.faceId * 3 + 1) * 3 + 2]);
+ const vertex3 = indices
+ ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 2] * 3, tmp2)
+ : tmp2.copyFromFloats(positions[(this.faceId * 3 + 2) * 3], positions[(this.faceId * 3 + 2) * 3 + 1], positions[(this.faceId * 3 + 2) * 3 + 2]);
+ const p1p2 = vertex1.subtract(vertex2);
+ const p3p2 = vertex3.subtract(vertex2);
+ result = Vector3.Cross(p1p2, p3p2);
+ }
+ const transformNormalToWorld = (pickedMesh, n) => {
+ if (this.thinInstanceIndex !== -1) {
+ const tm = pickedMesh.thinInstanceGetWorldMatrices()[this.thinInstanceIndex];
+ if (tm) {
+ Vector3.TransformNormalToRef(n, tm, n);
+ }
+ }
+ let wm = pickedMesh.getWorldMatrix();
+ if (pickedMesh.nonUniformScaling) {
+ TmpVectors.Matrix[0].copyFrom(wm);
+ wm = TmpVectors.Matrix[0];
+ wm.setTranslationFromFloats(0, 0, 0);
+ wm.invert();
+ wm.transposeToRef(TmpVectors.Matrix[1]);
+ wm = TmpVectors.Matrix[1];
+ }
+ Vector3.TransformNormalToRef(n, wm, n);
+ };
+ if (useWorldCoordinates) {
+ transformNormalToWorld(this.pickedMesh, result);
+ }
+ if (this.ray) {
+ const normalForDirectionChecking = TmpVectors.Vector3[0].copyFrom(result);
+ if (!useWorldCoordinates) {
+ // the normal has not been transformed to world space as part as the normal processing, so we must do it now
+ transformNormalToWorld(this.pickedMesh, normalForDirectionChecking);
+ }
+ // Flip the normal if the picking ray is in the same direction.
+ if (Vector3.Dot(normalForDirectionChecking, this.ray.direction) > 0) {
+ result.negateInPlace();
+ }
+ }
+ result.normalize();
+ return result;
+ }
+ /**
+ * Gets the texture coordinates of where the pick occurred
+ * @param uvSet The UV set to use to calculate the texture coordinates (default: VertexBuffer.UVKind)
+ * @returns The vector containing the coordinates of the texture
+ */
+ getTextureCoordinates(uvSet = VertexBuffer.UVKind) {
+ if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(uvSet)) {
+ return null;
+ }
+ const indices = this.pickedMesh.getIndices();
+ if (!indices) {
+ return null;
+ }
+ const uvs = this.pickedMesh.getVerticesData(uvSet);
+ if (!uvs) {
+ return null;
+ }
+ let uv0 = Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
+ let uv1 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
+ let uv2 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
+ uv0 = uv0.scale(this.bu);
+ uv1 = uv1.scale(this.bv);
+ uv2 = uv2.scale(1.0 - this.bu - this.bv);
+ return new Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
+ }
+}
+
+/**
+ * ActionEvent is the event being sent when an action is triggered.
+ */
+class ActionEvent {
+ /**
+ * Creates a new ActionEvent
+ * @param source The mesh or sprite that triggered the action
+ * @param pointerX The X mouse cursor position at the time of the event
+ * @param pointerY The Y mouse cursor position at the time of the event
+ * @param meshUnderPointer The mesh that is currently pointed at (can be null)
+ * @param sourceEvent the original (browser) event that triggered the ActionEvent
+ * @param additionalData additional data for the event
+ */
+ constructor(
+ /** The mesh or sprite that triggered the action */
+ source,
+ /** The X mouse cursor position at the time of the event */
+ pointerX,
+ /** The Y mouse cursor position at the time of the event */
+ pointerY,
+ /** The mesh that is currently pointed at (can be null) */
+ meshUnderPointer,
+ /** the original (browser) event that triggered the ActionEvent */
+ sourceEvent,
+ /** additional data for the event */
+ additionalData) {
+ this.source = source;
+ this.pointerX = pointerX;
+ this.pointerY = pointerY;
+ this.meshUnderPointer = meshUnderPointer;
+ this.sourceEvent = sourceEvent;
+ this.additionalData = additionalData;
+ }
+ /**
+ * Helper function to auto-create an ActionEvent from a source mesh.
+ * @param source The source mesh that triggered the event
+ * @param evt The original (browser) event
+ * @param additionalData additional data for the event
+ * @returns the new ActionEvent
+ */
+ static CreateNew(source, evt, additionalData) {
+ const scene = source.getScene();
+ return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer || source, evt, additionalData);
+ }
+ /**
+ * Helper function to auto-create an ActionEvent from a source sprite
+ * @param source The source sprite that triggered the event
+ * @param scene Scene associated with the sprite
+ * @param evt The original (browser) event
+ * @param additionalData additional data for the event
+ * @returns the new ActionEvent
+ */
+ static CreateNewFromSprite(source, scene, evt, additionalData) {
+ return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
+ }
+ /**
+ * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
+ * @param scene the scene where the event occurred
+ * @param evt The original (browser) event
+ * @returns the new ActionEvent
+ */
+ static CreateNewFromScene(scene, evt) {
+ return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
+ }
+ /**
+ * Helper function to auto-create an ActionEvent from a primitive
+ * @param prim defines the target primitive
+ * @param pointerPos defines the pointer position
+ * @param evt The original (browser) event
+ * @param additionalData additional data for the event
+ * @returns the new ActionEvent
+ */
+ static CreateNewFromPrimitive(prim, pointerPos, evt, additionalData) {
+ return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
+ }
+}
+
+/**
+ * PostProcessManager is used to manage one or more post processes or post process pipelines
+ * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses
+ */
+class PostProcessManager {
+ /**
+ * Creates a new instance PostProcess
+ * @param scene The scene that the post process is associated with.
+ */
+ constructor(scene) {
+ this._vertexBuffers = {};
+ this.onBeforeRenderObservable = new Observable();
+ this._scene = scene;
+ }
+ _prepareBuffers() {
+ if (this._vertexBuffers[VertexBuffer.PositionKind]) {
+ return;
+ }
+ // VBO
+ const vertices = [];
+ vertices.push(1, 1);
+ vertices.push(-1, 1);
+ vertices.push(-1, -1);
+ vertices.push(1, -1);
+ this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._scene.getEngine(), vertices, VertexBuffer.PositionKind, false, false, 2);
+ this._buildIndexBuffer();
+ }
+ _buildIndexBuffer() {
+ // Indices
+ const indices = [];
+ indices.push(0);
+ indices.push(1);
+ indices.push(2);
+ indices.push(0);
+ indices.push(2);
+ indices.push(3);
+ this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
+ }
+ /**
+ * Rebuilds the vertex buffers of the manager.
+ * @internal
+ */
+ _rebuild() {
+ const vb = this._vertexBuffers[VertexBuffer.PositionKind];
+ if (!vb) {
+ return;
+ }
+ vb._rebuild();
+ this._buildIndexBuffer();
+ }
+ // Methods
+ /**
+ * Prepares a frame to be run through a post process.
+ * @param sourceTexture The input texture to the post processes. (default: null)
+ * @param postProcesses An array of post processes to be run. (default: null)
+ * @returns True if the post processes were able to be run.
+ * @internal
+ */
+ _prepareFrame(sourceTexture = null, postProcesses = null) {
+ const camera = this._scene.activeCamera;
+ if (!camera) {
+ return false;
+ }
+ postProcesses = postProcesses || camera._postProcesses.filter((pp) => {
+ return pp != null;
+ });
+ if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
+ return false;
+ }
+ postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
+ return true;
+ }
+ /**
+ * Manually render a set of post processes to a texture.
+ * Please note, the frame buffer won't be unbound after the call in case you have more render to do.
+ * @param postProcesses An array of post processes to be run.
+ * @param targetTexture The render target wrapper to render to.
+ * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
+ * @param faceIndex defines the face to render to if a cubemap is defined as the target
+ * @param lodLevel defines which lod of the texture to render to
+ * @param doNotBindFrambuffer If set to true, assumes that the framebuffer has been bound previously
+ */
+ directRender(postProcesses, targetTexture = null, forceFullscreenViewport = false, faceIndex = 0, lodLevel = 0, doNotBindFrambuffer = false) {
+ const engine = this._scene.getEngine();
+ for (let index = 0; index < postProcesses.length; index++) {
+ if (index < postProcesses.length - 1) {
+ postProcesses[index + 1].activate(this._scene.activeCamera || this._scene, targetTexture?.texture);
+ }
+ else {
+ if (targetTexture) {
+ engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, lodLevel);
+ }
+ else if (!doNotBindFrambuffer) {
+ engine.restoreDefaultFramebuffer();
+ }
+ engine._debugInsertMarker?.(`post process ${postProcesses[index].name} output`);
+ }
+ const pp = postProcesses[index];
+ const effect = pp.apply();
+ if (effect) {
+ pp.onBeforeRenderObservable.notifyObservers(effect);
+ // VBOs
+ this._prepareBuffers();
+ engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
+ // Draw order
+ engine.drawElementsType(0, 0, 6);
+ pp.onAfterRenderObservable.notifyObservers(effect);
+ }
+ }
+ // Restore depth buffer
+ engine.setDepthBuffer(true);
+ engine.setDepthWrite(true);
+ }
+ /**
+ * Finalize the result of the output of the postprocesses.
+ * @param doNotPresent If true the result will not be displayed to the screen.
+ * @param targetTexture The render target wrapper to render to.
+ * @param faceIndex The index of the face to bind the target texture to.
+ * @param postProcesses The array of post processes to render.
+ * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
+ * @internal
+ */
+ _finalizeFrame(doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport = false) {
+ const camera = this._scene.activeCamera;
+ if (!camera) {
+ return;
+ }
+ this.onBeforeRenderObservable.notifyObservers(this);
+ postProcesses = postProcesses || camera._postProcesses.filter((pp) => {
+ return pp != null;
+ });
+ if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
+ return;
+ }
+ const engine = this._scene.getEngine();
+ for (let index = 0, len = postProcesses.length; index < len; index++) {
+ const pp = postProcesses[index];
+ if (index < len - 1) {
+ pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture?.texture);
+ }
+ else {
+ if (targetTexture) {
+ engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
+ pp._outputTexture = targetTexture;
+ }
+ else {
+ engine.restoreDefaultFramebuffer();
+ pp._outputTexture = null;
+ }
+ engine._debugInsertMarker?.(`post process ${postProcesses[index].name} output`);
+ }
+ if (doNotPresent) {
+ break;
+ }
+ const effect = pp.apply();
+ if (effect) {
+ pp.onBeforeRenderObservable.notifyObservers(effect);
+ // VBOs
+ this._prepareBuffers();
+ engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
+ // Draw order
+ engine.drawElementsType(0, 0, 6);
+ pp.onAfterRenderObservable.notifyObservers(effect);
+ }
+ }
+ // Restore states
+ engine.setDepthBuffer(true);
+ engine.setDepthWrite(true);
+ engine.setAlphaMode(0);
+ }
+ /**
+ * Disposes of the post process manager.
+ */
+ dispose() {
+ const buffer = this._vertexBuffers[VertexBuffer.PositionKind];
+ if (buffer) {
+ buffer.dispose();
+ this._vertexBuffers[VertexBuffer.PositionKind] = null;
+ }
+ if (this._indexBuffer) {
+ this._scene.getEngine()._releaseBuffer(this._indexBuffer);
+ this._indexBuffer = null;
+ }
+ }
+}
+
+/**
+ * This represents the object necessary to create a rendering group.
+ * This is exclusively used and created by the rendering manager.
+ * To modify the behavior, you use the available helpers in your scene or meshes.
+ * @internal
+ */
+class RenderingGroup {
+ /**
+ * Set the opaque sort comparison function.
+ * If null the sub meshes will be render in the order they were created
+ */
+ set opaqueSortCompareFn(value) {
+ if (value) {
+ this._opaqueSortCompareFn = value;
+ }
+ else {
+ this._opaqueSortCompareFn = RenderingGroup.PainterSortCompare;
+ }
+ this._renderOpaque = this._renderOpaqueSorted;
+ }
+ /**
+ * Set the alpha test sort comparison function.
+ * If null the sub meshes will be render in the order they were created
+ */
+ set alphaTestSortCompareFn(value) {
+ if (value) {
+ this._alphaTestSortCompareFn = value;
+ }
+ else {
+ this._alphaTestSortCompareFn = RenderingGroup.PainterSortCompare;
+ }
+ this._renderAlphaTest = this._renderAlphaTestSorted;
+ }
+ /**
+ * Set the transparent sort comparison function.
+ * If null the sub meshes will be render in the order they were created
+ */
+ set transparentSortCompareFn(value) {
+ if (value) {
+ this._transparentSortCompareFn = value;
+ }
+ else {
+ this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
+ }
+ this._renderTransparent = this._renderTransparentSorted;
+ }
+ /**
+ * Creates a new rendering group.
+ * @param index The rendering group index
+ * @param scene
+ * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
+ * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
+ * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
+ */
+ constructor(index, scene, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {
+ this.index = index;
+ this._opaqueSubMeshes = new SmartArray(256);
+ this._transparentSubMeshes = new SmartArray(256);
+ this._alphaTestSubMeshes = new SmartArray(256);
+ this._depthOnlySubMeshes = new SmartArray(256);
+ this._particleSystems = new SmartArray(256);
+ this._spriteManagers = new SmartArray(256);
+ /** @internal */
+ this._empty = true;
+ /** @internal */
+ this._edgesRenderers = new SmartArrayNoDuplicate(16);
+ this._scene = scene;
+ this.opaqueSortCompareFn = opaqueSortCompareFn;
+ this.alphaTestSortCompareFn = alphaTestSortCompareFn;
+ this.transparentSortCompareFn = transparentSortCompareFn;
+ }
+ /**
+ * Render all the sub meshes contained in the group.
+ * @param customRenderFunction Used to override the default render behaviour of the group.
+ * @param renderSprites
+ * @param renderParticles
+ * @param activeMeshes
+ */
+ render(customRenderFunction, renderSprites, renderParticles, activeMeshes) {
+ if (customRenderFunction) {
+ customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
+ return;
+ }
+ const engine = this._scene.getEngine();
+ // Depth only
+ if (this._depthOnlySubMeshes.length !== 0) {
+ engine.setColorWrite(false);
+ this._renderAlphaTest(this._depthOnlySubMeshes);
+ engine.setColorWrite(true);
+ }
+ // Opaque
+ if (this._opaqueSubMeshes.length !== 0) {
+ this._renderOpaque(this._opaqueSubMeshes);
+ }
+ // Alpha test
+ if (this._alphaTestSubMeshes.length !== 0) {
+ this._renderAlphaTest(this._alphaTestSubMeshes);
+ }
+ const stencilState = engine.getStencilBuffer();
+ engine.setStencilBuffer(false);
+ // Sprites
+ if (renderSprites) {
+ this._renderSprites();
+ }
+ // Particles
+ if (renderParticles) {
+ this._renderParticles(activeMeshes);
+ }
+ if (this.onBeforeTransparentRendering) {
+ this.onBeforeTransparentRendering();
+ }
+ // Transparent
+ if (this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) {
+ engine.setStencilBuffer(stencilState);
+ if (this._scene.useOrderIndependentTransparency) {
+ const excludedMeshes = this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);
+ if (excludedMeshes.length) {
+ // Render leftover meshes that could not be processed by depth peeling
+ this._renderTransparent(excludedMeshes);
+ }
+ }
+ else {
+ this._renderTransparent(this._transparentSubMeshes);
+ }
+ engine.setAlphaMode(0);
+ }
+ // Set back stencil to false in case it changes before the edge renderer.
+ engine.setStencilBuffer(false);
+ // Edges
+ if (this._edgesRenderers.length) {
+ for (let edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
+ this._edgesRenderers.data[edgesRendererIndex].render();
+ }
+ engine.setAlphaMode(0);
+ }
+ // Restore Stencil state.
+ engine.setStencilBuffer(stencilState);
+ }
+ /**
+ * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
+ * @param subMeshes The submeshes to render
+ */
+ _renderOpaqueSorted(subMeshes) {
+ RenderingGroup._RenderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
+ }
+ /**
+ * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
+ * @param subMeshes The submeshes to render
+ */
+ _renderAlphaTestSorted(subMeshes) {
+ RenderingGroup._RenderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
+ }
+ /**
+ * Renders the opaque submeshes in the order from the transparentSortCompareFn.
+ * @param subMeshes The submeshes to render
+ */
+ _renderTransparentSorted(subMeshes) {
+ RenderingGroup._RenderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
+ }
+ /**
+ * Renders the submeshes in a specified order.
+ * @param subMeshes The submeshes to sort before render
+ * @param sortCompareFn The comparison function use to sort
+ * @param camera The camera position use to preprocess the submeshes to help sorting
+ * @param transparent Specifies to activate blending if true
+ */
+ static _RenderSorted(subMeshes, sortCompareFn, camera, transparent) {
+ let subIndex = 0;
+ let subMesh;
+ const cameraPosition = camera ? camera.globalPosition : RenderingGroup._ZeroVector;
+ if (transparent) {
+ for (; subIndex < subMeshes.length; subIndex++) {
+ subMesh = subMeshes.data[subIndex];
+ subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
+ subMesh._distanceToCamera = Vector3.Distance(subMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition);
+ }
+ }
+ const sortedArray = subMeshes.length === subMeshes.data.length ? subMeshes.data : subMeshes.data.slice(0, subMeshes.length);
+ if (sortCompareFn) {
+ sortedArray.sort(sortCompareFn);
+ }
+ const scene = sortedArray[0].getMesh().getScene();
+ for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
+ subMesh = sortedArray[subIndex];
+ if (scene._activeMeshesFrozenButKeepClipping && !subMesh.isInFrustum(scene._frustumPlanes)) {
+ continue;
+ }
+ if (transparent) {
+ const material = subMesh.getMaterial();
+ if (material && material.needDepthPrePass) {
+ const engine = material.getScene().getEngine();
+ engine.setColorWrite(false);
+ engine.setAlphaMode(0);
+ subMesh.render(false);
+ engine.setColorWrite(true);
+ }
+ }
+ subMesh.render(transparent);
+ }
+ }
+ /**
+ * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
+ * are rendered back to front if in the same alpha index.
+ *
+ * @param a The first submesh
+ * @param b The second submesh
+ * @returns The result of the comparison
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static defaultTransparentSortCompare(a, b) {
+ // Alpha index first
+ if (a._alphaIndex > b._alphaIndex) {
+ return 1;
+ }
+ if (a._alphaIndex < b._alphaIndex) {
+ return -1;
+ }
+ // Then distance to camera
+ return RenderingGroup.backToFrontSortCompare(a, b);
+ }
+ /**
+ * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
+ * are rendered back to front.
+ *
+ * @param a The first submesh
+ * @param b The second submesh
+ * @returns The result of the comparison
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static backToFrontSortCompare(a, b) {
+ // Then distance to camera
+ if (a._distanceToCamera < b._distanceToCamera) {
+ return 1;
+ }
+ if (a._distanceToCamera > b._distanceToCamera) {
+ return -1;
+ }
+ return 0;
+ }
+ /**
+ * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
+ * are rendered front to back (prevent overdraw).
+ *
+ * @param a The first submesh
+ * @param b The second submesh
+ * @returns The result of the comparison
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static frontToBackSortCompare(a, b) {
+ // Then distance to camera
+ if (a._distanceToCamera < b._distanceToCamera) {
+ return -1;
+ }
+ if (a._distanceToCamera > b._distanceToCamera) {
+ return 1;
+ }
+ return 0;
+ }
+ /**
+ * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
+ * are grouped by material then geometry.
+ *
+ * @param a The first submesh
+ * @param b The second submesh
+ * @returns The result of the comparison
+ */
+ static PainterSortCompare(a, b) {
+ const meshA = a.getMesh();
+ const meshB = b.getMesh();
+ if (meshA.material && meshB.material) {
+ return meshA.material.uniqueId - meshB.material.uniqueId;
+ }
+ return meshA.uniqueId - meshB.uniqueId;
+ }
+ /**
+ * Resets the different lists of submeshes to prepare a new frame.
+ */
+ prepare() {
+ this._opaqueSubMeshes.reset();
+ this._transparentSubMeshes.reset();
+ this._alphaTestSubMeshes.reset();
+ this._depthOnlySubMeshes.reset();
+ this._particleSystems.reset();
+ this.prepareSprites();
+ this._edgesRenderers.reset();
+ this._empty = true;
+ }
+ /**
+ * Resets the different lists of sprites to prepare a new frame.
+ */
+ prepareSprites() {
+ this._spriteManagers.reset();
+ }
+ dispose() {
+ this._opaqueSubMeshes.dispose();
+ this._transparentSubMeshes.dispose();
+ this._alphaTestSubMeshes.dispose();
+ this._depthOnlySubMeshes.dispose();
+ this._particleSystems.dispose();
+ this._spriteManagers.dispose();
+ this._edgesRenderers.dispose();
+ }
+ /**
+ * Inserts the submesh in its correct queue depending on its material.
+ * @param subMesh The submesh to dispatch
+ * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
+ * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
+ */
+ dispatch(subMesh, mesh, material) {
+ // Get mesh and materials if not provided
+ if (mesh === undefined) {
+ mesh = subMesh.getMesh();
+ }
+ if (material === undefined) {
+ material = subMesh.getMaterial();
+ }
+ if (material === null || material === undefined) {
+ return;
+ }
+ if (material.needAlphaBlendingForMesh(mesh)) {
+ // Transparent
+ this._transparentSubMeshes.push(subMesh);
+ }
+ else if (material.needAlphaTestingForMesh(mesh)) {
+ // Alpha test
+ if (material.needDepthPrePass) {
+ this._depthOnlySubMeshes.push(subMesh);
+ }
+ this._alphaTestSubMeshes.push(subMesh);
+ }
+ else {
+ if (material.needDepthPrePass) {
+ this._depthOnlySubMeshes.push(subMesh);
+ }
+ this._opaqueSubMeshes.push(subMesh); // Opaque
+ }
+ mesh._renderingGroup = this;
+ if (mesh._edgesRenderer && mesh.isEnabled() && mesh.isVisible && mesh._edgesRenderer.isEnabled) {
+ this._edgesRenderers.pushNoDuplicate(mesh._edgesRenderer);
+ }
+ this._empty = false;
+ }
+ dispatchSprites(spriteManager) {
+ this._spriteManagers.push(spriteManager);
+ this._empty = false;
+ }
+ dispatchParticles(particleSystem) {
+ this._particleSystems.push(particleSystem);
+ this._empty = false;
+ }
+ _renderParticles(activeMeshes) {
+ if (this._particleSystems.length === 0) {
+ return;
+ }
+ // Particles
+ const activeCamera = this._scene.activeCamera;
+ this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
+ for (let particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
+ const particleSystem = this._particleSystems.data[particleIndex];
+ if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
+ continue;
+ }
+ const emitter = particleSystem.emitter;
+ if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
+ this._scene._activeParticles.addCount(particleSystem.render(), false);
+ }
+ }
+ this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
+ }
+ _renderSprites() {
+ if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
+ return;
+ }
+ // Sprites
+ const activeCamera = this._scene.activeCamera;
+ this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
+ for (let id = 0; id < this._spriteManagers.length; id++) {
+ const spriteManager = this._spriteManagers.data[id];
+ if ((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0) {
+ spriteManager.render();
+ }
+ }
+ this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
+ }
+}
+RenderingGroup._ZeroVector = Vector3.Zero();
+
+/**
+ * This class is used by the onRenderingGroupObservable
+ */
+class RenderingGroupInfo {
+}
+/**
+ * This is the manager responsible of all the rendering for meshes sprites and particles.
+ * It is enable to manage the different groups as well as the different necessary sort functions.
+ * This should not be used directly aside of the few static configurations
+ */
+class RenderingManager {
+ /**
+ * Gets or sets a boolean indicating that the manager will not reset between frames.
+ * This means that if a mesh becomes invisible or transparent it will not be visible until this boolean is set to false again.
+ * By default, the rendering manager will dispatch all active meshes per frame (moving them to the transparent, opaque or alpha testing lists).
+ * By turning this property on, you will accelerate the rendering by keeping all these lists unchanged between frames.
+ */
+ get maintainStateBetweenFrames() {
+ return this._maintainStateBetweenFrames;
+ }
+ set maintainStateBetweenFrames(value) {
+ if (value === this._maintainStateBetweenFrames) {
+ return;
+ }
+ this._maintainStateBetweenFrames = value;
+ if (!this._maintainStateBetweenFrames) {
+ this.restoreDispachedFlags();
+ }
+ }
+ /**
+ * Restore wasDispatched flags on the lists of elements to render.
+ */
+ restoreDispachedFlags() {
+ for (const mesh of this._scene.meshes) {
+ if (mesh.subMeshes) {
+ for (const subMesh of mesh.subMeshes) {
+ subMesh._wasDispatched = false;
+ }
+ }
+ }
+ if (this._scene.spriteManagers) {
+ for (const spriteManager of this._scene.spriteManagers) {
+ spriteManager._wasDispatched = false;
+ }
+ }
+ for (const particleSystem of this._scene.particleSystems) {
+ particleSystem._wasDispatched = false;
+ }
+ }
+ /**
+ * Instantiates a new rendering group for a particular scene
+ * @param scene Defines the scene the groups belongs to
+ */
+ constructor(scene) {
+ /**
+ * @internal
+ */
+ this._useSceneAutoClearSetup = false;
+ this._renderingGroups = new Array();
+ this._autoClearDepthStencil = {};
+ this._customOpaqueSortCompareFn = {};
+ this._customAlphaTestSortCompareFn = {};
+ this._customTransparentSortCompareFn = {};
+ this._renderingGroupInfo = new RenderingGroupInfo();
+ this._maintainStateBetweenFrames = false;
+ this._scene = scene;
+ for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
+ this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
+ }
+ }
+ /**
+ * @returns the rendering group with the specified id.
+ * @param id the id of the rendering group (0 by default)
+ */
+ getRenderingGroup(id) {
+ const renderingGroupId = id || 0;
+ this._prepareRenderingGroup(renderingGroupId);
+ return this._renderingGroups[renderingGroupId];
+ }
+ _clearDepthStencilBuffer(depth = true, stencil = true) {
+ if (this._depthStencilBufferAlreadyCleaned) {
+ return;
+ }
+ this._scene.getEngine().clear(null, false, depth, stencil);
+ this._depthStencilBufferAlreadyCleaned = true;
+ }
+ /**
+ * Renders the entire managed groups. This is used by the scene or the different render targets.
+ * @internal
+ */
+ render(customRenderFunction, activeMeshes, renderParticles, renderSprites) {
+ // Update the observable context (not null as it only goes away on dispose)
+ const info = this._renderingGroupInfo;
+ info.scene = this._scene;
+ info.camera = this._scene.activeCamera;
+ info.renderingManager = this;
+ // Dispatch sprites
+ if (this._scene.spriteManagers && renderSprites) {
+ for (let index = 0; index < this._scene.spriteManagers.length; index++) {
+ const manager = this._scene.spriteManagers[index];
+ this.dispatchSprites(manager);
+ }
+ }
+ // Render
+ for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
+ this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
+ const renderingGroup = this._renderingGroups[index];
+ if (!renderingGroup || renderingGroup._empty) {
+ continue;
+ }
+ const renderingGroupMask = 1 << index;
+ info.renderingGroupId = index;
+ // Before Observable
+ this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
+ // Clear depth/stencil if needed
+ if (RenderingManager.AUTOCLEAR) {
+ const autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index];
+ if (autoClear && autoClear.autoClear) {
+ this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
+ }
+ }
+ // Render
+ for (const step of this._scene._beforeRenderingGroupDrawStage) {
+ step.action(index);
+ }
+ renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
+ for (const step of this._scene._afterRenderingGroupDrawStage) {
+ step.action(index);
+ }
+ // After Observable
+ this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
+ }
+ }
+ /**
+ * Resets the different information of the group to prepare a new frame
+ * @internal
+ */
+ reset() {
+ if (this.maintainStateBetweenFrames) {
+ return;
+ }
+ for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
+ const renderingGroup = this._renderingGroups[index];
+ if (renderingGroup) {
+ renderingGroup.prepare();
+ }
+ }
+ }
+ /**
+ * Resets the sprites information of the group to prepare a new frame
+ * @internal
+ */
+ resetSprites() {
+ if (this.maintainStateBetweenFrames) {
+ return;
+ }
+ for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
+ const renderingGroup = this._renderingGroups[index];
+ if (renderingGroup) {
+ renderingGroup.prepareSprites();
+ }
+ }
+ }
+ /**
+ * Dispose and release the group and its associated resources.
+ * @internal
+ */
+ dispose() {
+ this.freeRenderingGroups();
+ this._renderingGroups.length = 0;
+ this._renderingGroupInfo = null;
+ }
+ /**
+ * Clear the info related to rendering groups preventing retention points during dispose.
+ */
+ freeRenderingGroups() {
+ for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
+ const renderingGroup = this._renderingGroups[index];
+ if (renderingGroup) {
+ renderingGroup.dispose();
+ }
+ }
+ }
+ _prepareRenderingGroup(renderingGroupId) {
+ if (this._renderingGroups[renderingGroupId] === undefined) {
+ this._renderingGroups[renderingGroupId] = new RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
+ }
+ }
+ /**
+ * Add a sprite manager to the rendering manager in order to render it this frame.
+ * @param spriteManager Define the sprite manager to render
+ */
+ dispatchSprites(spriteManager) {
+ if (this.maintainStateBetweenFrames && spriteManager._wasDispatched) {
+ return;
+ }
+ spriteManager._wasDispatched = true;
+ this.getRenderingGroup(spriteManager.renderingGroupId).dispatchSprites(spriteManager);
+ }
+ /**
+ * Add a particle system to the rendering manager in order to render it this frame.
+ * @param particleSystem Define the particle system to render
+ */
+ dispatchParticles(particleSystem) {
+ if (this.maintainStateBetweenFrames && particleSystem._wasDispatched) {
+ return;
+ }
+ particleSystem._wasDispatched = true;
+ this.getRenderingGroup(particleSystem.renderingGroupId).dispatchParticles(particleSystem);
+ }
+ /**
+ * Add a submesh to the manager in order to render it this frame
+ * @param subMesh The submesh to dispatch
+ * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
+ * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
+ */
+ dispatch(subMesh, mesh, material) {
+ if (mesh === undefined) {
+ mesh = subMesh.getMesh();
+ }
+ if (this.maintainStateBetweenFrames && subMesh._wasDispatched) {
+ return;
+ }
+ subMesh._wasDispatched = true;
+ this.getRenderingGroup(mesh.renderingGroupId).dispatch(subMesh, mesh, material);
+ }
+ /**
+ * Overrides the default sort function applied in the rendering group to prepare the meshes.
+ * This allowed control for front to back rendering or reversely depending of the special needs.
+ *
+ * @param renderingGroupId The rendering group id corresponding to its index
+ * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
+ * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
+ * @param transparentSortCompareFn The transparent queue comparison function use to sort.
+ */
+ setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {
+ this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
+ this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
+ this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
+ if (this._renderingGroups[renderingGroupId]) {
+ const group = this._renderingGroups[renderingGroupId];
+ group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
+ group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
+ group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
+ }
+ }
+ /**
+ * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
+ *
+ * @param renderingGroupId The rendering group id corresponding to its index
+ * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
+ * @param depth Automatically clears depth between groups if true and autoClear is true.
+ * @param stencil Automatically clears stencil between groups if true and autoClear is true.
+ */
+ setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) {
+ this._autoClearDepthStencil[renderingGroupId] = {
+ autoClear: autoClearDepthStencil,
+ depth: depth,
+ stencil: stencil,
+ };
+ }
+ /**
+ * Gets the current auto clear configuration for one rendering group of the rendering
+ * manager.
+ * @param index the rendering group index to get the information for
+ * @returns The auto clear setup for the requested rendering group
+ */
+ getAutoClearDepthStencilSetup(index) {
+ return this._autoClearDepthStencil[index];
+ }
+}
+/**
+ * The max id used for rendering groups (not included)
+ */
+RenderingManager.MAX_RENDERINGGROUPS = 4;
+/**
+ * The min id used for rendering groups (included)
+ */
+RenderingManager.MIN_RENDERINGGROUPS = 0;
+/**
+ * Used to globally prevent autoclearing scenes.
+ */
+RenderingManager.AUTOCLEAR = true;
+
+/**
+ * Groups all the scene component constants in one place to ease maintenance.
+ * @internal
+ */
+class SceneComponentConstants {
+}
+SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
+SceneComponentConstants.NAME_LAYER = "Layer";
+SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
+SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
+SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
+SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
+SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
+SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
+SceneComponentConstants.NAME_PREPASSRENDERER = "PrePassRenderer";
+SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
+SceneComponentConstants.NAME_DEPTHPEELINGRENDERER = "DepthPeelingRenderer";
+SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
+SceneComponentConstants.NAME_SPRITE = "Sprite";
+SceneComponentConstants.NAME_SUBSURFACE = "SubSurface";
+SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
+SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
+SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
+SceneComponentConstants.NAME_OCTREE = "Octree";
+SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
+SceneComponentConstants.NAME_AUDIO = "Audio";
+SceneComponentConstants.NAME_FLUIDRENDERER = "FluidRenderer";
+SceneComponentConstants.NAME_IBLCDFGENERATOR = "iblCDFGenerator";
+SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
+SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
+SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
+SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0;
+SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
+SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS = 0;
+SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1;
+SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 2;
+SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0;
+SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER = 1;
+SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS = 0;
+SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 1;
+SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS = 0;
+SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 1;
+SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
+SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
+SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
+SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
+SceneComponentConstants.STEP_BEFORECLEAR_PREPASS = 1;
+SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS = 0;
+SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0;
+SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER = 1;
+SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS = 0;
+SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1;
+SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2;
+SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
+SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
+SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER = 5;
+SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER = 0;
+SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER = 0;
+SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
+SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0;
+SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
+SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2;
+SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
+SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
+SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER = 1;
+SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
+SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
+SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
+/**
+ * Representation of a stage in the scene (Basically a list of ordered steps)
+ * @internal
+ */
+class Stage extends Array {
+ /**
+ * Hide ctor from the rest of the world.
+ * @param items The items to add.
+ */
+ constructor(items) {
+ super(...items);
+ }
+ /**
+ * Creates a new Stage.
+ * @returns A new instance of a Stage
+ */
+ static Create() {
+ return Object.create(Stage.prototype);
+ }
+ /**
+ * Registers a step in an ordered way in the targeted stage.
+ * @param index Defines the position to register the step in
+ * @param component Defines the component attached to the step
+ * @param action Defines the action to launch during the step
+ */
+ registerStep(index, component, action) {
+ let i = 0;
+ let maxIndex = Number.MAX_VALUE;
+ for (; i < this.length; i++) {
+ const step = this[i];
+ maxIndex = step.index;
+ if (index < maxIndex) {
+ break;
+ }
+ }
+ this.splice(i, 0, { index, component, action: action.bind(component) });
+ }
+ /**
+ * Clears all the steps from the stage.
+ */
+ clear() {
+ this.length = 0;
+ }
+}
+
+/**
+ * Gather the list of pointer event types as constants.
+ */
+class PointerEventTypes {
+}
+/**
+ * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
+ */
+PointerEventTypes.POINTERDOWN = 0x01;
+/**
+ * The pointerup event is fired when a pointer is no longer active.
+ */
+PointerEventTypes.POINTERUP = 0x02;
+/**
+ * The pointermove event is fired when a pointer changes coordinates.
+ */
+PointerEventTypes.POINTERMOVE = 0x04;
+/**
+ * The pointerwheel event is fired when a mouse wheel has been rotated.
+ */
+PointerEventTypes.POINTERWHEEL = 0x08;
+/**
+ * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
+ */
+PointerEventTypes.POINTERPICK = 0x10;
+/**
+ * The pointertap event is fired when a the object has been touched and released without drag.
+ */
+PointerEventTypes.POINTERTAP = 0x20;
+/**
+ * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
+ */
+PointerEventTypes.POINTERDOUBLETAP = 0x40;
+/**
+ * Base class of pointer info types.
+ */
+class PointerInfoBase {
+ /**
+ * Instantiates the base class of pointers info.
+ * @param type Defines the type of event (PointerEventTypes)
+ * @param event Defines the related dom event
+ */
+ constructor(
+ /**
+ * Defines the type of event (PointerEventTypes)
+ */
+ type,
+ /**
+ * Defines the related dom event
+ */
+ event) {
+ this.type = type;
+ this.event = event;
+ }
+}
+/**
+ * This class is used to store pointer related info for the onPrePointerObservable event.
+ * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
+ */
+class PointerInfoPre extends PointerInfoBase {
+ /**
+ * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
+ * @param type Defines the type of event (PointerEventTypes)
+ * @param event Defines the related dom event
+ * @param localX Defines the local x coordinates of the pointer when the event occured
+ * @param localY Defines the local y coordinates of the pointer when the event occured
+ */
+ constructor(type, event, localX, localY) {
+ super(type, event);
+ /**
+ * Ray from a pointer if available (eg. 6dof controller)
+ */
+ this.ray = null;
+ /**
+ * The original picking info that was used to trigger the pointer event
+ */
+ this.originalPickingInfo = null;
+ this.skipOnPointerObservable = false;
+ this.localPosition = new Vector2(localX, localY);
+ }
+}
+/**
+ * This type contains all the data related to a pointer event in Babylon.js.
+ * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
+ */
+class PointerInfo extends PointerInfoBase {
+ /**
+ * Defines the picking info associated with this PointerInfo object (if applicable)
+ */
+ get pickInfo() {
+ if (!this._pickInfo) {
+ this._generatePickInfo();
+ }
+ return this._pickInfo;
+ }
+ /**
+ * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
+ * @param type Defines the type of event (PointerEventTypes)
+ * @param event Defines the related dom event
+ * @param pickInfo Defines the picking info associated to the info (if any)
+ * @param inputManager Defines the InputManager to use if there is no pickInfo
+ */
+ constructor(type, event, pickInfo, inputManager = null) {
+ super(type, event);
+ this._pickInfo = pickInfo;
+ this._inputManager = inputManager;
+ }
+ /**
+ * Generates the picking info if needed
+ */
+ /** @internal */
+ _generatePickInfo() {
+ if (this._inputManager) {
+ this._pickInfo = this._inputManager._pickMove(this.event);
+ this._inputManager._setRayOnPointerInfo(this._pickInfo, this.event);
+ this._inputManager = null;
+ }
+ }
+}
+
+/**
+ * Abstract class used to decouple action Manager from scene and meshes.
+ * Do not instantiate.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions
+ */
+class AbstractActionManager {
+ constructor() {
+ /** Gets the cursor to use when hovering items */
+ this.hoverCursor = "";
+ /** Gets the list of actions */
+ this.actions = [];
+ /**
+ * Gets or sets a boolean indicating that the manager is recursive meaning that it can trigger action from children
+ */
+ this.isRecursive = false;
+ /**
+ * Gets or sets a boolean indicating if this ActionManager should be disposed once the last Mesh using it is disposed
+ */
+ this.disposeWhenUnowned = true;
+ }
+ /**
+ * Does exist one action manager with at least one trigger
+ **/
+ static get HasTriggers() {
+ for (const t in AbstractActionManager.Triggers) {
+ if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * Does exist one action manager with at least one pick trigger
+ **/
+ static get HasPickTriggers() {
+ for (const t in AbstractActionManager.Triggers) {
+ if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {
+ const tAsInt = parseInt(t);
+ if (tAsInt >= 1 && tAsInt <= 7) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ /**
+ * Does exist one action manager that handles actions of a given trigger
+ * @param trigger defines the trigger to be tested
+ * @returns a boolean indicating whether the trigger is handled by at least one action manager
+ **/
+ static HasSpecificTrigger(trigger) {
+ for (const t in AbstractActionManager.Triggers) {
+ if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {
+ const tAsInt = parseInt(t);
+ if (tAsInt === trigger) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
+/** Gets the list of active triggers */
+AbstractActionManager.Triggers = {};
+
+/**
+ * Gather the list of keyboard event types as constants.
+ */
+class KeyboardEventTypes {
+}
+/**
+ * The keydown event is fired when a key becomes active (pressed).
+ */
+KeyboardEventTypes.KEYDOWN = 0x01;
+/**
+ * The keyup event is fired when a key has been released.
+ */
+KeyboardEventTypes.KEYUP = 0x02;
+/**
+ * This class is used to store keyboard related info for the onKeyboardObservable event.
+ */
+class KeyboardInfo {
+ /**
+ * Instantiates a new keyboard info.
+ * This class is used to store keyboard related info for the onKeyboardObservable event.
+ * @param type Defines the type of event (KeyboardEventTypes)
+ * @param event Defines the related dom event
+ */
+ constructor(
+ /**
+ * Defines the type of event (KeyboardEventTypes)
+ */
+ type,
+ /**
+ * Defines the related dom event
+ */
+ event) {
+ this.type = type;
+ this.event = event;
+ }
+}
+/**
+ * This class is used to store keyboard related info for the onPreKeyboardObservable event.
+ * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
+ */
+class KeyboardInfoPre extends KeyboardInfo {
+ /**
+ * Defines whether the engine should skip the next onKeyboardObservable associated to this pre.
+ * @deprecated use skipOnKeyboardObservable property instead
+ */
+ get skipOnPointerObservable() {
+ return this.skipOnKeyboardObservable;
+ }
+ set skipOnPointerObservable(value) {
+ this.skipOnKeyboardObservable = value;
+ }
+ /**
+ * Instantiates a new keyboard pre info.
+ * This class is used to store keyboard related info for the onPreKeyboardObservable event.
+ * @param type Defines the type of event (KeyboardEventTypes)
+ * @param event Defines the related dom event
+ */
+ constructor(
+ /**
+ * Defines the type of event (KeyboardEventTypes)
+ */
+ type,
+ /**
+ * Defines the related dom event
+ */
+ event) {
+ super(type, event);
+ this.type = type;
+ this.event = event;
+ this.skipOnKeyboardObservable = false;
+ }
+}
+
+/**
+ * Enum for Device Types
+ */
+var DeviceType;
+(function (DeviceType) {
+ /** Generic */
+ DeviceType[DeviceType["Generic"] = 0] = "Generic";
+ /** Keyboard */
+ DeviceType[DeviceType["Keyboard"] = 1] = "Keyboard";
+ /** Mouse */
+ DeviceType[DeviceType["Mouse"] = 2] = "Mouse";
+ /** Touch Pointers */
+ DeviceType[DeviceType["Touch"] = 3] = "Touch";
+ /** PS4 Dual Shock */
+ DeviceType[DeviceType["DualShock"] = 4] = "DualShock";
+ /** Xbox */
+ DeviceType[DeviceType["Xbox"] = 5] = "Xbox";
+ /** Switch Controller */
+ DeviceType[DeviceType["Switch"] = 6] = "Switch";
+ /** PS5 DualSense */
+ DeviceType[DeviceType["DualSense"] = 7] = "DualSense";
+})(DeviceType || (DeviceType = {}));
+// Device Enums
+/**
+ * Enum for All Pointers (Touch/Mouse)
+ */
+var PointerInput;
+(function (PointerInput) {
+ /** Horizontal Axis (Not used in events/observables; only in polling) */
+ PointerInput[PointerInput["Horizontal"] = 0] = "Horizontal";
+ /** Vertical Axis (Not used in events/observables; only in polling) */
+ PointerInput[PointerInput["Vertical"] = 1] = "Vertical";
+ /** Left Click or Touch */
+ PointerInput[PointerInput["LeftClick"] = 2] = "LeftClick";
+ /** Middle Click */
+ PointerInput[PointerInput["MiddleClick"] = 3] = "MiddleClick";
+ /** Right Click */
+ PointerInput[PointerInput["RightClick"] = 4] = "RightClick";
+ /** Browser Back */
+ PointerInput[PointerInput["BrowserBack"] = 5] = "BrowserBack";
+ /** Browser Forward */
+ PointerInput[PointerInput["BrowserForward"] = 6] = "BrowserForward";
+ /** Mouse Wheel X */
+ PointerInput[PointerInput["MouseWheelX"] = 7] = "MouseWheelX";
+ /** Mouse Wheel Y */
+ PointerInput[PointerInput["MouseWheelY"] = 8] = "MouseWheelY";
+ /** Mouse Wheel Z */
+ PointerInput[PointerInput["MouseWheelZ"] = 9] = "MouseWheelZ";
+ /** Used in events/observables to identify if x/y changes occurred */
+ PointerInput[PointerInput["Move"] = 12] = "Move";
+})(PointerInput || (PointerInput = {}));
+/** @internal */
+var NativePointerInput;
+(function (NativePointerInput) {
+ /** Horizontal Axis */
+ NativePointerInput[NativePointerInput["Horizontal"] = 0] = "Horizontal";
+ /** Vertical Axis */
+ NativePointerInput[NativePointerInput["Vertical"] = 1] = "Vertical";
+ /** Left Click or Touch */
+ NativePointerInput[NativePointerInput["LeftClick"] = 2] = "LeftClick";
+ /** Middle Click */
+ NativePointerInput[NativePointerInput["MiddleClick"] = 3] = "MiddleClick";
+ /** Right Click */
+ NativePointerInput[NativePointerInput["RightClick"] = 4] = "RightClick";
+ /** Browser Back */
+ NativePointerInput[NativePointerInput["BrowserBack"] = 5] = "BrowserBack";
+ /** Browser Forward */
+ NativePointerInput[NativePointerInput["BrowserForward"] = 6] = "BrowserForward";
+ /** Mouse Wheel X */
+ NativePointerInput[NativePointerInput["MouseWheelX"] = 7] = "MouseWheelX";
+ /** Mouse Wheel Y */
+ NativePointerInput[NativePointerInput["MouseWheelY"] = 8] = "MouseWheelY";
+ /** Mouse Wheel Z */
+ NativePointerInput[NativePointerInput["MouseWheelZ"] = 9] = "MouseWheelZ";
+ /** Delta X */
+ NativePointerInput[NativePointerInput["DeltaHorizontal"] = 10] = "DeltaHorizontal";
+ /** Delta Y */
+ NativePointerInput[NativePointerInput["DeltaVertical"] = 11] = "DeltaVertical";
+})(NativePointerInput || (NativePointerInput = {}));
+/**
+ * Enum for Dual Shock Gamepad
+ */
+var DualShockInput;
+(function (DualShockInput) {
+ /** Cross */
+ DualShockInput[DualShockInput["Cross"] = 0] = "Cross";
+ /** Circle */
+ DualShockInput[DualShockInput["Circle"] = 1] = "Circle";
+ /** Square */
+ DualShockInput[DualShockInput["Square"] = 2] = "Square";
+ /** Triangle */
+ DualShockInput[DualShockInput["Triangle"] = 3] = "Triangle";
+ /** L1 */
+ DualShockInput[DualShockInput["L1"] = 4] = "L1";
+ /** R1 */
+ DualShockInput[DualShockInput["R1"] = 5] = "R1";
+ /** L2 */
+ DualShockInput[DualShockInput["L2"] = 6] = "L2";
+ /** R2 */
+ DualShockInput[DualShockInput["R2"] = 7] = "R2";
+ /** Share */
+ DualShockInput[DualShockInput["Share"] = 8] = "Share";
+ /** Options */
+ DualShockInput[DualShockInput["Options"] = 9] = "Options";
+ /** L3 */
+ DualShockInput[DualShockInput["L3"] = 10] = "L3";
+ /** R3 */
+ DualShockInput[DualShockInput["R3"] = 11] = "R3";
+ /** DPadUp */
+ DualShockInput[DualShockInput["DPadUp"] = 12] = "DPadUp";
+ /** DPadDown */
+ DualShockInput[DualShockInput["DPadDown"] = 13] = "DPadDown";
+ /** DPadLeft */
+ DualShockInput[DualShockInput["DPadLeft"] = 14] = "DPadLeft";
+ /** DRight */
+ DualShockInput[DualShockInput["DPadRight"] = 15] = "DPadRight";
+ /** Home */
+ DualShockInput[DualShockInput["Home"] = 16] = "Home";
+ /** TouchPad */
+ DualShockInput[DualShockInput["TouchPad"] = 17] = "TouchPad";
+ /** LStickXAxis */
+ DualShockInput[DualShockInput["LStickXAxis"] = 18] = "LStickXAxis";
+ /** LStickYAxis */
+ DualShockInput[DualShockInput["LStickYAxis"] = 19] = "LStickYAxis";
+ /** RStickXAxis */
+ DualShockInput[DualShockInput["RStickXAxis"] = 20] = "RStickXAxis";
+ /** RStickYAxis */
+ DualShockInput[DualShockInput["RStickYAxis"] = 21] = "RStickYAxis";
+})(DualShockInput || (DualShockInput = {}));
+/**
+ * Enum for Dual Sense Gamepad
+ */
+var DualSenseInput;
+(function (DualSenseInput) {
+ /** Cross */
+ DualSenseInput[DualSenseInput["Cross"] = 0] = "Cross";
+ /** Circle */
+ DualSenseInput[DualSenseInput["Circle"] = 1] = "Circle";
+ /** Square */
+ DualSenseInput[DualSenseInput["Square"] = 2] = "Square";
+ /** Triangle */
+ DualSenseInput[DualSenseInput["Triangle"] = 3] = "Triangle";
+ /** L1 */
+ DualSenseInput[DualSenseInput["L1"] = 4] = "L1";
+ /** R1 */
+ DualSenseInput[DualSenseInput["R1"] = 5] = "R1";
+ /** L2 */
+ DualSenseInput[DualSenseInput["L2"] = 6] = "L2";
+ /** R2 */
+ DualSenseInput[DualSenseInput["R2"] = 7] = "R2";
+ /** Create */
+ DualSenseInput[DualSenseInput["Create"] = 8] = "Create";
+ /** Options */
+ DualSenseInput[DualSenseInput["Options"] = 9] = "Options";
+ /** L3 */
+ DualSenseInput[DualSenseInput["L3"] = 10] = "L3";
+ /** R3 */
+ DualSenseInput[DualSenseInput["R3"] = 11] = "R3";
+ /** DPadUp */
+ DualSenseInput[DualSenseInput["DPadUp"] = 12] = "DPadUp";
+ /** DPadDown */
+ DualSenseInput[DualSenseInput["DPadDown"] = 13] = "DPadDown";
+ /** DPadLeft */
+ DualSenseInput[DualSenseInput["DPadLeft"] = 14] = "DPadLeft";
+ /** DRight */
+ DualSenseInput[DualSenseInput["DPadRight"] = 15] = "DPadRight";
+ /** Home */
+ DualSenseInput[DualSenseInput["Home"] = 16] = "Home";
+ /** TouchPad */
+ DualSenseInput[DualSenseInput["TouchPad"] = 17] = "TouchPad";
+ /** LStickXAxis */
+ DualSenseInput[DualSenseInput["LStickXAxis"] = 18] = "LStickXAxis";
+ /** LStickYAxis */
+ DualSenseInput[DualSenseInput["LStickYAxis"] = 19] = "LStickYAxis";
+ /** RStickXAxis */
+ DualSenseInput[DualSenseInput["RStickXAxis"] = 20] = "RStickXAxis";
+ /** RStickYAxis */
+ DualSenseInput[DualSenseInput["RStickYAxis"] = 21] = "RStickYAxis";
+})(DualSenseInput || (DualSenseInput = {}));
+/**
+ * Enum for Xbox Gamepad
+ */
+var XboxInput;
+(function (XboxInput) {
+ /** A */
+ XboxInput[XboxInput["A"] = 0] = "A";
+ /** B */
+ XboxInput[XboxInput["B"] = 1] = "B";
+ /** X */
+ XboxInput[XboxInput["X"] = 2] = "X";
+ /** Y */
+ XboxInput[XboxInput["Y"] = 3] = "Y";
+ /** LB */
+ XboxInput[XboxInput["LB"] = 4] = "LB";
+ /** RB */
+ XboxInput[XboxInput["RB"] = 5] = "RB";
+ /** LT */
+ XboxInput[XboxInput["LT"] = 6] = "LT";
+ /** RT */
+ XboxInput[XboxInput["RT"] = 7] = "RT";
+ /** Back */
+ XboxInput[XboxInput["Back"] = 8] = "Back";
+ /** Start */
+ XboxInput[XboxInput["Start"] = 9] = "Start";
+ /** LS */
+ XboxInput[XboxInput["LS"] = 10] = "LS";
+ /** RS */
+ XboxInput[XboxInput["RS"] = 11] = "RS";
+ /** DPadUp */
+ XboxInput[XboxInput["DPadUp"] = 12] = "DPadUp";
+ /** DPadDown */
+ XboxInput[XboxInput["DPadDown"] = 13] = "DPadDown";
+ /** DPadLeft */
+ XboxInput[XboxInput["DPadLeft"] = 14] = "DPadLeft";
+ /** DRight */
+ XboxInput[XboxInput["DPadRight"] = 15] = "DPadRight";
+ /** Home */
+ XboxInput[XboxInput["Home"] = 16] = "Home";
+ /** LStickXAxis */
+ XboxInput[XboxInput["LStickXAxis"] = 17] = "LStickXAxis";
+ /** LStickYAxis */
+ XboxInput[XboxInput["LStickYAxis"] = 18] = "LStickYAxis";
+ /** RStickXAxis */
+ XboxInput[XboxInput["RStickXAxis"] = 19] = "RStickXAxis";
+ /** RStickYAxis */
+ XboxInput[XboxInput["RStickYAxis"] = 20] = "RStickYAxis";
+})(XboxInput || (XboxInput = {}));
+/**
+ * Enum for Switch (Pro/JoyCon L+R) Gamepad
+ */
+var SwitchInput;
+(function (SwitchInput) {
+ /** B */
+ SwitchInput[SwitchInput["B"] = 0] = "B";
+ /** A */
+ SwitchInput[SwitchInput["A"] = 1] = "A";
+ /** Y */
+ SwitchInput[SwitchInput["Y"] = 2] = "Y";
+ /** X */
+ SwitchInput[SwitchInput["X"] = 3] = "X";
+ /** L */
+ SwitchInput[SwitchInput["L"] = 4] = "L";
+ /** R */
+ SwitchInput[SwitchInput["R"] = 5] = "R";
+ /** ZL */
+ SwitchInput[SwitchInput["ZL"] = 6] = "ZL";
+ /** ZR */
+ SwitchInput[SwitchInput["ZR"] = 7] = "ZR";
+ /** Minus */
+ SwitchInput[SwitchInput["Minus"] = 8] = "Minus";
+ /** Plus */
+ SwitchInput[SwitchInput["Plus"] = 9] = "Plus";
+ /** LS */
+ SwitchInput[SwitchInput["LS"] = 10] = "LS";
+ /** RS */
+ SwitchInput[SwitchInput["RS"] = 11] = "RS";
+ /** DPadUp */
+ SwitchInput[SwitchInput["DPadUp"] = 12] = "DPadUp";
+ /** DPadDown */
+ SwitchInput[SwitchInput["DPadDown"] = 13] = "DPadDown";
+ /** DPadLeft */
+ SwitchInput[SwitchInput["DPadLeft"] = 14] = "DPadLeft";
+ /** DRight */
+ SwitchInput[SwitchInput["DPadRight"] = 15] = "DPadRight";
+ /** Home */
+ SwitchInput[SwitchInput["Home"] = 16] = "Home";
+ /** Capture */
+ SwitchInput[SwitchInput["Capture"] = 17] = "Capture";
+ /** LStickXAxis */
+ SwitchInput[SwitchInput["LStickXAxis"] = 18] = "LStickXAxis";
+ /** LStickYAxis */
+ SwitchInput[SwitchInput["LStickYAxis"] = 19] = "LStickYAxis";
+ /** RStickXAxis */
+ SwitchInput[SwitchInput["RStickXAxis"] = 20] = "RStickXAxis";
+ /** RStickYAxis */
+ SwitchInput[SwitchInput["RStickYAxis"] = 21] = "RStickYAxis";
+})(SwitchInput || (SwitchInput = {}));
+
+/**
+ * Event Types
+ */
+var DeviceInputEventType;
+(function (DeviceInputEventType) {
+ // Pointers
+ /** PointerMove */
+ DeviceInputEventType[DeviceInputEventType["PointerMove"] = 0] = "PointerMove";
+ /** PointerDown */
+ DeviceInputEventType[DeviceInputEventType["PointerDown"] = 1] = "PointerDown";
+ /** PointerUp */
+ DeviceInputEventType[DeviceInputEventType["PointerUp"] = 2] = "PointerUp";
+})(DeviceInputEventType || (DeviceInputEventType = {}));
+/**
+ * Constants used for Events
+ */
+class EventConstants {
+}
+/**
+ * Pixel delta for Wheel Events (Default)
+ */
+EventConstants.DOM_DELTA_PIXEL = 0x00;
+/**
+ * Line delta for Wheel Events
+ */
+EventConstants.DOM_DELTA_LINE = 0x01;
+/**
+ * Page delta for Wheel Events
+ */
+EventConstants.DOM_DELTA_PAGE = 0x02;
+
+/**
+ * Class to wrap DeviceInputSystem data into an event object
+ */
+class DeviceEventFactory {
+ /**
+ * Create device input events based on provided type and slot
+ *
+ * @param deviceType Type of device
+ * @param deviceSlot "Slot" or index that device is referenced in
+ * @param inputIndex Id of input to be checked
+ * @param currentState Current value for given input
+ * @param deviceInputSystem Reference to DeviceInputSystem
+ * @param elementToAttachTo HTMLElement to reference as target for inputs
+ * @param pointerId PointerId to use for pointer events
+ * @returns IUIEvent object
+ */
+ static CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) {
+ switch (deviceType) {
+ case DeviceType.Keyboard:
+ return this._CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo);
+ case DeviceType.Mouse:
+ if (inputIndex === PointerInput.MouseWheelX || inputIndex === PointerInput.MouseWheelY || inputIndex === PointerInput.MouseWheelZ) {
+ return this._CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);
+ }
+ // eslint-disable-next-line no-fallthrough
+ case DeviceType.Touch:
+ return this._CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId);
+ default:
+ // eslint-disable-next-line no-throw-literal
+ throw `Unable to generate event for device ${DeviceType[deviceType]}`;
+ }
+ }
+ /**
+ * Creates pointer event
+ *
+ * @param deviceType Type of device
+ * @param deviceSlot "Slot" or index that device is referenced in
+ * @param inputIndex Id of input to be checked
+ * @param currentState Current value for given input
+ * @param deviceInputSystem Reference to DeviceInputSystem
+ * @param elementToAttachTo HTMLElement to reference as target for inputs
+ * @param pointerId PointerId to use for pointer events
+ * @returns IUIEvent object (Pointer)
+ */
+ static _CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) {
+ const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);
+ if (deviceType === DeviceType.Mouse) {
+ evt.deviceType = DeviceType.Mouse;
+ evt.pointerId = 1;
+ evt.pointerType = "mouse";
+ }
+ else {
+ evt.deviceType = DeviceType.Touch;
+ evt.pointerId = pointerId ?? deviceSlot;
+ evt.pointerType = "touch";
+ }
+ let buttons = 0;
+ // Populate buttons property with current state of all mouse buttons
+ // Uses values found on: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
+ buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.LeftClick);
+ buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.RightClick) * 2;
+ buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.MiddleClick) * 4;
+ evt.buttons = buttons;
+ if (inputIndex === PointerInput.Move) {
+ evt.type = "pointermove";
+ }
+ else if (inputIndex >= PointerInput.LeftClick && inputIndex <= PointerInput.RightClick) {
+ evt.type = currentState === 1 ? "pointerdown" : "pointerup";
+ evt.button = inputIndex - 2;
+ }
+ return evt;
+ }
+ /**
+ * Create Mouse Wheel Event
+ * @param deviceType Type of device
+ * @param deviceSlot "Slot" or index that device is referenced in
+ * @param inputIndex Id of input to be checked
+ * @param currentState Current value for given input
+ * @param deviceInputSystem Reference to DeviceInputSystem
+ * @param elementToAttachTo HTMLElement to reference as target for inputs
+ * @returns IUIEvent object (Wheel)
+ */
+ static _CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) {
+ const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);
+ // While WheelEvents don't generally have a pointerId, we used to add one in the InputManager
+ // This line has been added to make the InputManager more platform-agnostic
+ // Similar code exists in the WebDeviceInputSystem to handle browser created events
+ evt.pointerId = 1;
+ evt.type = "wheel";
+ evt.deltaMode = EventConstants.DOM_DELTA_PIXEL;
+ evt.deltaX = 0;
+ evt.deltaY = 0;
+ evt.deltaZ = 0;
+ switch (inputIndex) {
+ case PointerInput.MouseWheelX:
+ evt.deltaX = currentState;
+ break;
+ case PointerInput.MouseWheelY:
+ evt.deltaY = currentState;
+ break;
+ case PointerInput.MouseWheelZ:
+ evt.deltaZ = currentState;
+ break;
+ }
+ return evt;
+ }
+ /**
+ * Create Mouse Event
+ * @param deviceType Type of device
+ * @param deviceSlot "Slot" or index that device is referenced in
+ * @param inputIndex Id of input to be checked
+ * @param currentState Current value for given input
+ * @param deviceInputSystem Reference to DeviceInputSystem
+ * @param elementToAttachTo HTMLElement to reference as target for inputs
+ * @returns IUIEvent object (Mouse)
+ */
+ static _CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) {
+ const evt = this._CreateEvent(elementToAttachTo);
+ const pointerX = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Horizontal);
+ const pointerY = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Vertical);
+ // Handle offsets/deltas based on existence of HTMLElement
+ if (elementToAttachTo) {
+ evt.movementX = 0;
+ evt.movementY = 0;
+ evt.offsetX = evt.movementX - elementToAttachTo.getBoundingClientRect().x;
+ evt.offsetY = evt.movementY - elementToAttachTo.getBoundingClientRect().y;
+ }
+ else {
+ evt.movementX = deviceInputSystem.pollInput(deviceType, deviceSlot, 10 /* NativePointerInput.DeltaHorizontal */); // DeltaHorizontal
+ evt.movementY = deviceInputSystem.pollInput(deviceType, deviceSlot, 11 /* NativePointerInput.DeltaVertical */); // DeltaVertical
+ evt.offsetX = 0;
+ evt.offsetY = 0;
+ }
+ this._CheckNonCharacterKeys(evt, deviceInputSystem);
+ evt.clientX = pointerX;
+ evt.clientY = pointerY;
+ evt.x = pointerX;
+ evt.y = pointerY;
+ evt.deviceType = deviceType;
+ evt.deviceSlot = deviceSlot;
+ evt.inputIndex = inputIndex;
+ return evt;
+ }
+ /**
+ * Create Keyboard Event
+ * @param inputIndex Id of input to be checked
+ * @param currentState Current value for given input
+ * @param deviceInputSystem Reference to DeviceInputSystem
+ * @param elementToAttachTo HTMLElement to reference as target for inputs
+ * @returns IEvent object (Keyboard)
+ */
+ static _CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo) {
+ const evt = this._CreateEvent(elementToAttachTo);
+ this._CheckNonCharacterKeys(evt, deviceInputSystem);
+ evt.deviceType = DeviceType.Keyboard;
+ evt.deviceSlot = 0;
+ evt.inputIndex = inputIndex;
+ evt.type = currentState === 1 ? "keydown" : "keyup";
+ evt.key = String.fromCharCode(inputIndex);
+ evt.keyCode = inputIndex;
+ return evt;
+ }
+ /**
+ * Add parameters for non-character keys (Ctrl, Alt, Meta, Shift)
+ * @param evt Event object to add parameters to
+ * @param deviceInputSystem DeviceInputSystem to pull values from
+ */
+ static _CheckNonCharacterKeys(evt, deviceInputSystem) {
+ const isKeyboardActive = deviceInputSystem.isDeviceAvailable(DeviceType.Keyboard);
+ const altKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 18) === 1;
+ const ctrlKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 17) === 1;
+ const metaKey = isKeyboardActive &&
+ (deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 91) === 1 ||
+ deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 92) === 1 ||
+ deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 93) === 1);
+ const shiftKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 16) === 1;
+ evt.altKey = altKey;
+ evt.ctrlKey = ctrlKey;
+ evt.metaKey = metaKey;
+ evt.shiftKey = shiftKey;
+ }
+ /**
+ * Create base event object
+ * @param elementToAttachTo Value to use as event target
+ * @returns
+ */
+ static _CreateEvent(elementToAttachTo) {
+ const evt = {};
+ evt.preventDefault = () => { };
+ evt.target = elementToAttachTo;
+ return evt;
+ }
+}
+
+/** @internal */
+class NativeDeviceInputSystem {
+ constructor(onDeviceConnected, onDeviceDisconnected, onInputChanged) {
+ this._nativeInput = _native.DeviceInputSystem
+ ? new _native.DeviceInputSystem(onDeviceConnected, onDeviceDisconnected, (deviceType, deviceSlot, inputIndex, currentState) => {
+ const evt = DeviceEventFactory.CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, this);
+ onInputChanged(deviceType, deviceSlot, evt);
+ })
+ : this._createDummyNativeInput();
+ }
+ // Public functions
+ /**
+ * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized.
+ * @param deviceType Enum specifying device type
+ * @param deviceSlot "Slot" or index that device is referenced in
+ * @param inputIndex Id of input to be checked
+ * @returns Current value of input
+ */
+ pollInput(deviceType, deviceSlot, inputIndex) {
+ return this._nativeInput.pollInput(deviceType, deviceSlot, inputIndex);
+ }
+ /**
+ * Check for a specific device in the DeviceInputSystem
+ * @param deviceType Type of device to check for
+ * @returns bool with status of device's existence
+ */
+ isDeviceAvailable(deviceType) {
+ //TODO: FIx native side first
+ return deviceType === DeviceType.Mouse || deviceType === DeviceType.Touch;
+ }
+ /**
+ * Dispose of all the observables
+ */
+ dispose() {
+ this._nativeInput.dispose();
+ }
+ /**
+ * For versions of BabylonNative that don't have the NativeInput plugin initialized, create a dummy version
+ * @returns Object with dummy functions
+ */
+ _createDummyNativeInput() {
+ const nativeInput = {
+ pollInput: () => {
+ return 0;
+ },
+ isDeviceAvailable: () => {
+ return false;
+ },
+ dispose: () => { },
+ };
+ return nativeInput;
+ }
+}
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const MAX_KEYCODES = 255;
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2;
+/** @internal */
+class WebDeviceInputSystem {
+ /**
+ * Constructor for the WebDeviceInputSystem
+ * @param engine Engine to reference
+ * @param onDeviceConnected Callback to execute when device is connected
+ * @param onDeviceDisconnected Callback to execute when device is disconnected
+ * @param onInputChanged Callback to execute when input changes on device
+ */
+ constructor(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged) {
+ // Private Members
+ this._inputs = [];
+ this._keyboardActive = false;
+ this._pointerActive = false;
+ this._usingSafari = Tools.IsSafari();
+ // Found solution for determining if MacOS is being used here:
+ // https://stackoverflow.com/questions/10527983/best-way-to-detect-mac-os-x-or-windows-computers-with-javascript-or-jquery
+ this._usingMacOS = IsNavigatorAvailable() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._keyboardDownEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._keyboardUpEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._keyboardBlurEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerMoveEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerDownEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerUpEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerCancelEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerCancelTouch = (pointerId) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerLeaveEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerWheelEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerBlurEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._pointerMacOSChromeOutEvent = (evt) => { };
+ this._eventsAttached = false;
+ this._mouseId = -1;
+ this._isUsingFirefox = IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf("Firefox") !== -1;
+ this._isUsingChromium = IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf("Chrome") !== -1;
+ this._maxTouchPoints = 0;
+ this._pointerInputClearObserver = null;
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._gamepadConnectedEvent = (evt) => { };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ this._gamepadDisconnectedEvent = (evt) => { };
+ this._eventPrefix = Tools.GetPointerPrefix(engine);
+ this._engine = engine;
+ this._onDeviceConnected = onDeviceConnected;
+ this._onDeviceDisconnected = onDeviceDisconnected;
+ this._onInputChanged = onInputChanged;
+ // If we need a pointerId, set one for future use
+ this._mouseId = this._isUsingFirefox ? 0 : 1;
+ this._enableEvents();
+ if (this._usingMacOS) {
+ this._metaKeys = [];
+ }
+ // Set callback to enable event handler switching when inputElement changes
+ if (!this._engine._onEngineViewChanged) {
+ this._engine._onEngineViewChanged = () => {
+ this._enableEvents();
+ };
+ }
+ }
+ // Public functions
+ /**
+ * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized.
+ * @param deviceType Enum specifying device type
+ * @param deviceSlot "Slot" or index that device is referenced in
+ * @param inputIndex Id of input to be checked
+ * @returns Current value of input
+ */
+ pollInput(deviceType, deviceSlot, inputIndex) {
+ const device = this._inputs[deviceType][deviceSlot];
+ if (!device) {
+ // eslint-disable-next-line no-throw-literal
+ throw `Unable to find device ${DeviceType[deviceType]}`;
+ }
+ if (deviceType >= DeviceType.DualShock && deviceType <= DeviceType.DualSense) {
+ this._updateDevice(deviceType, deviceSlot, inputIndex);
+ }
+ const currentValue = device[inputIndex];
+ if (currentValue === undefined) {
+ // eslint-disable-next-line no-throw-literal
+ throw `Unable to find input ${inputIndex} for device ${DeviceType[deviceType]} in slot ${deviceSlot}`;
+ }
+ if (inputIndex === PointerInput.Move) {
+ Tools.Warn(`Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data.`);
+ }
+ return currentValue;
+ }
+ /**
+ * Check for a specific device in the DeviceInputSystem
+ * @param deviceType Type of device to check for
+ * @returns bool with status of device's existence
+ */
+ isDeviceAvailable(deviceType) {
+ return this._inputs[deviceType] !== undefined;
+ }
+ /**
+ * Dispose of all the eventlisteners
+ */
+ dispose() {
+ // Callbacks
+ this._onDeviceConnected = () => { };
+ this._onDeviceDisconnected = () => { };
+ this._onInputChanged = () => { };
+ delete this._engine._onEngineViewChanged;
+ if (this._elementToAttachTo) {
+ this._disableEvents();
+ }
+ }
+ /**
+ * Enable listening for user input events
+ */
+ _enableEvents() {
+ const inputElement = this?._engine.getInputElement();
+ if (inputElement && (!this._eventsAttached || this._elementToAttachTo !== inputElement)) {
+ // Remove events before adding to avoid double events or simultaneous events on multiple canvases
+ this._disableEvents();
+ // If the inputs array has already been created, zero it out to before setting up events
+ if (this._inputs) {
+ for (const inputs of this._inputs) {
+ if (inputs) {
+ for (const deviceSlotKey in inputs) {
+ const deviceSlot = +deviceSlotKey;
+ const device = inputs[deviceSlot];
+ if (device) {
+ for (let inputIndex = 0; inputIndex < device.length; inputIndex++) {
+ device[inputIndex] = 0;
+ }
+ }
+ }
+ }
+ }
+ }
+ this._elementToAttachTo = inputElement;
+ // Set tab index for the inputElement to the engine's canvasTabIndex, if and only if the element's tab index is -1
+ this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex;
+ this._handleKeyActions();
+ this._handlePointerActions();
+ this._handleGamepadActions();
+ this._eventsAttached = true;
+ // Check for devices that are already connected but aren't registered. Currently, only checks for gamepads and mouse
+ this._checkForConnectedDevices();
+ }
+ }
+ /**
+ * Disable listening for user input events
+ */
+ _disableEvents() {
+ if (this._elementToAttachTo) {
+ // Blur Events
+ this._elementToAttachTo.removeEventListener("blur", this._keyboardBlurEvent);
+ this._elementToAttachTo.removeEventListener("blur", this._pointerBlurEvent);
+ // Keyboard Events
+ this._elementToAttachTo.removeEventListener("keydown", this._keyboardDownEvent);
+ this._elementToAttachTo.removeEventListener("keyup", this._keyboardUpEvent);
+ // Pointer Events
+ this._elementToAttachTo.removeEventListener(this._eventPrefix + "move", this._pointerMoveEvent);
+ this._elementToAttachTo.removeEventListener(this._eventPrefix + "down", this._pointerDownEvent);
+ this._elementToAttachTo.removeEventListener(this._eventPrefix + "up", this._pointerUpEvent);
+ this._elementToAttachTo.removeEventListener(this._eventPrefix + "cancel", this._pointerCancelEvent);
+ this._elementToAttachTo.removeEventListener(this._eventPrefix + "leave", this._pointerLeaveEvent);
+ this._elementToAttachTo.removeEventListener(this._wheelEventName, this._pointerWheelEvent);
+ if (this._usingMacOS && this._isUsingChromium) {
+ this._elementToAttachTo.removeEventListener("lostpointercapture", this._pointerMacOSChromeOutEvent);
+ }
+ // Gamepad Events
+ window.removeEventListener("gamepadconnected", this._gamepadConnectedEvent);
+ window.removeEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent);
+ }
+ if (this._pointerInputClearObserver) {
+ this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver);
+ }
+ this._eventsAttached = false;
+ }
+ /**
+ * Checks for existing connections to devices and register them, if necessary
+ * Currently handles gamepads and mouse
+ */
+ _checkForConnectedDevices() {
+ if (navigator.getGamepads) {
+ const gamepads = navigator.getGamepads();
+ for (const gamepad of gamepads) {
+ if (gamepad) {
+ this._addGamePad(gamepad);
+ }
+ }
+ }
+ // If the device in use has mouse capabilities, pre-register mouse
+ if (typeof matchMedia === "function" && matchMedia("(pointer:fine)").matches) {
+ // This will provide a dummy value for the cursor position and is expected to be overridden when the first mouse event happens.
+ // There isn't any good way to get the current position outside of a pointer event so that's why this was done.
+ this._addPointerDevice(DeviceType.Mouse, 0, 0, 0);
+ }
+ }
+ // Private functions
+ /**
+ * Add a gamepad to the DeviceInputSystem
+ * @param gamepad A single DOM Gamepad object
+ */
+ _addGamePad(gamepad) {
+ const deviceType = this._getGamepadDeviceType(gamepad.id);
+ const deviceSlot = gamepad.index;
+ this._gamepads = this._gamepads || new Array(gamepad.index + 1);
+ this._registerDevice(deviceType, deviceSlot, gamepad.buttons.length + gamepad.axes.length);
+ this._gamepads[deviceSlot] = deviceType;
+ }
+ /**
+ * Add pointer device to DeviceInputSystem
+ * @param deviceType Type of Pointer to add
+ * @param deviceSlot Pointer ID (0 for mouse, pointerId for Touch)
+ * @param currentX Current X at point of adding
+ * @param currentY Current Y at point of adding
+ */
+ _addPointerDevice(deviceType, deviceSlot, currentX, currentY) {
+ if (!this._pointerActive) {
+ this._pointerActive = true;
+ }
+ this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS);
+ const pointer = this._inputs[deviceType][deviceSlot]; /* initialize our pointer position immediately after registration */
+ pointer[0] = currentX;
+ pointer[1] = currentY;
+ }
+ /**
+ * Add device and inputs to device array
+ * @param deviceType Enum specifying device type
+ * @param deviceSlot "Slot" or index that device is referenced in
+ * @param numberOfInputs Number of input entries to create for given device
+ */
+ _registerDevice(deviceType, deviceSlot, numberOfInputs) {
+ if (deviceSlot === undefined) {
+ // eslint-disable-next-line no-throw-literal
+ throw `Unable to register device ${DeviceType[deviceType]} to undefined slot.`;
+ }
+ if (!this._inputs[deviceType]) {
+ this._inputs[deviceType] = {};
+ }
+ if (!this._inputs[deviceType][deviceSlot]) {
+ const device = new Array(numberOfInputs);
+ device.fill(0);
+ this._inputs[deviceType][deviceSlot] = device;
+ this._onDeviceConnected(deviceType, deviceSlot);
+ }
+ }
+ /**
+ * Given a specific device name, remove that device from the device map
+ * @param deviceType Enum specifying device type
+ * @param deviceSlot "Slot" or index that device is referenced in
+ */
+ _unregisterDevice(deviceType, deviceSlot) {
+ if (this._inputs[deviceType][deviceSlot]) {
+ delete this._inputs[deviceType][deviceSlot];
+ this._onDeviceDisconnected(deviceType, deviceSlot);
+ }
+ }
+ /**
+ * Handle all actions that come from keyboard interaction
+ */
+ _handleKeyActions() {
+ this._keyboardDownEvent = (evt) => {
+ if (!this._keyboardActive) {
+ this._keyboardActive = true;
+ this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES);
+ }
+ const kbKey = this._inputs[DeviceType.Keyboard][0];
+ if (kbKey) {
+ kbKey[evt.keyCode] = 1;
+ const deviceEvent = evt;
+ deviceEvent.inputIndex = evt.keyCode;
+ if (this._usingMacOS && evt.metaKey && evt.key !== "Meta") {
+ if (!this._metaKeys.includes(evt.keyCode)) {
+ this._metaKeys.push(evt.keyCode);
+ }
+ }
+ this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);
+ }
+ };
+ this._keyboardUpEvent = (evt) => {
+ if (!this._keyboardActive) {
+ this._keyboardActive = true;
+ this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES);
+ }
+ const kbKey = this._inputs[DeviceType.Keyboard][0];
+ if (kbKey) {
+ kbKey[evt.keyCode] = 0;
+ const deviceEvent = evt;
+ deviceEvent.inputIndex = evt.keyCode;
+ if (this._usingMacOS && evt.key === "Meta" && this._metaKeys.length > 0) {
+ for (const keyCode of this._metaKeys) {
+ const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, keyCode, 0, this, this._elementToAttachTo);
+ kbKey[keyCode] = 0;
+ this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);
+ }
+ this._metaKeys.splice(0, this._metaKeys.length);
+ }
+ this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);
+ }
+ };
+ this._keyboardBlurEvent = () => {
+ if (this._keyboardActive) {
+ const kbKey = this._inputs[DeviceType.Keyboard][0];
+ for (let i = 0; i < kbKey.length; i++) {
+ if (kbKey[i] !== 0) {
+ kbKey[i] = 0;
+ const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, i, 0, this, this._elementToAttachTo);
+ this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);
+ }
+ }
+ if (this._usingMacOS) {
+ this._metaKeys.splice(0, this._metaKeys.length);
+ }
+ }
+ };
+ this._elementToAttachTo.addEventListener("keydown", this._keyboardDownEvent);
+ this._elementToAttachTo.addEventListener("keyup", this._keyboardUpEvent);
+ this._elementToAttachTo.addEventListener("blur", this._keyboardBlurEvent);
+ }
+ /**
+ * Handle all actions that come from pointer interaction
+ */
+ _handlePointerActions() {
+ // If maxTouchPoints is defined, use that value. Otherwise, allow for a minimum for supported gestures like pinch
+ this._maxTouchPoints = (IsNavigatorAvailable() && navigator.maxTouchPoints) || 2;
+ if (!this._activeTouchIds) {
+ this._activeTouchIds = new Array(this._maxTouchPoints);
+ }
+ for (let i = 0; i < this._maxTouchPoints; i++) {
+ this._activeTouchIds[i] = -1;
+ }
+ this._pointerMoveEvent = (evt) => {
+ const deviceType = this._getPointerType(evt);
+ let deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId);
+ // In the event that we're getting pointermove events from touch inputs that we aren't tracking,
+ // look for an available slot and retroactively connect it.
+ if (deviceType === DeviceType.Touch && deviceSlot === -1) {
+ const idx = this._activeTouchIds.indexOf(-1);
+ if (idx >= 0) {
+ deviceSlot = idx;
+ this._activeTouchIds[idx] = evt.pointerId;
+ // Because this is a "new" input, inform the connected callback
+ this._onDeviceConnected(deviceType, deviceSlot);
+ }
+ else {
+ // We can't find an open slot to store new pointer so just return (can only support max number of touches)
+ Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);
+ return;
+ }
+ }
+ if (!this._inputs[deviceType]) {
+ this._inputs[deviceType] = {};
+ }
+ if (!this._inputs[deviceType][deviceSlot]) {
+ this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY);
+ }
+ const pointer = this._inputs[deviceType][deviceSlot];
+ if (pointer) {
+ const deviceEvent = evt;
+ deviceEvent.inputIndex = PointerInput.Move;
+ pointer[PointerInput.Horizontal] = evt.clientX;
+ pointer[PointerInput.Vertical] = evt.clientY;
+ // For touches that aren't started with a down, we need to set the button state to 1
+ if (deviceType === DeviceType.Touch && pointer[PointerInput.LeftClick] === 0) {
+ pointer[PointerInput.LeftClick] = 1;
+ }
+ if (evt.pointerId === undefined) {
+ evt.pointerId = this._mouseId;
+ }
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ // Lets Propagate the event for move with same position.
+ if (!this._usingSafari && evt.button !== -1) {
+ deviceEvent.inputIndex = evt.button + 2;
+ pointer[evt.button + 2] = pointer[evt.button + 2] ? 0 : 1; // Reverse state of button if evt.button has value
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ }
+ }
+ };
+ this._pointerDownEvent = (evt) => {
+ const deviceType = this._getPointerType(evt);
+ let deviceSlot = deviceType === DeviceType.Mouse ? 0 : evt.pointerId;
+ if (deviceType === DeviceType.Touch) {
+ // See if this pointerId is already using an existing slot
+ // (possible on some devices which raise the pointerMove event before the pointerDown event, e.g. when using a pen)
+ let idx = this._activeTouchIds.indexOf(evt.pointerId);
+ if (idx === -1) {
+ // If the pointerId wasn't already using a slot, find an open one
+ idx = this._activeTouchIds.indexOf(-1);
+ }
+ if (idx >= 0) {
+ deviceSlot = idx;
+ this._activeTouchIds[idx] = evt.pointerId;
+ }
+ else {
+ // We can't find an open slot to store new pointer so just return (can only support max number of touches)
+ Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);
+ return;
+ }
+ }
+ if (!this._inputs[deviceType]) {
+ this._inputs[deviceType] = {};
+ }
+ if (!this._inputs[deviceType][deviceSlot]) {
+ this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY);
+ }
+ else if (deviceType === DeviceType.Touch) {
+ this._onDeviceConnected(deviceType, deviceSlot);
+ }
+ const pointer = this._inputs[deviceType][deviceSlot];
+ if (pointer) {
+ const previousHorizontal = pointer[PointerInput.Horizontal];
+ const previousVertical = pointer[PointerInput.Vertical];
+ if (deviceType === DeviceType.Mouse) {
+ // Mouse; Set pointerId if undefined
+ if (evt.pointerId === undefined) {
+ evt.pointerId = this._mouseId;
+ }
+ if (!document.pointerLockElement) {
+ try {
+ this._elementToAttachTo.setPointerCapture(this._mouseId);
+ }
+ catch (e) {
+ // DO NOTHING
+ }
+ }
+ }
+ else {
+ // Touch; Since touches are dynamically assigned, only set capture if we have an id
+ if (evt.pointerId && !document.pointerLockElement) {
+ try {
+ this._elementToAttachTo.setPointerCapture(evt.pointerId);
+ }
+ catch (e) {
+ // DO NOTHING
+ }
+ }
+ }
+ pointer[PointerInput.Horizontal] = evt.clientX;
+ pointer[PointerInput.Vertical] = evt.clientY;
+ pointer[evt.button + 2] = 1;
+ const deviceEvent = evt;
+ // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button
+ // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression
+ // EG. ([X, Y, Left-click], Middle-click, etc...)
+ deviceEvent.inputIndex = evt.button + 2;
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) {
+ deviceEvent.inputIndex = PointerInput.Move;
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ }
+ }
+ };
+ this._pointerUpEvent = (evt) => {
+ const deviceType = this._getPointerType(evt);
+ const deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId);
+ if (deviceType === DeviceType.Touch) {
+ // If we're getting a pointerup event for a touch that isn't active, just return.
+ if (deviceSlot === -1) {
+ return;
+ }
+ else {
+ this._activeTouchIds[deviceSlot] = -1;
+ }
+ }
+ const pointer = this._inputs[deviceType]?.[deviceSlot];
+ let button = evt.button;
+ let shouldProcessPointerUp = pointer && pointer[button + 2] !== 0;
+ // Workaround for an issue in Firefox on MacOS only where the browser allows the user to change left button
+ // actions into right button actions by holding down control. If the user starts a drag with the control button
+ // down, then lifts control, then releases the mouse, we'll get mismatched up and down events (the down will be
+ // the right button, and the up will be the left button). In that specific case, where we get an up from a button
+ // which didn't have a corresponding down, and we are in Firefox on MacOS, we should process the up event as if it
+ // was from the other button.
+ // Ideally this would be fixed in Firefox so that if you start a drag with the control button down, then the button
+ // passed along to both pointer down and up would be the right button regardless of the order in which control and the
+ // mouse button were released.
+ // If Firefox makes a fix to ensure this is the case, this workaround can be removed.
+ // Relevant forum thread: https://forum.babylonjs.com/t/camera-pan-getting-stuck-in-firefox/57158
+ if (!shouldProcessPointerUp && this._isUsingFirefox && this._usingMacOS && pointer) {
+ // Try the other button (left or right button)
+ button = button === 2 ? 0 : 2;
+ shouldProcessPointerUp = pointer[button + 2] !== 0;
+ }
+ if (shouldProcessPointerUp) {
+ const previousHorizontal = pointer[PointerInput.Horizontal];
+ const previousVertical = pointer[PointerInput.Vertical];
+ pointer[PointerInput.Horizontal] = evt.clientX;
+ pointer[PointerInput.Vertical] = evt.clientY;
+ pointer[button + 2] = 0;
+ const deviceEvent = evt;
+ if (evt.pointerId === undefined) {
+ evt.pointerId = this._mouseId;
+ }
+ if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) {
+ deviceEvent.inputIndex = PointerInput.Move;
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ }
+ // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button
+ // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression
+ // EG. ([X, Y, Left-click], Middle-click, etc...)
+ deviceEvent.inputIndex = button + 2;
+ if (deviceType === DeviceType.Mouse && this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) {
+ this._elementToAttachTo.releasePointerCapture(this._mouseId);
+ }
+ else if (evt.pointerId && this._elementToAttachTo.hasPointerCapture?.(evt.pointerId)) {
+ this._elementToAttachTo.releasePointerCapture(evt.pointerId);
+ }
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ if (deviceType === DeviceType.Touch) {
+ this._onDeviceDisconnected(deviceType, deviceSlot);
+ }
+ }
+ };
+ this._pointerCancelTouch = (pointerId) => {
+ const deviceSlot = this._activeTouchIds.indexOf(pointerId);
+ // If we're getting a pointercancel event for a touch that isn't active, just return
+ if (deviceSlot === -1) {
+ return;
+ }
+ if (this._elementToAttachTo.hasPointerCapture?.(pointerId)) {
+ this._elementToAttachTo.releasePointerCapture(pointerId);
+ }
+ this._inputs[DeviceType.Touch][deviceSlot][PointerInput.LeftClick] = 0;
+ const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId);
+ this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent);
+ this._activeTouchIds[deviceSlot] = -1;
+ this._onDeviceDisconnected(DeviceType.Touch, deviceSlot);
+ };
+ this._pointerCancelEvent = (evt) => {
+ if (evt.pointerType === "mouse") {
+ const pointer = this._inputs[DeviceType.Mouse][0];
+ if (this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) {
+ this._elementToAttachTo.releasePointerCapture(this._mouseId);
+ }
+ for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) {
+ if (pointer[inputIndex] === 1) {
+ pointer[inputIndex] = 0;
+ const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo);
+ this._onInputChanged(DeviceType.Mouse, 0, deviceEvent);
+ }
+ }
+ }
+ else {
+ this._pointerCancelTouch(evt.pointerId);
+ }
+ };
+ this._pointerLeaveEvent = (evt) => {
+ if (evt.pointerType === "pen") {
+ // If a pen leaves the hover range detectible by the hardware this event is raised and we need to cancel the operation
+ // Note that pen operations are treated as touch operations
+ this._pointerCancelTouch(evt.pointerId);
+ }
+ };
+ // Set Wheel Event Name, code originally from scene.inputManager
+ this._wheelEventName =
+ "onwheel" in document.createElement("div")
+ ? "wheel" // Modern browsers support "wheel"
+ : document.onmousewheel !== undefined
+ ? "mousewheel" // Webkit and IE support at least "mousewheel"
+ : "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
+ // Code originally in scene.inputManager.ts
+ // Chrome reports warning in console if wheel listener doesn't set an explicit passive option.
+ // IE11 only supports captureEvent:boolean, not options:object, and it defaults to false.
+ // Feature detection technique copied from: https://github.com/github/eventlistener-polyfill (MIT license)
+ let passiveSupported = false;
+ const noop = function () { };
+ try {
+ const options = Object.defineProperty({}, "passive", {
+ get: function () {
+ passiveSupported = true;
+ },
+ });
+ this._elementToAttachTo.addEventListener("test", noop, options);
+ this._elementToAttachTo.removeEventListener("test", noop, options);
+ }
+ catch (e) {
+ /* */
+ }
+ this._pointerBlurEvent = () => {
+ // Handle mouse buttons
+ if (this.isDeviceAvailable(DeviceType.Mouse)) {
+ const pointer = this._inputs[DeviceType.Mouse][0];
+ if (this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) {
+ this._elementToAttachTo.releasePointerCapture(this._mouseId);
+ }
+ for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) {
+ if (pointer[inputIndex] === 1) {
+ pointer[inputIndex] = 0;
+ const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo);
+ this._onInputChanged(DeviceType.Mouse, 0, deviceEvent);
+ }
+ }
+ }
+ // Handle Active Touches
+ if (this.isDeviceAvailable(DeviceType.Touch)) {
+ const pointer = this._inputs[DeviceType.Touch];
+ for (let deviceSlot = 0; deviceSlot < this._activeTouchIds.length; deviceSlot++) {
+ const pointerId = this._activeTouchIds[deviceSlot];
+ if (this._elementToAttachTo.hasPointerCapture?.(pointerId)) {
+ this._elementToAttachTo.releasePointerCapture(pointerId);
+ }
+ if (pointerId !== -1 && pointer[deviceSlot]?.[PointerInput.LeftClick] === 1) {
+ pointer[deviceSlot][PointerInput.LeftClick] = 0;
+ const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId);
+ this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent);
+ this._activeTouchIds[deviceSlot] = -1;
+ this._onDeviceDisconnected(DeviceType.Touch, deviceSlot);
+ }
+ }
+ }
+ };
+ this._pointerWheelEvent = (evt) => {
+ const deviceType = DeviceType.Mouse;
+ const deviceSlot = 0;
+ if (!this._inputs[deviceType]) {
+ this._inputs[deviceType] = [];
+ }
+ if (!this._inputs[deviceType][deviceSlot]) {
+ this._pointerActive = true;
+ this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS);
+ }
+ const pointer = this._inputs[deviceType][deviceSlot];
+ if (pointer) {
+ pointer[PointerInput.MouseWheelX] = evt.deltaX || 0;
+ pointer[PointerInput.MouseWheelY] = evt.deltaY || evt.wheelDelta || 0;
+ pointer[PointerInput.MouseWheelZ] = evt.deltaZ || 0;
+ const deviceEvent = evt;
+ // By default, there is no pointerId for mouse wheel events so we'll add one here
+ // This logic was originally in the InputManager but was added here to make the
+ // InputManager more platform-agnostic
+ if (evt.pointerId === undefined) {
+ evt.pointerId = this._mouseId;
+ }
+ if (pointer[PointerInput.MouseWheelX] !== 0) {
+ deviceEvent.inputIndex = PointerInput.MouseWheelX;
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ }
+ if (pointer[PointerInput.MouseWheelY] !== 0) {
+ deviceEvent.inputIndex = PointerInput.MouseWheelY;
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ }
+ if (pointer[PointerInput.MouseWheelZ] !== 0) {
+ deviceEvent.inputIndex = PointerInput.MouseWheelZ;
+ this._onInputChanged(deviceType, deviceSlot, deviceEvent);
+ }
+ }
+ };
+ // Workaround for MacOS Chromium Browsers for lost pointer capture bug
+ if (this._usingMacOS && this._isUsingChromium) {
+ this._pointerMacOSChromeOutEvent = (evt) => {
+ if (evt.buttons > 1) {
+ this._pointerCancelEvent(evt);
+ }
+ };
+ this._elementToAttachTo.addEventListener("lostpointercapture", this._pointerMacOSChromeOutEvent);
+ }
+ this._elementToAttachTo.addEventListener(this._eventPrefix + "move", this._pointerMoveEvent);
+ this._elementToAttachTo.addEventListener(this._eventPrefix + "down", this._pointerDownEvent);
+ this._elementToAttachTo.addEventListener(this._eventPrefix + "up", this._pointerUpEvent);
+ this._elementToAttachTo.addEventListener(this._eventPrefix + "cancel", this._pointerCancelEvent);
+ this._elementToAttachTo.addEventListener(this._eventPrefix + "leave", this._pointerLeaveEvent);
+ this._elementToAttachTo.addEventListener("blur", this._pointerBlurEvent);
+ this._elementToAttachTo.addEventListener(this._wheelEventName, this._pointerWheelEvent, passiveSupported ? { passive: false } : false);
+ // Since there's no up or down event for mouse wheel or delta x/y, clear mouse values at end of frame
+ this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(() => {
+ if (this.isDeviceAvailable(DeviceType.Mouse)) {
+ const pointer = this._inputs[DeviceType.Mouse][0];
+ pointer[PointerInput.MouseWheelX] = 0;
+ pointer[PointerInput.MouseWheelY] = 0;
+ pointer[PointerInput.MouseWheelZ] = 0;
+ }
+ });
+ }
+ /**
+ * Handle all actions that come from gamepad interaction
+ */
+ _handleGamepadActions() {
+ this._gamepadConnectedEvent = (evt) => {
+ this._addGamePad(evt.gamepad);
+ };
+ this._gamepadDisconnectedEvent = (evt) => {
+ if (this._gamepads) {
+ const deviceType = this._getGamepadDeviceType(evt.gamepad.id);
+ const deviceSlot = evt.gamepad.index;
+ this._unregisterDevice(deviceType, deviceSlot);
+ delete this._gamepads[deviceSlot];
+ }
+ };
+ window.addEventListener("gamepadconnected", this._gamepadConnectedEvent);
+ window.addEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent);
+ }
+ /**
+ * Update all non-event based devices with each frame
+ * @param deviceType Enum specifying device type
+ * @param deviceSlot "Slot" or index that device is referenced in
+ * @param inputIndex Id of input to be checked
+ */
+ _updateDevice(deviceType, deviceSlot, inputIndex) {
+ // Gamepads
+ const gp = navigator.getGamepads()[deviceSlot];
+ if (gp && deviceType === this._gamepads[deviceSlot]) {
+ const device = this._inputs[deviceType][deviceSlot];
+ if (inputIndex >= gp.buttons.length) {
+ device[inputIndex] = gp.axes[inputIndex - gp.buttons.length].valueOf();
+ }
+ else {
+ device[inputIndex] = gp.buttons[inputIndex].value;
+ }
+ }
+ }
+ /**
+ * Gets DeviceType from the device name
+ * @param deviceName Name of Device from DeviceInputSystem
+ * @returns DeviceType enum value
+ */
+ _getGamepadDeviceType(deviceName) {
+ if (deviceName.indexOf("054c") !== -1) {
+ // DualShock 4 Gamepad
+ return deviceName.indexOf("0ce6") !== -1 ? DeviceType.DualSense : DeviceType.DualShock;
+ }
+ else if (deviceName.indexOf("Xbox One") !== -1 || deviceName.search("Xbox 360") !== -1 || deviceName.search("xinput") !== -1) {
+ // Xbox Gamepad
+ return DeviceType.Xbox;
+ }
+ else if (deviceName.indexOf("057e") !== -1) {
+ // Switch Gamepad
+ return DeviceType.Switch;
+ }
+ return DeviceType.Generic;
+ }
+ /**
+ * Get DeviceType from a given pointer/mouse/touch event.
+ * @param evt PointerEvent to evaluate
+ * @returns DeviceType interpreted from event
+ */
+ _getPointerType(evt) {
+ let deviceType = DeviceType.Mouse;
+ if (evt.pointerType === "touch" || evt.pointerType === "pen" || evt.touches) {
+ deviceType = DeviceType.Touch;
+ }
+ return deviceType;
+ }
+}
+
+/**
+ * Class that handles all input for a specific device
+ */
+class DeviceSource {
+ /**
+ * Default Constructor
+ * @param deviceInputSystem - Reference to DeviceInputSystem
+ * @param deviceType - Type of device
+ * @param deviceSlot - "Slot" or index that device is referenced in
+ */
+ constructor(deviceInputSystem,
+ /** Type of device */
+ deviceType,
+ /** [0] "Slot" or index that device is referenced in */
+ deviceSlot = 0) {
+ this.deviceType = deviceType;
+ this.deviceSlot = deviceSlot;
+ // Public Members
+ /**
+ * Observable to handle device input changes per device
+ */
+ this.onInputChangedObservable = new Observable();
+ this._deviceInputSystem = deviceInputSystem;
+ }
+ /**
+ * Get input for specific input
+ * @param inputIndex - index of specific input on device
+ * @returns Input value from DeviceInputSystem
+ */
+ getInput(inputIndex) {
+ return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, inputIndex);
+ }
+}
+
+/** @internal */
+class InternalDeviceSourceManager {
+ constructor(engine) {
+ this._registeredManagers = new Array();
+ this._refCount = 0;
+ // Public Functions
+ this.registerManager = (manager) => {
+ for (let deviceType = 0; deviceType < this._devices.length; deviceType++) {
+ const device = this._devices[deviceType];
+ for (const deviceSlotKey in device) {
+ const deviceSlot = +deviceSlotKey;
+ manager._addDevice(new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot));
+ }
+ }
+ this._registeredManagers.push(manager);
+ };
+ this.unregisterManager = (manager) => {
+ const idx = this._registeredManagers.indexOf(manager);
+ if (idx > -1) {
+ this._registeredManagers.splice(idx, 1);
+ }
+ };
+ const numberOfDeviceTypes = Object.keys(DeviceType).length / 2;
+ this._devices = new Array(numberOfDeviceTypes);
+ const onDeviceConnected = (deviceType, deviceSlot) => {
+ if (!this._devices[deviceType]) {
+ this._devices[deviceType] = new Array();
+ }
+ if (!this._devices[deviceType][deviceSlot]) {
+ this._devices[deviceType][deviceSlot] = deviceSlot;
+ }
+ for (const manager of this._registeredManagers) {
+ const deviceSource = new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot);
+ manager._addDevice(deviceSource);
+ }
+ };
+ const onDeviceDisconnected = (deviceType, deviceSlot) => {
+ if (this._devices[deviceType]?.[deviceSlot]) {
+ delete this._devices[deviceType][deviceSlot];
+ }
+ for (const manager of this._registeredManagers) {
+ manager._removeDevice(deviceType, deviceSlot);
+ }
+ };
+ const onInputChanged = (deviceType, deviceSlot, eventData) => {
+ if (eventData) {
+ for (const manager of this._registeredManagers) {
+ manager._onInputChanged(deviceType, deviceSlot, eventData);
+ }
+ }
+ };
+ if (typeof _native !== "undefined") {
+ this._deviceInputSystem = new NativeDeviceInputSystem(onDeviceConnected, onDeviceDisconnected, onInputChanged);
+ }
+ else {
+ this._deviceInputSystem = new WebDeviceInputSystem(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged);
+ }
+ }
+ dispose() {
+ this._deviceInputSystem.dispose();
+ }
+}
+
+/**
+ * Class to keep track of devices
+ */
+class DeviceSourceManager {
+ // Public Functions
+ /**
+ * Gets a DeviceSource, given a type and slot
+ * @param deviceType - Type of Device
+ * @param deviceSlot - Slot or ID of device
+ * @returns DeviceSource
+ */
+ getDeviceSource(deviceType, deviceSlot) {
+ if (deviceSlot === undefined) {
+ if (this._firstDevice[deviceType] === undefined) {
+ return null;
+ }
+ deviceSlot = this._firstDevice[deviceType];
+ }
+ if (!this._devices[deviceType] || this._devices[deviceType][deviceSlot] === undefined) {
+ return null;
+ }
+ return this._devices[deviceType][deviceSlot];
+ }
+ /**
+ * Gets an array of DeviceSource objects for a given device type
+ * @param deviceType - Type of Device
+ * @returns All available DeviceSources of a given type
+ */
+ getDeviceSources(deviceType) {
+ // If device type hasn't had any devices connected yet, return empty array.
+ if (!this._devices[deviceType]) {
+ return [];
+ }
+ return this._devices[deviceType].filter((source) => {
+ return !!source;
+ });
+ }
+ /**
+ * Default constructor
+ * @param engine - Used to get canvas (if applicable)
+ */
+ constructor(engine) {
+ const numberOfDeviceTypes = Object.keys(DeviceType).length / 2;
+ this._devices = new Array(numberOfDeviceTypes);
+ this._firstDevice = new Array(numberOfDeviceTypes);
+ this._engine = engine;
+ if (!this._engine._deviceSourceManager) {
+ this._engine._deviceSourceManager = new InternalDeviceSourceManager(engine);
+ }
+ this._engine._deviceSourceManager._refCount++;
+ // Observables
+ this.onDeviceConnectedObservable = new Observable((observer) => {
+ for (const devices of this._devices) {
+ if (devices) {
+ for (const device of devices) {
+ if (device) {
+ this.onDeviceConnectedObservable.notifyObserver(observer, device);
+ }
+ }
+ }
+ }
+ });
+ this.onDeviceDisconnectedObservable = new Observable();
+ this._engine._deviceSourceManager.registerManager(this);
+ this._onDisposeObserver = engine.onDisposeObservable.add(() => {
+ this.dispose();
+ });
+ }
+ /**
+ * Dispose of DeviceSourceManager
+ */
+ dispose() {
+ // Null out observable refs
+ this.onDeviceConnectedObservable.clear();
+ this.onDeviceDisconnectedObservable.clear();
+ if (this._engine._deviceSourceManager) {
+ this._engine._deviceSourceManager.unregisterManager(this);
+ if (--this._engine._deviceSourceManager._refCount < 1) {
+ this._engine._deviceSourceManager.dispose();
+ delete this._engine._deviceSourceManager;
+ }
+ }
+ this._engine.onDisposeObservable.remove(this._onDisposeObserver);
+ }
+ // Hidden Functions
+ /**
+ * @param deviceSource - Source to add
+ * @internal
+ */
+ _addDevice(deviceSource) {
+ if (!this._devices[deviceSource.deviceType]) {
+ this._devices[deviceSource.deviceType] = new Array();
+ }
+ if (!this._devices[deviceSource.deviceType][deviceSource.deviceSlot]) {
+ this._devices[deviceSource.deviceType][deviceSource.deviceSlot] = deviceSource;
+ this._updateFirstDevices(deviceSource.deviceType);
+ }
+ this.onDeviceConnectedObservable.notifyObservers(deviceSource);
+ }
+ /**
+ * @param deviceType - DeviceType
+ * @param deviceSlot - DeviceSlot
+ * @internal
+ */
+ _removeDevice(deviceType, deviceSlot) {
+ const deviceSource = this._devices[deviceType]?.[deviceSlot]; // Grab local reference to use before removing from devices
+ this.onDeviceDisconnectedObservable.notifyObservers(deviceSource);
+ if (this._devices[deviceType]?.[deviceSlot]) {
+ delete this._devices[deviceType][deviceSlot];
+ }
+ // Even if we don't delete a device, we should still check for the first device as things may have gotten out of sync.
+ this._updateFirstDevices(deviceType);
+ }
+ /**
+ * @param deviceType - DeviceType
+ * @param deviceSlot - DeviceSlot
+ * @param eventData - Event
+ * @internal
+ */
+ _onInputChanged(deviceType, deviceSlot, eventData) {
+ this._devices[deviceType]?.[deviceSlot]?.onInputChangedObservable.notifyObservers(eventData);
+ }
+ // Private Functions
+ _updateFirstDevices(type) {
+ switch (type) {
+ case DeviceType.Keyboard:
+ case DeviceType.Mouse:
+ this._firstDevice[type] = 0;
+ break;
+ case DeviceType.Touch:
+ case DeviceType.DualSense:
+ case DeviceType.DualShock:
+ case DeviceType.Xbox:
+ case DeviceType.Switch:
+ case DeviceType.Generic: {
+ delete this._firstDevice[type];
+ // eslint-disable-next-line no-case-declarations
+ const devices = this._devices[type];
+ if (devices) {
+ for (let i = 0; i < devices.length; i++) {
+ if (devices[i]) {
+ this._firstDevice[type] = i;
+ break;
+ }
+ }
+ }
+ break;
+ }
+ }
+ }
+}
+
+/** @internal */
+class _ImportHelper {
+}
+/** @internal */
+_ImportHelper._IsPickingAvailable = false;
+
+/** @internal */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+class _ClickInfo {
+ constructor() {
+ this._singleClick = false;
+ this._doubleClick = false;
+ this._hasSwiped = false;
+ this._ignore = false;
+ }
+ get singleClick() {
+ return this._singleClick;
+ }
+ get doubleClick() {
+ return this._doubleClick;
+ }
+ get hasSwiped() {
+ return this._hasSwiped;
+ }
+ get ignore() {
+ return this._ignore;
+ }
+ set singleClick(b) {
+ this._singleClick = b;
+ }
+ set doubleClick(b) {
+ this._doubleClick = b;
+ }
+ set hasSwiped(b) {
+ this._hasSwiped = b;
+ }
+ set ignore(b) {
+ this._ignore = b;
+ }
+}
+/**
+ * Class used to manage all inputs for the scene.
+ */
+class InputManager {
+ /**
+ * Creates a new InputManager
+ * @param scene - defines the hosting scene
+ */
+ constructor(scene) {
+ /** This is a defensive check to not allow control attachment prior to an already active one. If already attached, previous control is unattached before attaching the new one. */
+ this._alreadyAttached = false;
+ this._meshPickProceed = false;
+ this._currentPickResult = null;
+ this._previousPickResult = null;
+ this._activePointerIds = new Array();
+ /** Tracks the count of used slots in _activePointerIds for perf */
+ this._activePointerIdsCount = 0;
+ this._doubleClickOccured = false;
+ this._isSwiping = false;
+ this._swipeButtonPressed = -1;
+ this._skipPointerTap = false;
+ this._isMultiTouchGesture = false;
+ this._pointerX = 0;
+ this._pointerY = 0;
+ this._startingPointerPosition = new Vector2(0, 0);
+ this._previousStartingPointerPosition = new Vector2(0, 0);
+ this._startingPointerTime = 0;
+ this._previousStartingPointerTime = 0;
+ this._pointerCaptures = {};
+ this._meshUnderPointerId = {};
+ this._movePointerInfo = null;
+ this._cameraObserverCount = 0;
+ this._delayedClicks = [null, null, null, null, null];
+ this._deviceSourceManager = null;
+ this._scene = scene || EngineStore.LastCreatedScene;
+ if (!this._scene) {
+ return;
+ }
+ }
+ /**
+ * Gets the mesh that is currently under the pointer
+ * @returns Mesh that the pointer is pointer is hovering over
+ */
+ get meshUnderPointer() {
+ if (this._movePointerInfo) {
+ // Because _pointerOverMesh is populated as part of _pickMove, we need to force a pick to update it.
+ // Calling _pickMove calls _setCursorAndPointerOverMesh which calls setPointerOverMesh
+ this._movePointerInfo._generatePickInfo();
+ // Once we have what we need, we can clear _movePointerInfo because we don't need it anymore
+ this._movePointerInfo = null;
+ }
+ return this._pointerOverMesh;
+ }
+ /**
+ * When using more than one pointer (for example in XR) you can get the mesh under the specific pointer
+ * @param pointerId - the pointer id to use
+ * @returns The mesh under this pointer id or null if not found
+ */
+ getMeshUnderPointerByPointerId(pointerId) {
+ return this._meshUnderPointerId[pointerId] || null;
+ }
+ /**
+ * Gets the pointer coordinates in 2D without any translation (ie. straight out of the pointer event)
+ * @returns Vector with X/Y values directly from pointer event
+ */
+ get unTranslatedPointer() {
+ return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
+ }
+ /**
+ * Gets or sets the current on-screen X position of the pointer
+ * @returns Translated X with respect to screen
+ */
+ get pointerX() {
+ return this._pointerX;
+ }
+ set pointerX(value) {
+ this._pointerX = value;
+ }
+ /**
+ * Gets or sets the current on-screen Y position of the pointer
+ * @returns Translated Y with respect to screen
+ */
+ get pointerY() {
+ return this._pointerY;
+ }
+ set pointerY(value) {
+ this._pointerY = value;
+ }
+ _updatePointerPosition(evt) {
+ const canvasRect = this._scene.getEngine().getInputElementClientRect();
+ if (!canvasRect) {
+ return;
+ }
+ this._pointerX = evt.clientX - canvasRect.left;
+ this._pointerY = evt.clientY - canvasRect.top;
+ this._unTranslatedPointerX = this._pointerX;
+ this._unTranslatedPointerY = this._pointerY;
+ }
+ _processPointerMove(pickResult, evt) {
+ const scene = this._scene;
+ const engine = scene.getEngine();
+ const canvas = engine.getInputElement();
+ if (canvas) {
+ canvas.tabIndex = engine.canvasTabIndex;
+ // Restore pointer
+ if (!scene.doNotHandleCursors) {
+ canvas.style.cursor = scene.defaultCursor;
+ }
+ }
+ this._setCursorAndPointerOverMesh(pickResult, evt, scene);
+ for (const step of scene._pointerMoveStage) {
+ // If _pointerMoveState is defined, we have an active spriteManager and can't use Lazy Picking
+ // Therefore, we need to force a pick to update the pickResult
+ pickResult = pickResult || this._pickMove(evt);
+ const isMeshPicked = pickResult?.pickedMesh ? true : false;
+ pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
+ }
+ const type = evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
+ if (scene.onPointerMove) {
+ // Because of lazy picking, we need to force a pick to update the pickResult
+ pickResult = pickResult || this._pickMove(evt);
+ scene.onPointerMove(evt, pickResult, type);
+ }
+ let pointerInfo;
+ if (pickResult) {
+ pointerInfo = new PointerInfo(type, evt, pickResult);
+ this._setRayOnPointerInfo(pickResult, evt);
+ }
+ else {
+ pointerInfo = new PointerInfo(type, evt, null, this);
+ this._movePointerInfo = pointerInfo;
+ }
+ if (scene.onPointerObservable.hasObservers()) {
+ scene.onPointerObservable.notifyObservers(pointerInfo, type);
+ }
+ }
+ // Pointers handling
+ /** @internal */
+ _setRayOnPointerInfo(pickInfo, event) {
+ const scene = this._scene;
+ if (pickInfo && _ImportHelper._IsPickingAvailable) {
+ if (!pickInfo.ray) {
+ pickInfo.ray = scene.createPickingRay(event.offsetX, event.offsetY, Matrix.Identity(), scene.activeCamera);
+ }
+ }
+ }
+ /** @internal */
+ _addCameraPointerObserver(observer, mask) {
+ this._cameraObserverCount++;
+ return this._scene.onPointerObservable.add(observer, mask);
+ }
+ /** @internal */
+ _removeCameraPointerObserver(observer) {
+ this._cameraObserverCount--;
+ return this._scene.onPointerObservable.remove(observer);
+ }
+ _checkForPicking() {
+ return !!(this._scene.onPointerObservable.observers.length > this._cameraObserverCount || this._scene.onPointerPick);
+ }
+ _checkPrePointerObservable(pickResult, evt, type) {
+ const scene = this._scene;
+ const pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
+ if (pickResult) {
+ pi.originalPickingInfo = pickResult;
+ pi.ray = pickResult.ray;
+ if (evt.pointerType === "xr-near" && pickResult.originMesh) {
+ pi.nearInteractionPickingInfo = pickResult;
+ }
+ }
+ scene.onPrePointerObservable.notifyObservers(pi, type);
+ if (pi.skipOnPointerObservable) {
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+ /** @internal */
+ _pickMove(evt) {
+ const scene = this._scene;
+ const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerMovePredicate, scene.pointerMoveFastCheck, scene.cameraToUseForPointers, scene.pointerMoveTrianglePredicate);
+ this._setCursorAndPointerOverMesh(pickResult, evt, scene);
+ return pickResult;
+ }
+ _setCursorAndPointerOverMesh(pickResult, evt, scene) {
+ const engine = scene.getEngine();
+ const canvas = engine.getInputElement();
+ if (pickResult?.pickedMesh) {
+ this.setPointerOverMesh(pickResult.pickedMesh, evt.pointerId, pickResult, evt);
+ if (!scene.doNotHandleCursors && canvas && this._pointerOverMesh) {
+ const actionManager = this._pointerOverMesh._getActionManagerForTrigger();
+ if (actionManager && actionManager.hasPointerTriggers) {
+ canvas.style.cursor = actionManager.hoverCursor || scene.hoverCursor;
+ }
+ }
+ }
+ else {
+ this.setPointerOverMesh(null, evt.pointerId, pickResult, evt);
+ }
+ }
+ /**
+ * Use this method to simulate a pointer move on a mesh
+ * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
+ * @param pickResult - pickingInfo of the object wished to simulate pointer event on
+ * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
+ */
+ simulatePointerMove(pickResult, pointerEventInit) {
+ const evt = new PointerEvent("pointermove", pointerEventInit);
+ evt.inputIndex = PointerInput.Move;
+ if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERMOVE)) {
+ return;
+ }
+ this._processPointerMove(pickResult, evt);
+ }
+ /**
+ * Use this method to simulate a pointer down on a mesh
+ * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
+ * @param pickResult - pickingInfo of the object wished to simulate pointer event on
+ * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
+ */
+ simulatePointerDown(pickResult, pointerEventInit) {
+ const evt = new PointerEvent("pointerdown", pointerEventInit);
+ evt.inputIndex = evt.button + 2;
+ if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)) {
+ return;
+ }
+ this._processPointerDown(pickResult, evt);
+ }
+ _processPointerDown(pickResult, evt) {
+ const scene = this._scene;
+ if (pickResult?.pickedMesh) {
+ this._pickedDownMesh = pickResult.pickedMesh;
+ const actionManager = pickResult.pickedMesh._getActionManagerForTrigger();
+ if (actionManager) {
+ if (actionManager.hasPickTriggers) {
+ actionManager.processTrigger(5, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult));
+ switch (evt.button) {
+ case 0:
+ actionManager.processTrigger(2, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult));
+ break;
+ case 1:
+ actionManager.processTrigger(4, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult));
+ break;
+ case 2:
+ actionManager.processTrigger(3, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult));
+ break;
+ }
+ }
+ if (actionManager.hasSpecificTrigger(8)) {
+ window.setTimeout(() => {
+ const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, (mesh) => ((mesh.isPickable &&
+ mesh.isVisible &&
+ mesh.isReady() &&
+ mesh.actionManager &&
+ mesh.actionManager.hasSpecificTrigger(8) &&
+ mesh === this._pickedDownMesh)), false, scene.cameraToUseForPointers);
+ if (pickResult?.pickedMesh && actionManager) {
+ if (this._activePointerIdsCount !== 0 && Date.now() - this._startingPointerTime > InputManager.LongPressDelay && !this._isPointerSwiping()) {
+ this._startingPointerTime = 0;
+ actionManager.processTrigger(8, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
+ }
+ }
+ }, InputManager.LongPressDelay);
+ }
+ }
+ }
+ else {
+ for (const step of scene._pointerDownStage) {
+ pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, false);
+ }
+ }
+ let pointerInfo;
+ const type = PointerEventTypes.POINTERDOWN;
+ if (pickResult) {
+ if (scene.onPointerDown) {
+ scene.onPointerDown(evt, pickResult, type);
+ }
+ pointerInfo = new PointerInfo(type, evt, pickResult);
+ this._setRayOnPointerInfo(pickResult, evt);
+ }
+ else {
+ pointerInfo = new PointerInfo(type, evt, null, this);
+ }
+ if (scene.onPointerObservable.hasObservers()) {
+ scene.onPointerObservable.notifyObservers(pointerInfo, type);
+ }
+ }
+ /**
+ * @internal
+ * @internals Boolean if delta for pointer exceeds drag movement threshold
+ */
+ _isPointerSwiping() {
+ return this._isSwiping;
+ }
+ /**
+ * Use this method to simulate a pointer up on a mesh
+ * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
+ * @param pickResult - pickingInfo of the object wished to simulate pointer event on
+ * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
+ * @param doubleTap - indicates that the pointer up event should be considered as part of a double click (false by default)
+ */
+ simulatePointerUp(pickResult, pointerEventInit, doubleTap) {
+ const evt = new PointerEvent("pointerup", pointerEventInit);
+ evt.inputIndex = PointerInput.Move;
+ const clickInfo = new _ClickInfo();
+ if (doubleTap) {
+ clickInfo.doubleClick = true;
+ }
+ else {
+ clickInfo.singleClick = true;
+ }
+ if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)) {
+ return;
+ }
+ this._processPointerUp(pickResult, evt, clickInfo);
+ }
+ _processPointerUp(pickResult, evt, clickInfo) {
+ const scene = this._scene;
+ if (pickResult?.pickedMesh) {
+ this._pickedUpMesh = pickResult.pickedMesh;
+ if (this._pickedDownMesh === this._pickedUpMesh) {
+ if (scene.onPointerPick) {
+ scene.onPointerPick(evt, pickResult);
+ }
+ if (clickInfo.singleClick && !clickInfo.ignore && scene.onPointerObservable.observers.length > this._cameraObserverCount) {
+ const type = PointerEventTypes.POINTERPICK;
+ const pi = new PointerInfo(type, evt, pickResult);
+ this._setRayOnPointerInfo(pickResult, evt);
+ scene.onPointerObservable.notifyObservers(pi, type);
+ }
+ }
+ const actionManager = pickResult.pickedMesh._getActionManagerForTrigger();
+ if (actionManager && !clickInfo.ignore) {
+ actionManager.processTrigger(7, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));
+ if (!clickInfo.hasSwiped && clickInfo.singleClick) {
+ actionManager.processTrigger(1, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));
+ }
+ const doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(6);
+ if (clickInfo.doubleClick && doubleClickActionManager) {
+ doubleClickActionManager.processTrigger(6, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));
+ }
+ }
+ }
+ else {
+ if (!clickInfo.ignore) {
+ for (const step of scene._pointerUpStage) {
+ pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, clickInfo.doubleClick);
+ }
+ }
+ }
+ if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) {
+ const pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(16);
+ if (pickedDownActionManager) {
+ pickedDownActionManager.processTrigger(16, ActionEvent.CreateNew(this._pickedDownMesh, evt));
+ }
+ }
+ if (!clickInfo.ignore) {
+ const pi = new PointerInfo(PointerEventTypes.POINTERUP, evt, pickResult);
+ // Set ray on picking info. Note that this info will also be reused for the tap notification.
+ this._setRayOnPointerInfo(pickResult, evt);
+ scene.onPointerObservable.notifyObservers(pi, PointerEventTypes.POINTERUP);
+ if (scene.onPointerUp) {
+ scene.onPointerUp(evt, pickResult, PointerEventTypes.POINTERUP);
+ }
+ if (!clickInfo.hasSwiped && !this._skipPointerTap && !this._isMultiTouchGesture) {
+ let type = 0;
+ if (clickInfo.singleClick) {
+ type = PointerEventTypes.POINTERTAP;
+ }
+ else if (clickInfo.doubleClick) {
+ type = PointerEventTypes.POINTERDOUBLETAP;
+ }
+ if (type) {
+ const pi = new PointerInfo(type, evt, pickResult);
+ if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {
+ scene.onPointerObservable.notifyObservers(pi, type);
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
+ * @param pointerId - defines the pointer id to use in a multi-touch scenario (0 by default)
+ * @returns true if the pointer was captured
+ */
+ isPointerCaptured(pointerId = 0) {
+ return this._pointerCaptures[pointerId];
+ }
+ /**
+ * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
+ * @param attachUp - defines if you want to attach events to pointerup
+ * @param attachDown - defines if you want to attach events to pointerdown
+ * @param attachMove - defines if you want to attach events to pointermove
+ * @param elementToAttachTo - defines the target DOM element to attach to (will use the canvas by default)
+ */
+ attachControl(attachUp = true, attachDown = true, attachMove = true, elementToAttachTo = null) {
+ const scene = this._scene;
+ const engine = scene.getEngine();
+ if (!elementToAttachTo) {
+ elementToAttachTo = engine.getInputElement();
+ }
+ if (this._alreadyAttached) {
+ this.detachControl();
+ }
+ if (elementToAttachTo) {
+ this._alreadyAttachedTo = elementToAttachTo;
+ }
+ this._deviceSourceManager = new DeviceSourceManager(engine);
+ // Because this is only called from _initClickEvent, which is called in _onPointerUp, we'll use the pointerUpPredicate for the pick call
+ this._initActionManager = (act) => {
+ if (!this._meshPickProceed) {
+ const pickResult = scene.skipPointerUpPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerUp)
+ ? null
+ : scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerUpPredicate, scene.pointerUpFastCheck, scene.cameraToUseForPointers, scene.pointerUpTrianglePredicate);
+ this._currentPickResult = pickResult;
+ if (pickResult) {
+ act = pickResult.hit && pickResult.pickedMesh ? pickResult.pickedMesh._getActionManagerForTrigger() : null;
+ }
+ this._meshPickProceed = true;
+ }
+ return act;
+ };
+ this._delayedSimpleClick = (btn, clickInfo, cb) => {
+ // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
+ if ((Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay && !this._doubleClickOccured) || btn !== this._previousButtonPressed) {
+ this._doubleClickOccured = false;
+ clickInfo.singleClick = true;
+ clickInfo.ignore = false;
+ // If we have a delayed click, we need to resolve the TAP event
+ if (this._delayedClicks[btn]) {
+ const evt = this._delayedClicks[btn].evt;
+ const type = PointerEventTypes.POINTERTAP;
+ const pi = new PointerInfo(type, evt, this._currentPickResult);
+ if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {
+ scene.onPointerObservable.notifyObservers(pi, type);
+ }
+ // Clear the delayed click
+ this._delayedClicks[btn] = null;
+ }
+ }
+ };
+ this._initClickEvent = (obs1, obs2, evt, cb) => {
+ const clickInfo = new _ClickInfo();
+ this._currentPickResult = null;
+ let act = null;
+ let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) ||
+ obs2.hasSpecificMask(PointerEventTypes.POINTERPICK) ||
+ obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) ||
+ obs2.hasSpecificMask(PointerEventTypes.POINTERTAP) ||
+ obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
+ obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
+ if (!checkPicking && AbstractActionManager) {
+ act = this._initActionManager(act, clickInfo);
+ if (act) {
+ checkPicking = act.hasPickTriggers;
+ }
+ }
+ let needToIgnoreNext = false;
+ // Never pick if this is a multi-touch gesture (e.g. pinch)
+ checkPicking = checkPicking && !this._isMultiTouchGesture;
+ if (checkPicking) {
+ const btn = evt.button;
+ clickInfo.hasSwiped = this._isPointerSwiping();
+ if (!clickInfo.hasSwiped) {
+ let checkSingleClickImmediately = !InputManager.ExclusiveDoubleClickMode;
+ if (!checkSingleClickImmediately) {
+ checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
+ if (checkSingleClickImmediately && !AbstractActionManager.HasSpecificTrigger(6)) {
+ act = this._initActionManager(act, clickInfo);
+ if (act) {
+ checkSingleClickImmediately = !act.hasSpecificTrigger(6);
+ }
+ }
+ }
+ if (checkSingleClickImmediately) {
+ // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
+ if (Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay || btn !== this._previousButtonPressed) {
+ clickInfo.singleClick = true;
+ cb(clickInfo, this._currentPickResult);
+ needToIgnoreNext = true;
+ }
+ }
+ // at least one double click is required to be check and exclusive double click is enabled
+ else {
+ // Queue up a delayed click, just in case this isn't a double click
+ // It should be noted that while this delayed event happens
+ // because of user input, it shouldn't be considered as a direct,
+ // timing-dependent result of that input. It's meant to just fire the TAP event
+ const delayedClick = {
+ evt: evt,
+ clickInfo: clickInfo,
+ timeoutId: window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), InputManager.DoubleClickDelay),
+ };
+ this._delayedClicks[btn] = delayedClick;
+ }
+ let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
+ if (!checkDoubleClick && AbstractActionManager.HasSpecificTrigger(6)) {
+ act = this._initActionManager(act, clickInfo);
+ if (act) {
+ checkDoubleClick = act.hasSpecificTrigger(6);
+ }
+ }
+ if (checkDoubleClick) {
+ // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
+ if (btn === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < InputManager.DoubleClickDelay && !this._doubleClickOccured) {
+ // pointer has not moved for 2 clicks, it's a double click
+ if (!clickInfo.hasSwiped && !this._isPointerSwiping()) {
+ this._previousStartingPointerTime = 0;
+ this._doubleClickOccured = true;
+ clickInfo.doubleClick = true;
+ clickInfo.ignore = false;
+ // If we have a pending click, we need to cancel it
+ if (InputManager.ExclusiveDoubleClickMode && this._delayedClicks[btn]) {
+ clearTimeout(this._delayedClicks[btn]?.timeoutId);
+ this._delayedClicks[btn] = null;
+ }
+ cb(clickInfo, this._currentPickResult);
+ }
+ // if the two successive clicks are too far, it's just two simple clicks
+ else {
+ this._doubleClickOccured = false;
+ this._previousStartingPointerTime = this._startingPointerTime;
+ this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
+ this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
+ this._previousButtonPressed = btn;
+ if (InputManager.ExclusiveDoubleClickMode) {
+ // If we have a delayed click, we need to cancel it
+ if (this._delayedClicks[btn]) {
+ clearTimeout(this._delayedClicks[btn]?.timeoutId);
+ this._delayedClicks[btn] = null;
+ }
+ cb(clickInfo, this._previousPickResult);
+ }
+ else {
+ cb(clickInfo, this._currentPickResult);
+ }
+ }
+ needToIgnoreNext = true;
+ }
+ // just the first click of the double has been raised
+ else {
+ this._doubleClickOccured = false;
+ this._previousStartingPointerTime = this._startingPointerTime;
+ this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
+ this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
+ this._previousButtonPressed = btn;
+ }
+ }
+ }
+ }
+ // Even if ExclusiveDoubleClickMode is true, we need to always handle
+ // up events at time of execution, unless we're explicitly ignoring them.
+ if (!needToIgnoreNext) {
+ cb(clickInfo, this._currentPickResult);
+ }
+ };
+ this._onPointerMove = (evt) => {
+ this._updatePointerPosition(evt);
+ // Check if pointer leaves DragMovementThreshold range to determine if swipe is occurring
+ if (!this._isSwiping && this._swipeButtonPressed !== -1) {
+ this._isSwiping =
+ Math.abs(this._startingPointerPosition.x - this._pointerX) > InputManager.DragMovementThreshold ||
+ Math.abs(this._startingPointerPosition.y - this._pointerY) > InputManager.DragMovementThreshold;
+ }
+ // Because there's a race condition between pointermove and pointerlockchange events, we need to
+ // verify that the pointer is still locked after each pointermove event.
+ if (engine.isPointerLock) {
+ engine._verifyPointerLock();
+ }
+ // PreObservable support
+ if (this._checkPrePointerObservable(null, evt, evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)) {
+ return;
+ }
+ if (!scene.cameraToUseForPointers && !scene.activeCamera) {
+ return;
+ }
+ if (scene.skipPointerMovePicking) {
+ this._processPointerMove(new PickingInfo(), evt);
+ return;
+ }
+ if (!scene.pointerMovePredicate) {
+ scene.pointerMovePredicate = (mesh) => mesh.isPickable &&
+ mesh.isVisible &&
+ mesh.isReady() &&
+ mesh.isEnabled() &&
+ (mesh.enablePointerMoveEvents || scene.constantlyUpdateMeshUnderPointer || mesh._getActionManagerForTrigger() !== null) &&
+ (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0);
+ }
+ const pickResult = scene._registeredActions > 0 || scene.constantlyUpdateMeshUnderPointer ? this._pickMove(evt) : null;
+ this._processPointerMove(pickResult, evt);
+ };
+ this._onPointerDown = (evt) => {
+ const freeIndex = this._activePointerIds.indexOf(-1);
+ if (freeIndex === -1) {
+ this._activePointerIds.push(evt.pointerId);
+ }
+ else {
+ this._activePointerIds[freeIndex] = evt.pointerId;
+ }
+ this._activePointerIdsCount++;
+ this._pickedDownMesh = null;
+ this._meshPickProceed = false;
+ // If ExclusiveDoubleClickMode is true, we need to resolve any pending delayed clicks
+ if (InputManager.ExclusiveDoubleClickMode) {
+ for (let i = 0; i < this._delayedClicks.length; i++) {
+ if (this._delayedClicks[i]) {
+ // If the button that was pressed is the same as the one that was released,
+ // just clear the timer. This will be resolved in the up event.
+ if (evt.button === i) {
+ clearTimeout(this._delayedClicks[i]?.timeoutId);
+ }
+ else {
+ // Otherwise, we need to resolve the click
+ const clickInfo = this._delayedClicks[i].clickInfo;
+ this._doubleClickOccured = false;
+ clickInfo.singleClick = true;
+ clickInfo.ignore = false;
+ const prevEvt = this._delayedClicks[i].evt;
+ const type = PointerEventTypes.POINTERTAP;
+ const pi = new PointerInfo(type, prevEvt, this._currentPickResult);
+ if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {
+ scene.onPointerObservable.notifyObservers(pi, type);
+ }
+ // Clear the delayed click
+ this._delayedClicks[i] = null;
+ }
+ }
+ }
+ }
+ this._updatePointerPosition(evt);
+ if (this._swipeButtonPressed === -1) {
+ this._swipeButtonPressed = evt.button;
+ }
+ if (scene.preventDefaultOnPointerDown && elementToAttachTo) {
+ evt.preventDefault();
+ elementToAttachTo.focus();
+ }
+ this._startingPointerPosition.x = this._pointerX;
+ this._startingPointerPosition.y = this._pointerY;
+ this._startingPointerTime = Date.now();
+ // PreObservable support
+ if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)) {
+ return;
+ }
+ if (!scene.cameraToUseForPointers && !scene.activeCamera) {
+ return;
+ }
+ this._pointerCaptures[evt.pointerId] = true;
+ if (!scene.pointerDownPredicate) {
+ scene.pointerDownPredicate = (mesh) => {
+ return (mesh.isPickable &&
+ mesh.isVisible &&
+ mesh.isReady() &&
+ mesh.isEnabled() &&
+ (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0));
+ };
+ }
+ // Meshes
+ this._pickedDownMesh = null;
+ let pickResult;
+ if (scene.skipPointerDownPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerDown)) {
+ pickResult = new PickingInfo();
+ }
+ else {
+ pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerDownPredicate, scene.pointerDownFastCheck, scene.cameraToUseForPointers, scene.pointerDownTrianglePredicate);
+ }
+ this._processPointerDown(pickResult, evt);
+ };
+ this._onPointerUp = (evt) => {
+ const pointerIdIndex = this._activePointerIds.indexOf(evt.pointerId);
+ if (pointerIdIndex === -1) {
+ // We are attaching the pointer up to windows because of a bug in FF
+ // If this pointerId is not paired with an _onPointerDown call, ignore it
+ return;
+ }
+ this._activePointerIds[pointerIdIndex] = -1;
+ this._activePointerIdsCount--;
+ this._pickedUpMesh = null;
+ this._meshPickProceed = false;
+ this._updatePointerPosition(evt);
+ if (scene.preventDefaultOnPointerUp && elementToAttachTo) {
+ evt.preventDefault();
+ elementToAttachTo.focus();
+ }
+ this._initClickEvent(scene.onPrePointerObservable, scene.onPointerObservable, evt, (clickInfo, pickResult) => {
+ // PreObservable support
+ if (scene.onPrePointerObservable.hasObservers()) {
+ this._skipPointerTap = false;
+ if (!clickInfo.ignore) {
+ if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) {
+ // If we're skipping the next observable, we need to reset the swipe state before returning
+ if (this._swipeButtonPressed === evt.button) {
+ this._isSwiping = false;
+ this._swipeButtonPressed = -1;
+ }
+ // If we're going to skip the POINTERUP, we need to reset the pointer capture
+ if (evt.buttons === 0) {
+ this._pointerCaptures[evt.pointerId] = false;
+ }
+ return;
+ }
+ if (!clickInfo.hasSwiped) {
+ if (clickInfo.singleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
+ if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)) {
+ this._skipPointerTap = true;
+ }
+ }
+ if (clickInfo.doubleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
+ if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)) {
+ this._skipPointerTap = true;
+ }
+ }
+ }
+ }
+ }
+ // There should be a pointer captured at this point so if there isn't we should reset and return
+ if (!this._pointerCaptures[evt.pointerId]) {
+ if (this._swipeButtonPressed === evt.button) {
+ this._isSwiping = false;
+ this._swipeButtonPressed = -1;
+ }
+ return;
+ }
+ // Only release capture if all buttons are released
+ if (evt.buttons === 0) {
+ this._pointerCaptures[evt.pointerId] = false;
+ }
+ if (!scene.cameraToUseForPointers && !scene.activeCamera) {
+ return;
+ }
+ if (!scene.pointerUpPredicate) {
+ scene.pointerUpPredicate = (mesh) => {
+ return (mesh.isPickable &&
+ mesh.isVisible &&
+ mesh.isReady() &&
+ mesh.isEnabled() &&
+ (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0));
+ };
+ }
+ // Meshes
+ if (!this._meshPickProceed && ((AbstractActionManager && AbstractActionManager.HasTriggers) || this._checkForPicking() || scene.onPointerUp)) {
+ this._initActionManager(null, clickInfo);
+ }
+ if (!pickResult) {
+ pickResult = this._currentPickResult;
+ }
+ this._processPointerUp(pickResult, evt, clickInfo);
+ this._previousPickResult = this._currentPickResult;
+ if (this._swipeButtonPressed === evt.button) {
+ this._isSwiping = false;
+ this._swipeButtonPressed = -1;
+ }
+ });
+ };
+ this._onKeyDown = (evt) => {
+ const type = KeyboardEventTypes.KEYDOWN;
+ if (scene.onPreKeyboardObservable.hasObservers()) {
+ const pi = new KeyboardInfoPre(type, evt);
+ scene.onPreKeyboardObservable.notifyObservers(pi, type);
+ if (pi.skipOnKeyboardObservable) {
+ return;
+ }
+ }
+ if (scene.onKeyboardObservable.hasObservers()) {
+ const pi = new KeyboardInfo(type, evt);
+ scene.onKeyboardObservable.notifyObservers(pi, type);
+ }
+ if (scene.actionManager) {
+ scene.actionManager.processTrigger(14, ActionEvent.CreateNewFromScene(scene, evt));
+ }
+ };
+ this._onKeyUp = (evt) => {
+ const type = KeyboardEventTypes.KEYUP;
+ if (scene.onPreKeyboardObservable.hasObservers()) {
+ const pi = new KeyboardInfoPre(type, evt);
+ scene.onPreKeyboardObservable.notifyObservers(pi, type);
+ if (pi.skipOnKeyboardObservable) {
+ return;
+ }
+ }
+ if (scene.onKeyboardObservable.hasObservers()) {
+ const pi = new KeyboardInfo(type, evt);
+ scene.onKeyboardObservable.notifyObservers(pi, type);
+ }
+ if (scene.actionManager) {
+ scene.actionManager.processTrigger(15, ActionEvent.CreateNewFromScene(scene, evt));
+ }
+ };
+ // If a device connects that we can handle, wire up the observable
+ this._deviceSourceManager.onDeviceConnectedObservable.add((deviceSource) => {
+ if (deviceSource.deviceType === DeviceType.Mouse) {
+ deviceSource.onInputChangedObservable.add((eventData) => {
+ this._originMouseEvent = eventData;
+ if (eventData.inputIndex === PointerInput.LeftClick ||
+ eventData.inputIndex === PointerInput.MiddleClick ||
+ eventData.inputIndex === PointerInput.RightClick ||
+ eventData.inputIndex === PointerInput.BrowserBack ||
+ eventData.inputIndex === PointerInput.BrowserForward) {
+ if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) {
+ this._onPointerDown(eventData);
+ }
+ else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) {
+ this._onPointerUp(eventData);
+ }
+ }
+ else if (attachMove) {
+ if (eventData.inputIndex === PointerInput.Move) {
+ this._onPointerMove(eventData);
+ }
+ else if (eventData.inputIndex === PointerInput.MouseWheelX ||
+ eventData.inputIndex === PointerInput.MouseWheelY ||
+ eventData.inputIndex === PointerInput.MouseWheelZ) {
+ this._onPointerMove(eventData);
+ }
+ }
+ });
+ }
+ else if (deviceSource.deviceType === DeviceType.Touch) {
+ deviceSource.onInputChangedObservable.add((eventData) => {
+ if (eventData.inputIndex === PointerInput.LeftClick) {
+ if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) {
+ this._onPointerDown(eventData);
+ if (this._activePointerIdsCount > 1) {
+ this._isMultiTouchGesture = true;
+ }
+ }
+ else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) {
+ this._onPointerUp(eventData);
+ if (this._activePointerIdsCount === 0) {
+ this._isMultiTouchGesture = false;
+ }
+ }
+ }
+ if (attachMove && eventData.inputIndex === PointerInput.Move) {
+ this._onPointerMove(eventData);
+ }
+ });
+ }
+ else if (deviceSource.deviceType === DeviceType.Keyboard) {
+ deviceSource.onInputChangedObservable.add((eventData) => {
+ if (eventData.type === "keydown") {
+ this._onKeyDown(eventData);
+ }
+ else if (eventData.type === "keyup") {
+ this._onKeyUp(eventData);
+ }
+ });
+ }
+ });
+ this._alreadyAttached = true;
+ }
+ /**
+ * Detaches all event handlers
+ */
+ detachControl() {
+ if (this._alreadyAttached) {
+ this._deviceSourceManager.dispose();
+ this._deviceSourceManager = null;
+ // Cursor
+ if (this._alreadyAttachedTo && !this._scene.doNotHandleCursors) {
+ this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor;
+ }
+ this._alreadyAttached = false;
+ this._alreadyAttachedTo = null;
+ }
+ }
+ /**
+ * Set the value of meshUnderPointer for a given pointerId
+ * @param mesh - defines the mesh to use
+ * @param pointerId - optional pointer id when using more than one pointer. Defaults to 0
+ * @param pickResult - optional pickingInfo data used to find mesh
+ * @param evt - optional pointer event
+ */
+ setPointerOverMesh(mesh, pointerId = 0, pickResult, evt) {
+ if (this._meshUnderPointerId[pointerId] === mesh && (!mesh || !mesh._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting)) {
+ return;
+ }
+ const underPointerMesh = this._meshUnderPointerId[pointerId];
+ let actionManager;
+ if (underPointerMesh) {
+ actionManager = underPointerMesh._getActionManagerForTrigger(10);
+ if (actionManager) {
+ actionManager.processTrigger(10, new ActionEvent(underPointerMesh, this._pointerX, this._pointerY, mesh, evt, { pointerId }));
+ }
+ }
+ if (mesh) {
+ this._meshUnderPointerId[pointerId] = mesh;
+ this._pointerOverMesh = mesh;
+ actionManager = mesh._getActionManagerForTrigger(9);
+ if (actionManager) {
+ actionManager.processTrigger(9, new ActionEvent(mesh, this._pointerX, this._pointerY, mesh, evt, { pointerId, pickResult }));
+ }
+ }
+ else {
+ delete this._meshUnderPointerId[pointerId];
+ this._pointerOverMesh = null;
+ }
+ // if we reached this point, meshUnderPointerId has been updated. We need to notify observers that are registered.
+ if (this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()) {
+ this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({
+ mesh,
+ pointerId,
+ });
+ }
+ }
+ /**
+ * Gets the mesh under the pointer
+ * @returns a Mesh or null if no mesh is under the pointer
+ */
+ getPointerOverMesh() {
+ return this.meshUnderPointer;
+ }
+ /**
+ * @param mesh - Mesh to invalidate
+ * @internal
+ */
+ _invalidateMesh(mesh) {
+ if (this._pointerOverMesh === mesh) {
+ this._pointerOverMesh = null;
+ }
+ if (this._pickedDownMesh === mesh) {
+ this._pickedDownMesh = null;
+ }
+ if (this._pickedUpMesh === mesh) {
+ this._pickedUpMesh = null;
+ }
+ for (const pointerId in this._meshUnderPointerId) {
+ if (this._meshUnderPointerId[pointerId] === mesh) {
+ delete this._meshUnderPointerId[pointerId];
+ }
+ }
+ }
+}
+/** The distance in pixel that you have to move to prevent some events */
+InputManager.DragMovementThreshold = 10; // in pixels
+/** Time in milliseconds to wait to raise long press events if button is still pressed */
+InputManager.LongPressDelay = 500; // in milliseconds
+/** Time in milliseconds with two consecutive clicks will be considered as a double click */
+InputManager.DoubleClickDelay = 300; // in milliseconds
+/**
+ * This flag will modify the behavior so that, when true, a click will happen if and only if
+ * another click DOES NOT happen within the DoubleClickDelay time frame. If another click does
+ * happen within that time frame, the first click will not fire an event and and a double click will occur.
+ */
+InputManager.ExclusiveDoubleClickMode = false;
+
+/**
+ * Helper class used to generate session unique ID
+ */
+class UniqueIdGenerator {
+ /**
+ * Gets an unique (relatively to the current scene) Id
+ */
+ static get UniqueId() {
+ const result = this._UniqueIdCounter;
+ this._UniqueIdCounter++;
+ return result;
+ }
+}
+// Statics
+UniqueIdGenerator._UniqueIdCounter = 1;
+
+/** Defines the cross module constantsused by lights to avoid circular dependencies */
+class LightConstants {
+ /**
+ * Sort function to order lights for rendering.
+ * @param a First Light object to compare to second.
+ * @param b Second Light object to compare first.
+ * @returns -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
+ */
+ static CompareLightsPriority(a, b) {
+ //shadow-casting lights have priority over non-shadow-casting lights
+ //the renderPriority is a secondary sort criterion
+ if (a.shadowEnabled !== b.shadowEnabled) {
+ return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
+ }
+ return b.renderPriority - a.renderPriority;
+ }
+}
+/**
+ * Falloff Default: light is falling off following the material specification:
+ * standard material is using standard falloff whereas pbr material can request special falloff per materials.
+ */
+LightConstants.FALLOFF_DEFAULT = 0;
+/**
+ * Falloff Physical: light is falling off following the inverse squared distance law.
+ */
+LightConstants.FALLOFF_PHYSICAL = 1;
+/**
+ * Falloff gltf: light is falling off as described in the gltf moving to PBR document
+ * to enhance interoperability with other engines.
+ */
+LightConstants.FALLOFF_GLTF = 2;
+/**
+ * Falloff Standard: light is falling off like in the standard material
+ * to enhance interoperability with other materials.
+ */
+LightConstants.FALLOFF_STANDARD = 3;
+//lightmapMode Consts
+/**
+ * If every light affecting the material is in this lightmapMode,
+ * material.lightmapTexture adds or multiplies
+ * (depends on material.useLightmapAsShadowmap)
+ * after every other light calculations.
+ */
+LightConstants.LIGHTMAP_DEFAULT = 0;
+/**
+ * material.lightmapTexture as only diffuse lighting from this light
+ * adds only specular lighting from this light
+ * adds dynamic shadows
+ */
+LightConstants.LIGHTMAP_SPECULAR = 1;
+/**
+ * material.lightmapTexture as only lighting
+ * no light calculation from this light
+ * only adds dynamic shadows from this light
+ */
+LightConstants.LIGHTMAP_SHADOWSONLY = 2;
+// Intensity Mode Consts
+/**
+ * Each light type uses the default quantity according to its type:
+ * point/spot lights use luminous intensity
+ * directional lights use illuminance
+ */
+LightConstants.INTENSITYMODE_AUTOMATIC = 0;
+/**
+ * lumen (lm)
+ */
+LightConstants.INTENSITYMODE_LUMINOUSPOWER = 1;
+/**
+ * candela (lm/sr)
+ */
+LightConstants.INTENSITYMODE_LUMINOUSINTENSITY = 2;
+/**
+ * lux (lm/m^2)
+ */
+LightConstants.INTENSITYMODE_ILLUMINANCE = 3;
+/**
+ * nit (cd/m^2)
+ */
+LightConstants.INTENSITYMODE_LUMINANCE = 4;
+// Light types ids const.
+/**
+ * Light type const id of the point light.
+ */
+LightConstants.LIGHTTYPEID_POINTLIGHT = 0;
+/**
+ * Light type const id of the directional light.
+ */
+LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
+/**
+ * Light type const id of the spot light.
+ */
+LightConstants.LIGHTTYPEID_SPOTLIGHT = 2;
+/**
+ * Light type const id of the hemispheric light.
+ */
+LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
+/**
+ * Light type const id of the area light.
+ */
+LightConstants.LIGHTTYPEID_RECT_AREALIGHT = 4;
+
+/**
+ * Class used to store configuration data associated with pointer picking
+ */
+class PointerPickingConfiguration {
+ constructor() {
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer down event
+ */
+ this.pointerDownFastCheck = false;
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer up event
+ */
+ this.pointerUpFastCheck = false;
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer move event
+ */
+ this.pointerMoveFastCheck = false;
+ /**
+ * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs.
+ */
+ this.skipPointerMovePicking = false;
+ /**
+ * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs.
+ */
+ this.skipPointerDownPicking = false;
+ /**
+ * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer up event occurs. Off by default.
+ */
+ this.skipPointerUpPicking = false;
+ }
+}
+
+/**
+ * Define how the scene should favor performance over ease of use
+ */
+var ScenePerformancePriority;
+(function (ScenePerformancePriority) {
+ /** Default mode. No change. Performance will be treated as less important than backward compatibility */
+ ScenePerformancePriority[ScenePerformancePriority["BackwardCompatible"] = 0] = "BackwardCompatible";
+ /** Some performance options will be turned on trying to strike a balance between perf and ease of use */
+ ScenePerformancePriority[ScenePerformancePriority["Intermediate"] = 1] = "Intermediate";
+ /** Performance will be top priority */
+ ScenePerformancePriority[ScenePerformancePriority["Aggressive"] = 2] = "Aggressive";
+})(ScenePerformancePriority || (ScenePerformancePriority = {}));
+/**
+ * Represents a scene to be rendered by the engine.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene
+ */
+class Scene {
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Factory used to create the default material.
+ * @param scene The scene to create the material for
+ * @returns The default material
+ */
+ static DefaultMaterialFactory(scene) {
+ throw _WarnImport("StandardMaterial");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Factory used to create the a collision coordinator.
+ * @returns The collision coordinator
+ */
+ static CollisionCoordinatorFactory() {
+ throw _WarnImport("DefaultCollisionCoordinator");
+ }
+ /**
+ * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
+ */
+ get clearColor() {
+ return this._clearColor;
+ }
+ set clearColor(value) {
+ if (value !== this._clearColor) {
+ this._clearColor = value;
+ this.onClearColorChangedObservable.notifyObservers(this._clearColor);
+ }
+ }
+ /**
+ * Default image processing configuration used either in the rendering
+ * Forward main pass or through the imageProcessingPostProcess if present.
+ * As in the majority of the scene they are the same (exception for multi camera),
+ * this is easier to reference from here than from all the materials and post process.
+ *
+ * No setter as we it is a shared configuration, you can set the values instead.
+ */
+ get imageProcessingConfiguration() {
+ return this._imageProcessingConfiguration;
+ }
+ /**
+ * Gets or sets a value indicating how to treat performance relatively to ease of use and backward compatibility
+ */
+ get performancePriority() {
+ return this._performancePriority;
+ }
+ set performancePriority(value) {
+ if (value === this._performancePriority) {
+ return;
+ }
+ this._performancePriority = value;
+ switch (value) {
+ case 0 /* ScenePerformancePriority.BackwardCompatible */:
+ this.skipFrustumClipping = false;
+ this._renderingManager.maintainStateBetweenFrames = false;
+ this.skipPointerMovePicking = false;
+ this.autoClear = true;
+ break;
+ case 1 /* ScenePerformancePriority.Intermediate */:
+ this.skipFrustumClipping = false;
+ this._renderingManager.maintainStateBetweenFrames = false;
+ this.skipPointerMovePicking = true;
+ this.autoClear = false;
+ break;
+ case 2 /* ScenePerformancePriority.Aggressive */:
+ this.skipFrustumClipping = true;
+ this._renderingManager.maintainStateBetweenFrames = true;
+ this.skipPointerMovePicking = true;
+ this.autoClear = false;
+ break;
+ }
+ this.onScenePerformancePriorityChangedObservable.notifyObservers(value);
+ }
+ /**
+ * Gets or sets a boolean indicating if all rendering must be done in wireframe
+ */
+ set forceWireframe(value) {
+ if (this._forceWireframe === value) {
+ return;
+ }
+ this._forceWireframe = value;
+ this.markAllMaterialsAsDirty(16);
+ }
+ get forceWireframe() {
+ return this._forceWireframe;
+ }
+ /**
+ * Gets or sets a boolean indicating if we should skip the frustum clipping part of the active meshes selection
+ */
+ set skipFrustumClipping(value) {
+ if (this._skipFrustumClipping === value) {
+ return;
+ }
+ this._skipFrustumClipping = value;
+ }
+ get skipFrustumClipping() {
+ return this._skipFrustumClipping;
+ }
+ /**
+ * Gets or sets a boolean indicating if all rendering must be done in point cloud
+ */
+ set forcePointsCloud(value) {
+ if (this._forcePointsCloud === value) {
+ return;
+ }
+ this._forcePointsCloud = value;
+ this.markAllMaterialsAsDirty(16);
+ }
+ get forcePointsCloud() {
+ return this._forcePointsCloud;
+ }
+ /**
+ * Texture used in all pbr material as the reflection texture.
+ * As in the majority of the scene they are the same (exception for multi room and so on),
+ * this is easier to reference from here than from all the materials.
+ */
+ get environmentTexture() {
+ return this._environmentTexture;
+ }
+ /**
+ * Texture used in all pbr material as the reflection texture.
+ * As in the majority of the scene they are the same (exception for multi room and so on),
+ * this is easier to set here than in all the materials.
+ */
+ set environmentTexture(value) {
+ if (this._environmentTexture === value) {
+ return;
+ }
+ this._environmentTexture = value;
+ this.onEnvironmentTextureChangedObservable.notifyObservers(value);
+ this.markAllMaterialsAsDirty(1);
+ }
+ /**
+ * @returns all meshes, lights, cameras, transformNodes and bones
+ */
+ getNodes() {
+ let nodes = [];
+ nodes = nodes.concat(this.meshes);
+ nodes = nodes.concat(this.lights);
+ nodes = nodes.concat(this.cameras);
+ nodes = nodes.concat(this.transformNodes); // dummies
+ this.skeletons.forEach((skeleton) => (nodes = nodes.concat(skeleton.bones)));
+ return nodes;
+ }
+ /**
+ * Gets or sets the animation properties override
+ */
+ get animationPropertiesOverride() {
+ return this._animationPropertiesOverride;
+ }
+ set animationPropertiesOverride(value) {
+ this._animationPropertiesOverride = value;
+ }
+ /** Sets a function to be executed when this scene is disposed. */
+ set onDispose(callback) {
+ if (this._onDisposeObserver) {
+ this.onDisposeObservable.remove(this._onDisposeObserver);
+ }
+ this._onDisposeObserver = this.onDisposeObservable.add(callback);
+ }
+ /** Sets a function to be executed before rendering this scene */
+ set beforeRender(callback) {
+ if (this._onBeforeRenderObserver) {
+ this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
+ }
+ if (callback) {
+ this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
+ }
+ }
+ /** Sets a function to be executed after rendering this scene */
+ set afterRender(callback) {
+ if (this._onAfterRenderObserver) {
+ this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
+ }
+ if (callback) {
+ this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
+ }
+ }
+ /** Sets a function to be executed before rendering a camera*/
+ set beforeCameraRender(callback) {
+ if (this._onBeforeCameraRenderObserver) {
+ this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
+ }
+ this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
+ }
+ /** Sets a function to be executed after rendering a camera*/
+ set afterCameraRender(callback) {
+ if (this._onAfterCameraRenderObserver) {
+ this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
+ }
+ this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
+ }
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer down event
+ */
+ get pointerDownPredicate() {
+ return this._pointerPickingConfiguration.pointerDownPredicate;
+ }
+ set pointerDownPredicate(value) {
+ this._pointerPickingConfiguration.pointerDownPredicate = value;
+ }
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer up event
+ */
+ get pointerUpPredicate() {
+ return this._pointerPickingConfiguration.pointerUpPredicate;
+ }
+ set pointerUpPredicate(value) {
+ this._pointerPickingConfiguration.pointerUpPredicate = value;
+ }
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer move event
+ */
+ get pointerMovePredicate() {
+ return this._pointerPickingConfiguration.pointerMovePredicate;
+ }
+ set pointerMovePredicate(value) {
+ this._pointerPickingConfiguration.pointerMovePredicate = value;
+ }
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer down event
+ */
+ get pointerDownFastCheck() {
+ return this._pointerPickingConfiguration.pointerDownFastCheck;
+ }
+ set pointerDownFastCheck(value) {
+ this._pointerPickingConfiguration.pointerDownFastCheck = value;
+ }
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer up event
+ */
+ get pointerUpFastCheck() {
+ return this._pointerPickingConfiguration.pointerUpFastCheck;
+ }
+ set pointerUpFastCheck(value) {
+ this._pointerPickingConfiguration.pointerUpFastCheck = value;
+ }
+ /**
+ * Gets or sets a predicate used to select candidate meshes for a pointer move event
+ */
+ get pointerMoveFastCheck() {
+ return this._pointerPickingConfiguration.pointerMoveFastCheck;
+ }
+ set pointerMoveFastCheck(value) {
+ this._pointerPickingConfiguration.pointerMoveFastCheck = value;
+ }
+ /**
+ * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs.
+ */
+ get skipPointerMovePicking() {
+ return this._pointerPickingConfiguration.skipPointerMovePicking;
+ }
+ set skipPointerMovePicking(value) {
+ this._pointerPickingConfiguration.skipPointerMovePicking = value;
+ }
+ /**
+ * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs.
+ */
+ get skipPointerDownPicking() {
+ return this._pointerPickingConfiguration.skipPointerDownPicking;
+ }
+ set skipPointerDownPicking(value) {
+ this._pointerPickingConfiguration.skipPointerDownPicking = value;
+ }
+ /**
+ * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer up event occurs. Off by default.
+ */
+ get skipPointerUpPicking() {
+ return this._pointerPickingConfiguration.skipPointerUpPicking;
+ }
+ set skipPointerUpPicking(value) {
+ this._pointerPickingConfiguration.skipPointerUpPicking = value;
+ }
+ /**
+ * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
+ */
+ get unTranslatedPointer() {
+ return this._inputManager.unTranslatedPointer;
+ }
+ /**
+ * Gets or sets the distance in pixel that you have to move to prevent some events. Default is 10 pixels
+ */
+ static get DragMovementThreshold() {
+ return InputManager.DragMovementThreshold;
+ }
+ static set DragMovementThreshold(value) {
+ InputManager.DragMovementThreshold = value;
+ }
+ /**
+ * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 500 ms
+ */
+ static get LongPressDelay() {
+ return InputManager.LongPressDelay;
+ }
+ static set LongPressDelay(value) {
+ InputManager.LongPressDelay = value;
+ }
+ /**
+ * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 300 ms
+ */
+ static get DoubleClickDelay() {
+ return InputManager.DoubleClickDelay;
+ }
+ static set DoubleClickDelay(value) {
+ InputManager.DoubleClickDelay = value;
+ }
+ /** If you need to check double click without raising a single click at first click, enable this flag */
+ static get ExclusiveDoubleClickMode() {
+ return InputManager.ExclusiveDoubleClickMode;
+ }
+ static set ExclusiveDoubleClickMode(value) {
+ InputManager.ExclusiveDoubleClickMode = value;
+ }
+ /**
+ * Bind the current view position to an effect.
+ * @param effect The effect to be bound
+ * @param variableName name of the shader variable that will hold the eye position
+ * @param isVector3 true to indicates that variableName is a Vector3 and not a Vector4
+ * @returns the computed eye position
+ */
+ bindEyePosition(effect, variableName = "vEyePosition", isVector3 = false) {
+ const eyePosition = this._forcedViewPosition
+ ? this._forcedViewPosition
+ : this._mirroredCameraPosition
+ ? this._mirroredCameraPosition
+ : (this.activeCamera?.globalPosition ?? Vector3.ZeroReadOnly);
+ const invertNormal = this.useRightHandedSystem === (this._mirroredCameraPosition != null);
+ TmpVectors.Vector4[0].set(eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
+ if (effect) {
+ if (isVector3) {
+ effect.setFloat3(variableName, TmpVectors.Vector4[0].x, TmpVectors.Vector4[0].y, TmpVectors.Vector4[0].z);
+ }
+ else {
+ effect.setVector4(variableName, TmpVectors.Vector4[0]);
+ }
+ }
+ return TmpVectors.Vector4[0];
+ }
+ /**
+ * Update the scene ubo before it can be used in rendering processing
+ * @returns the scene UniformBuffer
+ */
+ finalizeSceneUbo() {
+ const ubo = this.getSceneUniformBuffer();
+ const eyePosition = this.bindEyePosition(null);
+ ubo.updateFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, eyePosition.w);
+ ubo.update();
+ return ubo;
+ }
+ /**
+ * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
+ */
+ set useRightHandedSystem(value) {
+ if (this._useRightHandedSystem === value) {
+ return;
+ }
+ this._useRightHandedSystem = value;
+ this.markAllMaterialsAsDirty(16);
+ }
+ get useRightHandedSystem() {
+ return this._useRightHandedSystem;
+ }
+ /**
+ * Sets the step Id used by deterministic lock step
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep
+ * @param newStepId defines the step Id
+ */
+ setStepId(newStepId) {
+ this._currentStepId = newStepId;
+ }
+ /**
+ * Gets the step Id used by deterministic lock step
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep
+ * @returns the step Id
+ */
+ getStepId() {
+ return this._currentStepId;
+ }
+ /**
+ * Gets the internal step used by deterministic lock step
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep
+ * @returns the internal step
+ */
+ getInternalStep() {
+ return this._currentInternalStep;
+ }
+ /**
+ * Gets or sets a boolean indicating if fog is enabled on this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog
+ * (Default is true)
+ */
+ set fogEnabled(value) {
+ if (this._fogEnabled === value) {
+ return;
+ }
+ this._fogEnabled = value;
+ this.markAllMaterialsAsDirty(16);
+ }
+ get fogEnabled() {
+ return this._fogEnabled;
+ }
+ /**
+ * Gets or sets the fog mode to use
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog
+ * | mode | value |
+ * | --- | --- |
+ * | FOGMODE_NONE | 0 |
+ * | FOGMODE_EXP | 1 |
+ * | FOGMODE_EXP2 | 2 |
+ * | FOGMODE_LINEAR | 3 |
+ */
+ set fogMode(value) {
+ if (this._fogMode === value) {
+ return;
+ }
+ this._fogMode = value;
+ this.markAllMaterialsAsDirty(16);
+ }
+ get fogMode() {
+ return this._fogMode;
+ }
+ /**
+ * Flag indicating that the frame buffer binding is handled by another component
+ */
+ get prePass() {
+ return !!this.prePassRenderer && this.prePassRenderer.defaultRT.enabled;
+ }
+ /**
+ * Gets or sets a boolean indicating if shadows are enabled on this scene
+ */
+ set shadowsEnabled(value) {
+ if (this._shadowsEnabled === value) {
+ return;
+ }
+ this._shadowsEnabled = value;
+ this.markAllMaterialsAsDirty(2);
+ }
+ get shadowsEnabled() {
+ return this._shadowsEnabled;
+ }
+ /**
+ * Gets or sets a boolean indicating if lights are enabled on this scene
+ */
+ set lightsEnabled(value) {
+ if (this._lightsEnabled === value) {
+ return;
+ }
+ this._lightsEnabled = value;
+ this.markAllMaterialsAsDirty(2);
+ }
+ get lightsEnabled() {
+ return this._lightsEnabled;
+ }
+ /** All of the active cameras added to this scene. */
+ get activeCameras() {
+ return this._activeCameras;
+ }
+ set activeCameras(cameras) {
+ if (this._unObserveActiveCameras) {
+ this._unObserveActiveCameras();
+ this._unObserveActiveCameras = null;
+ }
+ if (cameras) {
+ this._unObserveActiveCameras = _ObserveArray(cameras, () => {
+ this.onActiveCamerasChanged.notifyObservers(this);
+ });
+ }
+ this._activeCameras = cameras;
+ }
+ /** Gets or sets the current active camera */
+ get activeCamera() {
+ return this._activeCamera;
+ }
+ set activeCamera(value) {
+ if (value === this._activeCamera) {
+ return;
+ }
+ this._activeCamera = value;
+ this.onActiveCameraChanged.notifyObservers(this);
+ }
+ /** @internal */
+ get _hasDefaultMaterial() {
+ return Scene.DefaultMaterialFactory !== Scene._OriginalDefaultMaterialFactory;
+ }
+ /** The default material used on meshes when no material is affected */
+ get defaultMaterial() {
+ if (!this._defaultMaterial) {
+ this._defaultMaterial = Scene.DefaultMaterialFactory(this);
+ }
+ return this._defaultMaterial;
+ }
+ /** The default material used on meshes when no material is affected */
+ set defaultMaterial(value) {
+ this._defaultMaterial = value;
+ }
+ /**
+ * Gets or sets a boolean indicating if textures are enabled on this scene
+ */
+ set texturesEnabled(value) {
+ if (this._texturesEnabled === value) {
+ return;
+ }
+ this._texturesEnabled = value;
+ this.markAllMaterialsAsDirty(1);
+ }
+ get texturesEnabled() {
+ return this._texturesEnabled;
+ }
+ /**
+ * Gets or sets the frame graph used to render the scene. If set, the scene will use the frame graph to render the scene instead of the default render loop.
+ */
+ get frameGraph() {
+ return this._frameGraph;
+ }
+ set frameGraph(value) {
+ if (this._frameGraph) {
+ this._frameGraph = value;
+ if (!value) {
+ this.customRenderFunction = this._currentCustomRenderFunction;
+ }
+ return;
+ }
+ this._frameGraph = value;
+ if (value) {
+ this._currentCustomRenderFunction = this.customRenderFunction;
+ this.customRenderFunction = this._renderWithFrameGraph;
+ }
+ }
+ /**
+ * Gets or sets a boolean indicating if skeletons are enabled on this scene
+ */
+ set skeletonsEnabled(value) {
+ if (this._skeletonsEnabled === value) {
+ return;
+ }
+ this._skeletonsEnabled = value;
+ this.markAllMaterialsAsDirty(8);
+ }
+ get skeletonsEnabled() {
+ return this._skeletonsEnabled;
+ }
+ /** @internal */
+ get collisionCoordinator() {
+ if (!this._collisionCoordinator) {
+ this._collisionCoordinator = Scene.CollisionCoordinatorFactory();
+ this._collisionCoordinator.init(this);
+ }
+ return this._collisionCoordinator;
+ }
+ /**
+ * Gets the scene's rendering manager
+ */
+ get renderingManager() {
+ return this._renderingManager;
+ }
+ /**
+ * Gets the list of frustum planes (built from the active camera)
+ */
+ get frustumPlanes() {
+ return this._frustumPlanes;
+ }
+ /**
+ * Registers the transient components if needed.
+ */
+ _registerTransientComponents() {
+ // Register components that have been associated lately to the scene.
+ if (this._transientComponents.length > 0) {
+ for (const component of this._transientComponents) {
+ component.register();
+ }
+ this._transientComponents.length = 0;
+ }
+ }
+ /**
+ * @internal
+ * Add a component to the scene.
+ * Note that the ccomponent could be registered on th next frame if this is called after
+ * the register component stage.
+ * @param component Defines the component to add to the scene
+ */
+ _addComponent(component) {
+ this._components.push(component);
+ this._transientComponents.push(component);
+ const serializableComponent = component;
+ if (serializableComponent.addFromContainer && serializableComponent.serialize) {
+ this._serializableComponents.push(serializableComponent);
+ }
+ }
+ /**
+ * @internal
+ * Gets a component from the scene.
+ * @param name defines the name of the component to retrieve
+ * @returns the component or null if not present
+ */
+ _getComponent(name) {
+ for (const component of this._components) {
+ if (component.name === name) {
+ return component;
+ }
+ }
+ return null;
+ }
+ /**
+ * Creates a new Scene
+ * @param engine defines the engine to use to render this scene
+ * @param options defines the scene options
+ */
+ constructor(engine, options) {
+ /** @internal */
+ this._inputManager = new InputManager(this);
+ /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
+ this.cameraToUseForPointers = null;
+ /** @internal */
+ this._isScene = true;
+ /** @internal */
+ this._blockEntityCollection = false;
+ /**
+ * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
+ */
+ this.autoClear = true;
+ /**
+ * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
+ */
+ this.autoClearDepthAndStencil = true;
+ this._clearColor = new Color4(0.2, 0.2, 0.3, 1.0);
+ /**
+ * Observable triggered when the performance priority is changed
+ */
+ this.onClearColorChangedObservable = new Observable();
+ /**
+ * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
+ */
+ this.ambientColor = new Color3(0, 0, 0);
+ /**
+ * Intensity of the environment (i.e. all indirect lighting) in all pbr material.
+ * This dims or reinforces the indirect lighting overall (reflection and diffuse).
+ * As in the majority of the scene they are the same (exception for multi room and so on),
+ * this is easier to reference from here than from all the materials.
+ * Note that this is more of a debugging parameter and is not physically accurate.
+ * If you want to modify the intensity of the IBL texture, you should update iblIntensity instead.
+ */
+ this.environmentIntensity = 1;
+ /**
+ * Overall intensity of the IBL texture.
+ * This value is multiplied with the reflectionTexture.level value to calculate the final IBL intensity.
+ */
+ this.iblIntensity = 1;
+ this._performancePriority = 0 /* ScenePerformancePriority.BackwardCompatible */;
+ /**
+ * Observable triggered when the performance priority is changed
+ */
+ this.onScenePerformancePriorityChangedObservable = new Observable();
+ this._forceWireframe = false;
+ this._skipFrustumClipping = false;
+ this._forcePointsCloud = false;
+ /**
+ * Gets the list of root nodes (ie. nodes with no parent)
+ */
+ this.rootNodes = [];
+ /** All of the cameras added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras
+ */
+ this.cameras = [];
+ /**
+ * All of the lights added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ */
+ this.lights = [];
+ /**
+ * All of the (abstract) meshes added to this scene
+ */
+ this.meshes = [];
+ /**
+ * The list of skeletons added to the scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons
+ */
+ this.skeletons = [];
+ /**
+ * All of the particle systems added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro
+ */
+ this.particleSystems = [];
+ /**
+ * Gets a list of Animations associated with the scene
+ */
+ this.animations = [];
+ /**
+ * All of the animation groups added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations
+ */
+ this.animationGroups = [];
+ /**
+ * All of the multi-materials added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials
+ */
+ this.multiMaterials = [];
+ /**
+ * All of the materials added to this scene
+ * In the context of a Scene, it is not supposed to be modified manually.
+ * Any addition or removal should be done using the addMaterial and removeMaterial Scene methods.
+ * Note also that the order of the Material within the array is not significant and might change.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction
+ */
+ this.materials = [];
+ /**
+ * The list of morph target managers added to the scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph
+ */
+ this.morphTargetManagers = [];
+ /**
+ * The list of geometries used in the scene.
+ */
+ this.geometries = [];
+ /**
+ * All of the transform nodes added to this scene
+ * In the context of a Scene, it is not supposed to be modified manually.
+ * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
+ * Note also that the order of the TransformNode within the array is not significant and might change.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node
+ */
+ this.transformNodes = [];
+ /**
+ * ActionManagers available on the scene.
+ * @deprecated
+ */
+ this.actionManagers = [];
+ /**
+ * Textures to keep.
+ */
+ this.textures = [];
+ /** @internal */
+ this._environmentTexture = null;
+ /**
+ * The list of postprocesses added to the scene
+ */
+ this.postProcesses = [];
+ /**
+ * The list of effect layers (highlights/glow) added to the scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/highlightLayer
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/glowLayer
+ */
+ this.effectLayers = [];
+ /**
+ * The list of sounds used in the scene.
+ */
+ this.sounds = null;
+ /**
+ * The list of layers (background and foreground) of the scene
+ */
+ this.layers = [];
+ /**
+ * The list of lens flare system added to the scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare
+ */
+ this.lensFlareSystems = [];
+ /**
+ * The list of procedural textures added to the scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures
+ */
+ this.proceduralTextures = [];
+ /**
+ * Gets or sets a boolean indicating if animations are enabled
+ */
+ this.animationsEnabled = true;
+ this._animationPropertiesOverride = null;
+ /**
+ * Gets or sets a boolean indicating if a constant deltatime has to be used
+ * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
+ */
+ this.useConstantAnimationDeltaTime = false;
+ /**
+ * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
+ * Please note that it requires to run a ray cast through the scene on every frame
+ */
+ this.constantlyUpdateMeshUnderPointer = false;
+ /**
+ * Defines the HTML cursor to use when hovering over interactive elements
+ */
+ this.hoverCursor = "pointer";
+ /**
+ * Defines the HTML default cursor to use (empty by default)
+ */
+ this.defaultCursor = "";
+ /**
+ * Defines whether cursors are handled by the scene.
+ */
+ this.doNotHandleCursors = false;
+ /**
+ * This is used to call preventDefault() on pointer down
+ * in order to block unwanted artifacts like system double clicks
+ */
+ this.preventDefaultOnPointerDown = true;
+ /**
+ * This is used to call preventDefault() on pointer up
+ * in order to block unwanted artifacts like system double clicks
+ */
+ this.preventDefaultOnPointerUp = true;
+ // Metadata
+ /**
+ * Gets or sets user defined metadata
+ */
+ this.metadata = null;
+ /**
+ * For internal use only. Please do not use.
+ */
+ this.reservedDataStore = null;
+ /**
+ * Use this array to add regular expressions used to disable offline support for specific urls
+ */
+ this.disableOfflineSupportExceptionRules = [];
+ /**
+ * An event triggered when the scene is disposed.
+ */
+ this.onDisposeObservable = new Observable();
+ this._onDisposeObserver = null;
+ /**
+ * An event triggered before rendering the scene (right after animations and physics)
+ */
+ this.onBeforeRenderObservable = new Observable();
+ this._onBeforeRenderObserver = null;
+ /**
+ * An event triggered after rendering the scene
+ */
+ this.onAfterRenderObservable = new Observable();
+ /**
+ * An event triggered after rendering the scene for an active camera (When scene.render is called this will be called after each camera)
+ * This is triggered for each "sub" camera in a Camera Rig unlike onAfterCameraRenderObservable
+ */
+ this.onAfterRenderCameraObservable = new Observable();
+ this._onAfterRenderObserver = null;
+ /**
+ * An event triggered before animating the scene
+ */
+ this.onBeforeAnimationsObservable = new Observable();
+ /**
+ * An event triggered after animations processing
+ */
+ this.onAfterAnimationsObservable = new Observable();
+ /**
+ * An event triggered before draw calls are ready to be sent
+ */
+ this.onBeforeDrawPhaseObservable = new Observable();
+ /**
+ * An event triggered after draw calls have been sent
+ */
+ this.onAfterDrawPhaseObservable = new Observable();
+ /**
+ * An event triggered when the scene is ready
+ */
+ this.onReadyObservable = new Observable();
+ /**
+ * An event triggered before rendering a camera
+ */
+ this.onBeforeCameraRenderObservable = new Observable();
+ this._onBeforeCameraRenderObserver = null;
+ /**
+ * An event triggered after rendering a camera
+ * This is triggered for the full rig Camera only unlike onAfterRenderCameraObservable
+ */
+ this.onAfterCameraRenderObservable = new Observable();
+ this._onAfterCameraRenderObserver = null;
+ /**
+ * An event triggered when active meshes evaluation is about to start
+ */
+ this.onBeforeActiveMeshesEvaluationObservable = new Observable();
+ /**
+ * An event triggered when active meshes evaluation is done
+ */
+ this.onAfterActiveMeshesEvaluationObservable = new Observable();
+ /**
+ * An event triggered when particles rendering is about to start
+ * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
+ */
+ this.onBeforeParticlesRenderingObservable = new Observable();
+ /**
+ * An event triggered when particles rendering is done
+ * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
+ */
+ this.onAfterParticlesRenderingObservable = new Observable();
+ /**
+ * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
+ */
+ this.onDataLoadedObservable = new Observable();
+ /**
+ * An event triggered when a camera is created
+ */
+ this.onNewCameraAddedObservable = new Observable();
+ /**
+ * An event triggered when a camera is removed
+ */
+ this.onCameraRemovedObservable = new Observable();
+ /**
+ * An event triggered when a light is created
+ */
+ this.onNewLightAddedObservable = new Observable();
+ /**
+ * An event triggered when a light is removed
+ */
+ this.onLightRemovedObservable = new Observable();
+ /**
+ * An event triggered when a geometry is created
+ */
+ this.onNewGeometryAddedObservable = new Observable();
+ /**
+ * An event triggered when a geometry is removed
+ */
+ this.onGeometryRemovedObservable = new Observable();
+ /**
+ * An event triggered when a transform node is created
+ */
+ this.onNewTransformNodeAddedObservable = new Observable();
+ /**
+ * An event triggered when a transform node is removed
+ */
+ this.onTransformNodeRemovedObservable = new Observable();
+ /**
+ * An event triggered when a mesh is created
+ */
+ this.onNewMeshAddedObservable = new Observable();
+ /**
+ * An event triggered when a mesh is removed
+ */
+ this.onMeshRemovedObservable = new Observable();
+ /**
+ * An event triggered when a skeleton is created
+ */
+ this.onNewSkeletonAddedObservable = new Observable();
+ /**
+ * An event triggered when a skeleton is removed
+ */
+ this.onSkeletonRemovedObservable = new Observable();
+ /**
+ * An event triggered when a material is created
+ */
+ this.onNewMaterialAddedObservable = new Observable();
+ /**
+ * An event triggered when a multi material is created
+ */
+ this.onNewMultiMaterialAddedObservable = new Observable();
+ /**
+ * An event triggered when a material is removed
+ */
+ this.onMaterialRemovedObservable = new Observable();
+ /**
+ * An event triggered when a multi material is removed
+ */
+ this.onMultiMaterialRemovedObservable = new Observable();
+ /**
+ * An event triggered when a texture is created
+ */
+ this.onNewTextureAddedObservable = new Observable();
+ /**
+ * An event triggered when a texture is removed
+ */
+ this.onTextureRemovedObservable = new Observable();
+ /**
+ * An event triggered when render targets are about to be rendered
+ * Can happen multiple times per frame.
+ */
+ this.onBeforeRenderTargetsRenderObservable = new Observable();
+ /**
+ * An event triggered when render targets were rendered.
+ * Can happen multiple times per frame.
+ */
+ this.onAfterRenderTargetsRenderObservable = new Observable();
+ /**
+ * An event triggered before calculating deterministic simulation step
+ */
+ this.onBeforeStepObservable = new Observable();
+ /**
+ * An event triggered after calculating deterministic simulation step
+ */
+ this.onAfterStepObservable = new Observable();
+ /**
+ * An event triggered when the activeCamera property is updated
+ */
+ this.onActiveCameraChanged = new Observable();
+ /**
+ * An event triggered when the activeCameras property is updated
+ */
+ this.onActiveCamerasChanged = new Observable();
+ /**
+ * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
+ * The RenderingGroupInfo class contains all the information about the context in which the observable is called
+ * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
+ */
+ this.onBeforeRenderingGroupObservable = new Observable();
+ /**
+ * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
+ * The RenderingGroupInfo class contains all the information about the context in which the observable is called
+ * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
+ */
+ this.onAfterRenderingGroupObservable = new Observable();
+ /**
+ * This Observable will when a mesh has been imported into the scene.
+ */
+ this.onMeshImportedObservable = new Observable();
+ /**
+ * This Observable will when an animation file has been imported into the scene.
+ */
+ this.onAnimationFileImportedObservable = new Observable();
+ /**
+ * An event triggered when the environmentTexture is changed.
+ */
+ this.onEnvironmentTextureChangedObservable = new Observable();
+ /**
+ * An event triggered when the state of mesh under pointer, for a specific pointerId, changes.
+ */
+ this.onMeshUnderPointerUpdatedObservable = new Observable();
+ // Animations
+ /** @internal */
+ this._registeredForLateAnimationBindings = new SmartArrayNoDuplicate(256);
+ // Pointers
+ this._pointerPickingConfiguration = new PointerPickingConfiguration();
+ /**
+ * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
+ * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
+ */
+ this.onPrePointerObservable = new Observable();
+ /**
+ * Observable event triggered each time an input event is received from the rendering canvas
+ */
+ this.onPointerObservable = new Observable();
+ // Keyboard
+ /**
+ * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
+ * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
+ */
+ this.onPreKeyboardObservable = new Observable();
+ /**
+ * Observable event triggered each time an keyboard event is received from the hosting window
+ */
+ this.onKeyboardObservable = new Observable();
+ // Coordinates system
+ this._useRightHandedSystem = false;
+ // Deterministic lockstep
+ this._timeAccumulator = 0;
+ this._currentStepId = 0;
+ this._currentInternalStep = 0;
+ // Fog
+ this._fogEnabled = true;
+ this._fogMode = Scene.FOGMODE_NONE;
+ /**
+ * Gets or sets the fog color to use
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog
+ * (Default is Color3(0.2, 0.2, 0.3))
+ */
+ this.fogColor = new Color3(0.2, 0.2, 0.3);
+ /**
+ * Gets or sets the fog density to use
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog
+ * (Default is 0.1)
+ */
+ this.fogDensity = 0.1;
+ /**
+ * Gets or sets the fog start distance to use
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog
+ * (Default is 0)
+ */
+ this.fogStart = 0;
+ /**
+ * Gets or sets the fog end distance to use
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog
+ * (Default is 1000)
+ */
+ this.fogEnd = 1000.0;
+ /**
+ * Flag indicating if we need to store previous matrices when rendering
+ */
+ this.needsPreviousWorldMatrices = false;
+ // Lights
+ this._shadowsEnabled = true;
+ this._lightsEnabled = true;
+ this._unObserveActiveCameras = null;
+ // Textures
+ this._texturesEnabled = true;
+ this._frameGraph = null;
+ /**
+ * List of frame graphs associated with the scene
+ */
+ this.frameGraphs = [];
+ // Physics
+ /**
+ * Gets or sets a boolean indicating if physic engines are enabled on this scene
+ */
+ this.physicsEnabled = true;
+ // Particles
+ /**
+ * Gets or sets a boolean indicating if particles are enabled on this scene
+ */
+ this.particlesEnabled = true;
+ // Sprites
+ /**
+ * Gets or sets a boolean indicating if sprites are enabled on this scene
+ */
+ this.spritesEnabled = true;
+ // Skeletons
+ this._skeletonsEnabled = true;
+ // Lens flares
+ /**
+ * Gets or sets a boolean indicating if lens flares are enabled on this scene
+ */
+ this.lensFlaresEnabled = true;
+ // Collisions
+ /**
+ * Gets or sets a boolean indicating if collisions are enabled on this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions
+ */
+ this.collisionsEnabled = true;
+ /**
+ * Defines the gravity applied to this scene (used only for collisions)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions
+ */
+ this.gravity = new Vector3(0, -9.807, 0);
+ // Postprocesses
+ /**
+ * Gets or sets a boolean indicating if postprocesses are enabled on this scene
+ */
+ this.postProcessesEnabled = true;
+ // Customs render targets
+ /**
+ * Gets or sets a boolean indicating if render targets are enabled on this scene
+ */
+ this.renderTargetsEnabled = true;
+ /**
+ * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
+ * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
+ */
+ this.dumpNextRenderTargets = false;
+ /**
+ * The list of user defined render targets added to the scene
+ */
+ this.customRenderTargets = [];
+ /**
+ * Gets the list of meshes imported to the scene through SceneLoader
+ */
+ this.importedMeshesFiles = [];
+ // Probes
+ /**
+ * Gets or sets a boolean indicating if probes are enabled on this scene
+ */
+ this.probesEnabled = true;
+ this._meshesForIntersections = new SmartArrayNoDuplicate(256);
+ // Procedural textures
+ /**
+ * Gets or sets a boolean indicating if procedural textures are enabled on this scene
+ */
+ this.proceduralTexturesEnabled = true;
+ // Performance counters
+ this._totalVertices = new PerfCounter();
+ /** @internal */
+ this._activeIndices = new PerfCounter();
+ /** @internal */
+ this._activeParticles = new PerfCounter();
+ /** @internal */
+ this._activeBones = new PerfCounter();
+ /** @internal */
+ this._animationTime = 0;
+ /**
+ * Gets or sets a general scale for animation speed
+ * @see https://www.babylonjs-playground.com/#IBU2W7#3
+ */
+ this.animationTimeScale = 1;
+ this._renderId = 0;
+ this._frameId = 0;
+ this._executeWhenReadyTimeoutId = null;
+ this._intermediateRendering = false;
+ this._defaultFrameBufferCleared = false;
+ this._viewUpdateFlag = -1;
+ this._projectionUpdateFlag = -1;
+ /** @internal */
+ this._toBeDisposed = new Array(256);
+ this._activeRequests = new Array();
+ /** @internal */
+ this._pendingData = new Array();
+ this._isDisposed = false;
+ /**
+ * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
+ * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
+ */
+ this.dispatchAllSubMeshesOfActiveMeshes = false;
+ this._activeMeshes = new SmartArray(256);
+ this._processedMaterials = new SmartArray(256);
+ this._renderTargets = new SmartArrayNoDuplicate(256);
+ this._materialsRenderTargets = new SmartArrayNoDuplicate(256);
+ /** @internal */
+ this._activeParticleSystems = new SmartArray(256);
+ this._activeSkeletons = new SmartArrayNoDuplicate(32);
+ this._softwareSkinnedMeshes = new SmartArrayNoDuplicate(32);
+ /** @internal */
+ this._activeAnimatables = new Array();
+ this._transformMatrix = Matrix.Zero();
+ /**
+ * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
+ * This is useful if there are more lights that the maximum simulteanous authorized
+ */
+ this.requireLightSorting = false;
+ /**
+ * @internal
+ * Backing store of defined scene components.
+ */
+ this._components = [];
+ /**
+ * @internal
+ * Backing store of defined scene components.
+ */
+ this._serializableComponents = [];
+ /**
+ * List of components to register on the next registration step.
+ */
+ this._transientComponents = [];
+ /**
+ * @internal
+ * Defines the actions happening before camera updates.
+ */
+ this._beforeCameraUpdateStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening before clear the canvas.
+ */
+ this._beforeClearStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening before clear the canvas.
+ */
+ this._beforeRenderTargetClearStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions when collecting render targets for the frame.
+ */
+ this._gatherRenderTargetsStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening for one camera in the frame.
+ */
+ this._gatherActiveCameraRenderTargetsStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening during the per mesh ready checks.
+ */
+ this._isReadyForMeshStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening before evaluate active mesh checks.
+ */
+ this._beforeEvaluateActiveMeshStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening during the evaluate sub mesh checks.
+ */
+ this._evaluateSubMeshStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening during the active mesh stage.
+ */
+ this._preActiveMeshStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening during the per camera render target step.
+ */
+ this._cameraDrawRenderTargetStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just before the active camera is drawing.
+ */
+ this._beforeCameraDrawStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just before a render target is drawing.
+ */
+ this._beforeRenderTargetDrawStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just before a rendering group is drawing.
+ */
+ this._beforeRenderingGroupDrawStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just before a mesh is drawing.
+ */
+ this._beforeRenderingMeshStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just after a mesh has been drawn.
+ */
+ this._afterRenderingMeshStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just after a rendering group has been drawn.
+ */
+ this._afterRenderingGroupDrawStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just after the active camera has been drawn.
+ */
+ this._afterCameraDrawStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just after the post processing
+ */
+ this._afterCameraPostProcessStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just after a render target has been drawn.
+ */
+ this._afterRenderTargetDrawStage = Stage.Create();
+ /**
+ * Defines the actions happening just after the post processing on a render target
+ */
+ this._afterRenderTargetPostProcessStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening just after rendering all cameras and computing intersections.
+ */
+ this._afterRenderStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening when a pointer move event happens.
+ */
+ this._pointerMoveStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening when a pointer down event happens.
+ */
+ this._pointerDownStage = Stage.Create();
+ /**
+ * @internal
+ * Defines the actions happening when a pointer up event happens.
+ */
+ this._pointerUpStage = Stage.Create();
+ /**
+ * an optional map from Geometry Id to Geometry index in the 'geometries' array
+ */
+ this._geometriesByUniqueId = null;
+ this._defaultMeshCandidates = {
+ data: [],
+ length: 0,
+ };
+ this._defaultSubMeshCandidates = {
+ data: [],
+ length: 0,
+ };
+ this._preventFreeActiveMeshesAndRenderingGroups = false;
+ /** @internal */
+ this._activeMeshesFrozen = false;
+ /** @internal */
+ this._activeMeshesFrozenButKeepClipping = false;
+ this._skipEvaluateActiveMeshesCompletely = false;
+ /** @internal */
+ this._useCurrentFrameBuffer = false;
+ /** @internal */
+ this._allowPostProcessClearColor = true;
+ /**
+ * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
+ * @returns the frame time
+ */
+ this.getDeterministicFrameTime = () => {
+ return this._engine.getTimeStep();
+ };
+ /** @internal */
+ this._registeredActions = 0;
+ this._blockMaterialDirtyMechanism = false;
+ /**
+ * Internal perfCollector instance used for sharing between inspector and playground.
+ * Marked as protected to allow sharing between prototype extensions, but disallow access at toplevel.
+ */
+ this._perfCollector = null;
+ this.activeCameras = [];
+ const fullOptions = {
+ useGeometryUniqueIdsMap: true,
+ useMaterialMeshMap: true,
+ useClonedMeshMap: true,
+ virtual: false,
+ ...options,
+ };
+ engine = this._engine = engine || EngineStore.LastCreatedEngine;
+ if (fullOptions.virtual) {
+ engine._virtualScenes.push(this);
+ }
+ else {
+ EngineStore._LastCreatedScene = this;
+ engine.scenes.push(this);
+ }
+ this._uid = null;
+ this._renderingManager = new RenderingManager(this);
+ if (PostProcessManager) {
+ this.postProcessManager = new PostProcessManager(this);
+ }
+ if (IsWindowObjectExist()) {
+ this.attachControl();
+ }
+ // Uniform Buffer
+ this._createUbo();
+ // Default Image processing definition
+ if (ImageProcessingConfiguration) {
+ this._imageProcessingConfiguration = new ImageProcessingConfiguration();
+ }
+ this.setDefaultCandidateProviders();
+ if (fullOptions.useGeometryUniqueIdsMap) {
+ this._geometriesByUniqueId = {};
+ }
+ this.useMaterialMeshMap = fullOptions.useMaterialMeshMap;
+ this.useClonedMeshMap = fullOptions.useClonedMeshMap;
+ if (!options || !options.virtual) {
+ engine.onNewSceneAddedObservable.notifyObservers(this);
+ }
+ }
+ /**
+ * Gets a string identifying the name of the class
+ * @returns "Scene" string
+ */
+ getClassName() {
+ return "Scene";
+ }
+ /**
+ * @internal
+ */
+ _getDefaultMeshCandidates() {
+ this._defaultMeshCandidates.data = this.meshes;
+ this._defaultMeshCandidates.length = this.meshes.length;
+ return this._defaultMeshCandidates;
+ }
+ /**
+ * @internal
+ */
+ _getDefaultSubMeshCandidates(mesh) {
+ this._defaultSubMeshCandidates.data = mesh.subMeshes;
+ this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
+ return this._defaultSubMeshCandidates;
+ }
+ /**
+ * Sets the default candidate providers for the scene.
+ * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
+ * and getCollidingSubMeshCandidates to their default function
+ */
+ setDefaultCandidateProviders() {
+ this.getActiveMeshCandidates = () => this._getDefaultMeshCandidates();
+ this.getActiveSubMeshCandidates = (mesh) => this._getDefaultSubMeshCandidates(mesh);
+ this.getIntersectingSubMeshCandidates = (mesh, localRay) => this._getDefaultSubMeshCandidates(mesh);
+ this.getCollidingSubMeshCandidates = (mesh, collider) => this._getDefaultSubMeshCandidates(mesh);
+ }
+ /**
+ * Gets the mesh that is currently under the pointer
+ */
+ get meshUnderPointer() {
+ return this._inputManager.meshUnderPointer;
+ }
+ /**
+ * Gets or sets the current on-screen X position of the pointer
+ */
+ get pointerX() {
+ return this._inputManager.pointerX;
+ }
+ set pointerX(value) {
+ this._inputManager.pointerX = value;
+ }
+ /**
+ * Gets or sets the current on-screen Y position of the pointer
+ */
+ get pointerY() {
+ return this._inputManager.pointerY;
+ }
+ set pointerY(value) {
+ this._inputManager.pointerY = value;
+ }
+ /**
+ * Gets the cached material (ie. the latest rendered one)
+ * @returns the cached material
+ */
+ getCachedMaterial() {
+ return this._cachedMaterial;
+ }
+ /**
+ * Gets the cached effect (ie. the latest rendered one)
+ * @returns the cached effect
+ */
+ getCachedEffect() {
+ return this._cachedEffect;
+ }
+ /**
+ * Gets the cached visibility state (ie. the latest rendered one)
+ * @returns the cached visibility state
+ */
+ getCachedVisibility() {
+ return this._cachedVisibility;
+ }
+ /**
+ * Gets a boolean indicating if the current material / effect / visibility must be bind again
+ * @param material defines the current material
+ * @param effect defines the current effect
+ * @param visibility defines the current visibility state
+ * @returns true if one parameter is not cached
+ */
+ isCachedMaterialInvalid(material, effect, visibility = 1) {
+ return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
+ }
+ /**
+ * Gets the engine associated with the scene
+ * @returns an Engine
+ */
+ getEngine() {
+ return this._engine;
+ }
+ /**
+ * Gets the total number of vertices rendered per frame
+ * @returns the total number of vertices rendered per frame
+ */
+ getTotalVertices() {
+ return this._totalVertices.current;
+ }
+ /**
+ * Gets the performance counter for total vertices
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation
+ */
+ get totalVerticesPerfCounter() {
+ return this._totalVertices;
+ }
+ /**
+ * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
+ * @returns the total number of active indices rendered per frame
+ */
+ getActiveIndices() {
+ return this._activeIndices.current;
+ }
+ /**
+ * Gets the performance counter for active indices
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation
+ */
+ get totalActiveIndicesPerfCounter() {
+ return this._activeIndices;
+ }
+ /**
+ * Gets the total number of active particles rendered per frame
+ * @returns the total number of active particles rendered per frame
+ */
+ getActiveParticles() {
+ return this._activeParticles.current;
+ }
+ /**
+ * Gets the performance counter for active particles
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation
+ */
+ get activeParticlesPerfCounter() {
+ return this._activeParticles;
+ }
+ /**
+ * Gets the total number of active bones rendered per frame
+ * @returns the total number of active bones rendered per frame
+ */
+ getActiveBones() {
+ return this._activeBones.current;
+ }
+ /**
+ * Gets the performance counter for active bones
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation
+ */
+ get activeBonesPerfCounter() {
+ return this._activeBones;
+ }
+ /**
+ * Gets the array of active meshes
+ * @returns an array of AbstractMesh
+ */
+ getActiveMeshes() {
+ return this._activeMeshes;
+ }
+ /**
+ * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
+ * @returns a number
+ */
+ getAnimationRatio() {
+ return this._animationRatio !== undefined ? this._animationRatio : 1;
+ }
+ /**
+ * Gets an unique Id for the current render phase
+ * @returns a number
+ */
+ getRenderId() {
+ return this._renderId;
+ }
+ /**
+ * Gets an unique Id for the current frame
+ * @returns a number
+ */
+ getFrameId() {
+ return this._frameId;
+ }
+ /** Call this function if you want to manually increment the render Id*/
+ incrementRenderId() {
+ this._renderId++;
+ }
+ _createUbo() {
+ this.setSceneUniformBuffer(this.createSceneUniformBuffer());
+ }
+ /**
+ * Use this method to simulate a pointer move on a mesh
+ * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
+ * @param pickResult pickingInfo of the object wished to simulate pointer event on
+ * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
+ * @returns the current scene
+ */
+ simulatePointerMove(pickResult, pointerEventInit) {
+ this._inputManager.simulatePointerMove(pickResult, pointerEventInit);
+ return this;
+ }
+ /**
+ * Use this method to simulate a pointer down on a mesh
+ * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
+ * @param pickResult pickingInfo of the object wished to simulate pointer event on
+ * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
+ * @returns the current scene
+ */
+ simulatePointerDown(pickResult, pointerEventInit) {
+ this._inputManager.simulatePointerDown(pickResult, pointerEventInit);
+ return this;
+ }
+ /**
+ * Use this method to simulate a pointer up on a mesh
+ * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
+ * @param pickResult pickingInfo of the object wished to simulate pointer event on
+ * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
+ * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
+ * @returns the current scene
+ */
+ simulatePointerUp(pickResult, pointerEventInit, doubleTap) {
+ this._inputManager.simulatePointerUp(pickResult, pointerEventInit, doubleTap);
+ return this;
+ }
+ /**
+ * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
+ * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
+ * @returns true if the pointer was captured
+ */
+ isPointerCaptured(pointerId = 0) {
+ return this._inputManager.isPointerCaptured(pointerId);
+ }
+ /**
+ * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
+ * @param attachUp defines if you want to attach events to pointerup
+ * @param attachDown defines if you want to attach events to pointerdown
+ * @param attachMove defines if you want to attach events to pointermove
+ */
+ attachControl(attachUp = true, attachDown = true, attachMove = true) {
+ this._inputManager.attachControl(attachUp, attachDown, attachMove);
+ }
+ /** Detaches all event handlers*/
+ detachControl() {
+ this._inputManager.detachControl();
+ }
+ /**
+ * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
+ * Delay loaded resources are not taking in account
+ * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: true)
+ * @returns true if all required resources are ready
+ */
+ isReady(checkRenderTargets = true) {
+ if (this._isDisposed) {
+ return false;
+ }
+ let index;
+ const engine = this.getEngine();
+ const currentRenderPassId = engine.currentRenderPassId;
+ engine.currentRenderPassId = this.activeCamera?.renderPassId ?? currentRenderPassId;
+ let isReady = true;
+ // Pending data
+ if (this._pendingData.length > 0) {
+ isReady = false;
+ }
+ // Ensures that the pre-pass renderer is enabled if it is to be enabled.
+ this.prePassRenderer?.update();
+ // OIT
+ if (this.useOrderIndependentTransparency && this.depthPeelingRenderer) {
+ isReady && (isReady = this.depthPeelingRenderer.isReady());
+ }
+ // Meshes
+ if (checkRenderTargets) {
+ this._processedMaterials.reset();
+ this._materialsRenderTargets.reset();
+ }
+ for (index = 0; index < this.meshes.length; index++) {
+ const mesh = this.meshes[index];
+ if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
+ continue;
+ }
+ // Do not stop at the first encountered "unready" object as we want to ensure
+ // all materials are starting off their compilation in parallel.
+ if (!mesh.isReady(true)) {
+ isReady = false;
+ continue;
+ }
+ const hardwareInstancedRendering = mesh.hasThinInstances ||
+ mesh.getClassName() === "InstancedMesh" ||
+ mesh.getClassName() === "InstancedLinesMesh" ||
+ (engine.getCaps().instancedArrays && mesh.instances.length > 0);
+ // Is Ready For Mesh
+ for (const step of this._isReadyForMeshStage) {
+ if (!step.action(mesh, hardwareInstancedRendering)) {
+ isReady = false;
+ }
+ }
+ if (!checkRenderTargets) {
+ continue;
+ }
+ const mat = mesh.material || this.defaultMaterial;
+ if (mat) {
+ if (mat._storeEffectOnSubMeshes) {
+ for (const subMesh of mesh.subMeshes) {
+ const material = subMesh.getMaterial();
+ if (material && material.hasRenderTargetTextures && material.getRenderTargetTextures != null) {
+ if (this._processedMaterials.indexOf(material) === -1) {
+ this._processedMaterials.push(material);
+ this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
+ }
+ }
+ }
+ }
+ else {
+ if (mat.hasRenderTargetTextures && mat.getRenderTargetTextures != null) {
+ if (this._processedMaterials.indexOf(mat) === -1) {
+ this._processedMaterials.push(mat);
+ this._materialsRenderTargets.concatWithNoDuplicate(mat.getRenderTargetTextures());
+ }
+ }
+ }
+ }
+ }
+ // Render targets
+ if (checkRenderTargets) {
+ for (index = 0; index < this._materialsRenderTargets.length; ++index) {
+ const rtt = this._materialsRenderTargets.data[index];
+ if (!rtt.isReadyForRendering()) {
+ isReady = false;
+ }
+ }
+ }
+ // Geometries
+ for (index = 0; index < this.geometries.length; index++) {
+ const geometry = this.geometries[index];
+ if (geometry.delayLoadState === 2) {
+ isReady = false;
+ }
+ }
+ // Post-processes
+ if (this.activeCameras && this.activeCameras.length > 0) {
+ for (const camera of this.activeCameras) {
+ if (!camera.isReady(true)) {
+ isReady = false;
+ }
+ }
+ }
+ else if (this.activeCamera) {
+ if (!this.activeCamera.isReady(true)) {
+ isReady = false;
+ }
+ }
+ // Particles
+ for (const particleSystem of this.particleSystems) {
+ if (!particleSystem.isReady()) {
+ isReady = false;
+ }
+ }
+ // Layers
+ if (this.layers) {
+ for (const layer of this.layers) {
+ if (!layer.isReady()) {
+ isReady = false;
+ }
+ }
+ }
+ // Effect layers
+ if (this.effectLayers) {
+ for (const effectLayer of this.effectLayers) {
+ if (!effectLayer.isLayerReady()) {
+ isReady = false;
+ }
+ }
+ }
+ // Effects
+ if (!engine.areAllEffectsReady()) {
+ isReady = false;
+ }
+ engine.currentRenderPassId = currentRenderPassId;
+ return isReady;
+ }
+ /** Resets all cached information relative to material (including effect and visibility) */
+ resetCachedMaterial() {
+ this._cachedMaterial = null;
+ this._cachedEffect = null;
+ this._cachedVisibility = null;
+ }
+ /**
+ * Registers a function to be called before every frame render
+ * @param func defines the function to register
+ */
+ registerBeforeRender(func) {
+ this.onBeforeRenderObservable.add(func);
+ }
+ /**
+ * Unregisters a function called before every frame render
+ * @param func defines the function to unregister
+ */
+ unregisterBeforeRender(func) {
+ this.onBeforeRenderObservable.removeCallback(func);
+ }
+ /**
+ * Registers a function to be called after every frame render
+ * @param func defines the function to register
+ */
+ registerAfterRender(func) {
+ this.onAfterRenderObservable.add(func);
+ }
+ /**
+ * Unregisters a function called after every frame render
+ * @param func defines the function to unregister
+ */
+ unregisterAfterRender(func) {
+ this.onAfterRenderObservable.removeCallback(func);
+ }
+ _executeOnceBeforeRender(func) {
+ const execFunc = () => {
+ func();
+ setTimeout(() => {
+ this.unregisterBeforeRender(execFunc);
+ });
+ };
+ this.registerBeforeRender(execFunc);
+ }
+ /**
+ * The provided function will run before render once and will be disposed afterwards.
+ * A timeout delay can be provided so that the function will be executed in N ms.
+ * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
+ * @param func The function to be executed.
+ * @param timeout optional delay in ms
+ */
+ executeOnceBeforeRender(func, timeout) {
+ if (timeout !== undefined) {
+ setTimeout(() => {
+ this._executeOnceBeforeRender(func);
+ }, timeout);
+ }
+ else {
+ this._executeOnceBeforeRender(func);
+ }
+ }
+ /**
+ * This function can help adding any object to the list of data awaited to be ready in order to check for a complete scene loading.
+ * @param data defines the object to wait for
+ */
+ addPendingData(data) {
+ this._pendingData.push(data);
+ }
+ /**
+ * Remove a pending data from the loading list which has previously been added with addPendingData.
+ * @param data defines the object to remove from the pending list
+ */
+ removePendingData(data) {
+ const wasLoading = this.isLoading;
+ const index = this._pendingData.indexOf(data);
+ if (index !== -1) {
+ this._pendingData.splice(index, 1);
+ }
+ if (wasLoading && !this.isLoading) {
+ this.onDataLoadedObservable.notifyObservers(this);
+ }
+ }
+ /**
+ * Returns the number of items waiting to be loaded
+ * @returns the number of items waiting to be loaded
+ */
+ getWaitingItemsCount() {
+ return this._pendingData.length;
+ }
+ /**
+ * Returns a boolean indicating if the scene is still loading data
+ */
+ get isLoading() {
+ return this._pendingData.length > 0;
+ }
+ /**
+ * Registers a function to be executed when the scene is ready
+ * @param func - the function to be executed
+ * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: false)
+ */
+ executeWhenReady(func, checkRenderTargets = false) {
+ this.onReadyObservable.addOnce(func);
+ if (this._executeWhenReadyTimeoutId !== null) {
+ return;
+ }
+ this._checkIsReady(checkRenderTargets);
+ }
+ /**
+ * Returns a promise that resolves when the scene is ready
+ * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: false)
+ * @returns A promise that resolves when the scene is ready
+ */
+ whenReadyAsync(checkRenderTargets = false) {
+ return new Promise((resolve) => {
+ this.executeWhenReady(() => {
+ resolve();
+ }, checkRenderTargets);
+ });
+ }
+ /**
+ * @internal
+ */
+ _checkIsReady(checkRenderTargets = false) {
+ this._registerTransientComponents();
+ if (this.isReady(checkRenderTargets)) {
+ this.onReadyObservable.notifyObservers(this);
+ this.onReadyObservable.clear();
+ this._executeWhenReadyTimeoutId = null;
+ return;
+ }
+ if (this._isDisposed) {
+ this.onReadyObservable.clear();
+ this._executeWhenReadyTimeoutId = null;
+ return;
+ }
+ this._executeWhenReadyTimeoutId = setTimeout(() => {
+ // Ensure materials effects are checked outside render loops
+ this.incrementRenderId();
+ this._checkIsReady(checkRenderTargets);
+ }, 100);
+ }
+ /**
+ * Gets all animatable attached to the scene
+ */
+ get animatables() {
+ return this._activeAnimatables;
+ }
+ /**
+ * Resets the last animation time frame.
+ * Useful to override when animations start running when loading a scene for the first time.
+ */
+ resetLastAnimationTimeFrame() {
+ this._animationTimeLast = PrecisionDate.Now;
+ }
+ // Matrix
+ /**
+ * Gets the current view matrix
+ * @returns a Matrix
+ */
+ getViewMatrix() {
+ return this._viewMatrix;
+ }
+ /**
+ * Gets the current projection matrix
+ * @returns a Matrix
+ */
+ getProjectionMatrix() {
+ return this._projectionMatrix;
+ }
+ /**
+ * Gets the current transform matrix
+ * @returns a Matrix made of View * Projection
+ */
+ getTransformMatrix() {
+ return this._transformMatrix;
+ }
+ /**
+ * Sets the current transform matrix
+ * @param viewL defines the View matrix to use
+ * @param projectionL defines the Projection matrix to use
+ * @param viewR defines the right View matrix to use (if provided)
+ * @param projectionR defines the right Projection matrix to use (if provided)
+ */
+ setTransformMatrix(viewL, projectionL, viewR, projectionR) {
+ // clear the multiviewSceneUbo if no viewR and projectionR are defined
+ if (!viewR && !projectionR && this._multiviewSceneUbo) {
+ this._multiviewSceneUbo.dispose();
+ this._multiviewSceneUbo = null;
+ }
+ if (this._viewUpdateFlag === viewL.updateFlag && this._projectionUpdateFlag === projectionL.updateFlag) {
+ return;
+ }
+ this._viewUpdateFlag = viewL.updateFlag;
+ this._projectionUpdateFlag = projectionL.updateFlag;
+ this._viewMatrix = viewL;
+ this._projectionMatrix = projectionL;
+ this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
+ // Update frustum
+ if (!this._frustumPlanes) {
+ this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
+ }
+ else {
+ Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
+ }
+ if (this._multiviewSceneUbo && this._multiviewSceneUbo.useUbo) {
+ this._updateMultiviewUbo(viewR, projectionR);
+ }
+ else if (this._sceneUbo.useUbo) {
+ this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
+ this._sceneUbo.updateMatrix("view", this._viewMatrix);
+ this._sceneUbo.updateMatrix("projection", this._projectionMatrix);
+ }
+ }
+ /**
+ * Gets the uniform buffer used to store scene data
+ * @returns a UniformBuffer
+ */
+ getSceneUniformBuffer() {
+ return this._multiviewSceneUbo ? this._multiviewSceneUbo : this._sceneUbo;
+ }
+ /**
+ * Creates a scene UBO
+ * @param name name of the uniform buffer (optional, for debugging purpose only)
+ * @returns a new ubo
+ */
+ createSceneUniformBuffer(name) {
+ const sceneUbo = new UniformBuffer(this._engine, undefined, false, name ?? "scene");
+ sceneUbo.addUniform("viewProjection", 16);
+ sceneUbo.addUniform("view", 16);
+ sceneUbo.addUniform("projection", 16);
+ sceneUbo.addUniform("vEyePosition", 4);
+ return sceneUbo;
+ }
+ /**
+ * Sets the scene ubo
+ * @param ubo the ubo to set for the scene
+ */
+ setSceneUniformBuffer(ubo) {
+ this._sceneUbo = ubo;
+ this._viewUpdateFlag = -1;
+ this._projectionUpdateFlag = -1;
+ }
+ /**
+ * Gets an unique (relatively to the current scene) Id
+ * @returns an unique number for the scene
+ */
+ getUniqueId() {
+ return UniqueIdGenerator.UniqueId;
+ }
+ /**
+ * Add a mesh to the list of scene's meshes
+ * @param newMesh defines the mesh to add
+ * @param recursive if all child meshes should also be added to the scene
+ */
+ addMesh(newMesh, recursive = false) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.meshes.push(newMesh);
+ newMesh._resyncLightSources();
+ if (!newMesh.parent) {
+ newMesh._addToSceneRootNodes();
+ }
+ Tools.SetImmediate(() => {
+ this.onNewMeshAddedObservable.notifyObservers(newMesh);
+ });
+ if (recursive) {
+ newMesh.getChildMeshes().forEach((m) => {
+ this.addMesh(m);
+ });
+ }
+ }
+ /**
+ * Remove a mesh for the list of scene's meshes
+ * @param toRemove defines the mesh to remove
+ * @param recursive if all child meshes should also be removed from the scene
+ * @returns the index where the mesh was in the mesh list
+ */
+ removeMesh(toRemove, recursive = false) {
+ const index = this.meshes.indexOf(toRemove);
+ if (index !== -1) {
+ // Remove from the scene if the mesh found
+ this.meshes.splice(index, 1);
+ if (!toRemove.parent) {
+ toRemove._removeFromSceneRootNodes();
+ }
+ }
+ this._inputManager._invalidateMesh(toRemove);
+ this.onMeshRemovedObservable.notifyObservers(toRemove);
+ if (recursive) {
+ toRemove.getChildMeshes().forEach((m) => {
+ this.removeMesh(m);
+ });
+ }
+ return index;
+ }
+ /**
+ * Add a transform node to the list of scene's transform nodes
+ * @param newTransformNode defines the transform node to add
+ */
+ addTransformNode(newTransformNode) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ if (newTransformNode.getScene() === this && newTransformNode._indexInSceneTransformNodesArray !== -1) {
+ // Already there?
+ return;
+ }
+ newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
+ this.transformNodes.push(newTransformNode);
+ if (!newTransformNode.parent) {
+ newTransformNode._addToSceneRootNodes();
+ }
+ this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
+ }
+ /**
+ * Remove a transform node for the list of scene's transform nodes
+ * @param toRemove defines the transform node to remove
+ * @returns the index where the transform node was in the transform node list
+ */
+ removeTransformNode(toRemove) {
+ const index = toRemove._indexInSceneTransformNodesArray;
+ if (index !== -1) {
+ if (index !== this.transformNodes.length - 1) {
+ const lastNode = this.transformNodes[this.transformNodes.length - 1];
+ this.transformNodes[index] = lastNode;
+ lastNode._indexInSceneTransformNodesArray = index;
+ }
+ toRemove._indexInSceneTransformNodesArray = -1;
+ this.transformNodes.pop();
+ if (!toRemove.parent) {
+ toRemove._removeFromSceneRootNodes();
+ }
+ }
+ this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
+ return index;
+ }
+ /**
+ * Remove a skeleton for the list of scene's skeletons
+ * @param toRemove defines the skeleton to remove
+ * @returns the index where the skeleton was in the skeleton list
+ */
+ removeSkeleton(toRemove) {
+ const index = this.skeletons.indexOf(toRemove);
+ if (index !== -1) {
+ // Remove from the scene if found
+ this.skeletons.splice(index, 1);
+ this.onSkeletonRemovedObservable.notifyObservers(toRemove);
+ // Clean active container
+ this._executeActiveContainerCleanup(this._activeSkeletons);
+ }
+ return index;
+ }
+ /**
+ * Remove a morph target for the list of scene's morph targets
+ * @param toRemove defines the morph target to remove
+ * @returns the index where the morph target was in the morph target list
+ */
+ removeMorphTargetManager(toRemove) {
+ const index = this.morphTargetManagers.indexOf(toRemove);
+ if (index !== -1) {
+ // Remove from the scene if found
+ this.morphTargetManagers.splice(index, 1);
+ }
+ return index;
+ }
+ /**
+ * Remove a light for the list of scene's lights
+ * @param toRemove defines the light to remove
+ * @returns the index where the light was in the light list
+ */
+ removeLight(toRemove) {
+ const index = this.lights.indexOf(toRemove);
+ if (index !== -1) {
+ // Remove from meshes
+ for (const mesh of this.meshes) {
+ mesh._removeLightSource(toRemove, false);
+ }
+ // Remove from the scene if mesh found
+ this.lights.splice(index, 1);
+ this.sortLightsByPriority();
+ if (!toRemove.parent) {
+ toRemove._removeFromSceneRootNodes();
+ }
+ }
+ this.onLightRemovedObservable.notifyObservers(toRemove);
+ return index;
+ }
+ /**
+ * Remove a camera for the list of scene's cameras
+ * @param toRemove defines the camera to remove
+ * @returns the index where the camera was in the camera list
+ */
+ removeCamera(toRemove) {
+ const index = this.cameras.indexOf(toRemove);
+ if (index !== -1) {
+ // Remove from the scene if mesh found
+ this.cameras.splice(index, 1);
+ if (!toRemove.parent) {
+ toRemove._removeFromSceneRootNodes();
+ }
+ }
+ // Remove from activeCameras
+ if (this.activeCameras) {
+ const index2 = this.activeCameras.indexOf(toRemove);
+ if (index2 !== -1) {
+ // Remove from the scene if mesh found
+ this.activeCameras.splice(index2, 1);
+ }
+ }
+ // Reset the activeCamera
+ if (this.activeCamera === toRemove) {
+ if (this.cameras.length > 0) {
+ this.activeCamera = this.cameras[0];
+ }
+ else {
+ this.activeCamera = null;
+ }
+ }
+ this.onCameraRemovedObservable.notifyObservers(toRemove);
+ return index;
+ }
+ /**
+ * Remove a particle system for the list of scene's particle systems
+ * @param toRemove defines the particle system to remove
+ * @returns the index where the particle system was in the particle system list
+ */
+ removeParticleSystem(toRemove) {
+ const index = this.particleSystems.indexOf(toRemove);
+ if (index !== -1) {
+ this.particleSystems.splice(index, 1);
+ // Clean active container
+ this._executeActiveContainerCleanup(this._activeParticleSystems);
+ }
+ return index;
+ }
+ /**
+ * Remove a animation for the list of scene's animations
+ * @param toRemove defines the animation to remove
+ * @returns the index where the animation was in the animation list
+ */
+ removeAnimation(toRemove) {
+ const index = this.animations.indexOf(toRemove);
+ if (index !== -1) {
+ this.animations.splice(index, 1);
+ }
+ return index;
+ }
+ /**
+ * Will stop the animation of the given target
+ * @param target - the target
+ * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
+ * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
+ */
+ stopAnimation(target, animationName, targetMask) {
+ // Do nothing as code will be provided by animation component
+ }
+ /**
+ * Removes the given animation group from this scene.
+ * @param toRemove The animation group to remove
+ * @returns The index of the removed animation group
+ */
+ removeAnimationGroup(toRemove) {
+ const index = this.animationGroups.indexOf(toRemove);
+ if (index !== -1) {
+ this.animationGroups.splice(index, 1);
+ }
+ return index;
+ }
+ /**
+ * Removes the given multi-material from this scene.
+ * @param toRemove The multi-material to remove
+ * @returns The index of the removed multi-material
+ */
+ removeMultiMaterial(toRemove) {
+ const index = this.multiMaterials.indexOf(toRemove);
+ if (index !== -1) {
+ this.multiMaterials.splice(index, 1);
+ }
+ this.onMultiMaterialRemovedObservable.notifyObservers(toRemove);
+ return index;
+ }
+ /**
+ * Removes the given material from this scene.
+ * @param toRemove The material to remove
+ * @returns The index of the removed material
+ */
+ removeMaterial(toRemove) {
+ const index = toRemove._indexInSceneMaterialArray;
+ if (index !== -1 && index < this.materials.length) {
+ if (index !== this.materials.length - 1) {
+ const lastMaterial = this.materials[this.materials.length - 1];
+ this.materials[index] = lastMaterial;
+ lastMaterial._indexInSceneMaterialArray = index;
+ }
+ toRemove._indexInSceneMaterialArray = -1;
+ this.materials.pop();
+ }
+ this.onMaterialRemovedObservable.notifyObservers(toRemove);
+ return index;
+ }
+ /**
+ * Removes the given action manager from this scene.
+ * @deprecated
+ * @param toRemove The action manager to remove
+ * @returns The index of the removed action manager
+ */
+ removeActionManager(toRemove) {
+ const index = this.actionManagers.indexOf(toRemove);
+ if (index !== -1) {
+ this.actionManagers.splice(index, 1);
+ }
+ return index;
+ }
+ /**
+ * Removes the given texture from this scene.
+ * @param toRemove The texture to remove
+ * @returns The index of the removed texture
+ */
+ removeTexture(toRemove) {
+ const index = this.textures.indexOf(toRemove);
+ if (index !== -1) {
+ this.textures.splice(index, 1);
+ }
+ this.onTextureRemovedObservable.notifyObservers(toRemove);
+ return index;
+ }
+ /**
+ * Adds the given light to this scene
+ * @param newLight The light to add
+ */
+ addLight(newLight) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.lights.push(newLight);
+ this.sortLightsByPriority();
+ if (!newLight.parent) {
+ newLight._addToSceneRootNodes();
+ }
+ // Add light to all meshes (To support if the light is removed and then re-added)
+ for (const mesh of this.meshes) {
+ if (mesh.lightSources.indexOf(newLight) === -1) {
+ mesh.lightSources.push(newLight);
+ mesh._resyncLightSources();
+ }
+ }
+ Tools.SetImmediate(() => {
+ this.onNewLightAddedObservable.notifyObservers(newLight);
+ });
+ }
+ /**
+ * Sorts the list list based on light priorities
+ */
+ sortLightsByPriority() {
+ if (this.requireLightSorting) {
+ this.lights.sort(LightConstants.CompareLightsPriority);
+ }
+ }
+ /**
+ * Adds the given camera to this scene
+ * @param newCamera The camera to add
+ */
+ addCamera(newCamera) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.cameras.push(newCamera);
+ Tools.SetImmediate(() => {
+ this.onNewCameraAddedObservable.notifyObservers(newCamera);
+ });
+ if (!newCamera.parent) {
+ newCamera._addToSceneRootNodes();
+ }
+ }
+ /**
+ * Adds the given skeleton to this scene
+ * @param newSkeleton The skeleton to add
+ */
+ addSkeleton(newSkeleton) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.skeletons.push(newSkeleton);
+ Tools.SetImmediate(() => {
+ this.onNewSkeletonAddedObservable.notifyObservers(newSkeleton);
+ });
+ }
+ /**
+ * Adds the given particle system to this scene
+ * @param newParticleSystem The particle system to add
+ */
+ addParticleSystem(newParticleSystem) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.particleSystems.push(newParticleSystem);
+ }
+ /**
+ * Adds the given animation to this scene
+ * @param newAnimation The animation to add
+ */
+ addAnimation(newAnimation) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.animations.push(newAnimation);
+ }
+ /**
+ * Adds the given animation group to this scene.
+ * @param newAnimationGroup The animation group to add
+ */
+ addAnimationGroup(newAnimationGroup) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.animationGroups.push(newAnimationGroup);
+ }
+ /**
+ * Adds the given multi-material to this scene
+ * @param newMultiMaterial The multi-material to add
+ */
+ addMultiMaterial(newMultiMaterial) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.multiMaterials.push(newMultiMaterial);
+ Tools.SetImmediate(() => {
+ this.onNewMultiMaterialAddedObservable.notifyObservers(newMultiMaterial);
+ });
+ }
+ /**
+ * Adds the given material to this scene
+ * @param newMaterial The material to add
+ */
+ addMaterial(newMaterial) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ if (newMaterial.getScene() === this && newMaterial._indexInSceneMaterialArray !== -1) {
+ // Already there??
+ return;
+ }
+ newMaterial._indexInSceneMaterialArray = this.materials.length;
+ this.materials.push(newMaterial);
+ Tools.SetImmediate(() => {
+ this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
+ });
+ }
+ /**
+ * Adds the given morph target to this scene
+ * @param newMorphTargetManager The morph target to add
+ */
+ addMorphTargetManager(newMorphTargetManager) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.morphTargetManagers.push(newMorphTargetManager);
+ }
+ /**
+ * Adds the given geometry to this scene
+ * @param newGeometry The geometry to add
+ */
+ addGeometry(newGeometry) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ if (this._geometriesByUniqueId) {
+ this._geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length;
+ }
+ this.geometries.push(newGeometry);
+ }
+ /**
+ * Adds the given action manager to this scene
+ * @deprecated
+ * @param newActionManager The action manager to add
+ */
+ addActionManager(newActionManager) {
+ this.actionManagers.push(newActionManager);
+ }
+ /**
+ * Adds the given texture to this scene.
+ * @param newTexture The texture to add
+ */
+ addTexture(newTexture) {
+ if (this._blockEntityCollection) {
+ return;
+ }
+ this.textures.push(newTexture);
+ this.onNewTextureAddedObservable.notifyObservers(newTexture);
+ }
+ /**
+ * Switch active camera
+ * @param newCamera defines the new active camera
+ * @param attachControl defines if attachControl must be called for the new active camera (default: true)
+ */
+ switchActiveCamera(newCamera, attachControl = true) {
+ const canvas = this._engine.getInputElement();
+ if (!canvas) {
+ return;
+ }
+ if (this.activeCamera) {
+ this.activeCamera.detachControl();
+ }
+ this.activeCamera = newCamera;
+ if (attachControl) {
+ newCamera.attachControl();
+ }
+ }
+ /**
+ * sets the active camera of the scene using its Id
+ * @param id defines the camera's Id
+ * @returns the new active camera or null if none found.
+ */
+ setActiveCameraById(id) {
+ const camera = this.getCameraById(id);
+ if (camera) {
+ this.activeCamera = camera;
+ return camera;
+ }
+ return null;
+ }
+ /**
+ * sets the active camera of the scene using its name
+ * @param name defines the camera's name
+ * @returns the new active camera or null if none found.
+ */
+ setActiveCameraByName(name) {
+ const camera = this.getCameraByName(name);
+ if (camera) {
+ this.activeCamera = camera;
+ return camera;
+ }
+ return null;
+ }
+ /**
+ * get an animation group using its name
+ * @param name defines the material's name
+ * @returns the animation group or null if none found.
+ */
+ getAnimationGroupByName(name) {
+ for (let index = 0; index < this.animationGroups.length; index++) {
+ if (this.animationGroups[index].name === name) {
+ return this.animationGroups[index];
+ }
+ }
+ return null;
+ }
+ _getMaterial(allowMultiMaterials, predicate) {
+ for (let index = 0; index < this.materials.length; index++) {
+ const material = this.materials[index];
+ if (predicate(material)) {
+ return material;
+ }
+ }
+ if (allowMultiMaterials) {
+ for (let index = 0; index < this.multiMaterials.length; index++) {
+ const material = this.multiMaterials[index];
+ if (predicate(material)) {
+ return material;
+ }
+ }
+ }
+ return null;
+ }
+ /**
+ * Get a material using its unique id
+ * @param uniqueId defines the material's unique id
+ * @param allowMultiMaterials determines whether multimaterials should be considered
+ * @returns the material or null if none found.
+ */
+ getMaterialByUniqueID(uniqueId, allowMultiMaterials = false) {
+ return this._getMaterial(allowMultiMaterials, (m) => m.uniqueId === uniqueId);
+ }
+ /**
+ * get a material using its id
+ * @param id defines the material's Id
+ * @param allowMultiMaterials determines whether multimaterials should be considered
+ * @returns the material or null if none found.
+ */
+ getMaterialById(id, allowMultiMaterials = false) {
+ return this._getMaterial(allowMultiMaterials, (m) => m.id === id);
+ }
+ /**
+ * Gets a material using its name
+ * @param name defines the material's name
+ * @param allowMultiMaterials determines whether multimaterials should be considered
+ * @returns the material or null if none found.
+ */
+ getMaterialByName(name, allowMultiMaterials = false) {
+ return this._getMaterial(allowMultiMaterials, (m) => m.name === name);
+ }
+ /**
+ * Gets a last added material using a given id
+ * @param id defines the material's id
+ * @param allowMultiMaterials determines whether multimaterials should be considered
+ * @returns the last material with the given id or null if none found.
+ */
+ getLastMaterialById(id, allowMultiMaterials = false) {
+ for (let index = this.materials.length - 1; index >= 0; index--) {
+ if (this.materials[index].id === id) {
+ return this.materials[index];
+ }
+ }
+ if (allowMultiMaterials) {
+ for (let index = this.multiMaterials.length - 1; index >= 0; index--) {
+ if (this.multiMaterials[index].id === id) {
+ return this.multiMaterials[index];
+ }
+ }
+ }
+ return null;
+ }
+ /**
+ * Get a texture using its unique id
+ * @param uniqueId defines the texture's unique id
+ * @returns the texture or null if none found.
+ */
+ getTextureByUniqueId(uniqueId) {
+ for (let index = 0; index < this.textures.length; index++) {
+ if (this.textures[index].uniqueId === uniqueId) {
+ return this.textures[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a texture using its name
+ * @param name defines the texture's name
+ * @returns the texture or null if none found.
+ */
+ getTextureByName(name) {
+ for (let index = 0; index < this.textures.length; index++) {
+ if (this.textures[index].name === name) {
+ return this.textures[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a camera using its Id
+ * @param id defines the Id to look for
+ * @returns the camera or null if not found
+ */
+ getCameraById(id) {
+ for (let index = 0; index < this.cameras.length; index++) {
+ if (this.cameras[index].id === id) {
+ return this.cameras[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a camera using its unique Id
+ * @param uniqueId defines the unique Id to look for
+ * @returns the camera or null if not found
+ */
+ getCameraByUniqueId(uniqueId) {
+ for (let index = 0; index < this.cameras.length; index++) {
+ if (this.cameras[index].uniqueId === uniqueId) {
+ return this.cameras[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a camera using its name
+ * @param name defines the camera's name
+ * @returns the camera or null if none found.
+ */
+ getCameraByName(name) {
+ for (let index = 0; index < this.cameras.length; index++) {
+ if (this.cameras[index].name === name) {
+ return this.cameras[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a bone using its Id
+ * @param id defines the bone's Id
+ * @returns the bone or null if not found
+ */
+ getBoneById(id) {
+ for (let skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
+ const skeleton = this.skeletons[skeletonIndex];
+ for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
+ if (skeleton.bones[boneIndex].id === id) {
+ return skeleton.bones[boneIndex];
+ }
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a bone using its id
+ * @param name defines the bone's name
+ * @returns the bone or null if not found
+ */
+ getBoneByName(name) {
+ for (let skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
+ const skeleton = this.skeletons[skeletonIndex];
+ for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
+ if (skeleton.bones[boneIndex].name === name) {
+ return skeleton.bones[boneIndex];
+ }
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a light node using its name
+ * @param name defines the light's name
+ * @returns the light or null if none found.
+ */
+ getLightByName(name) {
+ for (let index = 0; index < this.lights.length; index++) {
+ if (this.lights[index].name === name) {
+ return this.lights[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a light node using its Id
+ * @param id defines the light's Id
+ * @returns the light or null if none found.
+ */
+ getLightById(id) {
+ for (let index = 0; index < this.lights.length; index++) {
+ if (this.lights[index].id === id) {
+ return this.lights[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a light node using its scene-generated unique Id
+ * @param uniqueId defines the light's unique Id
+ * @returns the light or null if none found.
+ */
+ getLightByUniqueId(uniqueId) {
+ for (let index = 0; index < this.lights.length; index++) {
+ if (this.lights[index].uniqueId === uniqueId) {
+ return this.lights[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a particle system by Id
+ * @param id defines the particle system Id
+ * @returns the corresponding system or null if none found
+ */
+ getParticleSystemById(id) {
+ for (let index = 0; index < this.particleSystems.length; index++) {
+ if (this.particleSystems[index].id === id) {
+ return this.particleSystems[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a geometry using its Id
+ * @param id defines the geometry's Id
+ * @returns the geometry or null if none found.
+ */
+ getGeometryById(id) {
+ for (let index = 0; index < this.geometries.length; index++) {
+ if (this.geometries[index].id === id) {
+ return this.geometries[index];
+ }
+ }
+ return null;
+ }
+ _getGeometryByUniqueId(uniqueId) {
+ if (this._geometriesByUniqueId) {
+ const index = this._geometriesByUniqueId[uniqueId];
+ if (index !== undefined) {
+ return this.geometries[index];
+ }
+ }
+ else {
+ for (let index = 0; index < this.geometries.length; index++) {
+ if (this.geometries[index].uniqueId === uniqueId) {
+ return this.geometries[index];
+ }
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a frame graph using its name
+ * @param name defines the frame graph's name
+ * @returns the frame graph or null if none found.
+ */
+ getFrameGraphByName(name) {
+ for (let index = 0; index < this.frameGraphs.length; index++) {
+ if (this.frameGraphs[index].name === name) {
+ return this.frameGraphs[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Add a new geometry to this scene
+ * @param geometry defines the geometry to be added to the scene.
+ * @param force defines if the geometry must be pushed even if a geometry with this id already exists
+ * @returns a boolean defining if the geometry was added or not
+ */
+ pushGeometry(geometry, force) {
+ if (!force && this._getGeometryByUniqueId(geometry.uniqueId)) {
+ return false;
+ }
+ this.addGeometry(geometry);
+ Tools.SetImmediate(() => {
+ this.onNewGeometryAddedObservable.notifyObservers(geometry);
+ });
+ return true;
+ }
+ /**
+ * Removes an existing geometry
+ * @param geometry defines the geometry to be removed from the scene
+ * @returns a boolean defining if the geometry was removed or not
+ */
+ removeGeometry(geometry) {
+ let index;
+ if (this._geometriesByUniqueId) {
+ index = this._geometriesByUniqueId[geometry.uniqueId];
+ if (index === undefined) {
+ return false;
+ }
+ }
+ else {
+ index = this.geometries.indexOf(geometry);
+ if (index < 0) {
+ return false;
+ }
+ }
+ if (index !== this.geometries.length - 1) {
+ const lastGeometry = this.geometries[this.geometries.length - 1];
+ if (lastGeometry) {
+ this.geometries[index] = lastGeometry;
+ if (this._geometriesByUniqueId) {
+ this._geometriesByUniqueId[lastGeometry.uniqueId] = index;
+ }
+ }
+ }
+ if (this._geometriesByUniqueId) {
+ this._geometriesByUniqueId[geometry.uniqueId] = undefined;
+ }
+ this.geometries.pop();
+ this.onGeometryRemovedObservable.notifyObservers(geometry);
+ return true;
+ }
+ /**
+ * Gets the list of geometries attached to the scene
+ * @returns an array of Geometry
+ */
+ getGeometries() {
+ return this.geometries;
+ }
+ /**
+ * Gets the first added mesh found of a given Id
+ * @param id defines the Id to search for
+ * @returns the mesh found or null if not found at all
+ */
+ getMeshById(id) {
+ for (let index = 0; index < this.meshes.length; index++) {
+ if (this.meshes[index].id === id) {
+ return this.meshes[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a list of meshes using their Id
+ * @param id defines the Id to search for
+ * @returns a list of meshes
+ */
+ getMeshesById(id) {
+ return this.meshes.filter(function (m) {
+ return m.id === id;
+ });
+ }
+ /**
+ * Gets the first added transform node found of a given Id
+ * @param id defines the Id to search for
+ * @returns the found transform node or null if not found at all.
+ */
+ getTransformNodeById(id) {
+ for (let index = 0; index < this.transformNodes.length; index++) {
+ if (this.transformNodes[index].id === id) {
+ return this.transformNodes[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a transform node with its auto-generated unique Id
+ * @param uniqueId defines the unique Id to search for
+ * @returns the found transform node or null if not found at all.
+ */
+ getTransformNodeByUniqueId(uniqueId) {
+ for (let index = 0; index < this.transformNodes.length; index++) {
+ if (this.transformNodes[index].uniqueId === uniqueId) {
+ return this.transformNodes[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a list of transform nodes using their Id
+ * @param id defines the Id to search for
+ * @returns a list of transform nodes
+ */
+ getTransformNodesById(id) {
+ return this.transformNodes.filter(function (m) {
+ return m.id === id;
+ });
+ }
+ /**
+ * Gets a mesh with its auto-generated unique Id
+ * @param uniqueId defines the unique Id to search for
+ * @returns the found mesh or null if not found at all.
+ */
+ getMeshByUniqueId(uniqueId) {
+ for (let index = 0; index < this.meshes.length; index++) {
+ if (this.meshes[index].uniqueId === uniqueId) {
+ return this.meshes[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a the last added mesh using a given Id
+ * @param id defines the Id to search for
+ * @returns the found mesh or null if not found at all.
+ */
+ getLastMeshById(id) {
+ for (let index = this.meshes.length - 1; index >= 0; index--) {
+ if (this.meshes[index].id === id) {
+ return this.meshes[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a the last transform node using a given Id
+ * @param id defines the Id to search for
+ * @returns the found mesh or null if not found at all.
+ */
+ getLastTransformNodeById(id) {
+ for (let index = this.transformNodes.length - 1; index >= 0; index--) {
+ if (this.transformNodes[index].id === id) {
+ return this.transformNodes[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a the last added node (Mesh, Camera, Light) using a given Id
+ * @param id defines the Id to search for
+ * @returns the found node or null if not found at all
+ */
+ getLastEntryById(id) {
+ let index;
+ for (index = this.meshes.length - 1; index >= 0; index--) {
+ if (this.meshes[index].id === id) {
+ return this.meshes[index];
+ }
+ }
+ for (index = this.transformNodes.length - 1; index >= 0; index--) {
+ if (this.transformNodes[index].id === id) {
+ return this.transformNodes[index];
+ }
+ }
+ for (index = this.cameras.length - 1; index >= 0; index--) {
+ if (this.cameras[index].id === id) {
+ return this.cameras[index];
+ }
+ }
+ for (index = this.lights.length - 1; index >= 0; index--) {
+ if (this.lights[index].id === id) {
+ return this.lights[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a node (Mesh, Camera, Light) using a given Id
+ * @param id defines the Id to search for
+ * @returns the found node or null if not found at all
+ */
+ getNodeById(id) {
+ const mesh = this.getMeshById(id);
+ if (mesh) {
+ return mesh;
+ }
+ const transformNode = this.getTransformNodeById(id);
+ if (transformNode) {
+ return transformNode;
+ }
+ const light = this.getLightById(id);
+ if (light) {
+ return light;
+ }
+ const camera = this.getCameraById(id);
+ if (camera) {
+ return camera;
+ }
+ const bone = this.getBoneById(id);
+ if (bone) {
+ return bone;
+ }
+ return null;
+ }
+ /**
+ * Gets a node (Mesh, Camera, Light) using a given name
+ * @param name defines the name to search for
+ * @returns the found node or null if not found at all.
+ */
+ getNodeByName(name) {
+ const mesh = this.getMeshByName(name);
+ if (mesh) {
+ return mesh;
+ }
+ const transformNode = this.getTransformNodeByName(name);
+ if (transformNode) {
+ return transformNode;
+ }
+ const light = this.getLightByName(name);
+ if (light) {
+ return light;
+ }
+ const camera = this.getCameraByName(name);
+ if (camera) {
+ return camera;
+ }
+ const bone = this.getBoneByName(name);
+ if (bone) {
+ return bone;
+ }
+ return null;
+ }
+ /**
+ * Gets a mesh using a given name
+ * @param name defines the name to search for
+ * @returns the found mesh or null if not found at all.
+ */
+ getMeshByName(name) {
+ for (let index = 0; index < this.meshes.length; index++) {
+ if (this.meshes[index].name === name) {
+ return this.meshes[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a transform node using a given name
+ * @param name defines the name to search for
+ * @returns the found transform node or null if not found at all.
+ */
+ getTransformNodeByName(name) {
+ for (let index = 0; index < this.transformNodes.length; index++) {
+ if (this.transformNodes[index].name === name) {
+ return this.transformNodes[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a skeleton using a given Id (if many are found, this function will pick the last one)
+ * @param id defines the Id to search for
+ * @returns the found skeleton or null if not found at all.
+ */
+ getLastSkeletonById(id) {
+ for (let index = this.skeletons.length - 1; index >= 0; index--) {
+ if (this.skeletons[index].id === id) {
+ return this.skeletons[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a skeleton using a given auto generated unique id
+ * @param uniqueId defines the unique id to search for
+ * @returns the found skeleton or null if not found at all.
+ */
+ getSkeletonByUniqueId(uniqueId) {
+ for (let index = 0; index < this.skeletons.length; index++) {
+ if (this.skeletons[index].uniqueId === uniqueId) {
+ return this.skeletons[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a skeleton using a given id (if many are found, this function will pick the first one)
+ * @param id defines the id to search for
+ * @returns the found skeleton or null if not found at all.
+ */
+ getSkeletonById(id) {
+ for (let index = 0; index < this.skeletons.length; index++) {
+ if (this.skeletons[index].id === id) {
+ return this.skeletons[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a skeleton using a given name
+ * @param name defines the name to search for
+ * @returns the found skeleton or null if not found at all.
+ */
+ getSkeletonByName(name) {
+ for (let index = 0; index < this.skeletons.length; index++) {
+ if (this.skeletons[index].name === name) {
+ return this.skeletons[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
+ * @param id defines the id to search for
+ * @returns the found morph target manager or null if not found at all.
+ */
+ getMorphTargetManagerById(id) {
+ for (let index = 0; index < this.morphTargetManagers.length; index++) {
+ if (this.morphTargetManagers[index].uniqueId === id) {
+ return this.morphTargetManagers[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a morph target using a given id (if many are found, this function will pick the first one)
+ * @param id defines the id to search for
+ * @returns the found morph target or null if not found at all.
+ */
+ getMorphTargetById(id) {
+ for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) {
+ const morphTargetManager = this.morphTargetManagers[managerIndex];
+ for (let index = 0; index < morphTargetManager.numTargets; ++index) {
+ const target = morphTargetManager.getTarget(index);
+ if (target.id === id) {
+ return target;
+ }
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a morph target using a given name (if many are found, this function will pick the first one)
+ * @param name defines the name to search for
+ * @returns the found morph target or null if not found at all.
+ */
+ getMorphTargetByName(name) {
+ for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) {
+ const morphTargetManager = this.morphTargetManagers[managerIndex];
+ for (let index = 0; index < morphTargetManager.numTargets; ++index) {
+ const target = morphTargetManager.getTarget(index);
+ if (target.name === name) {
+ return target;
+ }
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a post process using a given name (if many are found, this function will pick the first one)
+ * @param name defines the name to search for
+ * @returns the found post process or null if not found at all.
+ */
+ getPostProcessByName(name) {
+ for (let postProcessIndex = 0; postProcessIndex < this.postProcesses.length; ++postProcessIndex) {
+ const postProcess = this.postProcesses[postProcessIndex];
+ if (postProcess.name === name) {
+ return postProcess;
+ }
+ }
+ return null;
+ }
+ /**
+ * Gets a boolean indicating if the given mesh is active
+ * @param mesh defines the mesh to look for
+ * @returns true if the mesh is in the active list
+ */
+ isActiveMesh(mesh) {
+ return this._activeMeshes.indexOf(mesh) !== -1;
+ }
+ /**
+ * Return a unique id as a string which can serve as an identifier for the scene
+ */
+ get uid() {
+ if (!this._uid) {
+ this._uid = Tools.RandomId();
+ }
+ return this._uid;
+ }
+ /**
+ * Add an externally attached data from its key.
+ * This method call will fail and return false, if such key already exists.
+ * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
+ * @param key the unique key that identifies the data
+ * @param data the data object to associate to the key for this Engine instance
+ * @returns true if no such key were already present and the data was added successfully, false otherwise
+ */
+ addExternalData(key, data) {
+ if (!this._externalData) {
+ this._externalData = new StringDictionary();
+ }
+ return this._externalData.add(key, data);
+ }
+ /**
+ * Get an externally attached data from its key
+ * @param key the unique key that identifies the data
+ * @returns the associated data, if present (can be null), or undefined if not present
+ */
+ getExternalData(key) {
+ if (!this._externalData) {
+ return null;
+ }
+ return this._externalData.get(key);
+ }
+ /**
+ * Get an externally attached data from its key, create it using a factory if it's not already present
+ * @param key the unique key that identifies the data
+ * @param factory the factory that will be called to create the instance if and only if it doesn't exists
+ * @returns the associated data, can be null if the factory returned null.
+ */
+ getOrAddExternalDataWithFactory(key, factory) {
+ if (!this._externalData) {
+ this._externalData = new StringDictionary();
+ }
+ return this._externalData.getOrAddWithFactory(key, factory);
+ }
+ /**
+ * Remove an externally attached data from the Engine instance
+ * @param key the unique key that identifies the data
+ * @returns true if the data was successfully removed, false if it doesn't exist
+ */
+ removeExternalData(key) {
+ return this._externalData.remove(key);
+ }
+ _evaluateSubMesh(subMesh, mesh, initialMesh, forcePush) {
+ if (forcePush || subMesh.isInFrustum(this._frustumPlanes)) {
+ for (const step of this._evaluateSubMeshStage) {
+ step.action(mesh, subMesh);
+ }
+ const material = subMesh.getMaterial();
+ if (material !== null && material !== undefined) {
+ // Render targets
+ if (material.hasRenderTargetTextures && material.getRenderTargetTextures != null) {
+ if (this._processedMaterials.indexOf(material) === -1) {
+ this._processedMaterials.push(material);
+ this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
+ }
+ }
+ // Dispatch
+ this._renderingManager.dispatch(subMesh, mesh, material);
+ }
+ }
+ }
+ /**
+ * Clear the processed materials smart array preventing retention point in material dispose.
+ */
+ freeProcessedMaterials() {
+ this._processedMaterials.dispose();
+ }
+ /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
+ * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
+ * when disposing several meshes in a row or a hierarchy of meshes.
+ * When used, it is the responsibility of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
+ */
+ get blockfreeActiveMeshesAndRenderingGroups() {
+ return this._preventFreeActiveMeshesAndRenderingGroups;
+ }
+ set blockfreeActiveMeshesAndRenderingGroups(value) {
+ if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
+ return;
+ }
+ if (value) {
+ this.freeActiveMeshes();
+ this.freeRenderingGroups();
+ }
+ this._preventFreeActiveMeshesAndRenderingGroups = value;
+ }
+ /**
+ * Clear the active meshes smart array preventing retention point in mesh dispose.
+ */
+ freeActiveMeshes() {
+ if (this.blockfreeActiveMeshesAndRenderingGroups) {
+ return;
+ }
+ this._activeMeshes.dispose();
+ if (this.activeCamera && this.activeCamera._activeMeshes) {
+ this.activeCamera._activeMeshes.dispose();
+ }
+ if (this.activeCameras) {
+ for (let i = 0; i < this.activeCameras.length; i++) {
+ const activeCamera = this.activeCameras[i];
+ if (activeCamera && activeCamera._activeMeshes) {
+ activeCamera._activeMeshes.dispose();
+ }
+ }
+ }
+ }
+ /**
+ * Clear the info related to rendering groups preventing retention points during dispose.
+ */
+ freeRenderingGroups() {
+ if (this.blockfreeActiveMeshesAndRenderingGroups) {
+ return;
+ }
+ if (this._renderingManager) {
+ this._renderingManager.freeRenderingGroups();
+ }
+ if (this.textures) {
+ for (let i = 0; i < this.textures.length; i++) {
+ const texture = this.textures[i];
+ if (texture && texture.renderList) {
+ texture.freeRenderingGroups();
+ }
+ }
+ }
+ }
+ /** @internal */
+ _isInIntermediateRendering() {
+ return this._intermediateRendering;
+ }
+ /**
+ * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
+ * @param skipEvaluateActiveMeshes defines an optional boolean indicating that the evaluate active meshes step must be completely skipped
+ * @param onSuccess optional success callback
+ * @param onError optional error callback
+ * @param freezeMeshes defines if meshes should be frozen (true by default)
+ * @param keepFrustumCulling defines if you want to keep running the frustum clipping (false by default)
+ * @returns the current scene
+ */
+ freezeActiveMeshes(skipEvaluateActiveMeshes = false, onSuccess, onError, freezeMeshes = true, keepFrustumCulling = false) {
+ this.executeWhenReady(() => {
+ if (!this.activeCamera) {
+ onError && onError("No active camera found");
+ return;
+ }
+ if (!this._frustumPlanes) {
+ this.updateTransformMatrix();
+ }
+ this._evaluateActiveMeshes();
+ this._activeMeshesFrozen = true;
+ this._activeMeshesFrozenButKeepClipping = keepFrustumCulling;
+ this._skipEvaluateActiveMeshesCompletely = skipEvaluateActiveMeshes;
+ if (freezeMeshes) {
+ for (let index = 0; index < this._activeMeshes.length; index++) {
+ this._activeMeshes.data[index]._freeze();
+ }
+ }
+ onSuccess && onSuccess();
+ });
+ return this;
+ }
+ /**
+ * Use this function to restart evaluating active meshes on every frame
+ * @returns the current scene
+ */
+ unfreezeActiveMeshes() {
+ for (let index = 0; index < this.meshes.length; index++) {
+ const mesh = this.meshes[index];
+ if (mesh._internalAbstractMeshDataInfo) {
+ mesh._internalAbstractMeshDataInfo._isActive = false;
+ }
+ }
+ for (let index = 0; index < this._activeMeshes.length; index++) {
+ this._activeMeshes.data[index]._unFreeze();
+ }
+ this._activeMeshesFrozen = false;
+ return this;
+ }
+ _executeActiveContainerCleanup(container) {
+ const isInFastMode = this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1;
+ if (!isInFastMode && this._activeMeshesFrozen && this._activeMeshes.length) {
+ return; // Do not execute in frozen mode
+ }
+ // We need to ensure we are not in the rendering loop
+ this.onBeforeRenderObservable.addOnce(() => container.dispose());
+ }
+ _evaluateActiveMeshes() {
+ if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) {
+ if (this._activeMeshes.length > 0) {
+ this.activeCamera?._activeMeshes.reset();
+ this._activeMeshes.reset();
+ this._renderingManager.reset();
+ this._processedMaterials.reset();
+ this._activeParticleSystems.reset();
+ this._activeSkeletons.reset();
+ this._softwareSkinnedMeshes.reset();
+ }
+ return;
+ }
+ if (this._activeMeshesFrozen && this._activeMeshes.length) {
+ if (!this._skipEvaluateActiveMeshesCompletely) {
+ const len = this._activeMeshes.length;
+ for (let i = 0; i < len; i++) {
+ const mesh = this._activeMeshes.data[i];
+ mesh.computeWorldMatrix();
+ }
+ }
+ if (this._activeParticleSystems) {
+ const psLength = this._activeParticleSystems.length;
+ for (let i = 0; i < psLength; i++) {
+ this._activeParticleSystems.data[i].animate();
+ }
+ }
+ this._renderingManager.resetSprites();
+ return;
+ }
+ if (!this.activeCamera) {
+ return;
+ }
+ this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
+ this.activeCamera._activeMeshes.reset();
+ this._activeMeshes.reset();
+ this._renderingManager.reset();
+ this._processedMaterials.reset();
+ this._activeParticleSystems.reset();
+ this._activeSkeletons.reset();
+ this._softwareSkinnedMeshes.reset();
+ this._materialsRenderTargets.reset();
+ for (const step of this._beforeEvaluateActiveMeshStage) {
+ step.action();
+ }
+ // Determine mesh candidates
+ const meshes = this.getActiveMeshCandidates();
+ // Check each mesh
+ const len = meshes.length;
+ for (let i = 0; i < len; i++) {
+ const mesh = meshes.data[i];
+ let currentLOD = mesh._internalAbstractMeshDataInfo._currentLOD.get(this.activeCamera);
+ if (currentLOD) {
+ currentLOD[1] = -1;
+ }
+ else {
+ currentLOD = [mesh, -1];
+ mesh._internalAbstractMeshDataInfo._currentLOD.set(this.activeCamera, currentLOD);
+ }
+ if (mesh.isBlocked) {
+ continue;
+ }
+ this._totalVertices.addCount(mesh.getTotalVertices(), false);
+ if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) {
+ continue;
+ }
+ mesh.computeWorldMatrix();
+ // Intersections
+ if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) {
+ this._meshesForIntersections.pushNoDuplicate(mesh);
+ }
+ // Switch to current LOD
+ let meshToRender = this.customLODSelector ? this.customLODSelector(mesh, this.activeCamera) : mesh.getLOD(this.activeCamera);
+ currentLOD[0] = meshToRender;
+ currentLOD[1] = this._frameId;
+ if (meshToRender === undefined || meshToRender === null) {
+ continue;
+ }
+ // Compute world matrix if LOD is billboard
+ if (meshToRender !== mesh && meshToRender.billboardMode !== 0) {
+ meshToRender.computeWorldMatrix();
+ }
+ mesh._preActivate();
+ if (mesh.isVisible &&
+ mesh.visibility > 0 &&
+ (mesh.layerMask & this.activeCamera.layerMask) !== 0 &&
+ (this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
+ this._activeMeshes.push(mesh);
+ this.activeCamera._activeMeshes.push(mesh);
+ if (meshToRender !== mesh) {
+ meshToRender._activate(this._renderId, false);
+ }
+ for (const step of this._preActiveMeshStage) {
+ step.action(mesh);
+ }
+ if (mesh._activate(this._renderId, false)) {
+ if (!mesh.isAnInstance) {
+ meshToRender._internalAbstractMeshDataInfo._onlyForInstances = false;
+ }
+ else {
+ if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) {
+ meshToRender = mesh;
+ }
+ }
+ meshToRender._internalAbstractMeshDataInfo._isActive = true;
+ this._activeMesh(mesh, meshToRender);
+ }
+ mesh._postActivate();
+ }
+ }
+ this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
+ // Particle systems
+ if (this.particlesEnabled) {
+ this.onBeforeParticlesRenderingObservable.notifyObservers(this);
+ for (let particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
+ const particleSystem = this.particleSystems[particleIndex];
+ if (!particleSystem.isStarted() || !particleSystem.emitter) {
+ continue;
+ }
+ const emitter = particleSystem.emitter;
+ if (!emitter.position || emitter.isEnabled()) {
+ this._activeParticleSystems.push(particleSystem);
+ particleSystem.animate();
+ this._renderingManager.dispatchParticles(particleSystem);
+ }
+ }
+ this.onAfterParticlesRenderingObservable.notifyObservers(this);
+ }
+ }
+ /** @internal */
+ _prepareSkeleton(mesh) {
+ if (!this._skeletonsEnabled || !mesh.skeleton) {
+ return;
+ }
+ if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
+ mesh.skeleton.prepare();
+ this._activeBones.addCount(mesh.skeleton.bones.length, false);
+ }
+ if (!mesh.computeBonesUsingShaders) {
+ if (this._softwareSkinnedMeshes.pushNoDuplicate(mesh) && this.frameGraph) {
+ mesh.applySkeleton(mesh.skeleton);
+ }
+ }
+ }
+ _activeMesh(sourceMesh, mesh) {
+ this._prepareSkeleton(mesh);
+ let forcePush = sourceMesh.hasInstances || sourceMesh.isAnInstance || this.dispatchAllSubMeshesOfActiveMeshes || this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh;
+ if (mesh && mesh.subMeshes && mesh.subMeshes.length > 0) {
+ const subMeshes = this.getActiveSubMeshCandidates(mesh);
+ const len = subMeshes.length;
+ forcePush = forcePush || len === 1;
+ for (let i = 0; i < len; i++) {
+ const subMesh = subMeshes.data[i];
+ this._evaluateSubMesh(subMesh, mesh, sourceMesh, forcePush);
+ }
+ }
+ }
+ /**
+ * Update the transform matrix to update from the current active camera
+ * @param force defines a boolean used to force the update even if cache is up to date
+ */
+ updateTransformMatrix(force) {
+ const activeCamera = this.activeCamera;
+ if (!activeCamera) {
+ return;
+ }
+ if (activeCamera._renderingMultiview) {
+ const leftCamera = activeCamera._rigCameras[0];
+ const rightCamera = activeCamera._rigCameras[1];
+ this.setTransformMatrix(leftCamera.getViewMatrix(), leftCamera.getProjectionMatrix(force), rightCamera.getViewMatrix(), rightCamera.getProjectionMatrix(force));
+ }
+ else {
+ this.setTransformMatrix(activeCamera.getViewMatrix(), activeCamera.getProjectionMatrix(force));
+ }
+ }
+ _bindFrameBuffer(camera, clear = true) {
+ if (!this._useCurrentFrameBuffer) {
+ if (camera && camera._multiviewTexture) {
+ camera._multiviewTexture._bindFrameBuffer();
+ }
+ else if (camera && camera.outputRenderTarget) {
+ camera.outputRenderTarget._bindFrameBuffer();
+ }
+ else {
+ if (!this._engine._currentFrameBufferIsDefaultFrameBuffer()) {
+ this._engine.restoreDefaultFramebuffer();
+ }
+ }
+ }
+ if (clear) {
+ this._clearFrameBuffer(camera);
+ }
+ }
+ _clearFrameBuffer(camera) {
+ // we assume the framebuffer currently bound is the right one
+ if (camera && camera._multiviewTexture) ;
+ else if (camera && camera.outputRenderTarget && !camera._renderingMultiview) {
+ const rtt = camera.outputRenderTarget;
+ if (rtt.onClearObservable.hasObservers()) {
+ rtt.onClearObservable.notifyObservers(this._engine);
+ }
+ else if (!rtt.skipInitialClear && !camera.isRightCamera) {
+ if (this.autoClear) {
+ this._engine.clear(rtt.clearColor || this._clearColor, !rtt._cleared, true, true);
+ }
+ rtt._cleared = true;
+ }
+ }
+ else {
+ if (!this._defaultFrameBufferCleared) {
+ this._defaultFrameBufferCleared = true;
+ this._clear();
+ }
+ else {
+ this._engine.clear(null, false, true, true);
+ }
+ }
+ }
+ /**
+ * @internal
+ */
+ _renderForCamera(camera, rigParent, bindFrameBuffer = true) {
+ if (camera && camera._skipRendering) {
+ return;
+ }
+ const engine = this._engine;
+ // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged
+ this._activeCamera = camera;
+ if (!this.activeCamera) {
+ throw new Error("Active camera not set");
+ }
+ // Viewport
+ engine.setViewport(this.activeCamera.viewport);
+ // Camera
+ this.resetCachedMaterial();
+ this._renderId++;
+ if (!this.prePass && bindFrameBuffer) {
+ let skipInitialClear = true;
+ if (camera._renderingMultiview && camera.outputRenderTarget) {
+ skipInitialClear = camera.outputRenderTarget.skipInitialClear;
+ if (this.autoClear) {
+ this._defaultFrameBufferCleared = false;
+ camera.outputRenderTarget.skipInitialClear = false;
+ }
+ }
+ this._bindFrameBuffer(this._activeCamera);
+ if (camera._renderingMultiview && camera.outputRenderTarget) {
+ camera.outputRenderTarget.skipInitialClear = skipInitialClear;
+ }
+ }
+ this.updateTransformMatrix();
+ this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
+ // Meshes
+ this._evaluateActiveMeshes();
+ // Software skinning
+ for (let softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
+ const mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
+ mesh.applySkeleton(mesh.skeleton);
+ }
+ // Render targets
+ this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
+ this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets);
+ if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
+ this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
+ }
+ if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
+ this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
+ }
+ if (this.environmentTexture && this.environmentTexture.isRenderTarget) {
+ this._renderTargets.pushNoDuplicate(this.environmentTexture);
+ }
+ // Collects render targets from external components.
+ for (const step of this._gatherActiveCameraRenderTargetsStage) {
+ step.action(this._renderTargets);
+ }
+ let needRebind = false;
+ if (this.renderTargetsEnabled) {
+ this._intermediateRendering = true;
+ if (this._renderTargets.length > 0) {
+ Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
+ for (let renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
+ const renderTarget = this._renderTargets.data[renderIndex];
+ if (renderTarget._shouldRender()) {
+ this._renderId++;
+ const hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
+ renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
+ needRebind = true;
+ }
+ }
+ Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
+ this._renderId++;
+ }
+ for (const step of this._cameraDrawRenderTargetStage) {
+ needRebind = step.action(this.activeCamera) || needRebind;
+ }
+ this._intermediateRendering = false;
+ }
+ this._engine.currentRenderPassId = camera.outputRenderTarget?.renderPassId ?? camera.renderPassId ?? 0;
+ // Restore framebuffer after rendering to targets
+ if (needRebind && !this.prePass) {
+ this._bindFrameBuffer(this._activeCamera, false);
+ this.updateTransformMatrix();
+ }
+ this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
+ // Prepare Frame
+ if (this.postProcessManager && !camera._multiviewTexture && !this.prePass) {
+ this.postProcessManager._prepareFrame();
+ }
+ // Before Camera Draw
+ for (const step of this._beforeCameraDrawStage) {
+ step.action(this.activeCamera);
+ }
+ // Render
+ this.onBeforeDrawPhaseObservable.notifyObservers(this);
+ if (engine.snapshotRendering && engine.snapshotRenderingMode === 1) {
+ this.finalizeSceneUbo();
+ }
+ this._renderingManager.render(null, null, true, true);
+ this.onAfterDrawPhaseObservable.notifyObservers(this);
+ // After Camera Draw
+ for (const step of this._afterCameraDrawStage) {
+ step.action(this.activeCamera);
+ }
+ // Finalize frame
+ if (this.postProcessManager && !camera._multiviewTexture) {
+ // if the camera has an output render target, render the post process to the render target
+ const texture = camera.outputRenderTarget ? camera.outputRenderTarget.renderTarget : undefined;
+ this.postProcessManager._finalizeFrame(camera.isIntermediate, texture);
+ }
+ // After post process
+ for (const step of this._afterCameraPostProcessStage) {
+ step.action(this.activeCamera);
+ }
+ // Reset some special arrays
+ this._renderTargets.reset();
+ this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
+ }
+ _processSubCameras(camera, bindFrameBuffer = true) {
+ if (camera.cameraRigMode === 0 || camera._renderingMultiview) {
+ if (camera._renderingMultiview && !this._multiviewSceneUbo) {
+ this._createMultiviewUbo();
+ }
+ this._renderForCamera(camera, undefined, bindFrameBuffer);
+ this.onAfterRenderCameraObservable.notifyObservers(camera);
+ return;
+ }
+ if (camera._useMultiviewToSingleView) {
+ this._renderMultiviewToSingleView(camera);
+ }
+ else {
+ // rig cameras
+ this.onBeforeCameraRenderObservable.notifyObservers(camera);
+ for (let index = 0; index < camera._rigCameras.length; index++) {
+ this._renderForCamera(camera._rigCameras[index], camera);
+ }
+ }
+ // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged
+ this._activeCamera = camera;
+ this.updateTransformMatrix();
+ this.onAfterRenderCameraObservable.notifyObservers(camera);
+ }
+ _checkIntersections() {
+ for (let index = 0; index < this._meshesForIntersections.length; index++) {
+ const sourceMesh = this._meshesForIntersections.data[index];
+ if (!sourceMesh.actionManager) {
+ continue;
+ }
+ for (let actionIndex = 0; sourceMesh.actionManager && actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
+ const action = sourceMesh.actionManager.actions[actionIndex];
+ if (action.trigger === 12 || action.trigger === 13) {
+ const parameters = action.getTriggerParameter();
+ const otherMesh = parameters.mesh ? parameters.mesh : parameters;
+ const areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
+ const currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
+ if (areIntersecting && currentIntersectionInProgress === -1) {
+ if (action.trigger === 12) {
+ action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
+ sourceMesh._intersectionsInProgress.push(otherMesh);
+ }
+ else if (action.trigger === 13) {
+ sourceMesh._intersectionsInProgress.push(otherMesh);
+ }
+ }
+ else if (!areIntersecting && currentIntersectionInProgress > -1) {
+ //They intersected, and now they don't.
+ //is this trigger an exit trigger? execute an event.
+ if (action.trigger === 13) {
+ action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
+ }
+ //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
+ if (!sourceMesh.actionManager.hasSpecificTrigger(13, (parameter) => {
+ const parameterMesh = parameter.mesh ? parameter.mesh : parameter;
+ return otherMesh === parameterMesh;
+ }) ||
+ action.trigger === 13) {
+ sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
+ }
+ }
+ }
+ }
+ }
+ }
+ /**
+ * @internal
+ */
+ _advancePhysicsEngineStep(step) {
+ // Do nothing. Code will be replaced if physics engine component is referenced
+ }
+ /** @internal */
+ _animate(customDeltaTime) {
+ // Nothing to do as long as Animatable have not been imported.
+ }
+ /** Execute all animations (for a frame) */
+ animate() {
+ if (this._engine.isDeterministicLockStep()) {
+ let deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
+ const defaultFrameTime = this._engine.getTimeStep();
+ const defaultFPS = 1000.0 / defaultFrameTime / 1000.0;
+ let stepsTaken = 0;
+ const maxSubSteps = this._engine.getLockstepMaxSteps();
+ let internalSteps = Math.floor(deltaTime / defaultFrameTime);
+ internalSteps = Math.min(internalSteps, maxSubSteps);
+ while (deltaTime > 0 && stepsTaken < internalSteps) {
+ this.onBeforeStepObservable.notifyObservers(this);
+ // Animations
+ this._animationRatio = defaultFrameTime * defaultFPS;
+ this._animate(defaultFrameTime);
+ this.onAfterAnimationsObservable.notifyObservers(this);
+ // Physics
+ if (this.physicsEnabled) {
+ this._advancePhysicsEngineStep(defaultFrameTime);
+ }
+ this.onAfterStepObservable.notifyObservers(this);
+ this._currentStepId++;
+ stepsTaken++;
+ deltaTime -= defaultFrameTime;
+ }
+ this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
+ }
+ else {
+ // Animations
+ const deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
+ this._animationRatio = deltaTime * (60.0 / 1000.0);
+ this._animate();
+ this.onAfterAnimationsObservable.notifyObservers(this);
+ // Physics
+ if (this.physicsEnabled) {
+ this._advancePhysicsEngineStep(deltaTime);
+ }
+ }
+ }
+ _clear() {
+ if (this.autoClearDepthAndStencil || this.autoClear) {
+ this._engine.clear(this._clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
+ }
+ }
+ _checkCameraRenderTarget(camera) {
+ if (camera?.outputRenderTarget && !camera?.isRigCamera) {
+ camera.outputRenderTarget._cleared = false;
+ }
+ if (camera?.rigCameras?.length) {
+ for (let i = 0; i < camera.rigCameras.length; ++i) {
+ const rtt = camera.rigCameras[i].outputRenderTarget;
+ if (rtt) {
+ rtt._cleared = false;
+ }
+ }
+ }
+ }
+ /**
+ * Resets the draw wrappers cache of all meshes
+ * @param passId If provided, releases only the draw wrapper corresponding to this render pass id
+ */
+ resetDrawCache(passId) {
+ if (!this.meshes) {
+ return;
+ }
+ for (const mesh of this.meshes) {
+ mesh.resetDrawCache(passId);
+ }
+ }
+ _renderWithFrameGraph(updateCameras = true, ignoreAnimations = false) {
+ this.activeCamera = null;
+ this._activeParticleSystems.reset();
+ this._activeSkeletons.reset();
+ // Update Cameras
+ if (updateCameras) {
+ for (const camera of this.cameras) {
+ camera.update();
+ if (camera.cameraRigMode !== 0) {
+ // rig cameras
+ for (let index = 0; index < camera._rigCameras.length; index++) {
+ camera._rigCameras[index].update();
+ }
+ }
+ }
+ }
+ // We must keep these steps because the procedural texture component relies on them.
+ // TODO: move the procedural texture component to the frame graph.
+ for (const step of this._beforeClearStage) {
+ step.action();
+ }
+ // Process meshes
+ const meshes = this.getActiveMeshCandidates();
+ const len = meshes.length;
+ for (let i = 0; i < len; i++) {
+ const mesh = meshes.data[i];
+ if (mesh.isBlocked) {
+ continue;
+ }
+ this._totalVertices.addCount(mesh.getTotalVertices(), false);
+ if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) {
+ continue;
+ }
+ mesh.computeWorldMatrix();
+ if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) {
+ this._meshesForIntersections.pushNoDuplicate(mesh);
+ }
+ }
+ // Animate Particle systems
+ if (this.particlesEnabled) {
+ for (let particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
+ const particleSystem = this.particleSystems[particleIndex];
+ if (!particleSystem.isStarted() || !particleSystem.emitter) {
+ continue;
+ }
+ const emitter = particleSystem.emitter;
+ if (!emitter.position || emitter.isEnabled()) {
+ this._activeParticleSystems.push(particleSystem);
+ particleSystem.animate();
+ }
+ }
+ }
+ // Render the graph
+ this.frameGraph?.execute();
+ }
+ /**
+ * Render the scene
+ * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
+ * @param ignoreAnimations defines a boolean indicating if animations should not be executed (false by default)
+ */
+ render(updateCameras = true, ignoreAnimations = false) {
+ if (this.isDisposed) {
+ return;
+ }
+ if (this.onReadyObservable.hasObservers() && this._executeWhenReadyTimeoutId === null) {
+ this._checkIsReady();
+ }
+ this._frameId++;
+ this._defaultFrameBufferCleared = false;
+ this._checkCameraRenderTarget(this.activeCamera);
+ if (this.activeCameras?.length) {
+ this.activeCameras.forEach(this._checkCameraRenderTarget);
+ }
+ // Register components that have been associated lately to the scene.
+ this._registerTransientComponents();
+ this._activeParticles.fetchNewFrame();
+ this._totalVertices.fetchNewFrame();
+ this._activeIndices.fetchNewFrame();
+ this._activeBones.fetchNewFrame();
+ this._meshesForIntersections.reset();
+ this.resetCachedMaterial();
+ this.onBeforeAnimationsObservable.notifyObservers(this);
+ // Actions
+ if (this.actionManager) {
+ this.actionManager.processTrigger(11);
+ }
+ // Animations
+ if (!ignoreAnimations) {
+ this.animate();
+ }
+ // Before camera update steps
+ for (const step of this._beforeCameraUpdateStage) {
+ step.action();
+ }
+ // Update Cameras
+ if (updateCameras) {
+ if (this.activeCameras && this.activeCameras.length > 0) {
+ for (let cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
+ const camera = this.activeCameras[cameraIndex];
+ camera.update();
+ if (camera.cameraRigMode !== 0) {
+ // rig cameras
+ for (let index = 0; index < camera._rigCameras.length; index++) {
+ camera._rigCameras[index].update();
+ }
+ }
+ }
+ }
+ else if (this.activeCamera) {
+ this.activeCamera.update();
+ if (this.activeCamera.cameraRigMode !== 0) {
+ // rig cameras
+ for (let index = 0; index < this.activeCamera._rigCameras.length; index++) {
+ this.activeCamera._rigCameras[index].update();
+ }
+ }
+ }
+ }
+ // Before render
+ this.onBeforeRenderObservable.notifyObservers(this);
+ // Custom render function?
+ if (this.customRenderFunction) {
+ this._renderId++;
+ this._engine.currentRenderPassId = 0;
+ this.customRenderFunction(updateCameras, ignoreAnimations);
+ }
+ else {
+ const engine = this.getEngine();
+ // Customs render targets
+ this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
+ const currentActiveCamera = this.activeCameras?.length ? this.activeCameras[0] : this.activeCamera;
+ if (this.renderTargetsEnabled) {
+ Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
+ this._intermediateRendering = true;
+ for (let customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
+ const renderTarget = this.customRenderTargets[customIndex];
+ if (renderTarget._shouldRender()) {
+ this._renderId++;
+ this.activeCamera = renderTarget.activeCamera || this.activeCamera;
+ if (!this.activeCamera) {
+ throw new Error("Active camera not set");
+ }
+ // Viewport
+ engine.setViewport(this.activeCamera.viewport);
+ // Camera
+ this.updateTransformMatrix();
+ renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
+ }
+ }
+ Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
+ this._intermediateRendering = false;
+ this._renderId++;
+ }
+ this._engine.currentRenderPassId = currentActiveCamera?.renderPassId ?? 0;
+ // Restore back buffer
+ this.activeCamera = currentActiveCamera;
+ if (this._activeCamera && this._activeCamera.cameraRigMode !== 22 && !this.prePass) {
+ this._bindFrameBuffer(this._activeCamera, false);
+ }
+ this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
+ for (const step of this._beforeClearStage) {
+ step.action();
+ }
+ // Clear
+ this._clearFrameBuffer(this.activeCamera);
+ // Collects render targets from external components.
+ for (const step of this._gatherRenderTargetsStage) {
+ step.action(this._renderTargets);
+ }
+ // Multi-cameras?
+ if (this.activeCameras && this.activeCameras.length > 0) {
+ for (let cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
+ this._processSubCameras(this.activeCameras[cameraIndex], cameraIndex > 0);
+ }
+ }
+ else {
+ if (!this.activeCamera) {
+ throw new Error("No camera defined");
+ }
+ this._processSubCameras(this.activeCamera, !!this.activeCamera.outputRenderTarget);
+ }
+ }
+ // Intersection checks
+ this._checkIntersections();
+ // Executes the after render stage actions.
+ for (const step of this._afterRenderStage) {
+ step.action();
+ }
+ // After render
+ if (this.afterRender) {
+ this.afterRender();
+ }
+ this.onAfterRenderObservable.notifyObservers(this);
+ // Cleaning
+ if (this._toBeDisposed.length) {
+ for (let index = 0; index < this._toBeDisposed.length; index++) {
+ const data = this._toBeDisposed[index];
+ if (data) {
+ data.dispose();
+ }
+ }
+ this._toBeDisposed.length = 0;
+ }
+ if (this.dumpNextRenderTargets) {
+ this.dumpNextRenderTargets = false;
+ }
+ this._activeBones.addCount(0, true);
+ this._activeIndices.addCount(0, true);
+ this._activeParticles.addCount(0, true);
+ this._engine.restoreDefaultFramebuffer();
+ }
+ /**
+ * Freeze all materials
+ * A frozen material will not be updatable but should be faster to render
+ * Note: multimaterials will not be frozen, but their submaterials will
+ */
+ freezeMaterials() {
+ for (let i = 0; i < this.materials.length; i++) {
+ this.materials[i].freeze();
+ }
+ }
+ /**
+ * Unfreeze all materials
+ * A frozen material will not be updatable but should be faster to render
+ */
+ unfreezeMaterials() {
+ for (let i = 0; i < this.materials.length; i++) {
+ this.materials[i].unfreeze();
+ }
+ }
+ /**
+ * Releases all held resources
+ */
+ dispose() {
+ if (this.isDisposed) {
+ return;
+ }
+ this.beforeRender = null;
+ this.afterRender = null;
+ this.metadata = null;
+ this.skeletons.length = 0;
+ this.morphTargetManagers.length = 0;
+ this._transientComponents.length = 0;
+ this._isReadyForMeshStage.clear();
+ this._beforeEvaluateActiveMeshStage.clear();
+ this._evaluateSubMeshStage.clear();
+ this._preActiveMeshStage.clear();
+ this._cameraDrawRenderTargetStage.clear();
+ this._beforeCameraDrawStage.clear();
+ this._beforeRenderTargetDrawStage.clear();
+ this._beforeRenderingGroupDrawStage.clear();
+ this._beforeRenderingMeshStage.clear();
+ this._afterRenderingMeshStage.clear();
+ this._afterRenderingGroupDrawStage.clear();
+ this._afterCameraDrawStage.clear();
+ this._afterRenderTargetDrawStage.clear();
+ this._afterRenderStage.clear();
+ this._beforeCameraUpdateStage.clear();
+ this._beforeClearStage.clear();
+ this._gatherRenderTargetsStage.clear();
+ this._gatherActiveCameraRenderTargetsStage.clear();
+ this._pointerMoveStage.clear();
+ this._pointerDownStage.clear();
+ this._pointerUpStage.clear();
+ this.importedMeshesFiles = [];
+ if (this._activeAnimatables && this.stopAllAnimations) {
+ // Ensures that no animatable notifies a callback that could start a new animation group, constantly adding new animatables to the active list...
+ this._activeAnimatables.forEach((animatable) => {
+ animatable.onAnimationEndObservable.clear();
+ animatable.onAnimationEnd = null;
+ });
+ this.stopAllAnimations();
+ }
+ this.resetCachedMaterial();
+ // Smart arrays
+ if (this.activeCamera) {
+ this.activeCamera._activeMeshes.dispose();
+ this.activeCamera = null;
+ }
+ this.activeCameras = null;
+ this._activeMeshes.dispose();
+ this._renderingManager.dispose();
+ this._processedMaterials.dispose();
+ this._activeParticleSystems.dispose();
+ this._activeSkeletons.dispose();
+ this._softwareSkinnedMeshes.dispose();
+ this._renderTargets.dispose();
+ this._materialsRenderTargets.dispose();
+ this._registeredForLateAnimationBindings.dispose();
+ this._meshesForIntersections.dispose();
+ this._toBeDisposed.length = 0;
+ // Abort active requests
+ const activeRequests = this._activeRequests.slice();
+ for (const request of activeRequests) {
+ request.abort();
+ }
+ this._activeRequests.length = 0;
+ // Events
+ try {
+ this.onDisposeObservable.notifyObservers(this);
+ }
+ catch (e) {
+ Logger.Error("An error occurred while calling onDisposeObservable!", e);
+ }
+ this.detachControl();
+ // Detach cameras
+ const canvas = this._engine.getInputElement();
+ if (canvas) {
+ for (let index = 0; index < this.cameras.length; index++) {
+ this.cameras[index].detachControl();
+ }
+ }
+ // Release animation groups
+ this._disposeList(this.animationGroups);
+ // Release lights
+ this._disposeList(this.lights);
+ // Release materials
+ if (this._defaultMaterial) {
+ this._defaultMaterial.dispose();
+ }
+ this._disposeList(this.multiMaterials);
+ this._disposeList(this.materials);
+ // Release meshes
+ this._disposeList(this.meshes, (item) => item.dispose(true));
+ this._disposeList(this.transformNodes, (item) => item.dispose(true));
+ // Release cameras
+ const cameras = this.cameras;
+ this._disposeList(cameras);
+ // Release particles
+ this._disposeList(this.particleSystems);
+ // Release postProcesses
+ this._disposeList(this.postProcesses);
+ // Release textures
+ this._disposeList(this.textures);
+ // Release morph targets
+ this._disposeList(this.morphTargetManagers);
+ // Release UBO
+ this._sceneUbo.dispose();
+ if (this._multiviewSceneUbo) {
+ this._multiviewSceneUbo.dispose();
+ }
+ // Post-processes
+ this.postProcessManager.dispose();
+ // Components
+ this._disposeList(this._components);
+ // Remove from engine
+ let index = this._engine.scenes.indexOf(this);
+ if (index > -1) {
+ this._engine.scenes.splice(index, 1);
+ }
+ if (EngineStore._LastCreatedScene === this) {
+ EngineStore._LastCreatedScene = null;
+ let engineIndex = EngineStore.Instances.length - 1;
+ while (engineIndex >= 0) {
+ const engine = EngineStore.Instances[engineIndex];
+ if (engine.scenes.length > 0) {
+ EngineStore._LastCreatedScene = engine.scenes[this._engine.scenes.length - 1];
+ break;
+ }
+ engineIndex--;
+ }
+ }
+ index = this._engine._virtualScenes.indexOf(this);
+ if (index > -1) {
+ this._engine._virtualScenes.splice(index, 1);
+ }
+ this._engine.wipeCaches(true);
+ this.onDisposeObservable.clear();
+ this.onBeforeRenderObservable.clear();
+ this.onAfterRenderObservable.clear();
+ this.onBeforeRenderTargetsRenderObservable.clear();
+ this.onAfterRenderTargetsRenderObservable.clear();
+ this.onAfterStepObservable.clear();
+ this.onBeforeStepObservable.clear();
+ this.onBeforeActiveMeshesEvaluationObservable.clear();
+ this.onAfterActiveMeshesEvaluationObservable.clear();
+ this.onBeforeParticlesRenderingObservable.clear();
+ this.onAfterParticlesRenderingObservable.clear();
+ this.onBeforeDrawPhaseObservable.clear();
+ this.onAfterDrawPhaseObservable.clear();
+ this.onBeforeAnimationsObservable.clear();
+ this.onAfterAnimationsObservable.clear();
+ this.onDataLoadedObservable.clear();
+ this.onBeforeRenderingGroupObservable.clear();
+ this.onAfterRenderingGroupObservable.clear();
+ this.onMeshImportedObservable.clear();
+ this.onBeforeCameraRenderObservable.clear();
+ this.onAfterCameraRenderObservable.clear();
+ this.onAfterRenderCameraObservable.clear();
+ this.onReadyObservable.clear();
+ this.onNewCameraAddedObservable.clear();
+ this.onCameraRemovedObservable.clear();
+ this.onNewLightAddedObservable.clear();
+ this.onLightRemovedObservable.clear();
+ this.onNewGeometryAddedObservable.clear();
+ this.onGeometryRemovedObservable.clear();
+ this.onNewTransformNodeAddedObservable.clear();
+ this.onTransformNodeRemovedObservable.clear();
+ this.onNewMeshAddedObservable.clear();
+ this.onMeshRemovedObservable.clear();
+ this.onNewSkeletonAddedObservable.clear();
+ this.onSkeletonRemovedObservable.clear();
+ this.onNewMaterialAddedObservable.clear();
+ this.onNewMultiMaterialAddedObservable.clear();
+ this.onMaterialRemovedObservable.clear();
+ this.onMultiMaterialRemovedObservable.clear();
+ this.onNewTextureAddedObservable.clear();
+ this.onTextureRemovedObservable.clear();
+ this.onPrePointerObservable.clear();
+ this.onPointerObservable.clear();
+ this.onPreKeyboardObservable.clear();
+ this.onKeyboardObservable.clear();
+ this.onActiveCameraChanged.clear();
+ this.onScenePerformancePriorityChangedObservable.clear();
+ this.onClearColorChangedObservable.clear();
+ this.onEnvironmentTextureChangedObservable.clear();
+ this.onMeshUnderPointerUpdatedObservable.clear();
+ this._isDisposed = true;
+ }
+ _disposeList(items, callback) {
+ const itemsCopy = items.slice(0);
+ callback = callback ?? ((item) => item.dispose());
+ for (const item of itemsCopy) {
+ callback(item);
+ }
+ items.length = 0;
+ }
+ /**
+ * Gets if the scene is already disposed
+ */
+ get isDisposed() {
+ return this._isDisposed;
+ }
+ /**
+ * Call this function to reduce memory footprint of the scene.
+ * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
+ */
+ clearCachedVertexData() {
+ for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
+ const mesh = this.meshes[meshIndex];
+ const geometry = mesh.geometry;
+ if (geometry) {
+ geometry.clearCachedData();
+ }
+ }
+ }
+ /**
+ * This function will remove the local cached buffer data from texture.
+ * It will save memory but will prevent the texture from being rebuilt
+ */
+ cleanCachedTextureBuffer() {
+ for (const baseTexture of this.textures) {
+ const buffer = baseTexture._buffer;
+ if (buffer) {
+ baseTexture._buffer = null;
+ }
+ }
+ }
+ /**
+ * Get the world extend vectors with an optional filter
+ *
+ * @param filterPredicate the predicate - which meshes should be included when calculating the world size
+ * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
+ */
+ getWorldExtends(filterPredicate) {
+ const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+ filterPredicate = filterPredicate || (() => true);
+ this.meshes.filter(filterPredicate).forEach((mesh) => {
+ mesh.computeWorldMatrix(true);
+ if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
+ return;
+ }
+ const boundingInfo = mesh.getBoundingInfo();
+ const minBox = boundingInfo.boundingBox.minimumWorld;
+ const maxBox = boundingInfo.boundingBox.maximumWorld;
+ Vector3.CheckExtends(minBox, min, max);
+ Vector3.CheckExtends(maxBox, min, max);
+ });
+ return {
+ min: min,
+ max: max,
+ };
+ }
+ // Picking
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Creates a ray that can be used to pick in the scene
+ * @param x defines the x coordinate of the origin (on-screen)
+ * @param y defines the y coordinate of the origin (on-screen)
+ * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
+ * @param camera defines the camera to use for the picking
+ * @param cameraViewSpace defines if picking will be done in view space (false by default)
+ * @returns a Ray
+ */
+ createPickingRay(x, y, world, camera, cameraViewSpace = false) {
+ throw _WarnImport("Ray");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Creates a ray that can be used to pick in the scene
+ * @param x defines the x coordinate of the origin (on-screen)
+ * @param y defines the y coordinate of the origin (on-screen)
+ * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
+ * @param result defines the ray where to store the picking ray
+ * @param camera defines the camera to use for the picking
+ * @param cameraViewSpace defines if picking will be done in view space (false by default)
+ * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default)
+ * @returns the current scene
+ */
+ createPickingRayToRef(x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) {
+ throw _WarnImport("Ray");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Creates a ray that can be used to pick in the scene
+ * @param x defines the x coordinate of the origin (on-screen)
+ * @param y defines the y coordinate of the origin (on-screen)
+ * @param camera defines the camera to use for the picking
+ * @returns a Ray
+ */
+ createPickingRayInCameraSpace(x, y, camera) {
+ throw _WarnImport("Ray");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Creates a ray that can be used to pick in the scene
+ * @param x defines the x coordinate of the origin (on-screen)
+ * @param y defines the y coordinate of the origin (on-screen)
+ * @param result defines the ray where to store the picking ray
+ * @param camera defines the camera to use for the picking
+ * @returns the current scene
+ */
+ createPickingRayInCameraSpaceToRef(x, y, result, camera) {
+ throw _WarnImport("Ray");
+ }
+ /** Launch a ray to try to pick a mesh in the scene
+ * @param x position on screen
+ * @param y position on screen
+ * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced
+ * @param fastCheck defines if the first intersection will be used (and not the closest)
+ * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
+ * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
+ * @returns a PickingInfo
+ */
+ pick(x, y, predicate, fastCheck, camera, trianglePredicate) {
+ const warn = _WarnImport("Ray", true);
+ if (warn) {
+ Logger.Warn(warn);
+ }
+ // Dummy info if picking as not been imported
+ return new PickingInfo();
+ }
+ /** Launch a ray to try to pick a mesh in the scene using only bounding information of the main mesh (not using submeshes)
+ * @param x position on screen
+ * @param y position on screen
+ * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced
+ * @param fastCheck defines if the first intersection will be used (and not the closest)
+ * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
+ * @returns a PickingInfo (Please note that some info will not be set like distance, bv, bu and everything that cannot be capture by only using bounding infos)
+ */
+ pickWithBoundingInfo(x, y, predicate, fastCheck, camera) {
+ const warn = _WarnImport("Ray", true);
+ if (warn) {
+ Logger.Warn(warn);
+ }
+ // Dummy info if picking as not been imported
+ return new PickingInfo();
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Use the given ray to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides,
+ * irrespective of orientation.
+ * @param ray The ray to use to pick meshes
+ * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced
+ * @param fastCheck defines if the first intersection will be used (and not the closest)
+ * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
+ * @returns a PickingInfo
+ */
+ pickWithRay(ray, predicate, fastCheck, trianglePredicate) {
+ throw _WarnImport("Ray");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Launch a ray to try to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides,
+ * irrespective of orientation.
+ * @param x X position on screen
+ * @param y Y position on screen
+ * @param predicate Predicate function used to determine eligible meshes and instances. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced
+ * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
+ * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
+ * @returns an array of PickingInfo
+ */
+ multiPick(x, y, predicate, camera, trianglePredicate) {
+ throw _WarnImport("Ray");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Launch a ray to try to pick a mesh in the scene
+ * @param ray Ray to use
+ * @param predicate Predicate function used to determine eligible meshes and instances. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced
+ * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
+ * @returns an array of PickingInfo
+ */
+ multiPickWithRay(ray, predicate, trianglePredicate) {
+ throw _WarnImport("Ray");
+ }
+ /**
+ * Force the value of meshUnderPointer
+ * @param mesh defines the mesh to use
+ * @param pointerId optional pointer id when using more than one pointer
+ * @param pickResult optional pickingInfo data used to find mesh
+ */
+ setPointerOverMesh(mesh, pointerId, pickResult) {
+ this._inputManager.setPointerOverMesh(mesh, pointerId, pickResult);
+ }
+ /**
+ * Gets the mesh under the pointer
+ * @returns a Mesh or null if no mesh is under the pointer
+ */
+ getPointerOverMesh() {
+ return this._inputManager.getPointerOverMesh();
+ }
+ // Misc.
+ /** @internal */
+ _rebuildGeometries() {
+ for (const geometry of this.geometries) {
+ geometry._rebuild();
+ }
+ for (const mesh of this.meshes) {
+ mesh._rebuild();
+ }
+ if (this.postProcessManager) {
+ this.postProcessManager._rebuild();
+ }
+ for (const component of this._components) {
+ component.rebuild();
+ }
+ for (const system of this.particleSystems) {
+ system.rebuild();
+ }
+ if (this.spriteManagers) {
+ for (const spriteMgr of this.spriteManagers) {
+ spriteMgr.rebuild();
+ }
+ }
+ }
+ /** @internal */
+ _rebuildTextures() {
+ for (const texture of this.textures) {
+ texture._rebuild(true);
+ }
+ this.markAllMaterialsAsDirty(1);
+ }
+ /**
+ * Get from a list of objects by tags
+ * @param list the list of objects to use
+ * @param tagsQuery the query to use
+ * @param filter a predicate to filter for tags
+ * @returns
+ */
+ _getByTags(list, tagsQuery, filter) {
+ if (tagsQuery === undefined) {
+ // returns the complete list (could be done with Tags.MatchesQuery but no need to have a for-loop here)
+ return list;
+ }
+ const listByTags = [];
+ for (const i in list) {
+ const item = list[i];
+ if (Tags && Tags.MatchesQuery(item, tagsQuery) && (!filter || filter(item))) {
+ listByTags.push(item);
+ }
+ }
+ return listByTags;
+ }
+ /**
+ * Get a list of meshes by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of Mesh
+ */
+ getMeshesByTags(tagsQuery, filter) {
+ return this._getByTags(this.meshes, tagsQuery, filter);
+ }
+ /**
+ * Get a list of cameras by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of Camera
+ */
+ getCamerasByTags(tagsQuery, filter) {
+ return this._getByTags(this.cameras, tagsQuery, filter);
+ }
+ /**
+ * Get a list of lights by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of Light
+ */
+ getLightsByTags(tagsQuery, filter) {
+ return this._getByTags(this.lights, tagsQuery, filter);
+ }
+ /**
+ * Get a list of materials by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of Material
+ */
+ getMaterialByTags(tagsQuery, filter) {
+ return this._getByTags(this.materials, tagsQuery, filter).concat(this._getByTags(this.multiMaterials, tagsQuery, filter));
+ }
+ /**
+ * Get a list of transform nodes by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of TransformNode
+ */
+ getTransformNodesByTags(tagsQuery, filter) {
+ return this._getByTags(this.transformNodes, tagsQuery, filter);
+ }
+ /**
+ * Overrides the default sort function applied in the rendering group to prepare the meshes.
+ * This allowed control for front to back rendering or reversly depending of the special needs.
+ *
+ * @param renderingGroupId The rendering group id corresponding to its index
+ * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
+ * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
+ * @param transparentSortCompareFn The transparent queue comparison function use to sort.
+ */
+ setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {
+ this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
+ }
+ /**
+ * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
+ *
+ * @param renderingGroupId The rendering group id corresponding to its index
+ * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
+ * @param depth Automatically clears depth between groups if true and autoClear is true.
+ * @param stencil Automatically clears stencil between groups if true and autoClear is true.
+ */
+ setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) {
+ this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
+ }
+ /**
+ * Gets the current auto clear configuration for one rendering group of the rendering
+ * manager.
+ * @param index the rendering group index to get the information for
+ * @returns The auto clear setup for the requested rendering group
+ */
+ getAutoClearDepthStencilSetup(index) {
+ return this._renderingManager.getAutoClearDepthStencilSetup(index);
+ }
+ /** @internal */
+ _forceBlockMaterialDirtyMechanism(value) {
+ this._blockMaterialDirtyMechanism = value;
+ }
+ /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
+ get blockMaterialDirtyMechanism() {
+ return this._blockMaterialDirtyMechanism;
+ }
+ set blockMaterialDirtyMechanism(value) {
+ if (this._blockMaterialDirtyMechanism === value) {
+ return;
+ }
+ this._blockMaterialDirtyMechanism = value;
+ if (!value) {
+ // Do a complete update
+ this.markAllMaterialsAsDirty(127);
+ }
+ }
+ /**
+ * Will flag all materials as dirty to trigger new shader compilation
+ * @param flag defines the flag used to specify which material part must be marked as dirty
+ * @param predicate If not null, it will be used to specify if a material has to be marked as dirty
+ */
+ markAllMaterialsAsDirty(flag, predicate) {
+ if (this._blockMaterialDirtyMechanism) {
+ return;
+ }
+ for (const material of this.materials) {
+ if (predicate && !predicate(material)) {
+ continue;
+ }
+ material.markAsDirty(flag);
+ }
+ }
+ /**
+ * @internal
+ */
+ _loadFile(fileOrUrl, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError, onOpened) {
+ const request = LoadFile(fileOrUrl, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError, onOpened);
+ this._activeRequests.push(request);
+ request.onCompleteObservable.add((request) => {
+ this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
+ });
+ return request;
+ }
+ /**
+ * @internal
+ */
+ _loadFileAsync(fileOrUrl, onProgress, useOfflineSupport, useArrayBuffer, onOpened) {
+ return new Promise((resolve, reject) => {
+ this._loadFile(fileOrUrl, (data) => {
+ resolve(data);
+ }, onProgress, useOfflineSupport, useArrayBuffer, (request, exception) => {
+ reject(exception);
+ }, onOpened);
+ });
+ }
+ /**
+ * @internal
+ */
+ _requestFile(url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError, onOpened) {
+ const request = RequestFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError, onOpened);
+ this._activeRequests.push(request);
+ request.onCompleteObservable.add((request) => {
+ this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
+ });
+ return request;
+ }
+ /**
+ * @internal
+ */
+ _requestFileAsync(url, onProgress, useOfflineSupport, useArrayBuffer, onOpened) {
+ return new Promise((resolve, reject) => {
+ this._requestFile(url, (data) => {
+ resolve(data);
+ }, onProgress, useOfflineSupport, useArrayBuffer, (error) => {
+ reject(error);
+ }, onOpened);
+ });
+ }
+ /**
+ * @internal
+ */
+ _readFile(file, onSuccess, onProgress, useArrayBuffer, onError) {
+ const request = ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError);
+ this._activeRequests.push(request);
+ request.onCompleteObservable.add((request) => {
+ this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
+ });
+ return request;
+ }
+ /**
+ * @internal
+ */
+ _readFileAsync(file, onProgress, useArrayBuffer) {
+ return new Promise((resolve, reject) => {
+ this._readFile(file, (data) => {
+ resolve(data);
+ }, onProgress, useArrayBuffer, (error) => {
+ reject(error);
+ });
+ });
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * This method gets the performance collector belonging to the scene, which is generally shared with the inspector.
+ * @returns the perf collector belonging to the scene.
+ */
+ getPerfCollector() {
+ throw _WarnImport("performanceViewerSceneExtension");
+ }
+ // deprecated
+ /**
+ * Sets the active camera of the scene using its Id
+ * @param id defines the camera's Id
+ * @returns the new active camera or null if none found.
+ * @deprecated Please use setActiveCameraById instead
+ */
+ setActiveCameraByID(id) {
+ return this.setActiveCameraById(id);
+ }
+ /**
+ * Get a material using its id
+ * @param id defines the material's Id
+ * @returns the material or null if none found.
+ * @deprecated Please use getMaterialById instead
+ */
+ getMaterialByID(id) {
+ return this.getMaterialById(id);
+ }
+ /**
+ * Gets a the last added material using a given id
+ * @param id defines the material's Id
+ * @returns the last material with the given id or null if none found.
+ * @deprecated Please use getLastMaterialById instead
+ */
+ getLastMaterialByID(id) {
+ return this.getLastMaterialById(id);
+ }
+ /**
+ * Get a texture using its unique id
+ * @param uniqueId defines the texture's unique id
+ * @returns the texture or null if none found.
+ * @deprecated Please use getTextureByUniqueId instead
+ */
+ getTextureByUniqueID(uniqueId) {
+ return this.getTextureByUniqueId(uniqueId);
+ }
+ /**
+ * Gets a camera using its Id
+ * @param id defines the Id to look for
+ * @returns the camera or null if not found
+ * @deprecated Please use getCameraById instead
+ */
+ getCameraByID(id) {
+ return this.getCameraById(id);
+ }
+ /**
+ * Gets a camera using its unique Id
+ * @param uniqueId defines the unique Id to look for
+ * @returns the camera or null if not found
+ * @deprecated Please use getCameraByUniqueId instead
+ */
+ getCameraByUniqueID(uniqueId) {
+ return this.getCameraByUniqueId(uniqueId);
+ }
+ /**
+ * Gets a bone using its Id
+ * @param id defines the bone's Id
+ * @returns the bone or null if not found
+ * @deprecated Please use getBoneById instead
+ */
+ getBoneByID(id) {
+ return this.getBoneById(id);
+ }
+ /**
+ * Gets a light node using its Id
+ * @param id defines the light's Id
+ * @returns the light or null if none found.
+ * @deprecated Please use getLightById instead
+ */
+ getLightByID(id) {
+ return this.getLightById(id);
+ }
+ /**
+ * Gets a light node using its scene-generated unique Id
+ * @param uniqueId defines the light's unique Id
+ * @returns the light or null if none found.
+ * @deprecated Please use getLightByUniqueId instead
+ */
+ getLightByUniqueID(uniqueId) {
+ return this.getLightByUniqueId(uniqueId);
+ }
+ /**
+ * Gets a particle system by Id
+ * @param id defines the particle system Id
+ * @returns the corresponding system or null if none found
+ * @deprecated Please use getParticleSystemById instead
+ */
+ getParticleSystemByID(id) {
+ return this.getParticleSystemById(id);
+ }
+ /**
+ * Gets a geometry using its Id
+ * @param id defines the geometry's Id
+ * @returns the geometry or null if none found.
+ * @deprecated Please use getGeometryById instead
+ */
+ getGeometryByID(id) {
+ return this.getGeometryById(id);
+ }
+ /**
+ * Gets the first added mesh found of a given Id
+ * @param id defines the Id to search for
+ * @returns the mesh found or null if not found at all
+ * @deprecated Please use getMeshById instead
+ */
+ getMeshByID(id) {
+ return this.getMeshById(id);
+ }
+ /**
+ * Gets a mesh with its auto-generated unique Id
+ * @param uniqueId defines the unique Id to search for
+ * @returns the found mesh or null if not found at all.
+ * @deprecated Please use getMeshByUniqueId instead
+ */
+ getMeshByUniqueID(uniqueId) {
+ return this.getMeshByUniqueId(uniqueId);
+ }
+ /**
+ * Gets a the last added mesh using a given Id
+ * @param id defines the Id to search for
+ * @returns the found mesh or null if not found at all.
+ * @deprecated Please use getLastMeshById instead
+ */
+ getLastMeshByID(id) {
+ return this.getLastMeshById(id);
+ }
+ /**
+ * Gets a list of meshes using their Id
+ * @param id defines the Id to search for
+ * @returns a list of meshes
+ * @deprecated Please use getMeshesById instead
+ */
+ getMeshesByID(id) {
+ return this.getMeshesById(id);
+ }
+ /**
+ * Gets the first added transform node found of a given Id
+ * @param id defines the Id to search for
+ * @returns the found transform node or null if not found at all.
+ * @deprecated Please use getTransformNodeById instead
+ */
+ getTransformNodeByID(id) {
+ return this.getTransformNodeById(id);
+ }
+ /**
+ * Gets a transform node with its auto-generated unique Id
+ * @param uniqueId defines the unique Id to search for
+ * @returns the found transform node or null if not found at all.
+ * @deprecated Please use getTransformNodeByUniqueId instead
+ */
+ getTransformNodeByUniqueID(uniqueId) {
+ return this.getTransformNodeByUniqueId(uniqueId);
+ }
+ /**
+ * Gets a list of transform nodes using their Id
+ * @param id defines the Id to search for
+ * @returns a list of transform nodes
+ * @deprecated Please use getTransformNodesById instead
+ */
+ getTransformNodesByID(id) {
+ return this.getTransformNodesById(id);
+ }
+ /**
+ * Gets a node (Mesh, Camera, Light) using a given Id
+ * @param id defines the Id to search for
+ * @returns the found node or null if not found at all
+ * @deprecated Please use getNodeById instead
+ */
+ getNodeByID(id) {
+ return this.getNodeById(id);
+ }
+ /**
+ * Gets a the last added node (Mesh, Camera, Light) using a given Id
+ * @param id defines the Id to search for
+ * @returns the found node or null if not found at all
+ * @deprecated Please use getLastEntryById instead
+ */
+ getLastEntryByID(id) {
+ return this.getLastEntryById(id);
+ }
+ /**
+ * Gets a skeleton using a given Id (if many are found, this function will pick the last one)
+ * @param id defines the Id to search for
+ * @returns the found skeleton or null if not found at all.
+ * @deprecated Please use getLastSkeletonById instead
+ */
+ getLastSkeletonByID(id) {
+ return this.getLastSkeletonById(id);
+ }
+}
+/** The fog is deactivated */
+Scene.FOGMODE_NONE = 0;
+/** The fog density is following an exponential function */
+Scene.FOGMODE_EXP = 1;
+/** The fog density is following an exponential function faster than FOGMODE_EXP */
+Scene.FOGMODE_EXP2 = 2;
+/** The fog density is following a linear function. */
+Scene.FOGMODE_LINEAR = 3;
+/**
+ * Gets or sets the minimum deltatime when deterministic lock step is enabled
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep
+ */
+Scene.MinDeltaTime = 1.0;
+/**
+ * Gets or sets the maximum deltatime when deterministic lock step is enabled
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep
+ */
+Scene.MaxDeltaTime = 1000.0;
+Scene._OriginalDefaultMaterialFactory = Scene.DefaultMaterialFactory;
+// Register Class Name
+RegisterClass("BABYLON.Scene", Scene);
+
+class AppScene extends Monobehiver {
+ object;
+ constructor(mainApp) {
+ super(mainApp);
+ this.object = null;
+ }
+ /** 初始化场景 */
+ Awake() {
+ this.object = new Scene(this.mainApp.appEngin.object);
+ this.object.clearColor = new Color4(0, 0, 0, 0);
+ this.object.skipFrustumClipping = true;
+ }
+}
+
+/** @internal */
+class _InternalNodeDataInfo {
+ constructor() {
+ this._doNotSerialize = false;
+ this._isDisposed = false;
+ this._sceneRootNodesIndex = -1;
+ this._isEnabled = true;
+ this._isParentEnabled = true;
+ this._isReady = true;
+ this._onEnabledStateChangedObservable = new Observable();
+ this._onClonedObservable = new Observable();
+ }
+}
+/**
+ * Node is the basic class for all scene objects (Mesh, Light, Camera.)
+ */
+let Node$2 = class Node {
+ /**
+ * Add a new node constructor
+ * @param type defines the type name of the node to construct
+ * @param constructorFunc defines the constructor function
+ */
+ static AddNodeConstructor(type, constructorFunc) {
+ this._NodeConstructors[type] = constructorFunc;
+ }
+ /**
+ * Returns a node constructor based on type name
+ * @param type defines the type name
+ * @param name defines the new node name
+ * @param scene defines the hosting scene
+ * @param options defines optional options to transmit to constructors
+ * @returns the new constructor or null
+ */
+ static Construct(type, name, scene, options) {
+ const constructorFunc = this._NodeConstructors[type];
+ if (!constructorFunc) {
+ return null;
+ }
+ return constructorFunc(name, scene, options);
+ }
+ /**
+ * Gets or sets the accessibility tag to describe the node for accessibility purpose.
+ */
+ set accessibilityTag(value) {
+ this._accessibilityTag = value;
+ this.onAccessibilityTagChangedObservable.notifyObservers(value);
+ }
+ get accessibilityTag() {
+ return this._accessibilityTag;
+ }
+ /**
+ * Gets or sets a boolean used to define if the node must be serialized
+ */
+ get doNotSerialize() {
+ if (this._nodeDataStorage._doNotSerialize) {
+ return true;
+ }
+ if (this._parentNode) {
+ return this._parentNode.doNotSerialize;
+ }
+ return false;
+ }
+ set doNotSerialize(value) {
+ this._nodeDataStorage._doNotSerialize = value;
+ }
+ /**
+ * Gets a boolean indicating if the node has been disposed
+ * @returns true if the node was disposed
+ */
+ isDisposed() {
+ return this._nodeDataStorage._isDisposed;
+ }
+ /**
+ * Gets or sets the parent of the node (without keeping the current position in the scene)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent
+ */
+ set parent(parent) {
+ if (this._parentNode === parent) {
+ return;
+ }
+ const previousParentNode = this._parentNode;
+ // Remove self from list of children of parent
+ if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
+ const index = this._parentNode._children.indexOf(this);
+ if (index !== -1) {
+ this._parentNode._children.splice(index, 1);
+ }
+ if (!parent && !this._nodeDataStorage._isDisposed) {
+ this._addToSceneRootNodes();
+ }
+ }
+ // Store new parent
+ this._parentNode = parent;
+ this._isDirty = true;
+ // Add as child to new parent
+ if (this._parentNode) {
+ if (this._parentNode._children === undefined || this._parentNode._children === null) {
+ this._parentNode._children = new Array();
+ }
+ this._parentNode._children.push(this);
+ if (!previousParentNode) {
+ this._removeFromSceneRootNodes();
+ }
+ }
+ // Enabled state
+ this._syncParentEnabledState();
+ }
+ get parent() {
+ return this._parentNode;
+ }
+ /**
+ * @internal
+ */
+ _serializeAsParent(serializationObject) {
+ serializationObject.parentId = this.uniqueId;
+ }
+ /** @internal */
+ _addToSceneRootNodes() {
+ if (this._nodeDataStorage._sceneRootNodesIndex === -1) {
+ this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length;
+ this._scene.rootNodes.push(this);
+ }
+ }
+ /** @internal */
+ _removeFromSceneRootNodes() {
+ if (this._nodeDataStorage._sceneRootNodesIndex !== -1) {
+ const rootNodes = this._scene.rootNodes;
+ const lastIdx = rootNodes.length - 1;
+ rootNodes[this._nodeDataStorage._sceneRootNodesIndex] = rootNodes[lastIdx];
+ rootNodes[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex = this._nodeDataStorage._sceneRootNodesIndex;
+ this._scene.rootNodes.pop();
+ this._nodeDataStorage._sceneRootNodesIndex = -1;
+ }
+ }
+ /**
+ * Gets or sets the animation properties override
+ */
+ get animationPropertiesOverride() {
+ if (!this._animationPropertiesOverride) {
+ return this._scene.animationPropertiesOverride;
+ }
+ return this._animationPropertiesOverride;
+ }
+ set animationPropertiesOverride(value) {
+ this._animationPropertiesOverride = value;
+ }
+ /**
+ * Gets a string identifying the name of the class
+ * @returns "Node" string
+ */
+ getClassName() {
+ return "Node";
+ }
+ /**
+ * Sets a callback that will be raised when the node will be disposed
+ */
+ set onDispose(callback) {
+ if (this._onDisposeObserver) {
+ this.onDisposeObservable.remove(this._onDisposeObserver);
+ }
+ this._onDisposeObserver = this.onDisposeObservable.add(callback);
+ }
+ /**
+ * An event triggered when the enabled state of the node changes
+ */
+ get onEnabledStateChangedObservable() {
+ return this._nodeDataStorage._onEnabledStateChangedObservable;
+ }
+ /**
+ * An event triggered when the node is cloned
+ */
+ get onClonedObservable() {
+ return this._nodeDataStorage._onClonedObservable;
+ }
+ /**
+ * Creates a new Node
+ * @param name the name and id to be given to this node
+ * @param scene the scene this node will be added to
+ * @param isPure indicates this Node is just a Node, and not a derived class like Mesh or Camera
+ */
+ constructor(name, scene = null, isPure = true) {
+ this._isDirty = false;
+ this._nodeDataStorage = new _InternalNodeDataInfo();
+ /**
+ * Gets or sets a string used to store user defined state for the node
+ */
+ this.state = "";
+ /**
+ * Gets or sets an object used to store user defined information for the node
+ */
+ this.metadata = null;
+ /**
+ * For internal use only. Please do not use.
+ */
+ this.reservedDataStore = null;
+ this._accessibilityTag = null;
+ /**
+ * Observable fired when an accessibility tag is changed
+ */
+ this.onAccessibilityTagChangedObservable = new Observable();
+ /** @internal */
+ this._parentContainer = null;
+ /**
+ * Gets a list of Animations associated with the node
+ */
+ this.animations = [];
+ this._ranges = {};
+ /**
+ * Callback raised when the node is ready to be used
+ */
+ this.onReady = null;
+ /** @internal */
+ this._currentRenderId = -1;
+ this._parentUpdateId = -1;
+ /** @internal */
+ this._childUpdateId = -1;
+ /** @internal */
+ this._waitingParentId = null;
+ /** @internal */
+ this._waitingParentInstanceIndex = null;
+ /** @internal */
+ this._waitingParsedUniqueId = null;
+ /** @internal */
+ this._cache = {};
+ this._parentNode = null;
+ /** @internal */
+ this._children = null;
+ /** @internal */
+ this._worldMatrix = Matrix.Identity();
+ /** @internal */
+ this._worldMatrixDeterminant = 0;
+ /** @internal */
+ this._worldMatrixDeterminantIsDirty = true;
+ this._animationPropertiesOverride = null;
+ /** @internal */
+ this._isNode = true;
+ /**
+ * An event triggered when the mesh is disposed
+ */
+ this.onDisposeObservable = new Observable();
+ this._onDisposeObserver = null;
+ // Behaviors
+ this._behaviors = new Array();
+ this.name = name;
+ this.id = name;
+ this._scene = (scene || EngineStore.LastCreatedScene);
+ this.uniqueId = this._scene.getUniqueId();
+ this._initCache();
+ if (isPure) {
+ this._addToSceneRootNodes();
+ }
+ }
+ /**
+ * Gets the scene of the node
+ * @returns a scene
+ */
+ getScene() {
+ return this._scene;
+ }
+ /**
+ * Gets the engine of the node
+ * @returns a Engine
+ */
+ getEngine() {
+ return this._scene.getEngine();
+ }
+ /**
+ * Attach a behavior to the node
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors
+ * @param behavior defines the behavior to attach
+ * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
+ * @returns the current Node
+ */
+ addBehavior(behavior, attachImmediately = false) {
+ const index = this._behaviors.indexOf(behavior);
+ if (index !== -1) {
+ return this;
+ }
+ behavior.init();
+ if (this._scene.isLoading && !attachImmediately) {
+ // We defer the attach when the scene will be loaded
+ this._scene.onDataLoadedObservable.addOnce(() => {
+ behavior.attach(this);
+ });
+ }
+ else {
+ behavior.attach(this);
+ }
+ this._behaviors.push(behavior);
+ return this;
+ }
+ /**
+ * Remove an attached behavior
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors
+ * @param behavior defines the behavior to attach
+ * @returns the current Node
+ */
+ removeBehavior(behavior) {
+ const index = this._behaviors.indexOf(behavior);
+ if (index === -1) {
+ return this;
+ }
+ this._behaviors[index].detach();
+ this._behaviors.splice(index, 1);
+ return this;
+ }
+ /**
+ * Gets the list of attached behaviors
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors
+ */
+ get behaviors() {
+ return this._behaviors;
+ }
+ /**
+ * Gets an attached behavior by name
+ * @param name defines the name of the behavior to look for
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors
+ * @returns null if behavior was not found else the requested behavior
+ */
+ getBehaviorByName(name) {
+ for (const behavior of this._behaviors) {
+ if (behavior.name === name) {
+ return behavior;
+ }
+ }
+ return null;
+ }
+ /**
+ * Returns the latest update of the World matrix
+ * @returns a Matrix
+ */
+ getWorldMatrix() {
+ if (this._currentRenderId !== this._scene.getRenderId()) {
+ this.computeWorldMatrix();
+ }
+ return this._worldMatrix;
+ }
+ /** @internal */
+ _getWorldMatrixDeterminant() {
+ if (this._worldMatrixDeterminantIsDirty) {
+ this._worldMatrixDeterminantIsDirty = false;
+ this._worldMatrixDeterminant = this._worldMatrix.determinant();
+ }
+ return this._worldMatrixDeterminant;
+ }
+ /**
+ * Returns directly the latest state of the mesh World matrix.
+ * A Matrix is returned.
+ */
+ get worldMatrixFromCache() {
+ return this._worldMatrix;
+ }
+ // override it in derived class if you add new variables to the cache
+ // and call the parent class method
+ /** @internal */
+ _initCache() {
+ this._cache = {};
+ }
+ /**
+ * @internal
+ */
+ updateCache(force) {
+ if (!force && this.isSynchronized()) {
+ return;
+ }
+ this._updateCache();
+ }
+ /**
+ * @internal
+ */
+ _getActionManagerForTrigger(trigger, _initialCall = true) {
+ if (!this.parent) {
+ return null;
+ }
+ return this.parent._getActionManagerForTrigger(trigger, false);
+ }
+ // override it in derived class if you add new variables to the cache
+ // and call the parent class method if !ignoreParentClass
+ /**
+ * @internal
+ */
+ _updateCache(_ignoreParentClass) { }
+ // override it in derived class if you add new variables to the cache
+ /** @internal */
+ _isSynchronized() {
+ return true;
+ }
+ /** @internal */
+ _markSyncedWithParent() {
+ if (this._parentNode) {
+ this._parentUpdateId = this._parentNode._childUpdateId;
+ }
+ }
+ /** @internal */
+ isSynchronizedWithParent() {
+ if (!this._parentNode) {
+ return true;
+ }
+ if (this._parentNode._isDirty || this._parentUpdateId !== this._parentNode._childUpdateId) {
+ return false;
+ }
+ return this._parentNode.isSynchronized();
+ }
+ /** @internal */
+ isSynchronized() {
+ if (this._parentNode && !this.isSynchronizedWithParent()) {
+ return false;
+ }
+ return this._isSynchronized();
+ }
+ /**
+ * Is this node ready to be used/rendered
+ * @param _completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
+ * @returns true if the node is ready
+ */
+ isReady(_completeCheck = false) {
+ return this._nodeDataStorage._isReady;
+ }
+ /**
+ * Flag the node as dirty (Forcing it to update everything)
+ * @param _property helps children apply precise "dirtyfication"
+ * @returns this node
+ */
+ markAsDirty(_property) {
+ this._currentRenderId = Number.MAX_VALUE;
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Is this node enabled?
+ * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
+ * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
+ * @returns whether this node (and its parent) is enabled
+ */
+ isEnabled(checkAncestors = true) {
+ if (checkAncestors === false) {
+ return this._nodeDataStorage._isEnabled;
+ }
+ if (!this._nodeDataStorage._isEnabled) {
+ return false;
+ }
+ return this._nodeDataStorage._isParentEnabled;
+ }
+ /** @internal */
+ _syncParentEnabledState() {
+ this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
+ if (this._children) {
+ this._children.forEach((c) => {
+ c._syncParentEnabledState(); // Force children to update accordingly
+ });
+ }
+ }
+ /**
+ * Set the enabled state of this node
+ * @param value defines the new enabled state
+ */
+ setEnabled(value) {
+ if (this._nodeDataStorage._isEnabled === value) {
+ return;
+ }
+ this._nodeDataStorage._isEnabled = value;
+ this._syncParentEnabledState();
+ this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(value);
+ }
+ /**
+ * Is this node a descendant of the given node?
+ * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
+ * @param ancestor defines the parent node to inspect
+ * @returns a boolean indicating if this node is a descendant of the given node
+ */
+ isDescendantOf(ancestor) {
+ if (this.parent) {
+ if (this.parent === ancestor) {
+ return true;
+ }
+ return this.parent.isDescendantOf(ancestor);
+ }
+ return false;
+ }
+ /**
+ * @internal
+ */
+ _getDescendants(results, directDescendantsOnly = false, predicate) {
+ if (!this._children) {
+ return;
+ }
+ for (let index = 0; index < this._children.length; index++) {
+ const item = this._children[index];
+ if (!predicate || predicate(item)) {
+ results.push(item);
+ }
+ if (!directDescendantsOnly) {
+ item._getDescendants(results, false, predicate);
+ }
+ }
+ }
+ /**
+ * Will return all nodes that have this node as ascendant
+ * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
+ * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
+ * @returns all children nodes of all types
+ */
+ getDescendants(directDescendantsOnly, predicate) {
+ const results = [];
+ this._getDescendants(results, directDescendantsOnly, predicate);
+ return results;
+ }
+ /**
+ * Get all child-meshes of this node
+ * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: false)
+ * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
+ * @returns an array of AbstractMesh
+ */
+ getChildMeshes(directDescendantsOnly, predicate) {
+ const results = [];
+ this._getDescendants(results, directDescendantsOnly, (node) => {
+ return (!predicate || predicate(node)) && node.cullingStrategy !== undefined;
+ });
+ return results;
+ }
+ /**
+ * Get all direct children of this node
+ * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
+ * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: true)
+ * @returns an array of Node
+ */
+ getChildren(predicate, directDescendantsOnly = true) {
+ return this.getDescendants(directDescendantsOnly, predicate);
+ }
+ /**
+ * @internal
+ */
+ _setReady(state) {
+ if (state === this._nodeDataStorage._isReady) {
+ return;
+ }
+ if (!state) {
+ this._nodeDataStorage._isReady = false;
+ return;
+ }
+ if (this.onReady) {
+ this.onReady(this);
+ }
+ this._nodeDataStorage._isReady = true;
+ }
+ /**
+ * Get an animation by name
+ * @param name defines the name of the animation to look for
+ * @returns null if not found else the requested animation
+ */
+ getAnimationByName(name) {
+ for (let i = 0; i < this.animations.length; i++) {
+ const animation = this.animations[i];
+ if (animation.name === name) {
+ return animation;
+ }
+ }
+ return null;
+ }
+ /**
+ * Creates an animation range for this node
+ * @param name defines the name of the range
+ * @param from defines the starting key
+ * @param to defines the end key
+ */
+ createAnimationRange(name, from, to) {
+ // check name not already in use
+ if (!this._ranges[name]) {
+ this._ranges[name] = Node._AnimationRangeFactory(name, from, to);
+ for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
+ if (this.animations[i]) {
+ this.animations[i].createRange(name, from, to);
+ }
+ }
+ }
+ }
+ /**
+ * Delete a specific animation range
+ * @param name defines the name of the range to delete
+ * @param deleteFrames defines if animation frames from the range must be deleted as well
+ */
+ deleteAnimationRange(name, deleteFrames = true) {
+ for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
+ if (this.animations[i]) {
+ this.animations[i].deleteRange(name, deleteFrames);
+ }
+ }
+ this._ranges[name] = null; // said much faster than 'delete this._range[name]'
+ }
+ /**
+ * Get an animation range by name
+ * @param name defines the name of the animation range to look for
+ * @returns null if not found else the requested animation range
+ */
+ getAnimationRange(name) {
+ return this._ranges[name] || null;
+ }
+ /**
+ * Clone the current node
+ * @param name Name of the new clone
+ * @param newParent New parent for the clone
+ * @param doNotCloneChildren Do not clone children hierarchy
+ * @returns the new transform node
+ */
+ clone(name, newParent, doNotCloneChildren) {
+ const result = SerializationHelper.Clone(() => new Node(name, this.getScene()), this);
+ if (newParent) {
+ result.parent = newParent;
+ }
+ if (!doNotCloneChildren) {
+ // Children
+ const directDescendants = this.getDescendants(true);
+ for (let index = 0; index < directDescendants.length; index++) {
+ const child = directDescendants[index];
+ child.clone(name + "." + child.name, result);
+ }
+ }
+ return result;
+ }
+ /**
+ * Gets the list of all animation ranges defined on this node
+ * @returns an array
+ */
+ getAnimationRanges() {
+ const animationRanges = [];
+ let name;
+ for (name in this._ranges) {
+ animationRanges.push(this._ranges[name]);
+ }
+ return animationRanges;
+ }
+ /**
+ * Will start the animation sequence
+ * @param name defines the range frames for animation sequence
+ * @param loop defines if the animation should loop (false by default)
+ * @param speedRatio defines the speed factor in which to run the animation (1 by default)
+ * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
+ * @returns the object created for this animation. If range does not exist, it will return null
+ */
+ beginAnimation(name, loop, speedRatio, onAnimationEnd) {
+ const range = this.getAnimationRange(name);
+ if (!range) {
+ return null;
+ }
+ return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
+ }
+ /**
+ * Serialize animation ranges into a JSON compatible object
+ * @returns serialization object
+ */
+ serializeAnimationRanges() {
+ const serializationRanges = [];
+ for (const name in this._ranges) {
+ const localRange = this._ranges[name];
+ if (!localRange) {
+ continue;
+ }
+ const range = {};
+ range.name = name;
+ range.from = localRange.from;
+ range.to = localRange.to;
+ serializationRanges.push(range);
+ }
+ return serializationRanges;
+ }
+ /**
+ * Computes the world matrix of the node
+ * @param _force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
+ * @returns the world matrix
+ */
+ computeWorldMatrix(_force) {
+ if (!this._worldMatrix) {
+ this._worldMatrix = Matrix.Identity();
+ }
+ return this._worldMatrix;
+ }
+ /**
+ * Releases resources associated with this node.
+ * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
+ * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
+ */
+ dispose(doNotRecurse, disposeMaterialAndTextures = false) {
+ this._nodeDataStorage._isDisposed = true;
+ if (!doNotRecurse) {
+ const nodes = this.getDescendants(true);
+ for (const node of nodes) {
+ node.dispose(doNotRecurse, disposeMaterialAndTextures);
+ }
+ }
+ if (!this.parent) {
+ this._removeFromSceneRootNodes();
+ }
+ else {
+ this.parent = null;
+ }
+ // Callback
+ this.onDisposeObservable.notifyObservers(this);
+ this.onDisposeObservable.clear();
+ this.onEnabledStateChangedObservable.clear();
+ this.onClonedObservable.clear();
+ // Behaviors
+ for (const behavior of this._behaviors) {
+ behavior.detach();
+ }
+ this._behaviors.length = 0;
+ this.metadata = null;
+ }
+ /**
+ * Parse animation range data from a serialization object and store them into a given node
+ * @param node defines where to store the animation ranges
+ * @param parsedNode defines the serialization object to read data from
+ * @param _scene defines the hosting scene
+ */
+ static ParseAnimationRanges(node, parsedNode, _scene) {
+ if (parsedNode.ranges) {
+ for (let index = 0; index < parsedNode.ranges.length; index++) {
+ const data = parsedNode.ranges[index];
+ node.createAnimationRange(data.name, data.from, data.to);
+ }
+ }
+ }
+ /**
+ * Return the minimum and maximum world vectors of the entire hierarchy under current node
+ * @param includeDescendants Include bounding info from descendants as well (true by default)
+ * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
+ * @returns the new bounding vectors
+ */
+ getHierarchyBoundingVectors(includeDescendants = true, predicate = null) {
+ // Ensures that all world matrix will be recomputed.
+ this.getScene().incrementRenderId();
+ this.computeWorldMatrix(true);
+ let min;
+ let max;
+ const thisAbstractMesh = this;
+ if (thisAbstractMesh.getBoundingInfo && thisAbstractMesh.subMeshes) {
+ // If this is an abstract mesh get its bounding info
+ const boundingInfo = thisAbstractMesh.getBoundingInfo();
+ min = boundingInfo.boundingBox.minimumWorld.clone();
+ max = boundingInfo.boundingBox.maximumWorld.clone();
+ }
+ else {
+ min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+ }
+ if (includeDescendants) {
+ const descendants = this.getDescendants(false);
+ for (const descendant of descendants) {
+ const childMesh = descendant;
+ childMesh.computeWorldMatrix(true);
+ // Filters meshes based on custom predicate function.
+ if (predicate && !predicate(childMesh)) {
+ continue;
+ }
+ //make sure we have the needed params to get mix and max
+ if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
+ continue;
+ }
+ const childBoundingInfo = childMesh.getBoundingInfo();
+ const boundingBox = childBoundingInfo.boundingBox;
+ const minBox = boundingBox.minimumWorld;
+ const maxBox = boundingBox.maximumWorld;
+ Vector3.CheckExtends(minBox, min, max);
+ Vector3.CheckExtends(maxBox, min, max);
+ }
+ }
+ return {
+ min: min,
+ max: max,
+ };
+ }
+};
+/**
+ * @internal
+ */
+Node$2._AnimationRangeFactory = (_name, _from, _to) => {
+ throw _WarnImport("AnimationRange");
+};
+Node$2._NodeConstructors = {};
+__decorate([
+ serialize()
+], Node$2.prototype, "name", void 0);
+__decorate([
+ serialize()
+], Node$2.prototype, "id", void 0);
+__decorate([
+ serialize()
+], Node$2.prototype, "uniqueId", void 0);
+__decorate([
+ serialize()
+], Node$2.prototype, "state", void 0);
+__decorate([
+ serialize()
+], Node$2.prototype, "metadata", void 0);
+
+/* eslint-disable @typescript-eslint/naming-convention */
+// "Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed."
+// https://en.wikipedia.org/wiki/Coroutine
+// The inline scheduler simply steps the coroutine synchronously. This is useful for running a coroutine synchronously, and also as a helper function for other schedulers.
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function inlineScheduler(coroutine, onStep, onError) {
+ try {
+ const step = coroutine.next();
+ if (step.done) {
+ onStep(step);
+ }
+ else if (!step.value) {
+ // NOTE: The properties of step have been narrowed, but the type of step itself is not narrowed, so the cast below is the most type safe way to deal with this without instantiating a new object to hold the values.
+ onStep(step);
+ }
+ else {
+ step.value.then(() => {
+ step.value = undefined;
+ onStep(step);
+ }, onError);
+ }
+ }
+ catch (error) {
+ onError(error);
+ }
+}
+// The yielding scheduler steps the coroutine synchronously until the specified time interval has elapsed, then yields control so other operations can be performed.
+// A single instance of a yielding scheduler could be shared across multiple coroutines to yield when their collective work exceeds the threshold.
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function createYieldingScheduler(yieldAfterMS = 25) {
+ let startTime;
+ return (coroutine, onStep, onError) => {
+ const currentTime = performance.now();
+ if (startTime === undefined || currentTime - startTime > yieldAfterMS) {
+ // If this is the first coroutine step, or if the time interval has elapsed, record a new start time, and schedule the coroutine step to happen later, effectively yielding control of the execution context.
+ startTime = currentTime;
+ setTimeout(() => {
+ inlineScheduler(coroutine, onStep, onError);
+ }, 0);
+ }
+ else {
+ // Otherwise it is not time to yield yet, so step the coroutine synchronously.
+ inlineScheduler(coroutine, onStep, onError);
+ }
+ };
+}
+// Runs the specified coroutine with the specified scheduler. The success or error callback will be invoked when the coroutine finishes.
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function runCoroutine(coroutine, scheduler, onSuccess, onError, abortSignal) {
+ const resume = () => {
+ let reschedule;
+ const onStep = (stepResult) => {
+ if (stepResult.done) {
+ // If the coroutine is done, report success.
+ onSuccess(stepResult.value);
+ }
+ else {
+ // If the coroutine is not done, resume the coroutine (via the scheduler).
+ if (reschedule === undefined) {
+ // If reschedule is undefined at this point, then the coroutine must have stepped synchronously, so just flag another loop iteration.
+ reschedule = true;
+ }
+ else {
+ // If reschedule is defined at this point, then the coroutine must have stepped asynchronously, so call resume to restart the step loop.
+ resume();
+ }
+ }
+ };
+ do {
+ reschedule = undefined;
+ {
+ scheduler(coroutine, onStep, onError);
+ }
+ if (reschedule === undefined) {
+ // If reschedule is undefined at this point, then the coroutine must have stepped asynchronously, so stop looping and let the coroutine be resumed later.
+ reschedule = false;
+ }
+ } while (reschedule);
+ };
+ resume();
+}
+// Runs the specified coroutine synchronously.
+/**
+ * @internal
+ */
+function runCoroutineSync(coroutine, abortSignal) {
+ // Run the coroutine with the inline scheduler, storing the returned value, or re-throwing the error (since the error callback will be called synchronously by the inline scheduler).
+ let result;
+ runCoroutine(coroutine, inlineScheduler, (r) => (result = r), (e) => {
+ throw e;
+ });
+ // Synchronously return the result of the coroutine.
+ return result;
+}
+// Runs the specified coroutine asynchronously with the specified scheduler.
+/**
+ * @internal
+ */
+function runCoroutineAsync(coroutine, scheduler, abortSignal) {
+ // Run the coroutine with a yielding scheduler, resolving or rejecting the result promise when the coroutine finishes.
+ return new Promise((resolve, reject) => {
+ runCoroutine(coroutine, scheduler, resolve, reject);
+ });
+}
+/**
+ * Given a function that returns a Coroutine, produce a function with the same parameters that returns a T.
+ * The returned function runs the coroutine synchronously.
+ * @param coroutineFactory A function that returns a Coroutine.
+ * @param abortSignal
+ * @returns A function that runs the coroutine synchronously.
+ * @internal
+ */
+function makeSyncFunction(coroutineFactory, abortSignal) {
+ return (...params) => {
+ // Run the coroutine synchronously.
+ return runCoroutineSync(coroutineFactory(...params));
+ };
+}
+
+/**
+ * This is the base class of all the camera used in the application.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras
+ */
+class Camera extends Node$2 {
+ /**
+ * Define the current local position of the camera in the scene
+ */
+ get position() {
+ return this._position;
+ }
+ set position(newPosition) {
+ this._position = newPosition;
+ }
+ /**
+ * The vector the camera should consider as up.
+ * (default is Vector3(0, 1, 0) aka Vector3.Up())
+ */
+ set upVector(vec) {
+ this._upVector = vec;
+ }
+ get upVector() {
+ return this._upVector;
+ }
+ /**
+ * The screen area in scene units squared
+ */
+ get screenArea() {
+ let x = 0;
+ let y = 0;
+ if (this.mode === Camera.PERSPECTIVE_CAMERA) {
+ if (this.fovMode === Camera.FOVMODE_VERTICAL_FIXED) {
+ y = this.minZ * 2 * Math.tan(this.fov / 2);
+ x = this.getEngine().getAspectRatio(this) * y;
+ }
+ else {
+ x = this.minZ * 2 * Math.tan(this.fov / 2);
+ y = x / this.getEngine().getAspectRatio(this);
+ }
+ }
+ else {
+ const halfWidth = this.getEngine().getRenderWidth() / 2.0;
+ const halfHeight = this.getEngine().getRenderHeight() / 2.0;
+ x = (this.orthoRight ?? halfWidth) - (this.orthoLeft ?? -halfWidth);
+ y = (this.orthoTop ?? halfHeight) - (this.orthoBottom ?? -halfHeight);
+ }
+ return x * y;
+ }
+ /**
+ * Define the current limit on the left side for an orthographic camera
+ * In scene unit
+ */
+ set orthoLeft(value) {
+ this._orthoLeft = value;
+ for (const rigCamera of this._rigCameras) {
+ rigCamera.orthoLeft = value;
+ }
+ }
+ get orthoLeft() {
+ return this._orthoLeft;
+ }
+ /**
+ * Define the current limit on the right side for an orthographic camera
+ * In scene unit
+ */
+ set orthoRight(value) {
+ this._orthoRight = value;
+ for (const rigCamera of this._rigCameras) {
+ rigCamera.orthoRight = value;
+ }
+ }
+ get orthoRight() {
+ return this._orthoRight;
+ }
+ /**
+ * Define the current limit on the bottom side for an orthographic camera
+ * In scene unit
+ */
+ set orthoBottom(value) {
+ this._orthoBottom = value;
+ for (const rigCamera of this._rigCameras) {
+ rigCamera.orthoBottom = value;
+ }
+ }
+ get orthoBottom() {
+ return this._orthoBottom;
+ }
+ /**
+ * Define the current limit on the top side for an orthographic camera
+ * In scene unit
+ */
+ set orthoTop(value) {
+ this._orthoTop = value;
+ for (const rigCamera of this._rigCameras) {
+ rigCamera.orthoTop = value;
+ }
+ }
+ get orthoTop() {
+ return this._orthoTop;
+ }
+ /**
+ * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA)
+ */
+ set mode(mode) {
+ this._mode = mode;
+ // Pass the mode down to the rig cameras
+ for (const rigCamera of this._rigCameras) {
+ rigCamera.mode = mode;
+ }
+ }
+ get mode() {
+ return this._mode;
+ }
+ /**
+ * Gets a flag indicating that the camera has moved in some way since the last call to Camera.update()
+ */
+ get hasMoved() {
+ return this._hasMoved;
+ }
+ /**
+ * Instantiates a new camera object.
+ * This should not be used directly but through the inherited cameras: ArcRotate, Free...
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras
+ * @param name Defines the name of the camera in the scene
+ * @param position Defines the position of the camera
+ * @param scene Defines the scene the camera belongs too
+ * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
+ */
+ constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {
+ super(name, scene, false);
+ /** @internal */
+ this._position = Vector3.Zero();
+ this._upVector = Vector3.Up();
+ /**
+ * Object containing oblique projection values (only used with ORTHOGRAPHIC_CAMERA)
+ */
+ this.oblique = null;
+ this._orthoLeft = null;
+ this._orthoRight = null;
+ this._orthoBottom = null;
+ this._orthoTop = null;
+ /**
+ * Field Of View is set in Radians. (default is 0.8)
+ */
+ this.fov = 0.8;
+ /**
+ * Projection plane tilt around the X axis (horizontal), set in Radians. (default is 0)
+ * Can be used to make vertical lines in world space actually vertical on the screen.
+ * See https://forum.babylonjs.com/t/add-vertical-shift-to-3ds-max-exporter-babylon-cameras/17480
+ */
+ this.projectionPlaneTilt = 0;
+ /**
+ * Define the minimum distance the camera can see from.
+ * This is important to note that the depth buffer are not infinite and the closer it starts
+ * the more your scene might encounter depth fighting issue.
+ */
+ this.minZ = 1;
+ /**
+ * Define the maximum distance the camera can see to. (default is 10000)
+ * This is important to note that the depth buffer are not infinite and the further it end
+ * the more your scene might encounter depth fighting issue.
+ */
+ this.maxZ = 10000.0;
+ /**
+ * Define the default inertia of the camera.
+ * This helps giving a smooth feeling to the camera movement.
+ */
+ this.inertia = 0.9;
+ this._mode = Camera.PERSPECTIVE_CAMERA;
+ /**
+ * Define whether the camera is intermediate.
+ * This is useful to not present the output directly to the screen in case of rig without post process for instance
+ */
+ this.isIntermediate = false;
+ /**
+ * Define the viewport of the camera.
+ * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
+ */
+ this.viewport = new Viewport(0, 0, 1.0, 1.0);
+ /**
+ * Restricts the camera to viewing objects with the same layerMask.
+ * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
+ */
+ this.layerMask = 0x0fffffff;
+ /**
+ * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
+ */
+ this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
+ /**
+ * Rig mode of the camera.
+ * This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
+ * This is normally controlled byt the camera themselves as internal use.
+ */
+ this.cameraRigMode = Camera.RIG_MODE_NONE;
+ /**
+ * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
+ * This is pretty helpful if you wish to make a camera render to a texture you could reuse somewhere
+ * else in the scene. (Eg. security camera)
+ *
+ * To change the final output target of the camera, camera.outputRenderTarget should be used instead (eg. webXR renders to a render target corresponding to an HMD)
+ */
+ this.customRenderTargets = [];
+ /**
+ * When set, the camera will render to this render target instead of the default canvas
+ *
+ * If the desire is to use the output of a camera as a texture in the scene consider using camera.customRenderTargets instead
+ */
+ this.outputRenderTarget = null;
+ /**
+ * Observable triggered when the camera view matrix has changed.
+ * Beware of reentrance! Some methods like Camera.getViewMatrix and Camera.getWorldMatrix can trigger the onViewMatrixChangedObservable
+ * observable, so using them inside an observer will require additional logic to avoid a stack overflow error.
+ */
+ this.onViewMatrixChangedObservable = new Observable();
+ /**
+ * Observable triggered when the camera Projection matrix has changed.
+ */
+ this.onProjectionMatrixChangedObservable = new Observable();
+ /**
+ * Observable triggered when the inputs have been processed.
+ */
+ this.onAfterCheckInputsObservable = new Observable();
+ /**
+ * Observable triggered when reset has been called and applied to the camera.
+ */
+ this.onRestoreStateObservable = new Observable();
+ /**
+ * Is this camera a part of a rig system?
+ */
+ this.isRigCamera = false;
+ this._hasMoved = false;
+ /** @internal */
+ this._rigCameras = new Array();
+ /** @internal */
+ this._skipRendering = false;
+ /** @internal */
+ this._projectionMatrix = new Matrix();
+ /** @internal */
+ this._postProcesses = new Array();
+ /** @internal */
+ this._activeMeshes = new SmartArray(256);
+ this._globalPosition = Vector3.Zero();
+ /** @internal */
+ this._computedViewMatrix = Matrix.Identity();
+ this._doNotComputeProjectionMatrix = false;
+ this._transformMatrix = Matrix.Zero();
+ this._refreshFrustumPlanes = true;
+ this._absoluteRotation = Quaternion.Identity();
+ /** @internal */
+ this._isCamera = true;
+ /** @internal */
+ this._isLeftCamera = false;
+ /** @internal */
+ this._isRightCamera = false;
+ this.getScene().addCamera(this);
+ if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) {
+ this.getScene().activeCamera = this;
+ }
+ this.position = position;
+ this.renderPassId = this.getScene().getEngine().createRenderPassId(`Camera ${name}`);
+ }
+ /**
+ * Store current camera state (fov, position, etc..)
+ * @returns the camera
+ */
+ storeState() {
+ this._stateStored = true;
+ this._storedFov = this.fov;
+ return this;
+ }
+ /**
+ * Returns true if a state has been stored by calling storeState method.
+ * @returns true if state has been stored.
+ */
+ hasStateStored() {
+ return !!this._stateStored;
+ }
+ /**
+ * Restores the camera state values if it has been stored. You must call storeState() first
+ * @returns true if restored and false otherwise
+ */
+ _restoreStateValues() {
+ if (!this._stateStored) {
+ return false;
+ }
+ this.fov = this._storedFov;
+ return true;
+ }
+ /**
+ * Restored camera state. You must call storeState() first.
+ * @returns true if restored and false otherwise
+ */
+ restoreState() {
+ if (this._restoreStateValues()) {
+ this.onRestoreStateObservable.notifyObservers(this);
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Gets the class name of the camera.
+ * @returns the class name
+ */
+ getClassName() {
+ return "Camera";
+ }
+ /**
+ * Gets a string representation of the camera useful for debug purpose.
+ * @param fullDetails Defines that a more verbose level of logging is required
+ * @returns the string representation
+ */
+ toString(fullDetails) {
+ let ret = "Name: " + this.name;
+ ret += ", type: " + this.getClassName();
+ if (this.animations) {
+ for (let i = 0; i < this.animations.length; i++) {
+ ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
+ }
+ }
+ return ret;
+ }
+ /**
+ * Automatically tilts the projection plane, using `projectionPlaneTilt`, to correct the perspective effect on vertical lines.
+ */
+ applyVerticalCorrection() {
+ const rot = this.absoluteRotation.toEulerAngles();
+ this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -rot.x : rot.x;
+ }
+ /**
+ * Gets the current world space position of the camera.
+ */
+ get globalPosition() {
+ return this._globalPosition;
+ }
+ /**
+ * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
+ * @returns the active meshe list
+ */
+ getActiveMeshes() {
+ return this._activeMeshes;
+ }
+ /**
+ * Check whether a mesh is part of the current active mesh list of the camera
+ * @param mesh Defines the mesh to check
+ * @returns true if active, false otherwise
+ */
+ isActiveMesh(mesh) {
+ return this._activeMeshes.indexOf(mesh) !== -1;
+ }
+ /**
+ * Is this camera ready to be used/rendered
+ * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
+ * @returns true if the camera is ready
+ */
+ isReady(completeCheck = false) {
+ if (completeCheck) {
+ for (const pp of this._postProcesses) {
+ if (pp && !pp.isReady()) {
+ return false;
+ }
+ }
+ }
+ return super.isReady(completeCheck);
+ }
+ /** @internal */
+ _initCache() {
+ super._initCache();
+ this._cache.position = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._cache.upVector = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._cache.mode = undefined;
+ this._cache.minZ = undefined;
+ this._cache.maxZ = undefined;
+ this._cache.fov = undefined;
+ this._cache.fovMode = undefined;
+ this._cache.aspectRatio = undefined;
+ this._cache.orthoLeft = undefined;
+ this._cache.orthoRight = undefined;
+ this._cache.orthoBottom = undefined;
+ this._cache.orthoTop = undefined;
+ this._cache.obliqueAngle = undefined;
+ this._cache.obliqueLength = undefined;
+ this._cache.obliqueOffset = undefined;
+ this._cache.renderWidth = undefined;
+ this._cache.renderHeight = undefined;
+ }
+ /**
+ * @internal
+ */
+ _updateCache(ignoreParentClass) {
+ if (!ignoreParentClass) {
+ super._updateCache();
+ }
+ this._cache.position.copyFrom(this.position);
+ this._cache.upVector.copyFrom(this.upVector);
+ }
+ /** @internal */
+ _isSynchronized() {
+ return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
+ }
+ /** @internal */
+ _isSynchronizedViewMatrix() {
+ if (!super._isSynchronized()) {
+ return false;
+ }
+ return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
+ }
+ /** @internal */
+ _isSynchronizedProjectionMatrix() {
+ let isSynchronized = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
+ if (!isSynchronized) {
+ return false;
+ }
+ const engine = this.getEngine();
+ if (this.mode === Camera.PERSPECTIVE_CAMERA) {
+ isSynchronized =
+ this._cache.fov === this.fov &&
+ this._cache.fovMode === this.fovMode &&
+ this._cache.aspectRatio === engine.getAspectRatio(this) &&
+ this._cache.projectionPlaneTilt === this.projectionPlaneTilt;
+ }
+ else {
+ isSynchronized =
+ this._cache.orthoLeft === this.orthoLeft &&
+ this._cache.orthoRight === this.orthoRight &&
+ this._cache.orthoBottom === this.orthoBottom &&
+ this._cache.orthoTop === this.orthoTop &&
+ this._cache.renderWidth === engine.getRenderWidth() &&
+ this._cache.renderHeight === engine.getRenderHeight();
+ if (this.oblique) {
+ isSynchronized =
+ isSynchronized &&
+ this._cache.obliqueAngle === this.oblique.angle &&
+ this._cache.obliqueLength === this.oblique.length &&
+ this._cache.obliqueOffset === this.oblique.offset;
+ }
+ }
+ return isSynchronized;
+ }
+ /**
+ * Attach the input controls to a specific dom element to get the input from.
+ * This function is here because typescript removes the typing of the last function.
+ * @param _ignored defines an ignored parameter kept for backward compatibility.
+ * @param _noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(_ignored, _noPreventDefault) { }
+ /**
+ * Detach the current controls from the specified dom element.
+ * This function is here because typescript removes the typing of the last function.
+ * @param _ignored defines an ignored parameter kept for backward compatibility.
+ */
+ detachControl(_ignored) { }
+ /**
+ * Update the camera state according to the different inputs gathered during the frame.
+ */
+ update() {
+ this._hasMoved = false;
+ this._checkInputs();
+ if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
+ this._updateRigCameras();
+ }
+ // Attempt to update the camera's view and projection matrices.
+ // This call is being made because these matrices are no longer being updated
+ // as a part of the picking ray process (in addition to scene.render).
+ this.getViewMatrix();
+ this.getProjectionMatrix();
+ }
+ /** @internal */
+ _checkInputs() {
+ this.onAfterCheckInputsObservable.notifyObservers(this);
+ }
+ /** @internal */
+ get rigCameras() {
+ return this._rigCameras;
+ }
+ /**
+ * Gets the post process used by the rig cameras
+ */
+ get rigPostProcess() {
+ return this._rigPostProcess;
+ }
+ /**
+ * Internal, gets the first post process.
+ * @returns the first post process to be run on this camera.
+ */
+ _getFirstPostProcess() {
+ for (let ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
+ if (this._postProcesses[ppIndex] !== null) {
+ return this._postProcesses[ppIndex];
+ }
+ }
+ return null;
+ }
+ _cascadePostProcessesToRigCams() {
+ // invalidate framebuffer
+ const firstPostProcess = this._getFirstPostProcess();
+ if (firstPostProcess) {
+ firstPostProcess.markTextureDirty();
+ }
+ // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
+ for (let i = 0, len = this._rigCameras.length; i < len; i++) {
+ const cam = this._rigCameras[i];
+ const rigPostProcess = cam._rigPostProcess;
+ // for VR rig, there does not have to be a post process
+ if (rigPostProcess) {
+ const isPass = rigPostProcess.getEffectName() === "pass";
+ if (isPass) {
+ // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
+ cam.isIntermediate = this._postProcesses.length === 0;
+ }
+ cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
+ rigPostProcess.markTextureDirty();
+ }
+ else {
+ cam._postProcesses = this._postProcesses.slice(0);
+ }
+ }
+ }
+ /**
+ * Attach a post process to the camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess
+ * @param postProcess The post process to attach to the camera
+ * @param insertAt The position of the post process in case several of them are in use in the scene
+ * @returns the position the post process has been inserted at
+ */
+ attachPostProcess(postProcess, insertAt = null) {
+ if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
+ Logger.Error("You're trying to reuse a post process not defined as reusable.");
+ return 0;
+ }
+ if (insertAt == null || insertAt < 0) {
+ this._postProcesses.push(postProcess);
+ }
+ else if (this._postProcesses[insertAt] === null) {
+ this._postProcesses[insertAt] = postProcess;
+ }
+ else {
+ this._postProcesses.splice(insertAt, 0, postProcess);
+ }
+ this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
+ // Update prePass
+ if (this._scene.prePassRenderer) {
+ this._scene.prePassRenderer.markAsDirty();
+ }
+ return this._postProcesses.indexOf(postProcess);
+ }
+ /**
+ * Detach a post process to the camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess
+ * @param postProcess The post process to detach from the camera
+ */
+ detachPostProcess(postProcess) {
+ const idx = this._postProcesses.indexOf(postProcess);
+ if (idx !== -1) {
+ this._postProcesses[idx] = null;
+ }
+ // Update prePass
+ if (this._scene.prePassRenderer) {
+ this._scene.prePassRenderer.markAsDirty();
+ }
+ this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
+ }
+ /**
+ * Gets the current world matrix of the camera
+ * @returns the world matrix
+ */
+ getWorldMatrix() {
+ if (this._isSynchronizedViewMatrix()) {
+ return this._worldMatrix;
+ }
+ // Getting the view matrix will also compute the world matrix.
+ this.getViewMatrix();
+ return this._worldMatrix;
+ }
+ /** @internal */
+ _getViewMatrix() {
+ return Matrix.Identity();
+ }
+ /**
+ * Gets the current view matrix of the camera.
+ * @param force forces the camera to recompute the matrix without looking at the cached state
+ * @returns the view matrix
+ */
+ getViewMatrix(force) {
+ if (!force && this._isSynchronizedViewMatrix()) {
+ return this._computedViewMatrix;
+ }
+ this._hasMoved = true;
+ this.updateCache();
+ this._computedViewMatrix = this._getViewMatrix();
+ this._currentRenderId = this.getScene().getRenderId();
+ this._childUpdateId++;
+ this._refreshFrustumPlanes = true;
+ if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
+ this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
+ }
+ // Notify parent camera if rig camera is changed
+ if (this.parent && this.parent.onViewMatrixChangedObservable) {
+ this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent);
+ }
+ this.onViewMatrixChangedObservable.notifyObservers(this);
+ this._computedViewMatrix.invertToRef(this._worldMatrix);
+ return this._computedViewMatrix;
+ }
+ /**
+ * Freeze the projection matrix.
+ * It will prevent the cache check of the camera projection compute and can speed up perf
+ * if no parameter of the camera are meant to change
+ * @param projection Defines manually a projection if necessary
+ */
+ freezeProjectionMatrix(projection) {
+ this._doNotComputeProjectionMatrix = true;
+ if (projection !== undefined) {
+ this._projectionMatrix = projection;
+ }
+ }
+ /**
+ * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
+ */
+ unfreezeProjectionMatrix() {
+ this._doNotComputeProjectionMatrix = false;
+ }
+ /**
+ * Gets the current projection matrix of the camera.
+ * @param force forces the camera to recompute the matrix without looking at the cached state
+ * @returns the projection matrix
+ */
+ getProjectionMatrix(force) {
+ if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
+ return this._projectionMatrix;
+ }
+ // Cache
+ this._cache.mode = this.mode;
+ this._cache.minZ = this.minZ;
+ this._cache.maxZ = this.maxZ;
+ // Matrix
+ this._refreshFrustumPlanes = true;
+ const engine = this.getEngine();
+ const scene = this.getScene();
+ const reverseDepth = engine.useReverseDepthBuffer;
+ if (this.mode === Camera.PERSPECTIVE_CAMERA) {
+ this._cache.fov = this.fov;
+ this._cache.fovMode = this.fovMode;
+ this._cache.aspectRatio = engine.getAspectRatio(this);
+ this._cache.projectionPlaneTilt = this.projectionPlaneTilt;
+ if (this.minZ <= 0) {
+ this.minZ = 0.1;
+ }
+ let getProjectionMatrix;
+ if (scene.useRightHandedSystem) {
+ getProjectionMatrix = Matrix.PerspectiveFovRHToRef;
+ }
+ else {
+ getProjectionMatrix = Matrix.PerspectiveFovLHToRef;
+ }
+ getProjectionMatrix(this.fov, engine.getAspectRatio(this), reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED, engine.isNDCHalfZRange, this.projectionPlaneTilt, reverseDepth);
+ }
+ else {
+ const halfWidth = engine.getRenderWidth() / 2.0;
+ const halfHeight = engine.getRenderHeight() / 2.0;
+ if (scene.useRightHandedSystem) {
+ if (this.oblique) {
+ Matrix.ObliqueOffCenterRHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this.oblique.length, this.oblique.angle, this._computeObliqueDistance(this.oblique.offset), this._projectionMatrix, engine.isNDCHalfZRange);
+ }
+ else {
+ Matrix.OrthoOffCenterRHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange);
+ }
+ }
+ else {
+ if (this.oblique) {
+ Matrix.ObliqueOffCenterLHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this.oblique.length, this.oblique.angle, this._computeObliqueDistance(this.oblique.offset), this._projectionMatrix, engine.isNDCHalfZRange);
+ }
+ else {
+ Matrix.OrthoOffCenterLHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange);
+ }
+ }
+ this._cache.orthoLeft = this.orthoLeft;
+ this._cache.orthoRight = this.orthoRight;
+ this._cache.orthoBottom = this.orthoBottom;
+ this._cache.orthoTop = this.orthoTop;
+ this._cache.obliqueAngle = this.oblique?.angle;
+ this._cache.obliqueLength = this.oblique?.length;
+ this._cache.obliqueOffset = this.oblique?.offset;
+ this._cache.renderWidth = engine.getRenderWidth();
+ this._cache.renderHeight = engine.getRenderHeight();
+ }
+ this.onProjectionMatrixChangedObservable.notifyObservers(this);
+ return this._projectionMatrix;
+ }
+ /**
+ * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
+ * @returns a Matrix
+ */
+ getTransformationMatrix() {
+ this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
+ return this._transformMatrix;
+ }
+ _computeObliqueDistance(offset) {
+ const arcRotateCamera = this;
+ const targetCamera = this;
+ return (arcRotateCamera.radius || (targetCamera.target ? Vector3.Distance(this.position, targetCamera.target) : this.position.length())) + offset;
+ }
+ /** @internal */
+ _updateFrustumPlanes() {
+ if (!this._refreshFrustumPlanes) {
+ return;
+ }
+ this.getTransformationMatrix();
+ if (!this._frustumPlanes) {
+ this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
+ }
+ else {
+ Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
+ }
+ this._refreshFrustumPlanes = false;
+ }
+ /**
+ * Checks if a cullable object (mesh...) is in the camera frustum
+ * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
+ * @param target The object to check
+ * @param checkRigCameras If the rig cameras should be checked (eg. with VR camera both eyes should be checked) (Default: false)
+ * @returns true if the object is in frustum otherwise false
+ */
+ isInFrustum(target, checkRigCameras = false) {
+ this._updateFrustumPlanes();
+ if (checkRigCameras && this.rigCameras.length > 0) {
+ let result = false;
+ this.rigCameras.forEach((cam) => {
+ cam._updateFrustumPlanes();
+ result = result || target.isInFrustum(cam._frustumPlanes);
+ });
+ return result;
+ }
+ else {
+ return target.isInFrustum(this._frustumPlanes);
+ }
+ }
+ /**
+ * Checks if a cullable object (mesh...) is in the camera frustum
+ * Unlike isInFrustum this checks the full bounding box
+ * @param target The object to check
+ * @returns true if the object is in frustum otherwise false
+ */
+ isCompletelyInFrustum(target) {
+ this._updateFrustumPlanes();
+ return target.isCompletelyInFrustum(this._frustumPlanes);
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Gets a ray in the forward direction from the camera.
+ * @param length Defines the length of the ray to create
+ * @param transform Defines the transform to apply to the ray, by default the world matrix is used to create a workd space ray
+ * @param origin Defines the start point of the ray which defaults to the camera position
+ * @returns the forward ray
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getForwardRay(length = 100, transform, origin) {
+ throw _WarnImport("Ray");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Gets a ray in the forward direction from the camera.
+ * @param refRay the ray to (re)use when setting the values
+ * @param length Defines the length of the ray to create
+ * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
+ * @param origin Defines the start point of the ray which defaults to the camera position
+ * @returns the forward ray
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getForwardRayToRef(refRay, length = 100, transform, origin) {
+ throw _WarnImport("Ray");
+ }
+ /**
+ * Releases resources associated with this node.
+ * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
+ * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
+ */
+ dispose(doNotRecurse, disposeMaterialAndTextures = false) {
+ // Observables
+ this.onViewMatrixChangedObservable.clear();
+ this.onProjectionMatrixChangedObservable.clear();
+ this.onAfterCheckInputsObservable.clear();
+ this.onRestoreStateObservable.clear();
+ // Inputs
+ if (this.inputs) {
+ this.inputs.clear();
+ }
+ // Animations
+ this.getScene().stopAnimation(this);
+ // Remove from scene
+ this.getScene().removeCamera(this);
+ while (this._rigCameras.length > 0) {
+ const camera = this._rigCameras.pop();
+ if (camera) {
+ camera.dispose();
+ }
+ }
+ if (this._parentContainer) {
+ const index = this._parentContainer.cameras.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.cameras.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ // Postprocesses
+ if (this._rigPostProcess) {
+ this._rigPostProcess.dispose(this);
+ this._rigPostProcess = null;
+ this._postProcesses.length = 0;
+ }
+ else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
+ this._rigPostProcess = null;
+ this._postProcesses.length = 0;
+ }
+ else {
+ let i = this._postProcesses.length;
+ while (--i >= 0) {
+ const postProcess = this._postProcesses[i];
+ if (postProcess) {
+ postProcess.dispose(this);
+ }
+ }
+ }
+ // Render targets
+ let i = this.customRenderTargets.length;
+ while (--i >= 0) {
+ this.customRenderTargets[i].dispose();
+ }
+ this.customRenderTargets.length = 0;
+ // Active Meshes
+ this._activeMeshes.dispose();
+ this.getScene().getEngine().releaseRenderPassId(this.renderPassId);
+ super.dispose(doNotRecurse, disposeMaterialAndTextures);
+ }
+ /**
+ * Gets the left camera of a rig setup in case of Rigged Camera
+ */
+ get isLeftCamera() {
+ return this._isLeftCamera;
+ }
+ /**
+ * Gets the right camera of a rig setup in case of Rigged Camera
+ */
+ get isRightCamera() {
+ return this._isRightCamera;
+ }
+ /**
+ * Gets the left camera of a rig setup in case of Rigged Camera
+ */
+ get leftCamera() {
+ if (this._rigCameras.length < 1) {
+ return null;
+ }
+ return this._rigCameras[0];
+ }
+ /**
+ * Gets the right camera of a rig setup in case of Rigged Camera
+ */
+ get rightCamera() {
+ if (this._rigCameras.length < 2) {
+ return null;
+ }
+ return this._rigCameras[1];
+ }
+ /**
+ * Gets the left camera target of a rig setup in case of Rigged Camera
+ * @returns the target position
+ */
+ getLeftTarget() {
+ if (this._rigCameras.length < 1) {
+ return null;
+ }
+ return this._rigCameras[0].getTarget();
+ }
+ /**
+ * Gets the right camera target of a rig setup in case of Rigged Camera
+ * @returns the target position
+ */
+ getRightTarget() {
+ if (this._rigCameras.length < 2) {
+ return null;
+ }
+ return this._rigCameras[1].getTarget();
+ }
+ /**
+ * @internal
+ */
+ setCameraRigMode(mode, rigParams) {
+ if (this.cameraRigMode === mode) {
+ return;
+ }
+ while (this._rigCameras.length > 0) {
+ const camera = this._rigCameras.pop();
+ if (camera) {
+ camera.dispose();
+ }
+ }
+ this.cameraRigMode = mode;
+ this._cameraRigParams = {};
+ //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
+ //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
+ this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
+ this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
+ // create the rig cameras, unless none
+ if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
+ const leftCamera = this.createRigCamera(this.name + "_L", 0);
+ if (leftCamera) {
+ leftCamera._isLeftCamera = true;
+ }
+ const rightCamera = this.createRigCamera(this.name + "_R", 1);
+ if (rightCamera) {
+ rightCamera._isRightCamera = true;
+ }
+ if (leftCamera && rightCamera) {
+ this._rigCameras.push(leftCamera);
+ this._rigCameras.push(rightCamera);
+ }
+ }
+ this._setRigMode(rigParams);
+ this._cascadePostProcessesToRigCams();
+ this.update();
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _setRigMode(rigParams) {
+ // no-op
+ }
+ /** @internal */
+ _getVRProjectionMatrix() {
+ Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, true, this.getEngine().isNDCHalfZRange);
+ this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
+ return this._projectionMatrix;
+ }
+ /**
+ * @internal
+ */
+ setCameraRigParameter(name, value) {
+ if (!this._cameraRigParams) {
+ this._cameraRigParams = {};
+ }
+ this._cameraRigParams[name] = value;
+ //provisionnally:
+ if (name === "interaxialDistance") {
+ this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(value / 0.0637);
+ }
+ }
+ /**
+ * needs to be overridden by children so sub has required properties to be copied
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ createRigCamera(name, cameraIndex) {
+ return null;
+ }
+ /**
+ * May need to be overridden by children
+ * @internal
+ */
+ _updateRigCameras() {
+ for (let i = 0; i < this._rigCameras.length; i++) {
+ this._rigCameras[i].minZ = this.minZ;
+ this._rigCameras[i].maxZ = this.maxZ;
+ this._rigCameras[i].fov = this.fov;
+ this._rigCameras[i].upVector.copyFrom(this.upVector);
+ }
+ // only update viewport when ANAGLYPH
+ if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
+ this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
+ }
+ }
+ /** @internal */
+ _setupInputs() { }
+ /**
+ * Serialiaze the camera setup to a json representation
+ * @returns the JSON representation
+ */
+ serialize() {
+ const serializationObject = SerializationHelper.Serialize(this);
+ serializationObject.uniqueId = this.uniqueId;
+ // Type
+ serializationObject.type = this.getClassName();
+ // Parent
+ if (this.parent) {
+ this.parent._serializeAsParent(serializationObject);
+ }
+ if (this.inputs) {
+ this.inputs.serialize(serializationObject);
+ }
+ // Animations
+ SerializationHelper.AppendSerializedAnimations(this, serializationObject);
+ serializationObject.ranges = this.serializeAnimationRanges();
+ serializationObject.isEnabled = this.isEnabled();
+ return serializationObject;
+ }
+ /**
+ * Clones the current camera.
+ * @param name The cloned camera name
+ * @param newParent The cloned camera's new parent (none by default)
+ * @returns the cloned camera
+ */
+ clone(name, newParent = null) {
+ const camera = SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
+ camera.name = name;
+ camera.parent = newParent;
+ this.onClonedObservable.notifyObservers(camera);
+ return camera;
+ }
+ /**
+ * Gets the direction of the camera relative to a given local axis.
+ * @param localAxis Defines the reference axis to provide a relative direction.
+ * @returns the direction
+ */
+ getDirection(localAxis) {
+ const result = Vector3.Zero();
+ this.getDirectionToRef(localAxis, result);
+ return result;
+ }
+ /**
+ * Returns the current camera absolute rotation
+ */
+ get absoluteRotation() {
+ this.getWorldMatrix().decompose(undefined, this._absoluteRotation);
+ return this._absoluteRotation;
+ }
+ /**
+ * Gets the direction of the camera relative to a given local axis into a passed vector.
+ * @param localAxis Defines the reference axis to provide a relative direction.
+ * @param result Defines the vector to store the result in
+ */
+ getDirectionToRef(localAxis, result) {
+ Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
+ }
+ /**
+ * Gets a camera constructor for a given camera type
+ * @param type The type of the camera to construct (should be equal to one of the camera class name)
+ * @param name The name of the camera the result will be able to instantiate
+ * @param scene The scene the result will construct the camera in
+ * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
+ * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
+ * @returns a factory method to construct the camera
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static GetConstructorFromName(type, name, scene, interaxial_distance = 0, isStereoscopicSideBySide = true) {
+ const constructorFunc = Node$2.Construct(type, name, scene, {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ interaxial_distance: interaxial_distance,
+ isStereoscopicSideBySide: isStereoscopicSideBySide,
+ });
+ if (constructorFunc) {
+ return constructorFunc;
+ }
+ // Default to universal camera
+ return () => Camera._CreateDefaultParsedCamera(name, scene);
+ }
+ /**
+ * Compute the world matrix of the camera.
+ * @returns the camera world matrix
+ */
+ computeWorldMatrix() {
+ return this.getWorldMatrix();
+ }
+ /**
+ * Parse a JSON and creates the camera from the parsed information
+ * @param parsedCamera The JSON to parse
+ * @param scene The scene to instantiate the camera in
+ * @returns the newly constructed camera
+ */
+ static Parse(parsedCamera, scene) {
+ const type = parsedCamera.type;
+ const construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
+ const camera = SerializationHelper.Parse(construct, parsedCamera, scene);
+ // Parent
+ if (parsedCamera.parentId !== undefined) {
+ camera._waitingParentId = parsedCamera.parentId;
+ }
+ // Parent instance index
+ if (parsedCamera.parentInstanceIndex !== undefined) {
+ camera._waitingParentInstanceIndex = parsedCamera.parentInstanceIndex;
+ }
+ //If camera has an input manager, let it parse inputs settings
+ if (camera.inputs) {
+ camera.inputs.parse(parsedCamera);
+ camera._setupInputs();
+ }
+ if (parsedCamera.upVector) {
+ camera.upVector = Vector3.FromArray(parsedCamera.upVector); // need to force the upVector
+ }
+ if (camera.setPosition) {
+ // need to force position
+ camera.position.copyFromFloats(0, 0, 0);
+ camera.setPosition(Vector3.FromArray(parsedCamera.position));
+ }
+ // Target
+ if (parsedCamera.target) {
+ if (camera.setTarget) {
+ camera.setTarget(Vector3.FromArray(parsedCamera.target));
+ }
+ }
+ // Apply 3d rig, when found
+ if (parsedCamera.cameraRigMode) {
+ const rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
+ camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
+ }
+ // Animations
+ if (parsedCamera.animations) {
+ for (let animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
+ const parsedAnimation = parsedCamera.animations[animationIndex];
+ const internalClass = GetClass("BABYLON.Animation");
+ if (internalClass) {
+ camera.animations.push(internalClass.Parse(parsedAnimation));
+ }
+ }
+ Node$2.ParseAnimationRanges(camera, parsedCamera, scene);
+ }
+ if (parsedCamera.autoAnimate) {
+ scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
+ }
+ // Check if isEnabled is defined to be back compatible with prior serialized versions.
+ if (parsedCamera.isEnabled !== undefined) {
+ camera.setEnabled(parsedCamera.isEnabled);
+ }
+ return camera;
+ }
+ /** @internal */
+ _calculateHandednessMultiplier() {
+ let handednessMultiplier = this.getScene().useRightHandedSystem ? -1 : 1;
+ if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
+ handednessMultiplier *= -1;
+ }
+ return handednessMultiplier;
+ }
+}
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Camera._CreateDefaultParsedCamera = (name, scene) => {
+ throw _WarnImport("UniversalCamera");
+};
+/**
+ * This is the default projection mode used by the cameras.
+ * It helps recreating a feeling of perspective and better appreciate depth.
+ * This is the best way to simulate real life cameras.
+ */
+Camera.PERSPECTIVE_CAMERA = 0;
+/**
+ * This helps creating camera with an orthographic mode.
+ * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
+ */
+Camera.ORTHOGRAPHIC_CAMERA = 1;
+/**
+ * This is the default FOV mode for perspective cameras.
+ * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
+ */
+Camera.FOVMODE_VERTICAL_FIXED = 0;
+/**
+ * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
+ */
+Camera.FOVMODE_HORIZONTAL_FIXED = 1;
+/**
+ * This specifies there is no need for a camera rig.
+ * Basically only one eye is rendered corresponding to the camera.
+ */
+Camera.RIG_MODE_NONE = 0;
+/**
+ * Simulates a camera Rig with one blue eye and one red eye.
+ * This can be use with 3d blue and red glasses.
+ */
+Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
+/**
+ * Defines that both eyes of the camera will be rendered side by side with a parallel target.
+ */
+Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
+/**
+ * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
+ */
+Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
+/**
+ * Defines that both eyes of the camera will be rendered over under each other.
+ */
+Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
+/**
+ * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors.
+ */
+Camera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;
+/**
+ * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
+ */
+Camera.RIG_MODE_VR = 20;
+/**
+ * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
+ */
+Camera.RIG_MODE_CUSTOM = 22;
+/**
+ * Defines if by default attaching controls should prevent the default javascript event to continue.
+ */
+Camera.ForceAttachControlToAlwaysPreventDefault = false;
+__decorate([
+ serializeAsVector3("position")
+], Camera.prototype, "_position", void 0);
+__decorate([
+ serializeAsVector3("upVector")
+], Camera.prototype, "_upVector", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "orthoLeft", null);
+__decorate([
+ serialize()
+], Camera.prototype, "orthoRight", null);
+__decorate([
+ serialize()
+], Camera.prototype, "orthoBottom", null);
+__decorate([
+ serialize()
+], Camera.prototype, "orthoTop", null);
+__decorate([
+ serialize()
+], Camera.prototype, "fov", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "projectionPlaneTilt", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "minZ", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "maxZ", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "inertia", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "mode", null);
+__decorate([
+ serialize()
+], Camera.prototype, "layerMask", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "fovMode", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "cameraRigMode", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "interaxialDistance", void 0);
+__decorate([
+ serialize()
+], Camera.prototype, "isStereoscopicSideBySide", void 0);
+
+/**
+ * @internal
+ */
+class IntersectionInfo {
+ constructor(bu, bv, distance) {
+ this.bu = bu;
+ this.bv = bv;
+ this.distance = distance;
+ this.faceId = 0;
+ this.subMeshId = 0;
+ }
+}
+
+/**
+ * Class used to store bounding box information
+ */
+class BoundingBox {
+ /**
+ * Creates a new bounding box
+ * @param min defines the minimum vector (in local space)
+ * @param max defines the maximum vector (in local space)
+ * @param worldMatrix defines the new world matrix
+ */
+ constructor(min, max, worldMatrix) {
+ /**
+ * Gets the 8 vectors representing the bounding box in local space
+ */
+ this.vectors = BuildArray(8, Vector3.Zero);
+ /**
+ * Gets the center of the bounding box in local space
+ */
+ this.center = Vector3.Zero();
+ /**
+ * Gets the center of the bounding box in world space
+ */
+ this.centerWorld = Vector3.Zero();
+ /**
+ * Gets half the size of the extent in local space. Multiply by 2 to obtain the full size of the box!
+ */
+ this.extendSize = Vector3.Zero();
+ /**
+ * Gets half the size of the extent in world space. Multiply by 2 to obtain the full size of the box!
+ */
+ this.extendSizeWorld = Vector3.Zero();
+ /**
+ * Gets the OBB (object bounding box) directions
+ */
+ this.directions = BuildArray(3, Vector3.Zero);
+ /**
+ * Gets the 8 vectors representing the bounding box in world space
+ */
+ this.vectorsWorld = BuildArray(8, Vector3.Zero);
+ /**
+ * Gets the minimum vector in world space
+ */
+ this.minimumWorld = Vector3.Zero();
+ /**
+ * Gets the maximum vector in world space
+ */
+ this.maximumWorld = Vector3.Zero();
+ /**
+ * Gets the minimum vector in local space
+ */
+ this.minimum = Vector3.Zero();
+ /**
+ * Gets the maximum vector in local space
+ */
+ this.maximum = Vector3.Zero();
+ /** @internal */
+ this._drawWrapperFront = null;
+ /** @internal */
+ this._drawWrapperBack = null;
+ this.reConstruct(min, max, worldMatrix);
+ }
+ // Methods
+ /**
+ * Recreates the entire bounding box from scratch as if we call the constructor in place
+ * @param min defines the new minimum vector (in local space)
+ * @param max defines the new maximum vector (in local space)
+ * @param worldMatrix defines the new world matrix
+ */
+ reConstruct(min, max, worldMatrix) {
+ const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
+ const vectors = this.vectors;
+ this.minimum.copyFromFloats(minX, minY, minZ);
+ this.maximum.copyFromFloats(maxX, maxY, maxZ);
+ vectors[0].copyFromFloats(minX, minY, minZ);
+ vectors[1].copyFromFloats(maxX, maxY, maxZ);
+ vectors[2].copyFromFloats(maxX, minY, minZ);
+ vectors[3].copyFromFloats(minX, maxY, minZ);
+ vectors[4].copyFromFloats(minX, minY, maxZ);
+ vectors[5].copyFromFloats(maxX, maxY, minZ);
+ vectors[6].copyFromFloats(minX, maxY, maxZ);
+ vectors[7].copyFromFloats(maxX, minY, maxZ);
+ // OBB
+ max.addToRef(min, this.center).scaleInPlace(0.5);
+ max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
+ this._worldMatrix = worldMatrix || Matrix.IdentityReadOnly;
+ this._update(this._worldMatrix);
+ }
+ /**
+ * Scale the current bounding box by applying a scale factor
+ * @param factor defines the scale factor to apply
+ * @returns the current bounding box
+ */
+ scale(factor) {
+ const tmpVectors = BoundingBox._TmpVector3;
+ const diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
+ const len = diff.length();
+ diff.normalizeFromLength(len);
+ const distance = len * factor;
+ const newRadius = diff.scaleInPlace(distance * 0.5);
+ const min = this.center.subtractToRef(newRadius, tmpVectors[1]);
+ const max = this.center.addToRef(newRadius, tmpVectors[2]);
+ this.reConstruct(min, max, this._worldMatrix);
+ return this;
+ }
+ /**
+ * Gets the world matrix of the bounding box
+ * @returns a matrix
+ */
+ getWorldMatrix() {
+ return this._worldMatrix;
+ }
+ /**
+ * @internal
+ */
+ _update(world) {
+ const minWorld = this.minimumWorld;
+ const maxWorld = this.maximumWorld;
+ const directions = this.directions;
+ const vectorsWorld = this.vectorsWorld;
+ const vectors = this.vectors;
+ if (!world.isIdentity()) {
+ minWorld.setAll(Number.MAX_VALUE);
+ maxWorld.setAll(-Number.MAX_VALUE);
+ for (let index = 0; index < 8; ++index) {
+ const v = vectorsWorld[index];
+ Vector3.TransformCoordinatesToRef(vectors[index], world, v);
+ minWorld.minimizeInPlace(v);
+ maxWorld.maximizeInPlace(v);
+ }
+ // Extend
+ maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
+ maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
+ }
+ else {
+ minWorld.copyFrom(this.minimum);
+ maxWorld.copyFrom(this.maximum);
+ for (let index = 0; index < 8; ++index) {
+ vectorsWorld[index].copyFrom(vectors[index]);
+ }
+ // Extend
+ this.extendSizeWorld.copyFrom(this.extendSize);
+ this.centerWorld.copyFrom(this.center);
+ }
+ Vector3.FromArrayToRef(world.m, 0, directions[0]);
+ Vector3.FromArrayToRef(world.m, 4, directions[1]);
+ Vector3.FromArrayToRef(world.m, 8, directions[2]);
+ this._worldMatrix = world;
+ }
+ /**
+ * Tests if the bounding box is intersecting the frustum planes
+ * @param frustumPlanes defines the frustum planes to test
+ * @returns true if there is an intersection
+ */
+ isInFrustum(frustumPlanes) {
+ return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
+ }
+ /**
+ * Tests if the bounding box is entirely inside the frustum planes
+ * @param frustumPlanes defines the frustum planes to test
+ * @returns true if there is an inclusion
+ */
+ isCompletelyInFrustum(frustumPlanes) {
+ return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
+ }
+ /**
+ * Tests if a point is inside the bounding box
+ * @param point defines the point to test
+ * @returns true if the point is inside the bounding box
+ */
+ intersectsPoint(point) {
+ const min = this.minimumWorld;
+ const max = this.maximumWorld;
+ const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
+ const pointX = point.x, pointY = point.y, pointZ = point.z;
+ const delta = -Epsilon;
+ if (maxX - pointX < delta || delta > pointX - minX) {
+ return false;
+ }
+ if (maxY - pointY < delta || delta > pointY - minY) {
+ return false;
+ }
+ if (maxZ - pointZ < delta || delta > pointZ - minZ) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Tests if the bounding box intersects with a bounding sphere
+ * @param sphere defines the sphere to test
+ * @returns true if there is an intersection
+ */
+ intersectsSphere(sphere) {
+ return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
+ }
+ /**
+ * Tests if the bounding box intersects with a box defined by a min and max vectors
+ * @param min defines the min vector to use
+ * @param max defines the max vector to use
+ * @returns true if there is an intersection
+ */
+ intersectsMinMax(min, max) {
+ const myMin = this.minimumWorld;
+ const myMax = this.maximumWorld;
+ const myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
+ const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
+ if (myMaxX < minX || myMinX > maxX) {
+ return false;
+ }
+ if (myMaxY < minY || myMinY > maxY) {
+ return false;
+ }
+ if (myMaxZ < minZ || myMinZ > maxZ) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Disposes the resources of the class
+ */
+ dispose() {
+ this._drawWrapperFront?.dispose();
+ this._drawWrapperBack?.dispose();
+ }
+ // Statics
+ /**
+ * Tests if two bounding boxes are intersections
+ * @param box0 defines the first box to test
+ * @param box1 defines the second box to test
+ * @returns true if there is an intersection
+ */
+ static Intersects(box0, box1) {
+ return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
+ }
+ /**
+ * Tests if a bounding box defines by a min/max vectors intersects a sphere
+ * @param minPoint defines the minimum vector of the bounding box
+ * @param maxPoint defines the maximum vector of the bounding box
+ * @param sphereCenter defines the sphere center
+ * @param sphereRadius defines the sphere radius
+ * @returns true if there is an intersection
+ */
+ static IntersectsSphere(minPoint, maxPoint, sphereCenter, sphereRadius) {
+ const vector = BoundingBox._TmpVector3[0];
+ Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);
+ const num = Vector3.DistanceSquared(sphereCenter, vector);
+ return num <= sphereRadius * sphereRadius;
+ }
+ /**
+ * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
+ * @param boundingVectors defines an array of 8 vectors representing a bounding box
+ * @param frustumPlanes defines the frustum planes to test
+ * @returns true if there is an inclusion
+ */
+ static IsCompletelyInFrustum(boundingVectors, frustumPlanes) {
+ for (let p = 0; p < 6; ++p) {
+ const frustumPlane = frustumPlanes[p];
+ for (let i = 0; i < 8; ++i) {
+ if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ /**
+ * Tests if a bounding box defined with 8 vectors intersects frustum planes
+ * @param boundingVectors defines an array of 8 vectors representing a bounding box
+ * @param frustumPlanes defines the frustum planes to test
+ * @returns true if there is an intersection
+ */
+ static IsInFrustum(boundingVectors, frustumPlanes) {
+ for (let p = 0; p < 6; ++p) {
+ let canReturnFalse = true;
+ const frustumPlane = frustumPlanes[p];
+ for (let i = 0; i < 8; ++i) {
+ if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
+ canReturnFalse = false;
+ break;
+ }
+ }
+ if (canReturnFalse) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
+BoundingBox._TmpVector3 = BuildArray(3, Vector3.Zero);
+
+/**
+ * Class used to store bounding sphere information
+ */
+class BoundingSphere {
+ /**
+ * Creates a new bounding sphere
+ * @param min defines the minimum vector (in local space)
+ * @param max defines the maximum vector (in local space)
+ * @param worldMatrix defines the new world matrix
+ */
+ constructor(min, max, worldMatrix) {
+ /**
+ * Gets the center of the bounding sphere in local space
+ */
+ this.center = Vector3.Zero();
+ /**
+ * Gets the center of the bounding sphere in world space
+ */
+ this.centerWorld = Vector3.Zero();
+ /**
+ * Gets the minimum vector in local space
+ */
+ this.minimum = Vector3.Zero();
+ /**
+ * Gets the maximum vector in local space
+ */
+ this.maximum = Vector3.Zero();
+ this.reConstruct(min, max, worldMatrix);
+ }
+ /**
+ * Recreates the entire bounding sphere from scratch as if we call the constructor in place
+ * @param min defines the new minimum vector (in local space)
+ * @param max defines the new maximum vector (in local space)
+ * @param worldMatrix defines the new world matrix
+ */
+ reConstruct(min, max, worldMatrix) {
+ this.minimum.copyFrom(min);
+ this.maximum.copyFrom(max);
+ const distance = Vector3.Distance(min, max);
+ max.addToRef(min, this.center).scaleInPlace(0.5);
+ this.radius = distance * 0.5;
+ this._update(worldMatrix || Matrix.IdentityReadOnly);
+ }
+ /**
+ * Scale the current bounding sphere by applying a scale factor
+ * @param factor defines the scale factor to apply
+ * @returns the current bounding box
+ */
+ scale(factor) {
+ const newRadius = this.radius * factor;
+ const tmpVectors = BoundingSphere._TmpVector3;
+ const tempRadiusVector = tmpVectors[0].setAll(newRadius);
+ const min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
+ const max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
+ this.reConstruct(min, max, this._worldMatrix);
+ return this;
+ }
+ /**
+ * Gets the world matrix of the bounding box
+ * @returns a matrix
+ */
+ getWorldMatrix() {
+ return this._worldMatrix;
+ }
+ // Methods
+ /**
+ * @internal
+ */
+ _update(worldMatrix) {
+ if (!worldMatrix.isIdentity()) {
+ Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
+ const tempVector = BoundingSphere._TmpVector3[0];
+ Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);
+ this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
+ }
+ else {
+ this.centerWorld.copyFrom(this.center);
+ this.radiusWorld = this.radius;
+ }
+ }
+ /**
+ * Tests if the bounding sphere is intersecting the frustum planes
+ * @param frustumPlanes defines the frustum planes to test
+ * @returns true if there is an intersection
+ */
+ isInFrustum(frustumPlanes) {
+ const center = this.centerWorld;
+ const radius = this.radiusWorld;
+ for (let i = 0; i < 6; i++) {
+ if (frustumPlanes[i].dotCoordinate(center) <= -radius) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Tests if the bounding sphere center is in between the frustum planes.
+ * Used for optimistic fast inclusion.
+ * @param frustumPlanes defines the frustum planes to test
+ * @returns true if the sphere center is in between the frustum planes
+ */
+ isCenterInFrustum(frustumPlanes) {
+ const center = this.centerWorld;
+ for (let i = 0; i < 6; i++) {
+ if (frustumPlanes[i].dotCoordinate(center) < 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Tests if a point is inside the bounding sphere
+ * @param point defines the point to test
+ * @returns true if the point is inside the bounding sphere
+ */
+ intersectsPoint(point) {
+ const squareDistance = Vector3.DistanceSquared(this.centerWorld, point);
+ if (this.radiusWorld * this.radiusWorld < squareDistance) {
+ return false;
+ }
+ return true;
+ }
+ // Statics
+ /**
+ * Checks if two sphere intersect
+ * @param sphere0 sphere 0
+ * @param sphere1 sphere 1
+ * @returns true if the spheres intersect
+ */
+ static Intersects(sphere0, sphere1) {
+ const squareDistance = Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
+ const radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
+ if (radiusSum * radiusSum < squareDistance) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Creates a sphere from a center and a radius
+ * @param center The center
+ * @param radius radius
+ * @param matrix Optional worldMatrix
+ * @returns The sphere
+ */
+ static CreateFromCenterAndRadius(center, radius, matrix) {
+ this._TmpVector3[0].copyFrom(center);
+ this._TmpVector3[1].copyFromFloats(0, 0, radius);
+ this._TmpVector3[2].copyFrom(center);
+ this._TmpVector3[0].addInPlace(this._TmpVector3[1]);
+ this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);
+ const sphere = new BoundingSphere(this._TmpVector3[0], this._TmpVector3[2]);
+ if (matrix) {
+ sphere._worldMatrix = matrix;
+ }
+ else {
+ sphere._worldMatrix = Matrix.Identity();
+ }
+ return sphere;
+ }
+}
+BoundingSphere._TmpVector3 = BuildArray(3, Vector3.Zero);
+
+const _result0 = { min: 0, max: 0 };
+const _result1 = { min: 0, max: 0 };
+const computeBoxExtents = (axis, box, result) => {
+ const p = Vector3.Dot(box.centerWorld, axis);
+ const r0 = Math.abs(Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
+ const r1 = Math.abs(Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
+ const r2 = Math.abs(Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
+ const r = r0 + r1 + r2;
+ result.min = p - r;
+ result.max = p + r;
+};
+const axisOverlap = (axis, box0, box1) => {
+ computeBoxExtents(axis, box0, _result0);
+ computeBoxExtents(axis, box1, _result1);
+ return !(_result0.min > _result1.max || _result1.min > _result0.max);
+};
+/**
+ * Info for a bounding data of a mesh
+ */
+class BoundingInfo {
+ /**
+ * Constructs bounding info
+ * @param minimum min vector of the bounding box/sphere
+ * @param maximum max vector of the bounding box/sphere
+ * @param worldMatrix defines the new world matrix
+ */
+ constructor(minimum, maximum, worldMatrix) {
+ this._isLocked = false;
+ this.boundingBox = new BoundingBox(minimum, maximum, worldMatrix);
+ this.boundingSphere = new BoundingSphere(minimum, maximum, worldMatrix);
+ }
+ /**
+ * Recreates the entire bounding info from scratch as if we call the constructor in place
+ * @param min defines the new minimum vector (in local space)
+ * @param max defines the new maximum vector (in local space)
+ * @param worldMatrix defines the new world matrix
+ */
+ reConstruct(min, max, worldMatrix) {
+ this.boundingBox.reConstruct(min, max, worldMatrix);
+ this.boundingSphere.reConstruct(min, max, worldMatrix);
+ }
+ /**
+ * min vector of the bounding box/sphere
+ */
+ get minimum() {
+ return this.boundingBox.minimum;
+ }
+ /**
+ * max vector of the bounding box/sphere
+ */
+ get maximum() {
+ return this.boundingBox.maximum;
+ }
+ /**
+ * If the info is locked and won't be updated to avoid perf overhead
+ */
+ get isLocked() {
+ return this._isLocked;
+ }
+ set isLocked(value) {
+ this._isLocked = value;
+ }
+ // Methods
+ /**
+ * Updates the bounding sphere and box
+ * @param world world matrix to be used to update
+ */
+ update(world) {
+ if (this._isLocked) {
+ return;
+ }
+ this.boundingBox._update(world);
+ this.boundingSphere._update(world);
+ }
+ /**
+ * Recreate the bounding info to be centered around a specific point given a specific extend.
+ * @param center New center of the bounding info
+ * @param extend New extend of the bounding info
+ * @returns the current bounding info
+ */
+ centerOn(center, extend) {
+ const minimum = BoundingInfo._TmpVector3[0].copyFrom(center).subtractInPlace(extend);
+ const maximum = BoundingInfo._TmpVector3[1].copyFrom(center).addInPlace(extend);
+ this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
+ this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
+ return this;
+ }
+ /**
+ * Grows the bounding info to include the given point.
+ * @param point The point that will be included in the current bounding info (in local space)
+ * @returns the current bounding info
+ */
+ encapsulate(point) {
+ const minimum = Vector3.Minimize(this.minimum, point);
+ const maximum = Vector3.Maximize(this.maximum, point);
+ this.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
+ return this;
+ }
+ /**
+ * Grows the bounding info to encapsulate the given bounding info.
+ * @param toEncapsulate The bounding info that will be encapsulated in the current bounding info
+ * @returns the current bounding info
+ */
+ encapsulateBoundingInfo(toEncapsulate) {
+ const invw = TmpVectors.Matrix[0];
+ this.boundingBox.getWorldMatrix().invertToRef(invw);
+ const v = TmpVectors.Vector3[0];
+ Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.minimumWorld, invw, v);
+ this.encapsulate(v);
+ Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.maximumWorld, invw, v);
+ this.encapsulate(v);
+ return this;
+ }
+ /**
+ * Scale the current bounding info by applying a scale factor
+ * @param factor defines the scale factor to apply
+ * @returns the current bounding info
+ */
+ scale(factor) {
+ this.boundingBox.scale(factor);
+ this.boundingSphere.scale(factor);
+ return this;
+ }
+ /**
+ * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
+ * @param frustumPlanes defines the frustum to test
+ * @param strategy defines the strategy to use for the culling (default is BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD)
+ * The different strategies available are:
+ * * BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD most accurate but slower @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_STANDARD
+ * * BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY faster but less accurate @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY
+ * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION
+ * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY
+ * @returns true if the bounding info is in the frustum planes
+ */
+ isInFrustum(frustumPlanes, strategy = 0) {
+ const inclusionTest = strategy === 2 || strategy === 3;
+ if (inclusionTest) {
+ if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) {
+ return true;
+ }
+ }
+ if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
+ return false;
+ }
+ const bSphereOnlyTest = strategy === 1 || strategy === 3;
+ if (bSphereOnlyTest) {
+ return true;
+ }
+ return this.boundingBox.isInFrustum(frustumPlanes);
+ }
+ /**
+ * Gets the world distance between the min and max points of the bounding box
+ */
+ get diagonalLength() {
+ const boundingBox = this.boundingBox;
+ const diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo._TmpVector3[0]);
+ return diag.length();
+ }
+ /**
+ * Checks if a cullable object (mesh...) is in the camera frustum
+ * Unlike isInFrustum this checks the full bounding box
+ * @param frustumPlanes Camera near/planes
+ * @returns true if the object is in frustum otherwise false
+ */
+ isCompletelyInFrustum(frustumPlanes) {
+ return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
+ }
+ /**
+ * @internal
+ */
+ _checkCollision(collider) {
+ return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
+ }
+ /**
+ * Checks if a point is inside the bounding box and bounding sphere or the mesh
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect
+ * @param point the point to check intersection with
+ * @returns if the point intersects
+ */
+ intersectsPoint(point) {
+ if (!this.boundingSphere.centerWorld) {
+ return false;
+ }
+ if (!this.boundingSphere.intersectsPoint(point)) {
+ return false;
+ }
+ if (!this.boundingBox.intersectsPoint(point)) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect
+ * @param boundingInfo the bounding info to check intersection with
+ * @param precise if the intersection should be done using OBB
+ * @returns if the bounding info intersects
+ */
+ intersects(boundingInfo, precise) {
+ if (!BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
+ return false;
+ }
+ if (!BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
+ return false;
+ }
+ if (!precise) {
+ return true;
+ }
+ const box0 = this.boundingBox;
+ const box1 = boundingInfo.boundingBox;
+ if (!axisOverlap(box0.directions[0], box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(box0.directions[1], box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(box0.directions[2], box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(box1.directions[0], box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(box1.directions[1], box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(box1.directions[2], box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
+ return false;
+ }
+ if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
+ return false;
+ }
+ return true;
+ }
+}
+BoundingInfo._TmpVector3 = BuildArray(2, Vector3.Zero);
+
+// This helper class is only here so we can apply the nativeOverride decorator to functions.
+class MathHelpers {
+ static extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum) {
+ for (let index = indexStart; index < indexStart + indexCount; index++) {
+ const offset = indices[index] * 3;
+ const x = positions[offset];
+ const y = positions[offset + 1];
+ const z = positions[offset + 2];
+ minimum.minimizeInPlaceFromFloats(x, y, z);
+ maximum.maximizeInPlaceFromFloats(x, y, z);
+ }
+ }
+ static extractMinAndMax(positions, start, count, stride, minimum, maximum) {
+ for (let index = start, offset = start * stride; index < start + count; index++, offset += stride) {
+ const x = positions[offset];
+ const y = positions[offset + 1];
+ const z = positions[offset + 2];
+ minimum.minimizeInPlaceFromFloats(x, y, z);
+ maximum.maximizeInPlaceFromFloats(x, y, z);
+ }
+ }
+}
+__decorate([
+ nativeOverride.filter((...[positions, indices]) => !Array.isArray(positions) && !Array.isArray(indices))
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+], MathHelpers, "extractMinAndMaxIndexed", null);
+__decorate([
+ nativeOverride.filter((...[positions]) => !Array.isArray(positions))
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+], MathHelpers, "extractMinAndMax", null);
+/**
+ * Extracts minimum and maximum values from a list of indexed positions
+ * @param positions defines the positions to use
+ * @param indices defines the indices to the positions
+ * @param indexStart defines the start index
+ * @param indexCount defines the end index
+ * @param bias defines bias value to add to the result
+ * @returns minimum and maximum values
+ */
+function extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, bias = null) {
+ const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+ MathHelpers.extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum);
+ if (bias) {
+ minimum.x -= minimum.x * bias.x + bias.y;
+ minimum.y -= minimum.y * bias.x + bias.y;
+ minimum.z -= minimum.z * bias.x + bias.y;
+ maximum.x += maximum.x * bias.x + bias.y;
+ maximum.y += maximum.y * bias.x + bias.y;
+ maximum.z += maximum.z * bias.x + bias.y;
+ }
+ return {
+ minimum: minimum,
+ maximum: maximum,
+ };
+}
+/**
+ * Extracts minimum and maximum values from a list of positions
+ * @param positions defines the positions to use
+ * @param start defines the start index in the positions array
+ * @param count defines the number of positions to handle
+ * @param bias defines bias value to add to the result
+ * @param stride defines the stride size to use (distance between two positions in the positions array)
+ * @returns minimum and maximum values
+ */
+function extractMinAndMax(positions, start, count, bias = null, stride) {
+ const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+ if (!stride) {
+ stride = 3;
+ }
+ MathHelpers.extractMinAndMax(positions, start, count, stride, minimum, maximum);
+ if (bias) {
+ minimum.x -= minimum.x * bias.x + bias.y;
+ minimum.y -= minimum.y * bias.x + bias.y;
+ minimum.z -= minimum.z * bias.x + bias.y;
+ maximum.x += maximum.x * bias.x + bias.y;
+ maximum.y += maximum.y * bias.x + bias.y;
+ maximum.z += maximum.z * bias.x + bias.y;
+ }
+ return {
+ minimum: minimum,
+ maximum: maximum,
+ };
+}
+/**
+ * Flip flipped faces
+ * @param positions defines the positions to use
+ * @param indices defines the indices to use and update
+ */
+function FixFlippedFaces(positions, indices) {
+ const boundingInfo = extractMinAndMax(positions, 0, positions.length / 3);
+ const inside = boundingInfo.maximum.subtract(boundingInfo.minimum).scale(0.5).add(boundingInfo.minimum);
+ const tmpVectorA = new Vector3();
+ const tmpVectorB = new Vector3();
+ const tmpVectorC = new Vector3();
+ const tmpVectorAB = new Vector3();
+ const tmpVectorAC = new Vector3();
+ const tmpVectorNormal = new Vector3();
+ const tmpVectorAvgNormal = new Vector3();
+ // Clean indices
+ for (let index = 0; index < indices.length; index += 3) {
+ const a = indices[index];
+ const b = indices[index + 1];
+ const c = indices[index + 2];
+ // Evaluate face normal
+ tmpVectorA.fromArray(positions, a * 3);
+ tmpVectorB.fromArray(positions, b * 3);
+ tmpVectorC.fromArray(positions, c * 3);
+ tmpVectorB.subtractToRef(tmpVectorA, tmpVectorAB);
+ tmpVectorC.subtractToRef(tmpVectorA, tmpVectorAC);
+ Vector3.CrossToRef(tmpVectorAB, tmpVectorAC, tmpVectorNormal);
+ tmpVectorNormal.normalize();
+ // Calculate normal from face center to the inside of the geometry
+ const avgX = tmpVectorA.x + tmpVectorB.x + tmpVectorC.x;
+ const avgY = tmpVectorA.y + tmpVectorB.y + tmpVectorC.y;
+ const avgZ = tmpVectorA.z + tmpVectorB.z + tmpVectorC.z;
+ tmpVectorAvgNormal.set(avgX / 3, avgY / 3, avgZ / 3);
+ tmpVectorAvgNormal.subtractInPlace(inside);
+ tmpVectorAvgNormal.normalize();
+ if (Vector3.Dot(tmpVectorNormal, tmpVectorAvgNormal) >= 0) {
+ // Flip!
+ indices[index] = c;
+ indices[index + 2] = a;
+ }
+ }
+}
+
+/** @internal */
+class DrawWrapper {
+ static GetEffect(effect) {
+ return effect.getPipelineContext === undefined ? effect.effect : effect;
+ }
+ constructor(engine, createMaterialContext = true) {
+ /**
+ * @internal
+ * Specifies if the effect was previously ready
+ */
+ this._wasPreviouslyReady = false;
+ /**
+ * @internal
+ * Forces the code from bindForSubMesh to be fully run the next time it is called
+ */
+ this._forceRebindOnNextCall = true;
+ /**
+ * @internal
+ * Specifies if the effect was previously using instances
+ */
+ this._wasPreviouslyUsingInstances = null;
+ this.effect = null;
+ this.defines = null;
+ this.drawContext = engine.createDrawContext();
+ if (createMaterialContext) {
+ this.materialContext = engine.createMaterialContext();
+ }
+ }
+ setEffect(effect, defines, resetContext = true) {
+ this.effect = effect;
+ if (defines !== undefined) {
+ this.defines = defines;
+ }
+ if (resetContext) {
+ this.drawContext?.reset();
+ }
+ }
+ /**
+ * Dispose the effect wrapper and its resources
+ * @param immediate if the effect should be disposed immediately or on the next frame.
+ * If dispose() is not called during a scene or engine dispose, we want to delay the dispose of the underlying effect. Mostly to give a chance to user code to reuse the effect in some way.
+ */
+ dispose(immediate = false) {
+ if (this.effect) {
+ const effect = this.effect;
+ if (immediate) {
+ effect.dispose();
+ }
+ else {
+ TimingTools.SetImmediate(() => {
+ effect.getEngine().onEndFrameObservable.addOnce(() => {
+ effect.dispose();
+ });
+ });
+ }
+ this.effect = null;
+ }
+ this.drawContext?.dispose();
+ }
+}
+
+/**
+ * Defines a subdivision inside a mesh
+ */
+class SubMesh {
+ /**
+ * Gets material defines used by the effect associated to the sub mesh
+ */
+ get materialDefines() {
+ return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : this._getDrawWrapper()?.defines;
+ }
+ /**
+ * Sets material defines used by the effect associated to the sub mesh
+ */
+ set materialDefines(defines) {
+ const drawWrapper = this._mainDrawWrapperOverride ?? this._getDrawWrapper(undefined, true);
+ drawWrapper.defines = defines;
+ }
+ /**
+ * @internal
+ */
+ _getDrawWrapper(passId, createIfNotExisting = false) {
+ passId = passId ?? this._engine.currentRenderPassId;
+ let drawWrapper = this._drawWrappers[passId];
+ if (!drawWrapper && createIfNotExisting) {
+ this._drawWrappers[passId] = drawWrapper = new DrawWrapper(this._mesh.getScene().getEngine());
+ }
+ return drawWrapper;
+ }
+ /**
+ * @internal
+ */
+ _removeDrawWrapper(passId, disposeWrapper = true, immediate = false) {
+ if (disposeWrapper) {
+ this._drawWrappers[passId]?.dispose(immediate);
+ }
+ this._drawWrappers[passId] = undefined;
+ }
+ /**
+ * Gets associated (main) effect (possibly the effect override if defined)
+ */
+ get effect() {
+ return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : (this._getDrawWrapper()?.effect ?? null);
+ }
+ /** @internal */
+ get _drawWrapper() {
+ return this._mainDrawWrapperOverride ?? this._getDrawWrapper(undefined, true);
+ }
+ /** @internal */
+ get _drawWrapperOverride() {
+ return this._mainDrawWrapperOverride;
+ }
+ /**
+ * @internal
+ */
+ _setMainDrawWrapperOverride(wrapper) {
+ this._mainDrawWrapperOverride = wrapper;
+ }
+ /**
+ * Sets associated effect (effect used to render this submesh)
+ * @param effect defines the effect to associate with
+ * @param defines defines the set of defines used to compile this effect
+ * @param materialContext material context associated to the effect
+ * @param resetContext true to reset the draw context
+ */
+ setEffect(effect, defines = null, materialContext, resetContext = true) {
+ const drawWrapper = this._drawWrapper;
+ drawWrapper.setEffect(effect, defines, resetContext);
+ if (materialContext !== undefined) {
+ drawWrapper.materialContext = materialContext;
+ }
+ if (!effect) {
+ drawWrapper.defines = null;
+ drawWrapper.materialContext = undefined;
+ }
+ }
+ /**
+ * Resets the draw wrappers cache
+ * @param passId If provided, releases only the draw wrapper corresponding to this render pass id
+ * @param immediate If true, the draw wrapper will dispose the effect immediately (false by default)
+ */
+ resetDrawCache(passId, immediate = false) {
+ if (this._drawWrappers) {
+ if (passId !== undefined) {
+ this._removeDrawWrapper(passId, true, immediate);
+ return;
+ }
+ else {
+ for (const drawWrapper of this._drawWrappers) {
+ drawWrapper?.dispose(immediate);
+ }
+ }
+ }
+ this._drawWrappers = [];
+ }
+ /**
+ * Add a new submesh to a mesh
+ * @param materialIndex defines the material index to use
+ * @param verticesStart defines vertex index start
+ * @param verticesCount defines vertices count
+ * @param indexStart defines index start
+ * @param indexCount defines indices count
+ * @param mesh defines the parent mesh
+ * @param renderingMesh defines an optional rendering mesh
+ * @param createBoundingBox defines if bounding box should be created for this submesh
+ * @returns the new submesh
+ */
+ static AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true) {
+ return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
+ }
+ /**
+ * Creates a new submesh
+ * @param materialIndex defines the material index to use
+ * @param verticesStart defines vertex index start
+ * @param verticesCount defines vertices count
+ * @param indexStart defines index start
+ * @param indexCount defines indices count
+ * @param mesh defines the parent mesh
+ * @param renderingMesh defines an optional rendering mesh
+ * @param createBoundingBox defines if bounding box should be created for this submesh
+ * @param addToMesh defines a boolean indicating that the submesh must be added to the mesh.subMeshes array (true by default)
+ */
+ constructor(
+ /** the material index to use */
+ materialIndex,
+ /** vertex index start */
+ verticesStart,
+ /** vertices count */
+ verticesCount,
+ /** index start */
+ indexStart,
+ /** indices count */
+ indexCount, mesh, renderingMesh, createBoundingBox = true, addToMesh = true) {
+ this.materialIndex = materialIndex;
+ this.verticesStart = verticesStart;
+ this.verticesCount = verticesCount;
+ this.indexStart = indexStart;
+ this.indexCount = indexCount;
+ this._mainDrawWrapperOverride = null;
+ /** @internal */
+ this._linesIndexCount = 0;
+ this._linesIndexBuffer = null;
+ /** @internal */
+ this._lastColliderWorldVertices = null;
+ /** @internal */
+ this._lastColliderTransformMatrix = null;
+ /** @internal */
+ this._wasDispatched = false;
+ /** @internal */
+ this._renderId = 0;
+ /** @internal */
+ this._alphaIndex = 0;
+ /** @internal */
+ this._distanceToCamera = 0;
+ this._currentMaterial = null;
+ this._mesh = mesh;
+ this._renderingMesh = renderingMesh || mesh;
+ if (addToMesh) {
+ mesh.subMeshes.push(this);
+ }
+ this._engine = this._mesh.getScene().getEngine();
+ this.resetDrawCache();
+ this._trianglePlanes = [];
+ this._id = mesh.subMeshes.length - 1;
+ if (createBoundingBox) {
+ this.refreshBoundingInfo();
+ mesh.computeWorldMatrix(true);
+ }
+ }
+ /**
+ * Returns true if this submesh covers the entire parent mesh
+ * @ignorenaming
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ get IsGlobal() {
+ return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices() && this.indexStart === 0 && this.indexCount === this._mesh.getTotalIndices();
+ }
+ /**
+ * Returns the submesh BoundingInfo object
+ * @returns current bounding info (or mesh's one if the submesh is global)
+ */
+ getBoundingInfo() {
+ if (this.IsGlobal || this._mesh.hasThinInstances) {
+ return this._mesh.getBoundingInfo();
+ }
+ return this._boundingInfo;
+ }
+ /**
+ * Sets the submesh BoundingInfo
+ * @param boundingInfo defines the new bounding info to use
+ * @returns the SubMesh
+ */
+ setBoundingInfo(boundingInfo) {
+ this._boundingInfo = boundingInfo;
+ return this;
+ }
+ /**
+ * Returns the mesh of the current submesh
+ * @returns the parent mesh
+ */
+ getMesh() {
+ return this._mesh;
+ }
+ /**
+ * Returns the rendering mesh of the submesh
+ * @returns the rendering mesh (could be different from parent mesh)
+ */
+ getRenderingMesh() {
+ return this._renderingMesh;
+ }
+ /**
+ * Returns the replacement mesh of the submesh
+ * @returns the replacement mesh (could be different from parent mesh)
+ */
+ getReplacementMesh() {
+ return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;
+ }
+ /**
+ * Returns the effective mesh of the submesh
+ * @returns the effective mesh (could be different from parent mesh)
+ */
+ getEffectiveMesh() {
+ const replacementMesh = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;
+ return replacementMesh ? replacementMesh : this._renderingMesh;
+ }
+ /**
+ * Returns the submesh material
+ * @param getDefaultMaterial Defines whether or not to get the default material if nothing has been defined.
+ * @returns null or the current material
+ */
+ getMaterial(getDefaultMaterial = true) {
+ const rootMaterial = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId) ?? this._renderingMesh.material;
+ if (!rootMaterial) {
+ return getDefaultMaterial && this._mesh.getScene()._hasDefaultMaterial ? this._mesh.getScene().defaultMaterial : null;
+ }
+ else if (this._isMultiMaterial(rootMaterial)) {
+ const effectiveMaterial = rootMaterial.getSubMaterial(this.materialIndex);
+ if (this._currentMaterial !== effectiveMaterial) {
+ this._currentMaterial = effectiveMaterial;
+ this.resetDrawCache();
+ }
+ return effectiveMaterial;
+ }
+ return rootMaterial;
+ }
+ _isMultiMaterial(material) {
+ return material.getSubMaterial !== undefined;
+ }
+ // Methods
+ /**
+ * Sets a new updated BoundingInfo object to the submesh
+ * @param data defines an optional position array to use to determine the bounding info
+ * @returns the SubMesh
+ */
+ refreshBoundingInfo(data = null) {
+ this._lastColliderWorldVertices = null;
+ if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
+ return this;
+ }
+ if (!data) {
+ data = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind);
+ }
+ if (!data) {
+ this._boundingInfo = this._mesh.getBoundingInfo();
+ return this;
+ }
+ const indices = this._renderingMesh.getIndices();
+ let extend;
+ //is this the only submesh?
+ if (this.indexStart === 0 && this.indexCount === indices.length) {
+ const boundingInfo = this._renderingMesh.getBoundingInfo();
+ //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
+ extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
+ }
+ else {
+ extend = extractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
+ }
+ if (this._boundingInfo) {
+ this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
+ }
+ else {
+ this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
+ }
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _checkCollision(collider) {
+ const boundingInfo = this.getBoundingInfo();
+ return boundingInfo._checkCollision(collider);
+ }
+ /**
+ * Updates the submesh BoundingInfo
+ * @param world defines the world matrix to use to update the bounding info
+ * @returns the submesh
+ */
+ updateBoundingInfo(world) {
+ let boundingInfo = this.getBoundingInfo();
+ if (!boundingInfo) {
+ this.refreshBoundingInfo();
+ boundingInfo = this.getBoundingInfo();
+ }
+ if (boundingInfo) {
+ boundingInfo.update(world);
+ }
+ return this;
+ }
+ /**
+ * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
+ * @param frustumPlanes defines the frustum planes
+ * @returns true if the submesh is intersecting with the frustum
+ */
+ isInFrustum(frustumPlanes) {
+ const boundingInfo = this.getBoundingInfo();
+ if (!boundingInfo) {
+ return false;
+ }
+ return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
+ }
+ /**
+ * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
+ * @param frustumPlanes defines the frustum planes
+ * @returns true if the submesh is inside the frustum
+ */
+ isCompletelyInFrustum(frustumPlanes) {
+ const boundingInfo = this.getBoundingInfo();
+ if (!boundingInfo) {
+ return false;
+ }
+ return boundingInfo.isCompletelyInFrustum(frustumPlanes);
+ }
+ /**
+ * Renders the submesh
+ * @param enableAlphaMode defines if alpha needs to be used
+ * @returns the submesh
+ */
+ render(enableAlphaMode) {
+ this._renderingMesh.render(this, enableAlphaMode, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : undefined);
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _getLinesIndexBuffer(indices, engine) {
+ if (!this._linesIndexBuffer) {
+ const adjustedIndexCount = Math.floor(this.indexCount / 3) * 6;
+ const shouldUseUint32 = this.verticesStart + this.verticesCount > 65535;
+ const linesIndices = shouldUseUint32 ? new Uint32Array(adjustedIndexCount) : new Uint16Array(adjustedIndexCount);
+ let offset = 0;
+ if (indices.length === 0) {
+ // Unindexed mesh
+ for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
+ linesIndices[offset++] = index;
+ linesIndices[offset++] = index + 1;
+ linesIndices[offset++] = index + 1;
+ linesIndices[offset++] = index + 2;
+ linesIndices[offset++] = index + 2;
+ linesIndices[offset++] = index;
+ }
+ }
+ else {
+ for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
+ linesIndices[offset++] = indices[index];
+ linesIndices[offset++] = indices[index + 1];
+ linesIndices[offset++] = indices[index + 1];
+ linesIndices[offset++] = indices[index + 2];
+ linesIndices[offset++] = indices[index + 2];
+ linesIndices[offset++] = indices[index];
+ }
+ }
+ this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
+ this._linesIndexCount = linesIndices.length;
+ }
+ return this._linesIndexBuffer;
+ }
+ /**
+ * Checks if the submesh intersects with a ray
+ * @param ray defines the ray to test
+ * @returns true is the passed ray intersects the submesh bounding box
+ */
+ canIntersects(ray) {
+ const boundingInfo = this.getBoundingInfo();
+ if (!boundingInfo) {
+ return false;
+ }
+ return ray.intersectsBox(boundingInfo.boundingBox);
+ }
+ /**
+ * Intersects current submesh with a ray
+ * @param ray defines the ray to test
+ * @param positions defines mesh's positions array
+ * @param indices defines mesh's indices array
+ * @param fastCheck defines if the first intersection will be used (and not the closest)
+ * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
+ * @returns intersection info or null if no intersection
+ */
+ intersects(ray, positions, indices, fastCheck, trianglePredicate) {
+ const material = this.getMaterial();
+ if (!material) {
+ return null;
+ }
+ let step = 3;
+ let checkStopper = false;
+ switch (material.fillMode) {
+ case 3:
+ case 5:
+ case 6:
+ case 8:
+ return null;
+ case 7:
+ step = 1;
+ checkStopper = true;
+ break;
+ }
+ // LineMesh first as it's also a Mesh...
+ if (material.fillMode === 4) {
+ // Check if mesh is unindexed
+ if (!indices.length) {
+ return this._intersectUnIndexedLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);
+ }
+ return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);
+ }
+ else {
+ // Check if mesh is unindexed
+ if (!indices.length && this._mesh._unIndexed) {
+ return this._intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate);
+ }
+ return this._intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate);
+ }
+ }
+ /**
+ * @internal
+ */
+ _intersectLines(ray, positions, indices, intersectionThreshold, fastCheck) {
+ let intersectInfo = null;
+ // Line test
+ for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
+ const p0 = positions[indices[index]];
+ const p1 = positions[indices[index + 1]];
+ const length = ray.intersectionSegment(p0, p1, intersectionThreshold);
+ if (length < 0) {
+ continue;
+ }
+ if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
+ intersectInfo = new IntersectionInfo(null, null, length);
+ intersectInfo.faceId = index / 2;
+ if (fastCheck) {
+ break;
+ }
+ }
+ }
+ return intersectInfo;
+ }
+ /**
+ * @internal
+ */
+ _intersectUnIndexedLines(ray, positions, indices, intersectionThreshold, fastCheck) {
+ let intersectInfo = null;
+ // Line test
+ for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 2) {
+ const p0 = positions[index];
+ const p1 = positions[index + 1];
+ const length = ray.intersectionSegment(p0, p1, intersectionThreshold);
+ if (length < 0) {
+ continue;
+ }
+ if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
+ intersectInfo = new IntersectionInfo(null, null, length);
+ intersectInfo.faceId = index / 2;
+ if (fastCheck) {
+ break;
+ }
+ }
+ }
+ return intersectInfo;
+ }
+ /**
+ * @internal
+ */
+ _intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate) {
+ let intersectInfo = null;
+ // Triangles test
+ let faceId = -1;
+ for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) {
+ faceId++;
+ const indexA = indices[index];
+ const indexB = indices[index + 1];
+ const indexC = indices[index + 2];
+ if (checkStopper && indexC === 0xffffffff) {
+ index += 2;
+ continue;
+ }
+ const p0 = positions[indexA];
+ const p1 = positions[indexB];
+ const p2 = positions[indexC];
+ // stay defensive and don't check against undefined positions.
+ if (!p0 || !p1 || !p2) {
+ continue;
+ }
+ if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, indexA, indexB, indexC)) {
+ continue;
+ }
+ const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
+ if (currentIntersectInfo) {
+ if (currentIntersectInfo.distance < 0) {
+ continue;
+ }
+ if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
+ intersectInfo = currentIntersectInfo;
+ intersectInfo.faceId = faceId;
+ if (fastCheck) {
+ break;
+ }
+ }
+ }
+ }
+ return intersectInfo;
+ }
+ /**
+ * @internal
+ */
+ _intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate) {
+ let intersectInfo = null;
+ // Triangles test
+ for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) {
+ const p0 = positions[index];
+ const p1 = positions[index + 1];
+ const p2 = positions[index + 2];
+ if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, -1, -1, -1)) {
+ continue;
+ }
+ const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
+ if (currentIntersectInfo) {
+ if (currentIntersectInfo.distance < 0) {
+ continue;
+ }
+ if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
+ intersectInfo = currentIntersectInfo;
+ intersectInfo.faceId = index / 3;
+ if (fastCheck) {
+ break;
+ }
+ }
+ }
+ }
+ return intersectInfo;
+ }
+ /** @internal */
+ _rebuild() {
+ if (this._linesIndexBuffer) {
+ this._linesIndexBuffer = null;
+ }
+ }
+ // Clone
+ /**
+ * Creates a new submesh from the passed mesh
+ * @param newMesh defines the new hosting mesh
+ * @param newRenderingMesh defines an optional rendering mesh
+ * @returns the new submesh
+ */
+ clone(newMesh, newRenderingMesh) {
+ const result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
+ if (!this.IsGlobal) {
+ const boundingInfo = this.getBoundingInfo();
+ if (!boundingInfo) {
+ return result;
+ }
+ result._boundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
+ }
+ return result;
+ }
+ // Dispose
+ /**
+ * Release associated resources
+ * @param immediate If true, the effect will be disposed immediately (false by default)
+ */
+ dispose(immediate = false) {
+ if (this._linesIndexBuffer) {
+ this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
+ this._linesIndexBuffer = null;
+ }
+ // Remove from mesh
+ const index = this._mesh.subMeshes.indexOf(this);
+ this._mesh.subMeshes.splice(index, 1);
+ this.resetDrawCache(undefined, immediate);
+ }
+ /**
+ * Gets the class name
+ * @returns the string "SubMesh".
+ */
+ getClassName() {
+ return "SubMesh";
+ }
+ // Statics
+ /**
+ * Creates a new submesh from indices data
+ * @param materialIndex the index of the main mesh material
+ * @param startIndex the index where to start the copy in the mesh indices array
+ * @param indexCount the number of indices to copy then from the startIndex
+ * @param mesh the main mesh to create the submesh from
+ * @param renderingMesh the optional rendering mesh
+ * @param createBoundingBox defines if bounding box should be created for this submesh
+ * @returns a new submesh
+ */
+ static CreateFromIndices(materialIndex, startIndex, indexCount, mesh, renderingMesh, createBoundingBox = true) {
+ let minVertexIndex = Number.MAX_VALUE;
+ let maxVertexIndex = -Number.MAX_VALUE;
+ const whatWillRender = renderingMesh || mesh;
+ const indices = whatWillRender.getIndices();
+ for (let index = startIndex; index < startIndex + indexCount; index++) {
+ const vertexIndex = indices[index];
+ if (vertexIndex < minVertexIndex) {
+ minVertexIndex = vertexIndex;
+ }
+ if (vertexIndex > maxVertexIndex) {
+ maxVertexIndex = vertexIndex;
+ }
+ }
+ return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh, createBoundingBox);
+ }
+}
+
+/** Class used to attach material info to sub section of a vertex data class */
+class VertexDataMaterialInfo {
+}
+/**
+ * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
+ */
+class VertexData {
+ /**
+ * Creates a new VertexData
+ */
+ constructor() {
+ /**
+ * Gets the unique ID of this vertex Data
+ */
+ this.uniqueId = 0;
+ /**
+ * Metadata used to store contextual values
+ */
+ this.metadata = {};
+ this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this));
+ this.uniqueId = VertexData._UniqueIDGenerator;
+ VertexData._UniqueIDGenerator++;
+ }
+ /**
+ * Uses the passed data array to set the set the values for the specified kind of data
+ * @param data a linear array of floating numbers
+ * @param kind the type of data that is being set, eg positions, colors etc
+ */
+ set(data, kind) {
+ if (!data.length) {
+ Logger.Warn(`Setting vertex data kind '${kind}' with an empty array`);
+ }
+ switch (kind) {
+ case VertexBuffer.PositionKind:
+ this.positions = data;
+ break;
+ case VertexBuffer.NormalKind:
+ this.normals = data;
+ break;
+ case VertexBuffer.TangentKind:
+ this.tangents = data;
+ break;
+ case VertexBuffer.UVKind:
+ this.uvs = data;
+ break;
+ case VertexBuffer.UV2Kind:
+ this.uvs2 = data;
+ break;
+ case VertexBuffer.UV3Kind:
+ this.uvs3 = data;
+ break;
+ case VertexBuffer.UV4Kind:
+ this.uvs4 = data;
+ break;
+ case VertexBuffer.UV5Kind:
+ this.uvs5 = data;
+ break;
+ case VertexBuffer.UV6Kind:
+ this.uvs6 = data;
+ break;
+ case VertexBuffer.ColorKind:
+ this.colors = data;
+ break;
+ case VertexBuffer.MatricesIndicesKind:
+ this.matricesIndices = data;
+ break;
+ case VertexBuffer.MatricesWeightsKind:
+ this.matricesWeights = data;
+ break;
+ case VertexBuffer.MatricesIndicesExtraKind:
+ this.matricesIndicesExtra = data;
+ break;
+ case VertexBuffer.MatricesWeightsExtraKind:
+ this.matricesWeightsExtra = data;
+ break;
+ }
+ }
+ /**
+ * Associates the vertexData to the passed Mesh.
+ * Sets it as updatable or not (default `false`)
+ * @param mesh the mesh the vertexData is applied to
+ * @param updatable when used and having the value true allows new data to update the vertexData
+ * @returns the VertexData
+ */
+ applyToMesh(mesh, updatable) {
+ this._applyTo(mesh, updatable, false);
+ return this;
+ }
+ /**
+ * Associates the vertexData to the passed Geometry.
+ * Sets it as updatable or not (default `false`)
+ * @param geometry the geometry the vertexData is applied to
+ * @param updatable when used and having the value true allows new data to update the vertexData
+ * @returns VertexData
+ */
+ applyToGeometry(geometry, updatable) {
+ this._applyTo(geometry, updatable, false);
+ return this;
+ }
+ /**
+ * Updates the associated mesh
+ * @param mesh the mesh to be updated
+ * @returns VertexData
+ */
+ updateMesh(mesh) {
+ this._update(mesh);
+ return this;
+ }
+ /**
+ * Updates the associated geometry
+ * @param geometry the geometry to be updated
+ * @returns VertexData.
+ */
+ updateGeometry(geometry) {
+ this._update(geometry);
+ return this;
+ }
+ /**
+ * @internal
+ */
+ *_applyToCoroutine(meshOrGeometry, updatable = false, isAsync) {
+ if (this.positions) {
+ meshOrGeometry.setVerticesData(VertexBuffer.PositionKind, this.positions, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.normals) {
+ meshOrGeometry.setVerticesData(VertexBuffer.NormalKind, this.normals, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.tangents) {
+ meshOrGeometry.setVerticesData(VertexBuffer.TangentKind, this.tangents, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.uvs) {
+ meshOrGeometry.setVerticesData(VertexBuffer.UVKind, this.uvs, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.uvs2) {
+ meshOrGeometry.setVerticesData(VertexBuffer.UV2Kind, this.uvs2, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.uvs3) {
+ meshOrGeometry.setVerticesData(VertexBuffer.UV3Kind, this.uvs3, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.uvs4) {
+ meshOrGeometry.setVerticesData(VertexBuffer.UV4Kind, this.uvs4, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.uvs5) {
+ meshOrGeometry.setVerticesData(VertexBuffer.UV5Kind, this.uvs5, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.uvs6) {
+ meshOrGeometry.setVerticesData(VertexBuffer.UV6Kind, this.uvs6, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.colors) {
+ const stride = this.positions && this.colors.length === this.positions.length ? 3 : 4;
+ meshOrGeometry.setVerticesData(VertexBuffer.ColorKind, this.colors, updatable, stride);
+ if (this.hasVertexAlpha && meshOrGeometry.hasVertexAlpha !== undefined) {
+ meshOrGeometry.hasVertexAlpha = true;
+ }
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.matricesIndices) {
+ meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.matricesWeights) {
+ meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.matricesIndicesExtra) {
+ meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.matricesWeightsExtra) {
+ meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (this.indices) {
+ meshOrGeometry.setIndices(this.indices, null, updatable);
+ if (isAsync) {
+ yield;
+ }
+ }
+ else {
+ meshOrGeometry.setIndices([], null);
+ }
+ if (meshOrGeometry.subMeshes && this.materialInfos && this.materialInfos.length > 1) {
+ const mesh = meshOrGeometry;
+ mesh.subMeshes = [];
+ for (const matInfo of this.materialInfos) {
+ new SubMesh(matInfo.materialIndex, matInfo.verticesStart, matInfo.verticesCount, matInfo.indexStart, matInfo.indexCount, mesh);
+ }
+ }
+ return this;
+ }
+ _update(meshOrGeometry, updateExtends, makeItUnique) {
+ if (this.positions) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
+ }
+ if (this.normals) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
+ }
+ if (this.tangents) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
+ }
+ if (this.uvs) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
+ }
+ if (this.uvs2) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
+ }
+ if (this.uvs3) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
+ }
+ if (this.uvs4) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
+ }
+ if (this.uvs5) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
+ }
+ if (this.uvs6) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
+ }
+ if (this.colors) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
+ }
+ if (this.matricesIndices) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
+ }
+ if (this.matricesWeights) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
+ }
+ if (this.matricesIndicesExtra) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
+ }
+ if (this.matricesWeightsExtra) {
+ meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
+ }
+ if (this.indices) {
+ meshOrGeometry.setIndices(this.indices, null);
+ }
+ return this;
+ }
+ static _TransformVector3Coordinates(coordinates, transformation, offset = 0, length = coordinates.length) {
+ const coordinate = TmpVectors.Vector3[0];
+ const transformedCoordinate = TmpVectors.Vector3[1];
+ for (let index = offset; index < offset + length; index += 3) {
+ Vector3.FromArrayToRef(coordinates, index, coordinate);
+ Vector3.TransformCoordinatesToRef(coordinate, transformation, transformedCoordinate);
+ coordinates[index] = transformedCoordinate.x;
+ coordinates[index + 1] = transformedCoordinate.y;
+ coordinates[index + 2] = transformedCoordinate.z;
+ }
+ }
+ static _TransformVector3Normals(normals, transformation, offset = 0, length = normals.length) {
+ const normal = TmpVectors.Vector3[0];
+ const transformedNormal = TmpVectors.Vector3[1];
+ for (let index = offset; index < offset + length; index += 3) {
+ Vector3.FromArrayToRef(normals, index, normal);
+ Vector3.TransformNormalToRef(normal, transformation, transformedNormal);
+ normals[index] = transformedNormal.x;
+ normals[index + 1] = transformedNormal.y;
+ normals[index + 2] = transformedNormal.z;
+ }
+ }
+ static _TransformVector4Normals(normals, transformation, offset = 0, length = normals.length) {
+ const normal = TmpVectors.Vector4[0];
+ const transformedNormal = TmpVectors.Vector4[1];
+ for (let index = offset; index < offset + length; index += 4) {
+ Vector4.FromArrayToRef(normals, index, normal);
+ Vector4.TransformNormalToRef(normal, transformation, transformedNormal);
+ normals[index] = transformedNormal.x;
+ normals[index + 1] = transformedNormal.y;
+ normals[index + 2] = transformedNormal.z;
+ normals[index + 3] = transformedNormal.w;
+ }
+ }
+ static _FlipFaces(indices, offset = 0, length = indices.length) {
+ for (let index = offset; index < offset + length; index += 3) {
+ const tmp = indices[index + 1];
+ indices[index + 1] = indices[index + 2];
+ indices[index + 2] = tmp;
+ }
+ }
+ /**
+ * Transforms each position and each normal of the vertexData according to the passed Matrix
+ * @param matrix the transforming matrix
+ * @returns the VertexData
+ */
+ transform(matrix) {
+ const flip = matrix.determinant() < 0;
+ if (this.positions) {
+ VertexData._TransformVector3Coordinates(this.positions, matrix);
+ }
+ if (this.normals) {
+ VertexData._TransformVector3Normals(this.normals, matrix);
+ }
+ if (this.tangents) {
+ VertexData._TransformVector4Normals(this.tangents, matrix);
+ }
+ if (flip && this.indices) {
+ VertexData._FlipFaces(this.indices);
+ }
+ return this;
+ }
+ /**
+ * Generates an array of vertex data where each vertex data only has one material info
+ * @returns An array of VertexData
+ */
+ splitBasedOnMaterialID() {
+ if (!this.materialInfos || this.materialInfos.length < 2) {
+ return [this];
+ }
+ const result = [];
+ for (const materialInfo of this.materialInfos) {
+ const vertexData = new VertexData();
+ if (this.positions) {
+ vertexData.positions = this.positions.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3);
+ }
+ if (this.normals) {
+ vertexData.normals = this.normals.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3);
+ }
+ if (this.tangents) {
+ vertexData.tangents = this.tangents.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
+ }
+ if (this.colors) {
+ vertexData.colors = this.colors.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
+ }
+ if (this.uvs) {
+ vertexData.uvs = this.uvs.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
+ }
+ if (this.uvs2) {
+ vertexData.uvs2 = this.uvs2.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
+ }
+ if (this.uvs3) {
+ vertexData.uvs3 = this.uvs3.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
+ }
+ if (this.uvs4) {
+ vertexData.uvs4 = this.uvs4.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
+ }
+ if (this.uvs5) {
+ vertexData.uvs5 = this.uvs5.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
+ }
+ if (this.uvs6) {
+ vertexData.uvs6 = this.uvs6.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
+ }
+ if (this.matricesIndices) {
+ vertexData.matricesIndices = this.matricesIndices.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
+ }
+ if (this.matricesIndicesExtra) {
+ vertexData.matricesIndicesExtra = this.matricesIndicesExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
+ }
+ if (this.matricesWeights) {
+ vertexData.matricesWeights = this.matricesWeights.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
+ }
+ if (this.matricesWeightsExtra) {
+ vertexData.matricesWeightsExtra = this.matricesWeightsExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
+ }
+ if (this.indices) {
+ vertexData.indices = [];
+ for (let index = materialInfo.indexStart; index < materialInfo.indexStart + materialInfo.indexCount; index++) {
+ vertexData.indices.push(this.indices[index] - materialInfo.verticesStart);
+ }
+ }
+ const newMaterialInfo = new VertexDataMaterialInfo();
+ newMaterialInfo.indexStart = 0;
+ newMaterialInfo.indexCount = vertexData.indices ? vertexData.indices.length : 0;
+ newMaterialInfo.materialIndex = materialInfo.materialIndex;
+ newMaterialInfo.verticesStart = 0;
+ newMaterialInfo.verticesCount = (vertexData.positions ? vertexData.positions.length : 0) / 3;
+ vertexData.materialInfos = [newMaterialInfo];
+ result.push(vertexData);
+ }
+ return result;
+ }
+ /**
+ * Merges the passed VertexData into the current one
+ * @param others the VertexData to be merged into the current one
+ * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
+ * @param forceCloneIndices defines a boolean indicating if indices are forced to be cloned
+ * @param mergeMaterialIds defines a boolean indicating if we need to merge the material infos
+ * @param enableCompletion defines a boolean indicating if the vertex data should be completed to be compatible
+ * @returns the modified VertexData
+ */
+ merge(others, use32BitsIndices = false, forceCloneIndices = false, mergeMaterialIds = false, enableCompletion = false) {
+ const vertexDatas = Array.isArray(others)
+ ? others.map((other) => {
+ return { vertexData: other };
+ })
+ : [{ vertexData: others }];
+ return runCoroutineSync(this._mergeCoroutine(undefined, vertexDatas, use32BitsIndices, false, forceCloneIndices, mergeMaterialIds, enableCompletion));
+ }
+ /**
+ * @internal
+ */
+ *_mergeCoroutine(transform, vertexDatas, use32BitsIndices = false, isAsync, forceCloneIndices, mergeMaterialIds = false, enableCompletion = false) {
+ this._validate();
+ let others = vertexDatas.map((vertexData) => vertexData.vertexData);
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ let root = this;
+ if (enableCompletion) {
+ // First let's make sure we have the max set of attributes on the main vertex data
+ for (const other of others) {
+ if (!other) {
+ continue;
+ }
+ other._validate();
+ if (!this.normals && other.normals) {
+ this.normals = new Float32Array(this.positions.length);
+ }
+ if (!this.tangents && other.tangents) {
+ this.tangents = new Float32Array((this.positions.length / 3) * 4);
+ }
+ if (!this.uvs && other.uvs) {
+ this.uvs = new Float32Array((this.positions.length / 3) * 2);
+ }
+ if (!this.uvs2 && other.uvs2) {
+ this.uvs2 = new Float32Array((this.positions.length / 3) * 2);
+ }
+ if (!this.uvs3 && other.uvs3) {
+ this.uvs3 = new Float32Array((this.positions.length / 3) * 2);
+ }
+ if (!this.uvs4 && other.uvs4) {
+ this.uvs4 = new Float32Array((this.positions.length / 3) * 2);
+ }
+ if (!this.uvs5 && other.uvs5) {
+ this.uvs5 = new Float32Array((this.positions.length / 3) * 2);
+ }
+ if (!this.uvs6 && other.uvs6) {
+ this.uvs6 = new Float32Array((this.positions.length / 3) * 2);
+ }
+ if (!this.colors && other.colors) {
+ this.colors = new Float32Array((this.positions.length / 3) * 4);
+ this.colors.fill(1); // Set to white by default
+ }
+ if (!this.matricesIndices && other.matricesIndices) {
+ this.matricesIndices = new Float32Array((this.positions.length / 3) * 4);
+ }
+ if (!this.matricesWeights && other.matricesWeights) {
+ this.matricesWeights = new Float32Array((this.positions.length / 3) * 4);
+ }
+ if (!this.matricesIndicesExtra && other.matricesIndicesExtra) {
+ this.matricesIndicesExtra = new Float32Array((this.positions.length / 3) * 4);
+ }
+ if (!this.matricesWeightsExtra && other.matricesWeightsExtra) {
+ this.matricesWeightsExtra = new Float32Array((this.positions.length / 3) * 4);
+ }
+ }
+ }
+ for (const other of others) {
+ if (!other) {
+ continue;
+ }
+ if (!enableCompletion) {
+ other._validate();
+ if (!this.normals !== !other.normals ||
+ !this.tangents !== !other.tangents ||
+ !this.uvs !== !other.uvs ||
+ !this.uvs2 !== !other.uvs2 ||
+ !this.uvs3 !== !other.uvs3 ||
+ !this.uvs4 !== !other.uvs4 ||
+ !this.uvs5 !== !other.uvs5 ||
+ !this.uvs6 !== !other.uvs6 ||
+ !this.colors !== !other.colors ||
+ !this.matricesIndices !== !other.matricesIndices ||
+ !this.matricesWeights !== !other.matricesWeights ||
+ !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
+ !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
+ throw new Error("Cannot merge vertex data that do not have the same set of attributes");
+ }
+ }
+ else {
+ // Align the others with main set of attributes
+ if (this.normals && !other.normals) {
+ other.normals = new Float32Array(other.positions.length);
+ }
+ if (this.tangents && !other.tangents) {
+ other.tangents = new Float32Array((other.positions.length / 3) * 4);
+ }
+ if (this.uvs && !other.uvs) {
+ other.uvs = new Float32Array((other.positions.length / 3) * 2);
+ }
+ if (this.uvs2 && !other.uvs2) {
+ other.uvs2 = new Float32Array((other.positions.length / 3) * 2);
+ }
+ if (this.uvs3 && !other.uvs3) {
+ other.uvs3 = new Float32Array((other.positions.length / 3) * 2);
+ }
+ if (this.uvs4 && !other.uvs4) {
+ other.uvs4 = new Float32Array((other.positions.length / 3) * 2);
+ }
+ if (this.uvs5 && !other.uvs5) {
+ other.uvs5 = new Float32Array((other.positions.length / 3) * 2);
+ }
+ if (this.uvs6 && !other.uvs6) {
+ other.uvs6 = new Float32Array((other.positions.length / 3) * 2);
+ }
+ if (this.colors && !other.colors) {
+ other.colors = new Float32Array((other.positions.length / 3) * 4);
+ other.colors.fill(1); // Set to white by default
+ }
+ if (this.matricesIndices && !other.matricesIndices) {
+ other.matricesIndices = new Float32Array((other.positions.length / 3) * 4);
+ }
+ if (this.matricesWeights && !other.matricesWeights) {
+ other.matricesWeights = new Float32Array((other.positions.length / 3) * 4);
+ }
+ if (this.matricesIndicesExtra && !other.matricesIndicesExtra) {
+ other.matricesIndicesExtra = new Float32Array((other.positions.length / 3) * 4);
+ }
+ if (this.matricesWeightsExtra && !other.matricesWeightsExtra) {
+ other.matricesWeightsExtra = new Float32Array((other.positions.length / 3) * 4);
+ }
+ }
+ }
+ if (mergeMaterialIds) {
+ // Merge material infos
+ let materialIndex = 0;
+ let indexOffset = 0;
+ let vertexOffset = 0;
+ const materialInfos = [];
+ let currentMaterialInfo = null;
+ const vertexDataList = [];
+ // We need to split vertexData with more than one materialInfo
+ for (const split of this.splitBasedOnMaterialID()) {
+ vertexDataList.push({ vertexData: split, transform: transform });
+ }
+ for (const data of vertexDatas) {
+ if (!data.vertexData) {
+ continue;
+ }
+ for (const split of data.vertexData.splitBasedOnMaterialID()) {
+ vertexDataList.push({ vertexData: split, transform: data.transform });
+ }
+ }
+ // Sort by material IDs
+ vertexDataList.sort((a, b) => {
+ const matInfoA = a.vertexData.materialInfos ? a.vertexData.materialInfos[0].materialIndex : 0;
+ const matInfoB = b.vertexData.materialInfos ? b.vertexData.materialInfos[0].materialIndex : 0;
+ if (matInfoA > matInfoB) {
+ return 1;
+ }
+ if (matInfoA === matInfoB) {
+ return 0;
+ }
+ return -1;
+ });
+ // Build the new material info
+ for (const vertexDataSource of vertexDataList) {
+ const vertexData = vertexDataSource.vertexData;
+ if (vertexData.materialInfos) {
+ materialIndex = vertexData.materialInfos[0].materialIndex;
+ }
+ else {
+ materialIndex = 0;
+ }
+ if (currentMaterialInfo && currentMaterialInfo.materialIndex === materialIndex) {
+ currentMaterialInfo.indexCount += vertexData.indices.length;
+ currentMaterialInfo.verticesCount += vertexData.positions.length / 3;
+ }
+ else {
+ const materialInfo = new VertexDataMaterialInfo();
+ materialInfo.materialIndex = materialIndex;
+ materialInfo.indexStart = indexOffset;
+ materialInfo.indexCount = vertexData.indices.length;
+ materialInfo.verticesStart = vertexOffset;
+ materialInfo.verticesCount = vertexData.positions.length / 3;
+ materialInfos.push(materialInfo);
+ currentMaterialInfo = materialInfo;
+ }
+ indexOffset += vertexData.indices.length;
+ vertexOffset += vertexData.positions.length / 3;
+ }
+ // Extract sorted values
+ const first = vertexDataList.splice(0, 1)[0];
+ root = first.vertexData;
+ transform = first.transform;
+ others = vertexDataList.map((v) => v.vertexData);
+ vertexDatas = vertexDataList;
+ this.materialInfos = materialInfos;
+ }
+ // Merge geometries
+ const totalIndices = others.reduce((indexSum, vertexData) => indexSum + (vertexData.indices?.length ?? 0), root.indices?.length ?? 0);
+ const sliceIndices = forceCloneIndices || others.some((vertexData) => vertexData.indices === root.indices);
+ let indices = sliceIndices ? root.indices?.slice() : root.indices;
+ if (totalIndices > 0) {
+ let indicesOffset = indices?.length ?? 0;
+ if (!indices) {
+ indices = new Array(totalIndices);
+ }
+ if (indices.length !== totalIndices) {
+ if (Array.isArray(indices)) {
+ indices.length = totalIndices;
+ }
+ else {
+ const temp = use32BitsIndices || indices instanceof Uint32Array ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices);
+ temp.set(indices);
+ indices = temp;
+ }
+ if (transform && transform.determinant() < 0) {
+ VertexData._FlipFaces(indices, 0, indicesOffset);
+ }
+ }
+ let positionsOffset = root.positions ? root.positions.length / 3 : 0;
+ for (const { vertexData: other, transform } of vertexDatas) {
+ if (other.indices) {
+ for (let index = 0; index < other.indices.length; index++) {
+ indices[indicesOffset + index] = other.indices[index] + positionsOffset;
+ }
+ if (transform && transform.determinant() < 0) {
+ VertexData._FlipFaces(indices, indicesOffset, other.indices.length);
+ }
+ // The call to _validate already checked for positions
+ positionsOffset += other.positions.length / 3;
+ indicesOffset += other.indices.length;
+ if (isAsync) {
+ yield;
+ }
+ }
+ }
+ }
+ this.indices = indices;
+ this.positions = VertexData._MergeElement(VertexBuffer.PositionKind, root.positions, transform, vertexDatas.map((other) => [other.vertexData.positions, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ if (root.normals) {
+ this.normals = VertexData._MergeElement(VertexBuffer.NormalKind, root.normals, transform, vertexDatas.map((other) => [other.vertexData.normals, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.tangents) {
+ this.tangents = VertexData._MergeElement(VertexBuffer.TangentKind, root.tangents, transform, vertexDatas.map((other) => [other.vertexData.tangents, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.uvs) {
+ this.uvs = VertexData._MergeElement(VertexBuffer.UVKind, root.uvs, transform, vertexDatas.map((other) => [other.vertexData.uvs, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.uvs2) {
+ this.uvs2 = VertexData._MergeElement(VertexBuffer.UV2Kind, root.uvs2, transform, vertexDatas.map((other) => [other.vertexData.uvs2, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.uvs3) {
+ this.uvs3 = VertexData._MergeElement(VertexBuffer.UV3Kind, root.uvs3, transform, vertexDatas.map((other) => [other.vertexData.uvs3, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.uvs4) {
+ this.uvs4 = VertexData._MergeElement(VertexBuffer.UV4Kind, root.uvs4, transform, vertexDatas.map((other) => [other.vertexData.uvs4, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.uvs5) {
+ this.uvs5 = VertexData._MergeElement(VertexBuffer.UV5Kind, root.uvs5, transform, vertexDatas.map((other) => [other.vertexData.uvs5, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.uvs6) {
+ this.uvs6 = VertexData._MergeElement(VertexBuffer.UV6Kind, root.uvs6, transform, vertexDatas.map((other) => [other.vertexData.uvs6, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.colors) {
+ this.colors = VertexData._MergeElement(VertexBuffer.ColorKind, root.colors, transform, vertexDatas.map((other) => [other.vertexData.colors, other.transform]));
+ if (root.hasVertexAlpha !== undefined || vertexDatas.some((other) => other.vertexData.hasVertexAlpha !== undefined)) {
+ this.hasVertexAlpha = root.hasVertexAlpha || vertexDatas.some((other) => other.vertexData.hasVertexAlpha);
+ }
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.matricesIndices) {
+ this.matricesIndices = VertexData._MergeElement(VertexBuffer.MatricesIndicesKind, root.matricesIndices, transform, vertexDatas.map((other) => [other.vertexData.matricesIndices, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.matricesWeights) {
+ this.matricesWeights = VertexData._MergeElement(VertexBuffer.MatricesWeightsKind, root.matricesWeights, transform, vertexDatas.map((other) => [other.vertexData.matricesWeights, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.matricesIndicesExtra) {
+ this.matricesIndicesExtra = VertexData._MergeElement(VertexBuffer.MatricesIndicesExtraKind, root.matricesIndicesExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesIndicesExtra, other.transform]));
+ if (isAsync) {
+ yield;
+ }
+ }
+ if (root.matricesWeightsExtra) {
+ this.matricesWeightsExtra = VertexData._MergeElement(VertexBuffer.MatricesWeightsExtraKind, root.matricesWeightsExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesWeightsExtra, other.transform]));
+ }
+ return this;
+ }
+ static _MergeElement(kind, source, transform, others) {
+ const nonNullOthers = others.filter((other) => other[0] !== null && other[0] !== undefined);
+ // If there is no source to copy and no other non-null sources then skip this element.
+ if (!source && nonNullOthers.length == 0) {
+ return source;
+ }
+ if (!source) {
+ return this._MergeElement(kind, nonNullOthers[0][0], nonNullOthers[0][1], nonNullOthers.slice(1));
+ }
+ const len = nonNullOthers.reduce((sumLen, elements) => sumLen + elements[0].length, source.length);
+ const transformRange = kind === VertexBuffer.PositionKind
+ ? VertexData._TransformVector3Coordinates
+ : kind === VertexBuffer.NormalKind
+ ? VertexData._TransformVector3Normals
+ : kind === VertexBuffer.TangentKind
+ ? VertexData._TransformVector4Normals
+ : () => { };
+ if (source instanceof Float32Array) {
+ // use non-loop method when the source is Float32Array
+ const ret32 = new Float32Array(len);
+ ret32.set(source);
+ transform && transformRange(ret32, transform, 0, source.length);
+ let offset = source.length;
+ for (const [vertexData, transform] of nonNullOthers) {
+ ret32.set(vertexData, offset);
+ transform && transformRange(ret32, transform, offset, vertexData.length);
+ offset += vertexData.length;
+ }
+ return ret32;
+ }
+ else {
+ // don't use concat as it is super slow, just loop for other cases
+ const ret = new Array(len);
+ for (let i = 0; i < source.length; i++) {
+ ret[i] = source[i];
+ }
+ transform && transformRange(ret, transform, 0, source.length);
+ let offset = source.length;
+ for (const [vertexData, transform] of nonNullOthers) {
+ for (let i = 0; i < vertexData.length; i++) {
+ ret[offset + i] = vertexData[i];
+ }
+ transform && transformRange(ret, transform, offset, vertexData.length);
+ offset += vertexData.length;
+ }
+ return ret;
+ }
+ }
+ _validate() {
+ if (!this.positions) {
+ throw new RuntimeError("Positions are required", ErrorCodes.MeshInvalidPositionsError);
+ }
+ const getElementCount = (kind, values) => {
+ const stride = VertexBuffer.DeduceStride(kind);
+ if (values.length % stride !== 0) {
+ throw new Error("The " + kind + "s array count must be a multiple of " + stride);
+ }
+ return values.length / stride;
+ };
+ const positionsElementCount = getElementCount(VertexBuffer.PositionKind, this.positions);
+ const validateElementCount = (kind, values) => {
+ const elementCount = getElementCount(kind, values);
+ if (elementCount !== positionsElementCount) {
+ throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
+ }
+ };
+ if (this.normals) {
+ validateElementCount(VertexBuffer.NormalKind, this.normals);
+ }
+ if (this.tangents) {
+ validateElementCount(VertexBuffer.TangentKind, this.tangents);
+ }
+ if (this.uvs) {
+ validateElementCount(VertexBuffer.UVKind, this.uvs);
+ }
+ if (this.uvs2) {
+ validateElementCount(VertexBuffer.UV2Kind, this.uvs2);
+ }
+ if (this.uvs3) {
+ validateElementCount(VertexBuffer.UV3Kind, this.uvs3);
+ }
+ if (this.uvs4) {
+ validateElementCount(VertexBuffer.UV4Kind, this.uvs4);
+ }
+ if (this.uvs5) {
+ validateElementCount(VertexBuffer.UV5Kind, this.uvs5);
+ }
+ if (this.uvs6) {
+ validateElementCount(VertexBuffer.UV6Kind, this.uvs6);
+ }
+ if (this.colors) {
+ validateElementCount(VertexBuffer.ColorKind, this.colors);
+ }
+ if (this.matricesIndices) {
+ validateElementCount(VertexBuffer.MatricesIndicesKind, this.matricesIndices);
+ }
+ if (this.matricesWeights) {
+ validateElementCount(VertexBuffer.MatricesWeightsKind, this.matricesWeights);
+ }
+ if (this.matricesIndicesExtra) {
+ validateElementCount(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
+ }
+ if (this.matricesWeightsExtra) {
+ validateElementCount(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
+ }
+ }
+ /**
+ * Clone the current vertex data
+ * @returns a copy of the current data
+ */
+ clone() {
+ const serializationObject = this.serialize();
+ return VertexData.Parse(serializationObject);
+ }
+ /**
+ * Serializes the VertexData
+ * @returns a serialized object
+ */
+ serialize() {
+ const serializationObject = {};
+ if (this.positions) {
+ serializationObject.positions = Array.from(this.positions);
+ }
+ if (this.normals) {
+ serializationObject.normals = Array.from(this.normals);
+ }
+ if (this.tangents) {
+ serializationObject.tangents = Array.from(this.tangents);
+ }
+ if (this.uvs) {
+ serializationObject.uvs = Array.from(this.uvs);
+ }
+ if (this.uvs2) {
+ serializationObject.uvs2 = Array.from(this.uvs2);
+ }
+ if (this.uvs3) {
+ serializationObject.uvs3 = Array.from(this.uvs3);
+ }
+ if (this.uvs4) {
+ serializationObject.uvs4 = Array.from(this.uvs4);
+ }
+ if (this.uvs5) {
+ serializationObject.uvs5 = Array.from(this.uvs5);
+ }
+ if (this.uvs6) {
+ serializationObject.uvs6 = Array.from(this.uvs6);
+ }
+ if (this.colors) {
+ serializationObject.colors = Array.from(this.colors);
+ serializationObject.hasVertexAlpha = this.hasVertexAlpha;
+ }
+ if (this.matricesIndices) {
+ serializationObject.matricesIndices = Array.from(this.matricesIndices);
+ serializationObject.matricesIndices._isExpanded = true;
+ }
+ if (this.matricesWeights) {
+ serializationObject.matricesWeights = Array.from(this.matricesWeights);
+ }
+ if (this.matricesIndicesExtra) {
+ serializationObject.matricesIndicesExtra = Array.from(this.matricesIndicesExtra);
+ serializationObject.matricesIndicesExtra._isExpanded = true;
+ }
+ if (this.matricesWeightsExtra) {
+ serializationObject.matricesWeightsExtra = Array.from(this.matricesWeightsExtra);
+ }
+ serializationObject.indices = this.indices ? Array.from(this.indices) : [];
+ if (this.materialInfos) {
+ serializationObject.materialInfos = [];
+ for (const materialInfo of this.materialInfos) {
+ const materialInfoSerializationObject = {
+ indexStart: materialInfo.indexStart,
+ indexCount: materialInfo.indexCount,
+ materialIndex: materialInfo.materialIndex,
+ verticesStart: materialInfo.verticesStart,
+ verticesCount: materialInfo.verticesCount,
+ };
+ serializationObject.materialInfos.push(materialInfoSerializationObject);
+ }
+ }
+ return serializationObject;
+ }
+ // Statics
+ /**
+ * Extracts the vertexData from a mesh
+ * @param mesh the mesh from which to extract the VertexData
+ * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
+ * @param forceCopy indicating that the VertexData must be cloned, optional, default false
+ * @returns the object VertexData associated to the passed mesh
+ */
+ static ExtractFromMesh(mesh, copyWhenShared, forceCopy) {
+ return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
+ }
+ /**
+ * Extracts the vertexData from the geometry
+ * @param geometry the geometry from which to extract the VertexData
+ * @param copyWhenShared defines if the VertexData must be cloned when the geometry is shared between multiple meshes, optional, default false
+ * @param forceCopy indicating that the VertexData must be cloned, optional, default false
+ * @returns the object VertexData associated to the passed mesh
+ */
+ static ExtractFromGeometry(geometry, copyWhenShared, forceCopy) {
+ return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
+ }
+ static _ExtractFrom(meshOrGeometry, copyWhenShared, forceCopy) {
+ const result = new VertexData();
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.PositionKind)) {
+ result.positions = meshOrGeometry.getVerticesData(VertexBuffer.PositionKind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+ result.normals = meshOrGeometry.getVerticesData(VertexBuffer.NormalKind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.TangentKind)) {
+ result.tangents = meshOrGeometry.getVerticesData(VertexBuffer.TangentKind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UVKind)) {
+ result.uvs = meshOrGeometry.getVerticesData(VertexBuffer.UVKind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
+ result.uvs2 = meshOrGeometry.getVerticesData(VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV3Kind)) {
+ result.uvs3 = meshOrGeometry.getVerticesData(VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV4Kind)) {
+ result.uvs4 = meshOrGeometry.getVerticesData(VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV5Kind)) {
+ result.uvs5 = meshOrGeometry.getVerticesData(VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV6Kind)) {
+ result.uvs6 = meshOrGeometry.getVerticesData(VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.ColorKind)) {
+ const geometry = meshOrGeometry.geometry || meshOrGeometry;
+ const vertexBuffer = geometry.getVertexBuffer(VertexBuffer.ColorKind);
+ const colors = geometry.getVerticesData(VertexBuffer.ColorKind, copyWhenShared, forceCopy);
+ if (vertexBuffer.getSize() === 3) {
+ const newColors = new Float32Array((colors.length * 4) / 3);
+ for (let i = 0, j = 0; i < colors.length; i += 3, j += 4) {
+ newColors[j] = colors[i];
+ newColors[j + 1] = colors[i + 1];
+ newColors[j + 2] = colors[i + 2];
+ newColors[j + 3] = 1;
+ }
+ result.colors = newColors;
+ }
+ else if (vertexBuffer.getSize() === 4) {
+ result.colors = colors;
+ }
+ else {
+ throw new Error(`Unexpected number of color components: ${vertexBuffer.getSize()}`);
+ }
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
+ result.matricesIndices = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
+ result.matricesWeights = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind)) {
+ result.matricesIndicesExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
+ }
+ if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) {
+ result.matricesWeightsExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
+ }
+ result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
+ return result;
+ }
+ /**
+ * Creates the VertexData for a Ribbon
+ * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
+ * * pathArray array of paths, each of which an array of successive Vector3
+ * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
+ * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
+ * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
+ * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
+ * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
+ * @returns the VertexData of the ribbon
+ * @deprecated use CreateRibbonVertexData instead
+ */
+ static CreateRibbon(options) {
+ throw _WarnImport("ribbonBuilder");
+ }
+ /**
+ * Creates the VertexData for a box
+ * @param options an object used to set the following optional parameters for the box, required but can be empty
+ * * size sets the width, height and depth of the box to the value of size, optional default 1
+ * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
+ * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
+ * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
+ * * faceUV an array of 6 Vector4 elements used to set different images to each box side
+ * * faceColors an array of 6 Color3 elements used to set different colors to each box side
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the box
+ * @deprecated Please use CreateBoxVertexData from the BoxBuilder file instead
+ */
+ static CreateBox(options) {
+ throw _WarnImport("boxBuilder");
+ }
+ /**
+ * Creates the VertexData for a tiled box
+ * @param options an object used to set the following optional parameters for the box, required but can be empty
+ * * faceTiles sets the pattern, tile size and number of tiles for a face
+ * * faceUV an array of 6 Vector4 elements used to set different images to each box side
+ * * faceColors an array of 6 Color3 elements used to set different colors to each box side
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * @param options.pattern
+ * @param options.width
+ * @param options.height
+ * @param options.depth
+ * @param options.tileSize
+ * @param options.tileWidth
+ * @param options.tileHeight
+ * @param options.alignHorizontal
+ * @param options.alignVertical
+ * @param options.faceUV
+ * @param options.faceColors
+ * @param options.sideOrientation
+ * @returns the VertexData of the box
+ * @deprecated Please use CreateTiledBoxVertexData instead
+ */
+ static CreateTiledBox(options) {
+ throw _WarnImport("tiledBoxBuilder");
+ }
+ /**
+ * Creates the VertexData for a tiled plane
+ * @param options an object used to set the following optional parameters for the box, required but can be empty
+ * * pattern a limited pattern arrangement depending on the number
+ * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1
+ * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size
+ * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the tiled plane
+ * @deprecated use CreateTiledPlaneVertexData instead
+ */
+ static CreateTiledPlane(options) {
+ throw _WarnImport("tiledPlaneBuilder");
+ }
+ /**
+ * Creates the VertexData for an ellipsoid, defaults to a sphere
+ * @param options an object used to set the following optional parameters for the box, required but can be empty
+ * * segments sets the number of horizontal strips optional, default 32
+ * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
+ * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
+ * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
+ * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
+ * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
+ * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the ellipsoid
+ * @deprecated use CreateSphereVertexData instead
+ */
+ static CreateSphere(options) {
+ throw _WarnImport("sphereBuilder");
+ }
+ /**
+ * Creates the VertexData for a cylinder, cone or prism
+ * @param options an object used to set the following optional parameters for the box, required but can be empty
+ * * height sets the height (y direction) of the cylinder, optional, default 2
+ * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
+ * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
+ * * diameter sets the diameter of the top and bottom of the cone, optional default 1
+ * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
+ * * subdivisions` the number of rings along the cylinder height, optional, default 1
+ * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
+ * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
+ * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
+ * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false
+ * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the cylinder, cone or prism
+ * @deprecated please use CreateCylinderVertexData instead
+ */
+ static CreateCylinder(options) {
+ throw _WarnImport("cylinderBuilder");
+ }
+ /**
+ * Creates the VertexData for a torus
+ * @param options an object used to set the following optional parameters for the box, required but can be empty
+ * * diameter the diameter of the torus, optional default 1
+ * * thickness the diameter of the tube forming the torus, optional default 0.5
+ * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the torus
+ * @deprecated use CreateTorusVertexData instead
+ */
+ static CreateTorus(options) {
+ throw _WarnImport("torusBuilder");
+ }
+ /**
+ * Creates the VertexData of the LineSystem
+ * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
+ * - lines an array of lines, each line being an array of successive Vector3
+ * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
+ * @returns the VertexData of the LineSystem
+ * @deprecated use CreateLineSystemVertexData instead
+ */
+ static CreateLineSystem(options) {
+ throw _WarnImport("linesBuilder");
+ }
+ /**
+ * Create the VertexData for a DashedLines
+ * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
+ * - points an array successive Vector3
+ * - dashSize the size of the dashes relative to the dash number, optional, default 3
+ * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
+ * - dashNb the intended total number of dashes, optional, default 200
+ * @returns the VertexData for the DashedLines
+ * @deprecated use CreateDashedLinesVertexData instead
+ */
+ static CreateDashedLines(options) {
+ throw _WarnImport("linesBuilder");
+ }
+ /**
+ * Creates the VertexData for a Ground
+ * @param options an object used to set the following optional parameters for the Ground, required but can be empty
+ * - width the width (x direction) of the ground, optional, default 1
+ * - height the height (z direction) of the ground, optional, default 1
+ * - subdivisions the number of subdivisions per side, optional, default 1
+ * @returns the VertexData of the Ground
+ * @deprecated Please use CreateGroundVertexData instead
+ */
+ static CreateGround(options) {
+ throw _WarnImport("groundBuilder");
+ }
+ /**
+ * Creates the VertexData for a TiledGround by subdividing the ground into tiles
+ * @param options an object used to set the following optional parameters for the Ground, required but can be empty
+ * * xmin the ground minimum X coordinate, optional, default -1
+ * * zmin the ground minimum Z coordinate, optional, default -1
+ * * xmax the ground maximum X coordinate, optional, default 1
+ * * zmax the ground maximum Z coordinate, optional, default 1
+ * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
+ * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
+ * @returns the VertexData of the TiledGround
+ * @deprecated use CreateTiledGroundVertexData instead
+ */
+ static CreateTiledGround(options) {
+ throw _WarnImport("groundBuilder");
+ }
+ /**
+ * Creates the VertexData of the Ground designed from a heightmap
+ * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap
+ * * width the width (x direction) of the ground
+ * * height the height (z direction) of the ground
+ * * subdivisions the number of subdivisions per side
+ * * minHeight the minimum altitude on the ground, optional, default 0
+ * * maxHeight the maximum altitude on the ground, optional default 1
+ * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
+ * * buffer the array holding the image color data
+ * * bufferWidth the width of image
+ * * bufferHeight the height of image
+ * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
+ * @returns the VertexData of the Ground designed from a heightmap
+ * @deprecated use CreateGroundFromHeightMapVertexData instead
+ */
+ static CreateGroundFromHeightMap(options) {
+ throw _WarnImport("groundBuilder");
+ }
+ /**
+ * Creates the VertexData for a Plane
+ * @param options an object used to set the following optional parameters for the plane, required but can be empty
+ * * size sets the width and height of the plane to the value of size, optional default 1
+ * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
+ * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the box
+ * @deprecated use CreatePlaneVertexData instead
+ */
+ static CreatePlane(options) {
+ throw _WarnImport("planeBuilder");
+ }
+ /**
+ * Creates the VertexData of the Disc or regular Polygon
+ * @param options an object used to set the following optional parameters for the disc, required but can be empty
+ * * radius the radius of the disc, optional default 0.5
+ * * tessellation the number of polygon sides, optional, default 64
+ * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the box
+ * @deprecated use CreateDiscVertexData instead
+ */
+ static CreateDisc(options) {
+ throw _WarnImport("discBuilder");
+ }
+ /**
+ * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
+ * All parameters are provided by CreatePolygon as needed
+ * @param polygon a mesh built from polygonTriangulation.build()
+ * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
+ * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
+ * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @param wrap a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side
+ * @returns the VertexData of the Polygon
+ * @deprecated use CreatePolygonVertexData instead
+ */
+ static CreatePolygon(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrap) {
+ throw _WarnImport("polygonBuilder");
+ }
+ /**
+ * Creates the VertexData of the IcoSphere
+ * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
+ * * radius the radius of the IcoSphere, optional default 1
+ * * radiusX allows stretching in the x direction, optional, default radius
+ * * radiusY allows stretching in the y direction, optional, default radius
+ * * radiusZ allows stretching in the z direction, optional, default radius
+ * * flat when true creates a flat shaded mesh, optional, default true
+ * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the IcoSphere
+ * @deprecated use CreateIcoSphereVertexData instead
+ */
+ static CreateIcoSphere(options) {
+ throw _WarnImport("icoSphereBuilder");
+ }
+ // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
+ /**
+ * Creates the VertexData for a Polyhedron
+ * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
+ * * type provided types are:
+ * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
+ * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
+ * * size the size of the IcoSphere, optional default 1
+ * * sizeX allows stretching in the x direction, optional, default size
+ * * sizeY allows stretching in the y direction, optional, default size
+ * * sizeZ allows stretching in the z direction, optional, default size
+ * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
+ * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
+ * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
+ * * flat when true creates a flat shaded mesh, optional, default true
+ * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the Polyhedron
+ * @deprecated use CreatePolyhedronVertexData instead
+ */
+ static CreatePolyhedron(options) {
+ throw _WarnImport("polyhedronBuilder");
+ }
+ /**
+ * Creates the VertexData for a Capsule, inspired from https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js
+ * @param options an object used to set the following optional parameters for the capsule, required but can be empty
+ * @returns the VertexData of the Capsule
+ * @deprecated Please use CreateCapsuleVertexData from the capsuleBuilder file instead
+ */
+ static CreateCapsule(options = {
+ orientation: Vector3.Up(),
+ subdivisions: 2,
+ tessellation: 16,
+ height: 1,
+ radius: 0.25,
+ capSubdivisions: 6,
+ }) {
+ throw _WarnImport("capsuleBuilder");
+ }
+ // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
+ /**
+ * Creates the VertexData for a TorusKnot
+ * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
+ * * radius the radius of the torus knot, optional, default 2
+ * * tube the thickness of the tube, optional, default 0.5
+ * * radialSegments the number of sides on each tube segments, optional, default 32
+ * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
+ * * p the number of windings around the z axis, optional, default 2
+ * * q the number of windings around the x axis, optional, default 3
+ * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
+ * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
+ * @returns the VertexData of the Torus Knot
+ * @deprecated use CreateTorusKnotVertexData instead
+ */
+ static CreateTorusKnot(options) {
+ throw _WarnImport("torusKnotBuilder");
+ }
+ // Tools
+ /**
+ * Compute normals for given positions and indices
+ * @param positions an array of vertex positions, [...., x, y, z, ......]
+ * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
+ * @param normals an array of vertex normals, [...., x, y, z, ......]
+ * @param options an object used to set the following optional parameters for the TorusKnot, optional
+ * * facetNormals : optional array of facet normals (vector3)
+ * * facetPositions : optional array of facet positions (vector3)
+ * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
+ * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
+ * * bInfo : optional bounding info, required for facetPartitioning computation
+ * * bbSize : optional bounding box size data, required for facetPartitioning computation
+ * * subDiv : optional partitioning data about subdivisions on each axis (int), required for facetPartitioning computation
+ * * useRightHandedSystem: optional boolean to for right handed system computation
+ * * depthSort : optional boolean to enable the facet depth sort computation
+ * * distanceTo : optional Vector3 to compute the facet depth from this location
+ * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
+ */
+ static ComputeNormals(positions, indices, normals, options) {
+ // temporary scalar variables
+ let index = 0; // facet index
+ let p1p2x = 0.0; // p1p2 vector x coordinate
+ let p1p2y = 0.0; // p1p2 vector y coordinate
+ let p1p2z = 0.0; // p1p2 vector z coordinate
+ let p3p2x = 0.0; // p3p2 vector x coordinate
+ let p3p2y = 0.0; // p3p2 vector y coordinate
+ let p3p2z = 0.0; // p3p2 vector z coordinate
+ let faceNormalx = 0.0; // facet normal x coordinate
+ let faceNormaly = 0.0; // facet normal y coordinate
+ let faceNormalz = 0.0; // facet normal z coordinate
+ let length = 0.0; // facet normal length before normalization
+ let v1x = 0; // vector1 x index in the positions array
+ let v1y = 0; // vector1 y index in the positions array
+ let v1z = 0; // vector1 z index in the positions array
+ let v2x = 0; // vector2 x index in the positions array
+ let v2y = 0; // vector2 y index in the positions array
+ let v2z = 0; // vector2 z index in the positions array
+ let v3x = 0; // vector3 x index in the positions array
+ let v3y = 0; // vector3 y index in the positions array
+ let v3z = 0; // vector3 z index in the positions array
+ let computeFacetNormals = false;
+ let computeFacetPositions = false;
+ let computeFacetPartitioning = false;
+ let computeDepthSort = false;
+ let faceNormalSign = 1;
+ let ratio = 0;
+ let distanceTo = null;
+ if (options) {
+ computeFacetNormals = options.facetNormals ? true : false;
+ computeFacetPositions = options.facetPositions ? true : false;
+ computeFacetPartitioning = options.facetPartitioning ? true : false;
+ faceNormalSign = options.useRightHandedSystem === true ? -1 : 1;
+ ratio = options.ratio || 0;
+ computeDepthSort = options.depthSort ? true : false;
+ distanceTo = options.distanceTo;
+ if (computeDepthSort) {
+ if (distanceTo === undefined) {
+ distanceTo = Vector3.Zero();
+ }
+ }
+ }
+ // facetPartitioning reinit if needed
+ let xSubRatio = 0;
+ let ySubRatio = 0;
+ let zSubRatio = 0;
+ let subSq = 0;
+ if (computeFacetPartitioning && options && options.bbSize) {
+ //let bbSizeMax = options.bbSize.x > options.bbSize.y ? options.bbSize.x : options.bbSize.y;
+ //bbSizeMax = bbSizeMax > options.bbSize.z ? bbSizeMax : options.bbSize.z;
+ xSubRatio = (options.subDiv.X * ratio) / options.bbSize.x;
+ ySubRatio = (options.subDiv.Y * ratio) / options.bbSize.y;
+ zSubRatio = (options.subDiv.Z * ratio) / options.bbSize.z;
+ subSq = options.subDiv.max * options.subDiv.max;
+ options.facetPartitioning.length = 0;
+ }
+ // reset the normals
+ for (index = 0; index < positions.length; index++) {
+ normals[index] = 0.0;
+ }
+ // Loop : 1 indice triplet = 1 facet
+ const nbFaces = (indices.length / 3) | 0;
+ for (index = 0; index < nbFaces; index++) {
+ // get the indexes of the coordinates of each vertex of the facet
+ v1x = indices[index * 3] * 3;
+ v1y = v1x + 1;
+ v1z = v1x + 2;
+ v2x = indices[index * 3 + 1] * 3;
+ v2y = v2x + 1;
+ v2z = v2x + 2;
+ v3x = indices[index * 3 + 2] * 3;
+ v3y = v3x + 1;
+ v3z = v3x + 2;
+ p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
+ p1p2y = positions[v1y] - positions[v2y];
+ p1p2z = positions[v1z] - positions[v2z];
+ p3p2x = positions[v3x] - positions[v2x];
+ p3p2y = positions[v3y] - positions[v2y];
+ p3p2z = positions[v3z] - positions[v2z];
+ // compute the face normal with the cross product
+ faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
+ faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
+ faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
+ // normalize this normal and store it in the array facetData
+ length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
+ length = length === 0 ? 1.0 : length;
+ faceNormalx /= length;
+ faceNormaly /= length;
+ faceNormalz /= length;
+ if (computeFacetNormals && options) {
+ options.facetNormals[index].x = faceNormalx;
+ options.facetNormals[index].y = faceNormaly;
+ options.facetNormals[index].z = faceNormalz;
+ }
+ if (computeFacetPositions && options) {
+ // compute and the facet barycenter coordinates in the array facetPositions
+ options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
+ options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
+ options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
+ }
+ if (computeFacetPartitioning && options) {
+ // store the facet indexes in arrays in the main facetPartitioning array :
+ // compute each facet vertex (+ facet barycenter) index in the partiniong array
+ const ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
+ const oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
+ const oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
+ const b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
+ const b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
+ const b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
+ const b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
+ const b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
+ const b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
+ const b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
+ const b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
+ const b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
+ const block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
+ const block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
+ const block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
+ const block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
+ options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
+ options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
+ options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
+ options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
+ // push each facet index in each block containing the vertex
+ options.facetPartitioning[block_idx_v1].push(index);
+ if (block_idx_v2 != block_idx_v1) {
+ options.facetPartitioning[block_idx_v2].push(index);
+ }
+ if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
+ options.facetPartitioning[block_idx_v3].push(index);
+ }
+ if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
+ options.facetPartitioning[block_idx_o].push(index);
+ }
+ }
+ if (computeDepthSort && options && options.facetPositions) {
+ const dsf = options.depthSortedFacets[index];
+ dsf.ind = index * 3;
+ dsf.sqDistance = Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
+ }
+ // compute the normals anyway
+ normals[v1x] += faceNormalx; // accumulate all the normals per face
+ normals[v1y] += faceNormaly;
+ normals[v1z] += faceNormalz;
+ normals[v2x] += faceNormalx;
+ normals[v2y] += faceNormaly;
+ normals[v2z] += faceNormalz;
+ normals[v3x] += faceNormalx;
+ normals[v3y] += faceNormaly;
+ normals[v3z] += faceNormalz;
+ }
+ // last normalization of each normal
+ for (index = 0; index < normals.length / 3; index++) {
+ faceNormalx = normals[index * 3];
+ faceNormaly = normals[index * 3 + 1];
+ faceNormalz = normals[index * 3 + 2];
+ length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
+ length = length === 0 ? 1.0 : length;
+ faceNormalx /= length;
+ faceNormaly /= length;
+ faceNormalz /= length;
+ normals[index * 3] = faceNormalx;
+ normals[index * 3 + 1] = faceNormaly;
+ normals[index * 3 + 2] = faceNormalz;
+ }
+ }
+ /**
+ * @internal
+ */
+ static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
+ const li = indices.length;
+ const ln = normals.length;
+ let i;
+ let n;
+ sideOrientation = sideOrientation || VertexData.DEFAULTSIDE;
+ switch (sideOrientation) {
+ case VertexData.FRONTSIDE:
+ // nothing changed
+ break;
+ case VertexData.BACKSIDE:
+ // indices
+ for (i = 0; i < li; i += 3) {
+ const tmp = indices[i];
+ indices[i] = indices[i + 2];
+ indices[i + 2] = tmp;
+ }
+ // normals
+ for (n = 0; n < ln; n++) {
+ normals[n] = -normals[n];
+ }
+ break;
+ case VertexData.DOUBLESIDE: {
+ // positions
+ const lp = positions.length;
+ const l = lp / 3;
+ for (let p = 0; p < lp; p++) {
+ positions[lp + p] = positions[p];
+ }
+ // indices
+ for (i = 0; i < li; i += 3) {
+ indices[i + li] = indices[i + 2] + l;
+ indices[i + 1 + li] = indices[i + 1] + l;
+ indices[i + 2 + li] = indices[i] + l;
+ }
+ // normals
+ for (n = 0; n < ln; n++) {
+ normals[ln + n] = -normals[n];
+ }
+ // uvs
+ const lu = uvs.length;
+ let u = 0;
+ for (u = 0; u < lu; u++) {
+ uvs[u + lu] = uvs[u];
+ }
+ frontUVs = frontUVs ? frontUVs : new Vector4(0.0, 0.0, 1.0, 1.0);
+ backUVs = backUVs ? backUVs : new Vector4(0.0, 0.0, 1.0, 1.0);
+ u = 0;
+ for (i = 0; i < lu / 2; i++) {
+ uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
+ uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
+ uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
+ uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
+ u += 2;
+ }
+ break;
+ }
+ }
+ }
+ /**
+ * Creates a VertexData from serialized data
+ * @param parsedVertexData the parsed data from an imported file
+ * @returns a VertexData
+ */
+ static Parse(parsedVertexData) {
+ const vertexData = new VertexData();
+ // positions
+ const positions = parsedVertexData.positions;
+ if (positions) {
+ vertexData.set(positions, VertexBuffer.PositionKind);
+ }
+ // normals
+ const normals = parsedVertexData.normals;
+ if (normals) {
+ vertexData.set(normals, VertexBuffer.NormalKind);
+ }
+ // tangents
+ const tangents = parsedVertexData.tangents;
+ if (tangents) {
+ vertexData.set(tangents, VertexBuffer.TangentKind);
+ }
+ // uvs
+ const uvs = parsedVertexData.uvs;
+ if (uvs) {
+ vertexData.set(uvs, VertexBuffer.UVKind);
+ }
+ // uv2s
+ const uvs2 = parsedVertexData.uvs2;
+ if (uvs2) {
+ vertexData.set(uvs2, VertexBuffer.UV2Kind);
+ }
+ // uv3s
+ const uvs3 = parsedVertexData.uvs3;
+ if (uvs3) {
+ vertexData.set(uvs3, VertexBuffer.UV3Kind);
+ }
+ // uv4s
+ const uvs4 = parsedVertexData.uvs4;
+ if (uvs4) {
+ vertexData.set(uvs4, VertexBuffer.UV4Kind);
+ }
+ // uv5s
+ const uvs5 = parsedVertexData.uvs5;
+ if (uvs5) {
+ vertexData.set(uvs5, VertexBuffer.UV5Kind);
+ }
+ // uv6s
+ const uvs6 = parsedVertexData.uvs6;
+ if (uvs6) {
+ vertexData.set(uvs6, VertexBuffer.UV6Kind);
+ }
+ // colors
+ const colors = parsedVertexData.colors;
+ if (colors) {
+ vertexData.set(Color4.CheckColors4(colors, positions.length / 3), VertexBuffer.ColorKind);
+ if (parsedVertexData.hasVertexAlpha !== undefined) {
+ vertexData.hasVertexAlpha = parsedVertexData.hasVertexAlpha;
+ }
+ }
+ // matricesIndices
+ const matricesIndices = parsedVertexData.matricesIndices;
+ if (matricesIndices) {
+ vertexData.set(matricesIndices, VertexBuffer.MatricesIndicesKind);
+ }
+ // matricesWeights
+ const matricesWeights = parsedVertexData.matricesWeights;
+ if (matricesWeights) {
+ vertexData.set(matricesWeights, VertexBuffer.MatricesWeightsKind);
+ }
+ // indices
+ const indices = parsedVertexData.indices;
+ if (indices) {
+ vertexData.indices = indices;
+ }
+ // MaterialInfos
+ const materialInfos = parsedVertexData.materialInfos;
+ if (materialInfos) {
+ vertexData.materialInfos = [];
+ for (const materialInfoFromJSON of materialInfos) {
+ const materialInfo = new VertexDataMaterialInfo();
+ materialInfo.indexCount = materialInfoFromJSON.indexCount;
+ materialInfo.indexStart = materialInfoFromJSON.indexStart;
+ materialInfo.verticesCount = materialInfoFromJSON.verticesCount;
+ materialInfo.verticesStart = materialInfoFromJSON.verticesStart;
+ materialInfo.materialIndex = materialInfoFromJSON.materialIndex;
+ vertexData.materialInfos.push(materialInfo);
+ }
+ }
+ return vertexData;
+ }
+ /**
+ * Applies VertexData created from the imported parameters to the geometry
+ * @param parsedVertexData the parsed data from an imported file
+ * @param geometry the geometry to apply the VertexData to
+ */
+ static ImportVertexData(parsedVertexData, geometry) {
+ const vertexData = VertexData.Parse(parsedVertexData);
+ geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
+ }
+}
+/**
+ * Mesh side orientation : usually the external or front surface
+ */
+VertexData.FRONTSIDE = 0;
+/**
+ * Mesh side orientation : usually the internal or back surface
+ */
+VertexData.BACKSIDE = 1;
+/**
+ * Mesh side orientation : both internal and external or front and back surfaces
+ */
+VertexData.DOUBLESIDE = 2;
+/**
+ * Mesh side orientation : by default, `FRONTSIDE`
+ */
+VertexData.DEFAULTSIDE = 0;
+VertexData._UniqueIDGenerator = 0;
+__decorate([
+ nativeOverride.filter((...[coordinates]) => !Array.isArray(coordinates))
+], VertexData, "_TransformVector3Coordinates", null);
+__decorate([
+ nativeOverride.filter((...[normals]) => !Array.isArray(normals))
+], VertexData, "_TransformVector3Normals", null);
+__decorate([
+ nativeOverride.filter((...[normals]) => !Array.isArray(normals))
+], VertexData, "_TransformVector4Normals", null);
+__decorate([
+ nativeOverride.filter((...[indices]) => !Array.isArray(indices))
+], VertexData, "_FlipFaces", null);
+
+/**
+ * Class used to represent data loading progression
+ */
+class SceneLoaderFlags {
+ /**
+ * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
+ */
+ static get ForceFullSceneLoadingForIncremental() {
+ return SceneLoaderFlags._ForceFullSceneLoadingForIncremental;
+ }
+ static set ForceFullSceneLoadingForIncremental(value) {
+ SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value;
+ }
+ /**
+ * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
+ */
+ static get ShowLoadingScreen() {
+ return SceneLoaderFlags._ShowLoadingScreen;
+ }
+ static set ShowLoadingScreen(value) {
+ SceneLoaderFlags._ShowLoadingScreen = value;
+ }
+ /**
+ * Defines the current logging level (while loading the scene)
+ * @ignorenaming
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static get loggingLevel() {
+ return SceneLoaderFlags._LoggingLevel;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static set loggingLevel(value) {
+ SceneLoaderFlags._LoggingLevel = value;
+ }
+ /**
+ * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
+ */
+ static get CleanBoneMatrixWeights() {
+ return SceneLoaderFlags._CleanBoneMatrixWeights;
+ }
+ static set CleanBoneMatrixWeights(value) {
+ SceneLoaderFlags._CleanBoneMatrixWeights = value;
+ }
+}
+// Flags
+SceneLoaderFlags._ForceFullSceneLoadingForIncremental = false;
+SceneLoaderFlags._ShowLoadingScreen = true;
+SceneLoaderFlags._CleanBoneMatrixWeights = false;
+SceneLoaderFlags._LoggingLevel = 0;
+
+/**
+ * Class used to store geometry data (vertex buffers + index buffer)
+ */
+class Geometry {
+ /**
+ * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
+ */
+ get boundingBias() {
+ return this._boundingBias;
+ }
+ /**
+ * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
+ */
+ set boundingBias(value) {
+ if (this._boundingBias) {
+ this._boundingBias.copyFrom(value);
+ }
+ else {
+ this._boundingBias = value.clone();
+ }
+ this._updateBoundingInfo(true, null);
+ }
+ /**
+ * Static function used to attach a new empty geometry to a mesh
+ * @param mesh defines the mesh to attach the geometry to
+ * @returns the new Geometry
+ */
+ static CreateGeometryForMesh(mesh) {
+ const geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
+ geometry.applyToMesh(mesh);
+ return geometry;
+ }
+ /** Get the list of meshes using this geometry */
+ get meshes() {
+ return this._meshes;
+ }
+ /**
+ * Creates a new geometry
+ * @param id defines the unique ID
+ * @param scene defines the hosting scene
+ * @param vertexData defines the VertexData used to get geometry data
+ * @param updatable defines if geometry must be updatable (false by default)
+ * @param mesh defines the mesh that will be associated with the geometry
+ */
+ constructor(id, scene, vertexData, updatable = false, mesh = null) {
+ /**
+ * Gets the delay loading state of the geometry (none by default which means not delayed)
+ */
+ this.delayLoadState = 0;
+ this._totalVertices = 0;
+ this._isDisposed = false;
+ this._extend = {
+ minimum: new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE),
+ maximum: new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE),
+ };
+ this._indexBufferIsUpdatable = false;
+ this._positionsCache = [];
+ /** @internal */
+ this._parentContainer = null;
+ /**
+ * If set to true (false by default), the bounding info applied to the meshes sharing this geometry will be the bounding info defined at the class level
+ * and won't be computed based on the vertex positions (which is what we get when useBoundingInfoFromGeometry = false)
+ */
+ this.useBoundingInfoFromGeometry = false;
+ this._scene = scene || EngineStore.LastCreatedScene;
+ if (!this._scene) {
+ return;
+ }
+ this.id = id;
+ this.uniqueId = this._scene.getUniqueId();
+ this._engine = this._scene.getEngine();
+ this._meshes = [];
+ //Init vertex buffer cache
+ this._vertexBuffers = {};
+ this._indices = [];
+ this._updatable = updatable;
+ // vertexData
+ if (vertexData) {
+ this.setAllVerticesData(vertexData, updatable);
+ }
+ else {
+ this._totalVertices = 0;
+ }
+ if (this._engine.getCaps().vertexArrayObject) {
+ this._vertexArrayObjects = {};
+ }
+ // applyToMesh
+ if (mesh) {
+ this.applyToMesh(mesh);
+ mesh.computeWorldMatrix(true);
+ }
+ }
+ /**
+ * Gets the current extend of the geometry
+ */
+ get extend() {
+ return this._extend;
+ }
+ /**
+ * Gets the hosting scene
+ * @returns the hosting Scene
+ */
+ getScene() {
+ return this._scene;
+ }
+ /**
+ * Gets the hosting engine
+ * @returns the hosting Engine
+ */
+ getEngine() {
+ return this._engine;
+ }
+ /**
+ * Defines if the geometry is ready to use
+ * @returns true if the geometry is ready to be used
+ */
+ isReady() {
+ return this.delayLoadState === 1 || this.delayLoadState === 0;
+ }
+ /**
+ * Gets a value indicating that the geometry should not be serialized
+ */
+ get doNotSerialize() {
+ for (let index = 0; index < this._meshes.length; index++) {
+ if (!this._meshes[index].doNotSerialize) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /** @internal */
+ _rebuild() {
+ if (this._vertexArrayObjects) {
+ this._vertexArrayObjects = {};
+ }
+ // Index buffer
+ if (this._meshes.length !== 0 && this._indices) {
+ this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable, "Geometry_" + this.id + "_IndexBuffer");
+ }
+ // Vertex buffers
+ const buffers = new Set();
+ for (const key in this._vertexBuffers) {
+ buffers.add(this._vertexBuffers[key].getWrapperBuffer());
+ }
+ buffers.forEach((buffer) => {
+ buffer._rebuild();
+ });
+ }
+ /**
+ * Affects all geometry data in one call
+ * @param vertexData defines the geometry data
+ * @param updatable defines if the geometry must be flagged as updatable (false as default)
+ */
+ setAllVerticesData(vertexData, updatable) {
+ vertexData.applyToGeometry(this, updatable);
+ this._notifyUpdate();
+ }
+ /**
+ * Set specific vertex data
+ * @param kind defines the data kind (Position, normal, etc...)
+ * @param data defines the vertex data to use
+ * @param updatable defines if the vertex must be flagged as updatable (false as default)
+ * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
+ */
+ setVerticesData(kind, data, updatable = false, stride) {
+ if (updatable && Array.isArray(data)) {
+ // to avoid converting to Float32Array at each draw call in engine.updateDynamicVertexBuffer, we make the conversion a single time here
+ data = new Float32Array(data);
+ }
+ const buffer = new VertexBuffer(this._engine, data, kind, {
+ updatable,
+ postponeInternalCreation: this._meshes.length === 0,
+ stride,
+ label: "Geometry_" + this.id + "_" + kind,
+ });
+ this.setVerticesBuffer(buffer);
+ }
+ /**
+ * Removes a specific vertex data
+ * @param kind defines the data kind (Position, normal, etc...)
+ */
+ removeVerticesData(kind) {
+ if (this._vertexBuffers[kind]) {
+ this._vertexBuffers[kind].dispose();
+ delete this._vertexBuffers[kind];
+ }
+ if (this._vertexArrayObjects) {
+ this._disposeVertexArrayObjects();
+ }
+ }
+ /**
+ * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
+ * @param buffer defines the vertex buffer to use
+ * @param totalVertices defines the total number of vertices for position kind (could be null)
+ * @param disposeExistingBuffer disposes the existing buffer, if any (default: true)
+ */
+ setVerticesBuffer(buffer, totalVertices = null, disposeExistingBuffer = true) {
+ const kind = buffer.getKind();
+ if (this._vertexBuffers[kind] && disposeExistingBuffer) {
+ this._vertexBuffers[kind].dispose();
+ }
+ if (buffer._buffer) {
+ buffer._buffer._increaseReferences();
+ }
+ this._vertexBuffers[kind] = buffer;
+ const meshes = this._meshes;
+ const numOfMeshes = meshes.length;
+ if (kind === VertexBuffer.PositionKind) {
+ this._totalVertices = totalVertices ?? buffer._maxVerticesCount;
+ this._updateExtend(buffer.getFloatData(this._totalVertices));
+ this._resetPointsArrayCache();
+ // this._extend can be empty if buffer.getFloatData(this._totalVertices) returned null
+ const minimum = (this._extend && this._extend.minimum) || new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+ const maximum = (this._extend && this._extend.maximum) || new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ for (let index = 0; index < numOfMeshes; index++) {
+ const mesh = meshes[index];
+ mesh.buildBoundingInfo(minimum, maximum);
+ mesh._createGlobalSubMesh(mesh.isUnIndexed);
+ mesh.computeWorldMatrix(true);
+ mesh.synchronizeInstances();
+ }
+ }
+ this._notifyUpdate(kind);
+ }
+ /**
+ * Update a specific vertex buffer
+ * This function will directly update the underlying DataBuffer according to the passed numeric array or Float32Array
+ * It will do nothing if the buffer is not updatable
+ * @param kind defines the data kind (Position, normal, etc...)
+ * @param data defines the data to use
+ * @param offset defines the offset in the target buffer where to store the data
+ * @param useBytes set to true if the offset is in bytes
+ */
+ updateVerticesDataDirectly(kind, data, offset, useBytes = false) {
+ const vertexBuffer = this.getVertexBuffer(kind);
+ if (!vertexBuffer) {
+ return;
+ }
+ vertexBuffer.updateDirectly(data, offset, useBytes);
+ this._notifyUpdate(kind);
+ }
+ /**
+ * Update a specific vertex buffer
+ * This function will create a new buffer if the current one is not updatable
+ * @param kind defines the data kind (Position, normal, etc...)
+ * @param data defines the data to use
+ * @param updateExtends defines if the geometry extends must be recomputed (false by default)
+ */
+ updateVerticesData(kind, data, updateExtends = false) {
+ const vertexBuffer = this.getVertexBuffer(kind);
+ if (!vertexBuffer) {
+ return;
+ }
+ vertexBuffer.update(data);
+ if (kind === VertexBuffer.PositionKind) {
+ this._updateBoundingInfo(updateExtends, data);
+ }
+ this._notifyUpdate(kind);
+ }
+ _updateBoundingInfo(updateExtends, data) {
+ if (updateExtends) {
+ this._updateExtend(data);
+ }
+ this._resetPointsArrayCache();
+ if (updateExtends) {
+ const meshes = this._meshes;
+ for (const mesh of meshes) {
+ if (mesh.hasBoundingInfo) {
+ mesh.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum);
+ }
+ else {
+ mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
+ }
+ const subMeshes = mesh.subMeshes;
+ for (const subMesh of subMeshes) {
+ subMesh.refreshBoundingInfo();
+ }
+ }
+ }
+ }
+ /**
+ * @internal
+ */
+ _bind(effect, indexToBind, overrideVertexBuffers, overrideVertexArrayObjects) {
+ if (!effect) {
+ return;
+ }
+ if (indexToBind === undefined) {
+ indexToBind = this._indexBuffer;
+ }
+ const vbs = this.getVertexBuffers();
+ if (!vbs) {
+ return;
+ }
+ if (indexToBind != this._indexBuffer || (!this._vertexArrayObjects && !overrideVertexArrayObjects)) {
+ this._engine.bindBuffers(vbs, indexToBind, effect, overrideVertexBuffers);
+ return;
+ }
+ const vaos = overrideVertexArrayObjects ? overrideVertexArrayObjects : this._vertexArrayObjects;
+ const engine = this._engine;
+ // Using VAO
+ if (!vaos[effect.key]) {
+ vaos[effect.key] = engine.recordVertexArrayObject(vbs, indexToBind, effect, overrideVertexBuffers);
+ }
+ engine.bindVertexArrayObject(vaos[effect.key], indexToBind);
+ }
+ /**
+ * Gets total number of vertices
+ * @returns the total number of vertices
+ */
+ getTotalVertices() {
+ if (!this.isReady()) {
+ return 0;
+ }
+ return this._totalVertices;
+ }
+ /**
+ * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
+ * @param kind defines the data kind (Position, normal, etc...)
+ * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
+ * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
+ * @returns a float array containing vertex data
+ */
+ getVerticesData(kind, copyWhenShared, forceCopy) {
+ const vertexBuffer = this.getVertexBuffer(kind);
+ if (!vertexBuffer) {
+ return null;
+ }
+ return vertexBuffer.getFloatData(this._totalVertices, forceCopy || (copyWhenShared && this._meshes.length !== 1));
+ }
+ /**
+ * Copies the requested vertex data kind into the given vertex data map. Float data is constructed if the map doesn't have the data.
+ * @param kind defines the data kind (Position, normal, etc...)
+ * @param vertexData defines the map that stores the resulting data
+ */
+ copyVerticesData(kind, vertexData) {
+ const vertexBuffer = this.getVertexBuffer(kind);
+ if (!vertexBuffer) {
+ return;
+ }
+ vertexData[kind] || (vertexData[kind] = new Float32Array(this._totalVertices * vertexBuffer.getSize()));
+ const data = vertexBuffer.getData();
+ if (data) {
+ CopyFloatData(data, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.normalized, this._totalVertices, vertexData[kind]);
+ }
+ }
+ /**
+ * Returns a boolean defining if the vertex data for the requested `kind` is updatable
+ * @param kind defines the data kind (Position, normal, etc...)
+ * @returns true if the vertex buffer with the specified kind is updatable
+ */
+ isVertexBufferUpdatable(kind) {
+ const vb = this._vertexBuffers[kind];
+ if (!vb) {
+ return false;
+ }
+ return vb.isUpdatable();
+ }
+ /**
+ * Gets a specific vertex buffer
+ * @param kind defines the data kind (Position, normal, etc...)
+ * @returns a VertexBuffer
+ */
+ getVertexBuffer(kind) {
+ if (!this.isReady()) {
+ return null;
+ }
+ return this._vertexBuffers[kind];
+ }
+ /**
+ * Returns all vertex buffers
+ * @returns an object holding all vertex buffers indexed by kind
+ */
+ getVertexBuffers() {
+ if (!this.isReady()) {
+ return null;
+ }
+ return this._vertexBuffers;
+ }
+ /**
+ * Gets a boolean indicating if specific vertex buffer is present
+ * @param kind defines the data kind (Position, normal, etc...)
+ * @returns true if data is present
+ */
+ isVerticesDataPresent(kind) {
+ if (!this._vertexBuffers) {
+ if (this._delayInfo) {
+ return this._delayInfo.indexOf(kind) !== -1;
+ }
+ return false;
+ }
+ return this._vertexBuffers[kind] !== undefined;
+ }
+ /**
+ * Gets a list of all attached data kinds (Position, normal, etc...)
+ * @returns a list of string containing all kinds
+ */
+ getVerticesDataKinds() {
+ const result = [];
+ let kind;
+ if (!this._vertexBuffers && this._delayInfo) {
+ for (kind in this._delayInfo) {
+ result.push(kind);
+ }
+ }
+ else {
+ for (kind in this._vertexBuffers) {
+ result.push(kind);
+ }
+ }
+ return result;
+ }
+ /**
+ * Update index buffer
+ * @param indices defines the indices to store in the index buffer
+ * @param offset defines the offset in the target buffer where to store the data
+ * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)
+ */
+ updateIndices(indices, offset, gpuMemoryOnly = false) {
+ if (!this._indexBuffer) {
+ return;
+ }
+ if (!this._indexBufferIsUpdatable) {
+ this.setIndices(indices, null, true);
+ }
+ else {
+ const needToUpdateSubMeshes = indices.length !== this._indices.length;
+ if (!gpuMemoryOnly) {
+ this._indices = indices.slice();
+ }
+ this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
+ if (needToUpdateSubMeshes) {
+ for (const mesh of this._meshes) {
+ mesh._createGlobalSubMesh(true);
+ }
+ }
+ }
+ }
+ /**
+ * Sets the index buffer for this geometry.
+ * @param indexBuffer Defines the index buffer to use for this geometry
+ * @param totalVertices Defines the total number of vertices used by the buffer
+ * @param totalIndices Defines the total number of indices in the index buffer
+ * @param is32Bits Defines if the indices are 32 bits. If null (default), the value is guessed from the number of vertices
+ */
+ setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits = null) {
+ this._indices = [];
+ this._indexBufferIsUpdatable = false;
+ this._indexBuffer = indexBuffer;
+ this._totalVertices = totalVertices;
+ this._totalIndices = totalIndices;
+ if (is32Bits === null) {
+ indexBuffer.is32Bits = totalVertices > 65535;
+ }
+ else {
+ indexBuffer.is32Bits = is32Bits;
+ }
+ for (const mesh of this._meshes) {
+ mesh._createGlobalSubMesh(true);
+ mesh.synchronizeInstances();
+ }
+ this._notifyUpdate();
+ }
+ /**
+ * Creates a new index buffer
+ * @param indices defines the indices to store in the index buffer
+ * @param totalVertices defines the total number of vertices (could be null)
+ * @param updatable defines if the index buffer must be flagged as updatable (false by default)
+ * @param dontForceSubMeshRecreation defines a boolean indicating that we don't want to force the recreation of sub-meshes if we don't have to (false by default)
+ */
+ setIndices(indices, totalVertices = null, updatable = false, dontForceSubMeshRecreation = false) {
+ if (this._indexBuffer) {
+ this._engine._releaseBuffer(this._indexBuffer);
+ }
+ this._indices = indices;
+ this._indexBufferIsUpdatable = updatable;
+ if (this._meshes.length !== 0 && this._indices) {
+ this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable, "Geometry_" + this.id + "_IndexBuffer");
+ }
+ if (totalVertices != undefined) {
+ // including null and undefined
+ this._totalVertices = totalVertices;
+ }
+ for (const mesh of this._meshes) {
+ mesh._createGlobalSubMesh(!dontForceSubMeshRecreation);
+ mesh.synchronizeInstances();
+ }
+ this._notifyUpdate();
+ }
+ /**
+ * Return the total number of indices
+ * @returns the total number of indices
+ */
+ getTotalIndices() {
+ if (!this.isReady()) {
+ return 0;
+ }
+ return this._totalIndices !== undefined ? this._totalIndices : this._indices.length;
+ }
+ /**
+ * Gets the index buffer array
+ * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
+ * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
+ * @returns the index buffer array
+ */
+ getIndices(copyWhenShared, forceCopy) {
+ if (!this.isReady()) {
+ return null;
+ }
+ const orig = this._indices;
+ if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
+ return orig;
+ }
+ else {
+ return orig.slice();
+ }
+ }
+ /**
+ * Gets the index buffer
+ * @returns the index buffer
+ */
+ getIndexBuffer() {
+ if (!this.isReady()) {
+ return null;
+ }
+ return this._indexBuffer;
+ }
+ /**
+ * @internal
+ */
+ _releaseVertexArrayObject(effect = null) {
+ if (!effect || !this._vertexArrayObjects) {
+ return;
+ }
+ if (this._vertexArrayObjects[effect.key]) {
+ this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
+ delete this._vertexArrayObjects[effect.key];
+ }
+ }
+ /**
+ * Release the associated resources for a specific mesh
+ * @param mesh defines the source mesh
+ * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
+ */
+ releaseForMesh(mesh, shouldDispose) {
+ const meshes = this._meshes;
+ const index = meshes.indexOf(mesh);
+ if (index === -1) {
+ return;
+ }
+ meshes.splice(index, 1);
+ if (this._vertexArrayObjects) {
+ mesh._invalidateInstanceVertexArrayObject();
+ }
+ mesh._geometry = null;
+ if (meshes.length === 0 && shouldDispose) {
+ this.dispose();
+ }
+ }
+ /**
+ * Apply current geometry to a given mesh
+ * @param mesh defines the mesh to apply geometry to
+ */
+ applyToMesh(mesh) {
+ if (mesh._geometry === this) {
+ return;
+ }
+ const previousGeometry = mesh._geometry;
+ if (previousGeometry) {
+ previousGeometry.releaseForMesh(mesh);
+ }
+ if (this._vertexArrayObjects) {
+ mesh._invalidateInstanceVertexArrayObject();
+ }
+ const meshes = this._meshes;
+ // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
+ mesh._geometry = this;
+ mesh._internalAbstractMeshDataInfo._positions = null;
+ this._scene.pushGeometry(this);
+ meshes.push(mesh);
+ if (this.isReady()) {
+ this._applyToMesh(mesh);
+ }
+ else if (this._boundingInfo) {
+ mesh.setBoundingInfo(this._boundingInfo);
+ }
+ }
+ _updateExtend(data = null) {
+ if (this.useBoundingInfoFromGeometry && this._boundingInfo) {
+ this._extend = {
+ minimum: this._boundingInfo.minimum.clone(),
+ maximum: this._boundingInfo.maximum.clone(),
+ };
+ }
+ else {
+ if (!data) {
+ data = this.getVerticesData(VertexBuffer.PositionKind);
+ // This can happen if the buffer comes from a Hardware Buffer where
+ // The data have not been uploaded by Babylon. (ex: Compute Shaders and Storage Buffers)
+ if (!data) {
+ return;
+ }
+ }
+ this._extend = extractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
+ }
+ }
+ _applyToMesh(mesh) {
+ const numOfMeshes = this._meshes.length;
+ // vertexBuffers
+ for (const kind in this._vertexBuffers) {
+ if (numOfMeshes === 1) {
+ this._vertexBuffers[kind].create();
+ }
+ if (kind === VertexBuffer.PositionKind) {
+ if (!this._extend) {
+ this._updateExtend();
+ }
+ mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
+ mesh._createGlobalSubMesh(mesh.isUnIndexed);
+ //bounding info was just created again, world matrix should be applied again.
+ mesh._updateBoundingInfo();
+ }
+ }
+ // indexBuffer
+ if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
+ this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable, "Geometry_" + this.id + "_IndexBuffer");
+ }
+ // morphTargets
+ mesh._syncGeometryWithMorphTargetManager();
+ // instances
+ mesh.synchronizeInstances();
+ }
+ _notifyUpdate(kind) {
+ if (this.onGeometryUpdated) {
+ this.onGeometryUpdated(this, kind);
+ }
+ if (this._vertexArrayObjects) {
+ this._disposeVertexArrayObjects();
+ }
+ for (const mesh of this._meshes) {
+ mesh._markSubMeshesAsAttributesDirty();
+ }
+ }
+ /**
+ * Load the geometry if it was flagged as delay loaded
+ * @param scene defines the hosting scene
+ * @param onLoaded defines a callback called when the geometry is loaded
+ */
+ load(scene, onLoaded) {
+ if (this.delayLoadState === 2) {
+ return;
+ }
+ if (this.isReady()) {
+ if (onLoaded) {
+ onLoaded();
+ }
+ return;
+ }
+ this.delayLoadState = 2;
+ this._queueLoad(scene, onLoaded);
+ }
+ _queueLoad(scene, onLoaded) {
+ if (!this.delayLoadingFile) {
+ return;
+ }
+ scene.addPendingData(this);
+ scene._loadFile(this.delayLoadingFile, (data) => {
+ if (!this._delayLoadingFunction) {
+ return;
+ }
+ this._delayLoadingFunction(JSON.parse(data), this);
+ this.delayLoadState = 1;
+ this._delayInfo = [];
+ scene.removePendingData(this);
+ const meshes = this._meshes;
+ const numOfMeshes = meshes.length;
+ for (let index = 0; index < numOfMeshes; index++) {
+ this._applyToMesh(meshes[index]);
+ }
+ if (onLoaded) {
+ onLoaded();
+ }
+ }, undefined, true);
+ }
+ /**
+ * Invert the geometry to move from a right handed system to a left handed one.
+ */
+ toLeftHanded() {
+ // Flip faces
+ const tIndices = this.getIndices(false);
+ if (tIndices != null && tIndices.length > 0) {
+ for (let i = 0; i < tIndices.length; i += 3) {
+ const tTemp = tIndices[i + 0];
+ tIndices[i + 0] = tIndices[i + 2];
+ tIndices[i + 2] = tTemp;
+ }
+ this.setIndices(tIndices);
+ }
+ // Negate position.z
+ const tPositions = this.getVerticesData(VertexBuffer.PositionKind, false);
+ if (tPositions != null && tPositions.length > 0) {
+ for (let i = 0; i < tPositions.length; i += 3) {
+ tPositions[i + 2] = -tPositions[i + 2];
+ }
+ this.setVerticesData(VertexBuffer.PositionKind, tPositions, false);
+ }
+ // Negate normal.z
+ const tNormals = this.getVerticesData(VertexBuffer.NormalKind, false);
+ if (tNormals != null && tNormals.length > 0) {
+ for (let i = 0; i < tNormals.length; i += 3) {
+ tNormals[i + 2] = -tNormals[i + 2];
+ }
+ this.setVerticesData(VertexBuffer.NormalKind, tNormals, false);
+ }
+ }
+ // Cache
+ /** @internal */
+ _resetPointsArrayCache() {
+ this._positions = null;
+ }
+ /** @internal */
+ _generatePointsArray() {
+ if (this._positions) {
+ return true;
+ }
+ const data = this.getVerticesData(VertexBuffer.PositionKind);
+ if (!data || data.length === 0) {
+ return false;
+ }
+ for (let index = this._positionsCache.length * 3, arrayIdx = this._positionsCache.length; index < data.length; index += 3, ++arrayIdx) {
+ this._positionsCache[arrayIdx] = Vector3.FromArray(data, index);
+ }
+ for (let index = 0, arrayIdx = 0; index < data.length; index += 3, ++arrayIdx) {
+ this._positionsCache[arrayIdx].set(data[0 + index], data[1 + index], data[2 + index]);
+ }
+ // just in case the number of positions was reduced, splice the array
+ this._positionsCache.length = data.length / 3;
+ this._positions = this._positionsCache;
+ return true;
+ }
+ /**
+ * Gets a value indicating if the geometry is disposed
+ * @returns true if the geometry was disposed
+ */
+ isDisposed() {
+ return this._isDisposed;
+ }
+ _disposeVertexArrayObjects() {
+ if (this._vertexArrayObjects) {
+ for (const kind in this._vertexArrayObjects) {
+ this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
+ }
+ this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
+ const meshes = this._meshes;
+ const numOfMeshes = meshes.length;
+ for (let index = 0; index < numOfMeshes; index++) {
+ meshes[index]._invalidateInstanceVertexArrayObject();
+ }
+ }
+ }
+ /**
+ * Free all associated resources
+ */
+ dispose() {
+ const meshes = this._meshes;
+ const numOfMeshes = meshes.length;
+ let index;
+ for (index = 0; index < numOfMeshes; index++) {
+ this.releaseForMesh(meshes[index]);
+ }
+ this._meshes.length = 0;
+ this._disposeVertexArrayObjects();
+ for (const kind in this._vertexBuffers) {
+ this._vertexBuffers[kind].dispose();
+ }
+ this._vertexBuffers = {};
+ this._totalVertices = 0;
+ if (this._indexBuffer) {
+ this._engine._releaseBuffer(this._indexBuffer);
+ }
+ this._indexBuffer = null;
+ this._indices = [];
+ this.delayLoadState = 0;
+ this.delayLoadingFile = null;
+ this._delayLoadingFunction = null;
+ this._delayInfo = [];
+ this._boundingInfo = null;
+ this._scene.removeGeometry(this);
+ if (this._parentContainer) {
+ const index = this._parentContainer.geometries.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.geometries.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ this._isDisposed = true;
+ }
+ /**
+ * Clone the current geometry into a new geometry
+ * @param id defines the unique ID of the new geometry
+ * @returns a new geometry object
+ */
+ copy(id) {
+ const vertexData = new VertexData();
+ vertexData.indices = [];
+ const indices = this.getIndices();
+ if (indices) {
+ for (let index = 0; index < indices.length; index++) {
+ vertexData.indices.push(indices[index]);
+ }
+ }
+ let updatable = false;
+ let stopChecking = false;
+ let kind;
+ for (kind in this._vertexBuffers) {
+ const data = this.getVerticesData(kind);
+ if (data) {
+ if (data instanceof Float32Array) {
+ vertexData.set(new Float32Array(data), kind);
+ }
+ else {
+ vertexData.set(data.slice(0), kind);
+ }
+ if (!stopChecking) {
+ const vb = this.getVertexBuffer(kind);
+ if (vb) {
+ updatable = vb.isUpdatable();
+ stopChecking = !updatable;
+ }
+ }
+ }
+ }
+ const geometry = new Geometry(id, this._scene, vertexData, updatable);
+ geometry.delayLoadState = this.delayLoadState;
+ geometry.delayLoadingFile = this.delayLoadingFile;
+ geometry._delayLoadingFunction = this._delayLoadingFunction;
+ for (kind in this._delayInfo) {
+ geometry._delayInfo = geometry._delayInfo || [];
+ geometry._delayInfo.push(kind);
+ }
+ // Bounding info
+ geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
+ return geometry;
+ }
+ /**
+ * Serialize the current geometry info (and not the vertices data) into a JSON object
+ * @returns a JSON representation of the current geometry data (without the vertices data)
+ */
+ serialize() {
+ const serializationObject = {};
+ serializationObject.id = this.id;
+ serializationObject.uniqueId = this.uniqueId;
+ serializationObject.updatable = this._updatable;
+ if (Tags && Tags.HasTags(this)) {
+ serializationObject.tags = Tags.GetTags(this);
+ }
+ return serializationObject;
+ }
+ _toNumberArray(origin) {
+ if (Array.isArray(origin)) {
+ return origin;
+ }
+ else {
+ return Array.prototype.slice.call(origin);
+ }
+ }
+ /**
+ * Release any memory retained by the cached data on the Geometry.
+ *
+ * Call this function to reduce memory footprint of the mesh.
+ * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
+ */
+ clearCachedData() {
+ this._indices = [];
+ this._resetPointsArrayCache();
+ for (const vbName in this._vertexBuffers) {
+ if (!Object.prototype.hasOwnProperty.call(this._vertexBuffers, vbName)) {
+ continue;
+ }
+ this._vertexBuffers[vbName]._buffer._data = null;
+ }
+ }
+ /**
+ * Serialize all vertices data into a JSON object
+ * @returns a JSON representation of the current geometry data
+ */
+ serializeVerticeData() {
+ const serializationObject = this.serialize();
+ if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
+ serializationObject.positions = this._toNumberArray(this.getVerticesData(VertexBuffer.PositionKind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
+ serializationObject.positions._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+ serializationObject.normals = this._toNumberArray(this.getVerticesData(VertexBuffer.NormalKind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
+ serializationObject.normals._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {
+ serializationObject.tangents = this._toNumberArray(this.getVerticesData(VertexBuffer.TangentKind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) {
+ serializationObject.tangents._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.UVKind)) {
+ serializationObject.uvs = this._toNumberArray(this.getVerticesData(VertexBuffer.UVKind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) {
+ serializationObject.uvs._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
+ serializationObject.uvs2 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) {
+ serializationObject.uvs2._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) {
+ serializationObject.uvs3 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) {
+ serializationObject.uvs3._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) {
+ serializationObject.uvs4 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) {
+ serializationObject.uvs4._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) {
+ serializationObject.uvs5 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) {
+ serializationObject.uvs5._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) {
+ serializationObject.uvs6 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) {
+ serializationObject.uvs6._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) {
+ serializationObject.colors = this._toNumberArray(this.getVerticesData(VertexBuffer.ColorKind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) {
+ serializationObject.colors._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
+ serializationObject.matricesIndices = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind));
+ serializationObject.matricesIndices._isExpanded = true;
+ if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) {
+ serializationObject.matricesIndices._updatable = true;
+ }
+ }
+ if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
+ serializationObject.matricesWeights = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind));
+ if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) {
+ serializationObject.matricesWeights._updatable = true;
+ }
+ }
+ serializationObject.indices = this._toNumberArray(this.getIndices());
+ return serializationObject;
+ }
+ // Statics
+ /**
+ * Extracts a clone of a mesh geometry
+ * @param mesh defines the source mesh
+ * @param id defines the unique ID of the new geometry object
+ * @returns the new geometry object
+ */
+ static ExtractFromMesh(mesh, id) {
+ const geometry = mesh._geometry;
+ if (!geometry) {
+ return null;
+ }
+ return geometry.copy(id);
+ }
+ /**
+ * You should now use Tools.RandomId(), this method is still here for legacy reasons.
+ * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
+ * Be aware Math.random() could cause collisions, but:
+ * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
+ * @returns a string containing a new GUID
+ */
+ static RandomId() {
+ return Tools.RandomId();
+ }
+ static _GetGeometryByLoadedUniqueId(uniqueId, scene) {
+ for (let index = 0; index < scene.geometries.length; index++) {
+ if (scene.geometries[index]._loadedUniqueId === uniqueId) {
+ return scene.geometries[index];
+ }
+ }
+ return null;
+ }
+ /**
+ * @internal
+ */
+ static _ImportGeometry(parsedGeometry, mesh) {
+ const scene = mesh.getScene();
+ // Geometry
+ const geometryUniqueId = parsedGeometry.geometryUniqueId;
+ const geometryId = parsedGeometry.geometryId;
+ if (geometryUniqueId || geometryId) {
+ const geometry = geometryUniqueId ? this._GetGeometryByLoadedUniqueId(geometryUniqueId, scene) : scene.getGeometryById(geometryId);
+ if (geometry) {
+ geometry.applyToMesh(mesh);
+ }
+ }
+ else if (parsedGeometry instanceof ArrayBuffer) {
+ const binaryInfo = mesh._binaryInfo;
+ if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
+ const positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false);
+ }
+ if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
+ const normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false);
+ }
+ if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
+ const tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false);
+ }
+ if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
+ const uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false);
+ }
+ if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
+ const uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false);
+ }
+ if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
+ const uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false);
+ }
+ if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
+ const uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false);
+ }
+ if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
+ const uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false);
+ }
+ if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
+ const uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false);
+ }
+ if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
+ const colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
+ }
+ if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
+ const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
+ const floatIndices = [];
+ for (let i = 0; i < matricesIndicesData.length; i++) {
+ const index = matricesIndicesData[i];
+ floatIndices.push(index & 0x000000ff);
+ floatIndices.push((index & 0x0000ff00) >> 8);
+ floatIndices.push((index & 0x00ff0000) >> 16);
+ floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0
+ }
+ mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false);
+ }
+ if (binaryInfo.matricesIndicesExtraAttrDesc && binaryInfo.matricesIndicesExtraAttrDesc.count > 0) {
+ const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesExtraAttrDesc.offset, binaryInfo.matricesIndicesExtraAttrDesc.count);
+ const floatIndices = [];
+ for (let i = 0; i < matricesIndicesData.length; i++) {
+ const index = matricesIndicesData[i];
+ floatIndices.push(index & 0x000000ff);
+ floatIndices.push((index & 0x0000ff00) >> 8);
+ floatIndices.push((index & 0x00ff0000) >> 16);
+ floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0
+ }
+ mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
+ }
+ if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
+ const matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
+ mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
+ }
+ if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
+ const indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
+ mesh.setIndices(indicesData, null);
+ }
+ if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
+ const subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
+ mesh.subMeshes = [];
+ for (let i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
+ const materialIndex = subMeshesData[i * 5 + 0];
+ const verticesStart = subMeshesData[i * 5 + 1];
+ const verticesCount = subMeshesData[i * 5 + 2];
+ const indexStart = subMeshesData[i * 5 + 3];
+ const indexCount = subMeshesData[i * 5 + 4];
+ SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
+ }
+ }
+ }
+ else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
+ mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
+ mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
+ if (parsedGeometry.tangents) {
+ mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
+ }
+ if (parsedGeometry.uvs) {
+ mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
+ }
+ if (parsedGeometry.uvs2) {
+ mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
+ }
+ if (parsedGeometry.uvs3) {
+ mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
+ }
+ if (parsedGeometry.uvs4) {
+ mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
+ }
+ if (parsedGeometry.uvs5) {
+ mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
+ }
+ if (parsedGeometry.uvs6) {
+ mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
+ }
+ if (parsedGeometry.colors) {
+ mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
+ }
+ if (parsedGeometry.matricesIndices) {
+ if (!parsedGeometry.matricesIndices._isExpanded) {
+ const floatIndices = [];
+ for (let i = 0; i < parsedGeometry.matricesIndices.length; i++) {
+ const matricesIndex = parsedGeometry.matricesIndices[i];
+ floatIndices.push(matricesIndex & 0x000000ff);
+ floatIndices.push((matricesIndex & 0x0000ff00) >> 8);
+ floatIndices.push((matricesIndex & 0x00ff0000) >> 16);
+ floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0
+ }
+ mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
+ }
+ else {
+ delete parsedGeometry.matricesIndices._isExpanded;
+ mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
+ }
+ }
+ if (parsedGeometry.matricesIndicesExtra) {
+ if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
+ const floatIndices = [];
+ for (let i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
+ const matricesIndex = parsedGeometry.matricesIndicesExtra[i];
+ floatIndices.push(matricesIndex & 0x000000ff);
+ floatIndices.push((matricesIndex & 0x0000ff00) >> 8);
+ floatIndices.push((matricesIndex & 0x00ff0000) >> 16);
+ floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0
+ }
+ mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
+ }
+ else {
+ delete parsedGeometry.matricesIndices._isExpanded;
+ mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
+ }
+ }
+ if (parsedGeometry.matricesWeights) {
+ Geometry._CleanMatricesWeights(parsedGeometry, mesh);
+ mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
+ }
+ if (parsedGeometry.matricesWeightsExtra) {
+ mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
+ }
+ mesh.setIndices(parsedGeometry.indices, null);
+ }
+ // SubMeshes
+ if (parsedGeometry.subMeshes) {
+ mesh.subMeshes = [];
+ for (let subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
+ const parsedSubMesh = parsedGeometry.subMeshes[subIndex];
+ SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
+ }
+ }
+ // Flat shading
+ if (mesh._shouldGenerateFlatShading) {
+ mesh.convertToFlatShadedMesh();
+ mesh._shouldGenerateFlatShading = false;
+ }
+ // Update
+ mesh.computeWorldMatrix(true);
+ scene.onMeshImportedObservable.notifyObservers(mesh);
+ }
+ static _CleanMatricesWeights(parsedGeometry, mesh) {
+ const epsilon = 1e-3;
+ if (!SceneLoaderFlags.CleanBoneMatrixWeights) {
+ return;
+ }
+ let noInfluenceBoneIndex = 0.0;
+ if (parsedGeometry.skeletonId > -1) {
+ const skeleton = mesh.getScene().getLastSkeletonById(parsedGeometry.skeletonId);
+ if (!skeleton) {
+ return;
+ }
+ noInfluenceBoneIndex = skeleton.bones.length;
+ }
+ else {
+ return;
+ }
+ const matricesIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);
+ const matricesIndicesExtra = mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind);
+ const matricesWeights = parsedGeometry.matricesWeights;
+ const matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
+ const influencers = parsedGeometry.numBoneInfluencer;
+ const size = matricesWeights.length;
+ for (let i = 0; i < size; i += 4) {
+ let weight = 0.0;
+ let firstZeroWeight = -1;
+ for (let j = 0; j < 4; j++) {
+ const w = matricesWeights[i + j];
+ weight += w;
+ if (w < epsilon && firstZeroWeight < 0) {
+ firstZeroWeight = j;
+ }
+ }
+ if (matricesWeightsExtra) {
+ for (let j = 0; j < 4; j++) {
+ const w = matricesWeightsExtra[i + j];
+ weight += w;
+ if (w < epsilon && firstZeroWeight < 0) {
+ firstZeroWeight = j + 4;
+ }
+ }
+ }
+ if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) {
+ firstZeroWeight = influencers - 1;
+ }
+ if (weight > epsilon) {
+ const mweight = 1.0 / weight;
+ for (let j = 0; j < 4; j++) {
+ matricesWeights[i + j] *= mweight;
+ }
+ if (matricesWeightsExtra) {
+ for (let j = 0; j < 4; j++) {
+ matricesWeightsExtra[i + j] *= mweight;
+ }
+ }
+ }
+ else {
+ if (firstZeroWeight >= 4) {
+ matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
+ matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
+ }
+ else {
+ matricesWeights[i + firstZeroWeight] = 1.0 - weight;
+ matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
+ }
+ }
+ }
+ mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices);
+ if (parsedGeometry.matricesWeightsExtra) {
+ mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
+ }
+ }
+ /**
+ * Create a new geometry from persisted data (Using .babylon file format)
+ * @param parsedVertexData defines the persisted data
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root url to use to load assets (like delayed data)
+ * @returns the new geometry object
+ */
+ static Parse(parsedVertexData, scene, rootUrl) {
+ const geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
+ geometry._loadedUniqueId = parsedVertexData.uniqueId;
+ if (Tags) {
+ Tags.AddTagsTo(geometry, parsedVertexData.tags);
+ }
+ if (parsedVertexData.delayLoadingFile) {
+ geometry.delayLoadState = 4;
+ geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
+ geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
+ geometry._delayInfo = [];
+ if (parsedVertexData.hasUVs) {
+ geometry._delayInfo.push(VertexBuffer.UVKind);
+ }
+ if (parsedVertexData.hasUVs2) {
+ geometry._delayInfo.push(VertexBuffer.UV2Kind);
+ }
+ if (parsedVertexData.hasUVs3) {
+ geometry._delayInfo.push(VertexBuffer.UV3Kind);
+ }
+ if (parsedVertexData.hasUVs4) {
+ geometry._delayInfo.push(VertexBuffer.UV4Kind);
+ }
+ if (parsedVertexData.hasUVs5) {
+ geometry._delayInfo.push(VertexBuffer.UV5Kind);
+ }
+ if (parsedVertexData.hasUVs6) {
+ geometry._delayInfo.push(VertexBuffer.UV6Kind);
+ }
+ if (parsedVertexData.hasColors) {
+ geometry._delayInfo.push(VertexBuffer.ColorKind);
+ }
+ if (parsedVertexData.hasMatricesIndices) {
+ geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind);
+ }
+ if (parsedVertexData.hasMatricesWeights) {
+ geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind);
+ }
+ geometry._delayLoadingFunction = VertexData.ImportVertexData;
+ }
+ else {
+ VertexData.ImportVertexData(parsedVertexData, geometry);
+ }
+ scene.pushGeometry(geometry, true);
+ return geometry;
+ }
+}
+
+const convertRHSToLHS = Matrix.Compose(Vector3.One(), Quaternion.FromEulerAngles(0, Math.PI, 0), Vector3.Zero());
+/**
+ * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node
+ */
+class TransformNode extends Node$2 {
+ /**
+ * Gets or sets the billboard mode. Default is 0.
+ *
+ * | Value | Type | Description |
+ * | --- | --- | --- |
+ * | 0 | BILLBOARDMODE_NONE | |
+ * | 1 | BILLBOARDMODE_X | |
+ * | 2 | BILLBOARDMODE_Y | |
+ * | 4 | BILLBOARDMODE_Z | |
+ * | 7 | BILLBOARDMODE_ALL | |
+ *
+ */
+ get billboardMode() {
+ return this._billboardMode;
+ }
+ set billboardMode(value) {
+ if (this._billboardMode === value) {
+ return;
+ }
+ this._billboardMode = value;
+ this._cache.useBillboardPosition = (this._billboardMode & TransformNode.BILLBOARDMODE_USE_POSITION) !== 0;
+ this._computeUseBillboardPath();
+ }
+ /**
+ * Gets or sets a boolean indicating that parent rotation should be preserved when using billboards.
+ * This could be useful for glTF objects where parent rotation helps converting from right handed to left handed
+ */
+ get preserveParentRotationForBillboard() {
+ return this._preserveParentRotationForBillboard;
+ }
+ set preserveParentRotationForBillboard(value) {
+ if (value === this._preserveParentRotationForBillboard) {
+ return;
+ }
+ this._preserveParentRotationForBillboard = value;
+ this._computeUseBillboardPath();
+ }
+ _computeUseBillboardPath() {
+ this._cache.useBillboardPath = this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;
+ }
+ /**
+ * Gets or sets the distance of the object to max, often used by skybox
+ */
+ get infiniteDistance() {
+ return this._infiniteDistance;
+ }
+ set infiniteDistance(value) {
+ if (this._infiniteDistance === value) {
+ return;
+ }
+ this._infiniteDistance = value;
+ }
+ constructor(name, scene = null, isPure = true) {
+ super(name, scene, false);
+ this._forward = new Vector3(0, 0, 1);
+ this._up = new Vector3(0, 1, 0);
+ this._right = new Vector3(1, 0, 0);
+ // Properties
+ this._position = Vector3.Zero();
+ this._rotation = Vector3.Zero();
+ this._rotationQuaternion = null;
+ this._scaling = Vector3.One();
+ this._transformToBoneReferal = null;
+ this._isAbsoluteSynced = false;
+ this._billboardMode = TransformNode.BILLBOARDMODE_NONE;
+ this._preserveParentRotationForBillboard = false;
+ /**
+ * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
+ */
+ this.scalingDeterminant = 1;
+ this._infiniteDistance = false;
+ /**
+ * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
+ * By default the system will update normals to compensate
+ */
+ this.ignoreNonUniformScaling = false;
+ /**
+ * Gets or sets a boolean indicating that even if rotationQuaternion is defined, you can keep updating rotation property and Babylon.js will just mix both
+ */
+ this.reIntegrateRotationIntoRotationQuaternion = false;
+ // Cache
+ /** @internal */
+ this._poseMatrix = null;
+ /** @internal */
+ this._localMatrix = Matrix.Zero();
+ this._usePivotMatrix = false;
+ this._absolutePosition = Vector3.Zero();
+ this._absoluteScaling = Vector3.Zero();
+ this._absoluteRotationQuaternion = Quaternion.Identity();
+ this._pivotMatrix = Matrix.Identity();
+ /** @internal */
+ this._postMultiplyPivotMatrix = false;
+ this._isWorldMatrixFrozen = false;
+ /** @internal */
+ this._indexInSceneTransformNodesArray = -1;
+ /**
+ * An event triggered after the world matrix is updated
+ */
+ this.onAfterWorldMatrixUpdateObservable = new Observable();
+ this._nonUniformScaling = false;
+ if (isPure) {
+ this.getScene().addTransformNode(this);
+ }
+ }
+ /**
+ * Gets a string identifying the name of the class
+ * @returns "TransformNode" string
+ */
+ getClassName() {
+ return "TransformNode";
+ }
+ /**
+ * Gets or set the node position (default is (0.0, 0.0, 0.0))
+ */
+ get position() {
+ return this._position;
+ }
+ set position(newPosition) {
+ this._position = newPosition;
+ this._markAsDirtyInternal();
+ }
+ /**
+ * return true if a pivot has been set
+ * @returns true if a pivot matrix is used
+ */
+ isUsingPivotMatrix() {
+ return this._usePivotMatrix;
+ }
+ /**
+ * @returns true if pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect.
+ */
+ isUsingPostMultiplyPivotMatrix() {
+ return this._postMultiplyPivotMatrix;
+ }
+ /**
+ * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
+ * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
+ */
+ get rotation() {
+ return this._rotation;
+ }
+ set rotation(newRotation) {
+ this._rotation = newRotation;
+ this._rotationQuaternion = null;
+ this._markAsDirtyInternal();
+ }
+ /**
+ * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (1.0, 1.0, 1.0)).
+ */
+ get scaling() {
+ return this._scaling;
+ }
+ set scaling(newScaling) {
+ this._scaling = newScaling;
+ this._markAsDirtyInternal();
+ }
+ /**
+ * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (undefined by default, but can be null).
+ * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
+ */
+ get rotationQuaternion() {
+ return this._rotationQuaternion;
+ }
+ set rotationQuaternion(quaternion) {
+ this._rotationQuaternion = quaternion;
+ //reset the rotation vector.
+ if (quaternion) {
+ this._rotation.setAll(0.0);
+ }
+ this._markAsDirtyInternal();
+ }
+ _markAsDirtyInternal() {
+ if (this._isDirty) {
+ return;
+ }
+ this._isDirty = true;
+ if (this.customMarkAsDirty) {
+ this.customMarkAsDirty();
+ }
+ }
+ /**
+ * The forward direction of that transform in world space.
+ */
+ get forward() {
+ Vector3.TransformNormalFromFloatsToRef(0, 0, this.getScene().useRightHandedSystem ? -1 : 1.0, this.getWorldMatrix(), this._forward);
+ return this._forward.normalize();
+ }
+ /**
+ * The up direction of that transform in world space.
+ */
+ get up() {
+ Vector3.TransformNormalFromFloatsToRef(0, 1, 0, this.getWorldMatrix(), this._up);
+ return this._up.normalize();
+ }
+ /**
+ * The right direction of that transform in world space.
+ */
+ get right() {
+ Vector3.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem ? -1 : 1.0, 0, 0, this.getWorldMatrix(), this._right);
+ return this._right.normalize();
+ }
+ /**
+ * Copies the parameter passed Matrix into the mesh Pose matrix.
+ * @param matrix the matrix to copy the pose from
+ * @returns this TransformNode.
+ */
+ updatePoseMatrix(matrix) {
+ if (!this._poseMatrix) {
+ this._poseMatrix = matrix.clone();
+ return this;
+ }
+ this._poseMatrix.copyFrom(matrix);
+ return this;
+ }
+ /**
+ * Returns the mesh Pose matrix.
+ * @returns the pose matrix
+ */
+ getPoseMatrix() {
+ if (!this._poseMatrix) {
+ this._poseMatrix = Matrix.Identity();
+ }
+ return this._poseMatrix;
+ }
+ /** @internal */
+ _isSynchronized() {
+ const cache = this._cache;
+ if (this._billboardMode !== cache.billboardMode || this._billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
+ return false;
+ }
+ if (cache.pivotMatrixUpdated) {
+ return false;
+ }
+ if (this._infiniteDistance) {
+ return false;
+ }
+ if (this._position._isDirty) {
+ return false;
+ }
+ if (this._scaling._isDirty) {
+ return false;
+ }
+ if ((this._rotationQuaternion && this._rotationQuaternion._isDirty) || this._rotation._isDirty) {
+ return false;
+ }
+ return true;
+ }
+ /** @internal */
+ _initCache() {
+ super._initCache();
+ const cache = this._cache;
+ cache.localMatrixUpdated = false;
+ cache.billboardMode = -1;
+ cache.infiniteDistance = false;
+ cache.useBillboardPosition = false;
+ cache.useBillboardPath = false;
+ }
+ /**
+ * Returns the current mesh absolute position.
+ * Returns a Vector3.
+ */
+ get absolutePosition() {
+ return this.getAbsolutePosition();
+ }
+ /**
+ * Returns the current mesh absolute scaling.
+ * Returns a Vector3.
+ */
+ get absoluteScaling() {
+ this._syncAbsoluteScalingAndRotation();
+ return this._absoluteScaling;
+ }
+ /**
+ * Returns the current mesh absolute rotation.
+ * Returns a Quaternion.
+ */
+ get absoluteRotationQuaternion() {
+ this._syncAbsoluteScalingAndRotation();
+ return this._absoluteRotationQuaternion;
+ }
+ /**
+ * Sets a new matrix to apply before all other transformation
+ * @param matrix defines the transform matrix
+ * @returns the current TransformNode
+ */
+ setPreTransformMatrix(matrix) {
+ return this.setPivotMatrix(matrix, false);
+ }
+ /**
+ * Sets a new pivot matrix to the current node
+ * @param matrix defines the new pivot matrix to use
+ * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
+ * @returns the current TransformNode
+ */
+ setPivotMatrix(matrix, postMultiplyPivotMatrix = true) {
+ this._pivotMatrix.copyFrom(matrix);
+ this._usePivotMatrix = !this._pivotMatrix.isIdentity();
+ this._cache.pivotMatrixUpdated = true;
+ this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
+ if (this._postMultiplyPivotMatrix) {
+ if (!this._pivotMatrixInverse) {
+ this._pivotMatrixInverse = Matrix.Invert(this._pivotMatrix);
+ }
+ else {
+ this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
+ }
+ }
+ return this;
+ }
+ /**
+ * Returns the mesh pivot matrix.
+ * Default : Identity.
+ * @returns the matrix
+ */
+ getPivotMatrix() {
+ return this._pivotMatrix;
+ }
+ /**
+ * Instantiate (when possible) or clone that node with its hierarchy
+ * @param newParent defines the new parent to use for the instance (or clone)
+ * @param options defines options to configure how copy is done
+ * @param options.doNotInstantiate defines if the model must be instantiated or just cloned
+ * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created
+ * @returns an instance (or a clone) of the current node with its hierarchy
+ */
+ instantiateHierarchy(newParent = null, options, onNewNodeCreated) {
+ const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true);
+ if (clone) {
+ if (onNewNodeCreated) {
+ onNewNodeCreated(this, clone);
+ }
+ }
+ for (const child of this.getChildTransformNodes(true)) {
+ child.instantiateHierarchy(clone, options, onNewNodeCreated);
+ }
+ return clone;
+ }
+ /**
+ * Prevents the World matrix to be computed any longer
+ * @param newWorldMatrix defines an optional matrix to use as world matrix
+ * @param decompose defines whether to decompose the given newWorldMatrix or directly assign
+ * @returns the TransformNode.
+ */
+ freezeWorldMatrix(newWorldMatrix = null, decompose = false) {
+ if (newWorldMatrix) {
+ if (decompose) {
+ this._rotation.setAll(0);
+ this._rotationQuaternion = this._rotationQuaternion || Quaternion.Identity();
+ newWorldMatrix.decompose(this._scaling, this._rotationQuaternion, this._position);
+ this.computeWorldMatrix(true);
+ }
+ else {
+ this._worldMatrix = newWorldMatrix;
+ this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
+ this._afterComputeWorldMatrix();
+ }
+ }
+ else {
+ this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
+ this.computeWorldMatrix(true);
+ }
+ this._isDirty = false;
+ this._isWorldMatrixFrozen = true;
+ return this;
+ }
+ /**
+ * Allows back the World matrix computation.
+ * @returns the TransformNode.
+ */
+ unfreezeWorldMatrix() {
+ this._isWorldMatrixFrozen = false;
+ this.computeWorldMatrix(true);
+ return this;
+ }
+ /**
+ * True if the World matrix has been frozen.
+ */
+ get isWorldMatrixFrozen() {
+ return this._isWorldMatrixFrozen;
+ }
+ /**
+ * Returns the mesh absolute position in the World.
+ * @returns a Vector3.
+ */
+ getAbsolutePosition() {
+ this.computeWorldMatrix();
+ return this._absolutePosition;
+ }
+ /**
+ * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
+ * @param absolutePosition the absolute position to set
+ * @returns the TransformNode.
+ */
+ setAbsolutePosition(absolutePosition) {
+ if (!absolutePosition) {
+ return this;
+ }
+ let absolutePositionX;
+ let absolutePositionY;
+ let absolutePositionZ;
+ if (absolutePosition.x === undefined) {
+ if (arguments.length < 3) {
+ return this;
+ }
+ absolutePositionX = arguments[0];
+ absolutePositionY = arguments[1];
+ absolutePositionZ = arguments[2];
+ }
+ else {
+ absolutePositionX = absolutePosition.x;
+ absolutePositionY = absolutePosition.y;
+ absolutePositionZ = absolutePosition.z;
+ }
+ if (this.parent) {
+ const invertParentWorldMatrix = TmpVectors.Matrix[0];
+ this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
+ Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
+ }
+ else {
+ this.position.x = absolutePositionX;
+ this.position.y = absolutePositionY;
+ this.position.z = absolutePositionZ;
+ }
+ this._absolutePosition.copyFrom(absolutePosition);
+ return this;
+ }
+ /**
+ * Sets the mesh position in its local space.
+ * @param vector3 the position to set in localspace
+ * @returns the TransformNode.
+ */
+ setPositionWithLocalVector(vector3) {
+ this.computeWorldMatrix();
+ this.position = Vector3.TransformNormal(vector3, this._localMatrix);
+ return this;
+ }
+ /**
+ * Returns the mesh position in the local space from the current World matrix values.
+ * @returns a new Vector3.
+ */
+ getPositionExpressedInLocalSpace() {
+ this.computeWorldMatrix();
+ const invLocalWorldMatrix = TmpVectors.Matrix[0];
+ this._localMatrix.invertToRef(invLocalWorldMatrix);
+ return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
+ }
+ /**
+ * Translates the mesh along the passed Vector3 in its local space.
+ * @param vector3 the distance to translate in localspace
+ * @returns the TransformNode.
+ */
+ locallyTranslate(vector3) {
+ this.computeWorldMatrix(true);
+ this.position = Vector3.TransformCoordinates(vector3, this._localMatrix);
+ return this;
+ }
+ /**
+ * Orients a mesh towards a target point. Mesh must be drawn facing user.
+ * @param targetPoint the position (must be in same space as current mesh) to look at
+ * @param yawCor optional yaw (y-axis) correction in radians
+ * @param pitchCor optional pitch (x-axis) correction in radians
+ * @param rollCor optional roll (z-axis) correction in radians
+ * @param space the chosen space of the target
+ * @returns the TransformNode.
+ */
+ lookAt(targetPoint, yawCor = 0, pitchCor = 0, rollCor = 0, space = 0 /* Space.LOCAL */) {
+ const dv = TransformNode._LookAtVectorCache;
+ const pos = space === 0 /* Space.LOCAL */ ? this.position : this.getAbsolutePosition();
+ targetPoint.subtractToRef(pos, dv);
+ this.setDirection(dv, yawCor, pitchCor, rollCor);
+ // Correct for parent's rotation offset
+ if (space === 1 /* Space.WORLD */ && this.parent) {
+ if (this.rotationQuaternion) {
+ // Get local rotation matrix of the looking object
+ const rotationMatrix = TmpVectors.Matrix[0];
+ this.rotationQuaternion.toRotationMatrix(rotationMatrix);
+ // Offset rotation by parent's inverted rotation matrix to correct in world space
+ const parentRotationMatrix = TmpVectors.Matrix[1];
+ this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
+ parentRotationMatrix.invert();
+ rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
+ this.rotationQuaternion.fromRotationMatrix(rotationMatrix);
+ }
+ else {
+ // Get local rotation matrix of the looking object
+ const quaternionRotation = TmpVectors.Quaternion[0];
+ Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation);
+ const rotationMatrix = TmpVectors.Matrix[0];
+ quaternionRotation.toRotationMatrix(rotationMatrix);
+ // Offset rotation by parent's inverted rotation matrix to correct in world space
+ const parentRotationMatrix = TmpVectors.Matrix[1];
+ this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
+ parentRotationMatrix.invert();
+ rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
+ quaternionRotation.fromRotationMatrix(rotationMatrix);
+ quaternionRotation.toEulerAnglesToRef(this.rotation);
+ }
+ }
+ return this;
+ }
+ /**
+ * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
+ * This Vector3 is expressed in the World space.
+ * @param localAxis axis to rotate
+ * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
+ */
+ getDirection(localAxis) {
+ const result = Vector3.Zero();
+ this.getDirectionToRef(localAxis, result);
+ return result;
+ }
+ /**
+ * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
+ * localAxis is expressed in the mesh local space.
+ * result is computed in the World space from the mesh World matrix.
+ * @param localAxis axis to rotate
+ * @param result the resulting transformnode
+ * @returns this TransformNode.
+ */
+ getDirectionToRef(localAxis, result) {
+ Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
+ return this;
+ }
+ /**
+ * Sets this transform node rotation to the given local axis.
+ * @param localAxis the axis in local space
+ * @param yawCor optional yaw (y-axis) correction in radians
+ * @param pitchCor optional pitch (x-axis) correction in radians
+ * @param rollCor optional roll (z-axis) correction in radians
+ * @returns this TransformNode
+ */
+ setDirection(localAxis, yawCor = 0, pitchCor = 0, rollCor = 0) {
+ const yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2;
+ const len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z);
+ const pitch = -Math.atan2(localAxis.y, len);
+ if (this.rotationQuaternion) {
+ Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
+ }
+ else {
+ this.rotation.x = pitch + pitchCor;
+ this.rotation.y = yaw + yawCor;
+ this.rotation.z = rollCor;
+ }
+ return this;
+ }
+ /**
+ * Sets a new pivot point to the current node
+ * @param point defines the new pivot point to use
+ * @param space defines if the point is in world or local space (local by default)
+ * @returns the current TransformNode
+ */
+ setPivotPoint(point, space = 0 /* Space.LOCAL */) {
+ if (this.getScene().getRenderId() == 0) {
+ this.computeWorldMatrix(true);
+ }
+ const wm = this.getWorldMatrix();
+ if (space == 1 /* Space.WORLD */) {
+ const tmat = TmpVectors.Matrix[0];
+ wm.invertToRef(tmat);
+ point = Vector3.TransformCoordinates(point, tmat);
+ }
+ return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true);
+ }
+ /**
+ * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
+ * @returns the pivot point
+ */
+ getPivotPoint() {
+ const point = Vector3.Zero();
+ this.getPivotPointToRef(point);
+ return point;
+ }
+ /**
+ * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
+ * @param result the vector3 to store the result
+ * @returns this TransformNode.
+ */
+ getPivotPointToRef(result) {
+ result.x = -this._pivotMatrix.m[12];
+ result.y = -this._pivotMatrix.m[13];
+ result.z = -this._pivotMatrix.m[14];
+ return this;
+ }
+ /**
+ * Returns a new Vector3 set with the mesh pivot point World coordinates.
+ * @returns a new Vector3 set with the mesh pivot point World coordinates.
+ */
+ getAbsolutePivotPoint() {
+ const point = Vector3.Zero();
+ this.getAbsolutePivotPointToRef(point);
+ return point;
+ }
+ /**
+ * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
+ * @param result vector3 to store the result
+ * @returns this TransformNode.
+ */
+ getAbsolutePivotPointToRef(result) {
+ this.getPivotPointToRef(result);
+ Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
+ return this;
+ }
+ /**
+ * Flag the transform node as dirty (Forcing it to update everything)
+ * @param property if set to "rotation" the objects rotationQuaternion will be set to null
+ * @returns this node
+ */
+ markAsDirty(property) {
+ if (this._isDirty) {
+ return this;
+ }
+ // We need to explicitly update the children
+ // as the scene.evaluateActiveMeshes will not poll the transform nodes
+ if (this._children) {
+ for (const child of this._children) {
+ child.markAsDirty(property);
+ }
+ }
+ return super.markAsDirty(property);
+ }
+ /**
+ * Defines the passed node as the parent of the current node.
+ * The node will remain exactly where it is and its position / rotation will be updated accordingly.
+ * If you don't want to preserve the current rotation / position, assign the parent through parent accessor.
+ * Note that if the mesh has a pivot matrix / point defined it will be applied after the parent was updated.
+ * In that case the node will not remain in the same space as it is, as the pivot will be applied.
+ * To avoid this, you can set updatePivot to true and the pivot will be updated to identity
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent
+ * @param node the node ot set as the parent
+ * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.
+ * @param updatePivot if true, update the pivot matrix to keep the node in the same space as before
+ * @returns this TransformNode.
+ */
+ setParent(node, preserveScalingSign = false, updatePivot = false) {
+ if (!node && !this.parent) {
+ return this;
+ }
+ const quatRotation = TmpVectors.Quaternion[0];
+ const position = TmpVectors.Vector3[0];
+ const scale = TmpVectors.Vector3[1];
+ const invParentMatrix = TmpVectors.Matrix[1];
+ Matrix.IdentityToRef(invParentMatrix);
+ const composedMatrix = TmpVectors.Matrix[0];
+ this.computeWorldMatrix(true);
+ let currentRotation = this.rotationQuaternion;
+ if (!currentRotation) {
+ currentRotation = TransformNode._TmpRotation;
+ Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, currentRotation);
+ }
+ // current global transformation without pivot
+ Matrix.ComposeToRef(this.scaling, currentRotation, this.position, composedMatrix);
+ if (this.parent) {
+ composedMatrix.multiplyToRef(this.parent.computeWorldMatrix(true), composedMatrix);
+ }
+ // is a node was set, calculate the difference between this and the node
+ if (node) {
+ node.computeWorldMatrix(true).invertToRef(invParentMatrix);
+ composedMatrix.multiplyToRef(invParentMatrix, composedMatrix);
+ }
+ composedMatrix.decompose(scale, quatRotation, position, preserveScalingSign ? this : undefined);
+ if (this.rotationQuaternion) {
+ this.rotationQuaternion.copyFrom(quatRotation);
+ }
+ else {
+ quatRotation.toEulerAnglesToRef(this.rotation);
+ }
+ this.scaling.copyFrom(scale);
+ this.position.copyFrom(position);
+ this.parent = node;
+ if (updatePivot) {
+ this.setPivotMatrix(Matrix.Identity());
+ }
+ return this;
+ }
+ /**
+ * Adds the passed mesh as a child to the current mesh.
+ * The node will remain exactly where it is and its position / rotation will be updated accordingly.
+ * This method is equivalent to calling setParent().
+ * @param mesh defines the child mesh
+ * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.
+ * @returns the current mesh
+ */
+ addChild(mesh, preserveScalingSign = false) {
+ mesh.setParent(this, preserveScalingSign);
+ return this;
+ }
+ /**
+ * Removes the passed mesh from the current mesh children list
+ * @param mesh defines the child mesh
+ * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.
+ * @returns the current mesh
+ */
+ removeChild(mesh, preserveScalingSign = false) {
+ if (mesh.parent !== this)
+ return this;
+ mesh.setParent(null, preserveScalingSign);
+ return this;
+ }
+ /**
+ * True if the scaling property of this object is non uniform eg. (1,2,1)
+ */
+ get nonUniformScaling() {
+ return this._nonUniformScaling;
+ }
+ /**
+ * @internal
+ */
+ _updateNonUniformScalingState(value) {
+ if (this._nonUniformScaling === value) {
+ return false;
+ }
+ this._nonUniformScaling = value;
+ return true;
+ }
+ /**
+ * Attach the current TransformNode to another TransformNode associated with a bone
+ * @param bone Bone affecting the TransformNode
+ * @param affectedTransformNode TransformNode associated with the bone
+ * @returns this object
+ */
+ attachToBone(bone, affectedTransformNode) {
+ this._currentParentWhenAttachingToBone = this.parent;
+ this._transformToBoneReferal = affectedTransformNode;
+ this.parent = bone;
+ bone.getSkeleton().prepare(true); // make sure bone.getFinalMatrix() is up to date
+ if (bone.getFinalMatrix().determinant() < 0) {
+ this.scalingDeterminant *= -1;
+ }
+ return this;
+ }
+ /**
+ * Detach the transform node if its associated with a bone
+ * @param resetToPreviousParent Indicates if the parent that was in effect when attachToBone was called should be set back or if we should set parent to null instead (defaults to the latter)
+ * @returns this object
+ */
+ detachFromBone(resetToPreviousParent = false) {
+ if (!this.parent) {
+ if (resetToPreviousParent) {
+ this.parent = this._currentParentWhenAttachingToBone;
+ }
+ return this;
+ }
+ if (this.parent.getWorldMatrix().determinant() < 0) {
+ this.scalingDeterminant *= -1;
+ }
+ this._transformToBoneReferal = null;
+ if (resetToPreviousParent) {
+ this.parent = this._currentParentWhenAttachingToBone;
+ }
+ else {
+ this.parent = null;
+ }
+ return this;
+ }
+ /**
+ * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
+ * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD.
+ * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
+ * The passed axis is also normalized.
+ * @param axis the axis to rotate around
+ * @param amount the amount to rotate in radians
+ * @param space Space to rotate in (Default: local)
+ * @returns the TransformNode.
+ */
+ rotate(axis, amount, space) {
+ axis.normalize();
+ if (!this.rotationQuaternion) {
+ this.rotationQuaternion = this.rotation.toQuaternion();
+ this.rotation.setAll(0);
+ }
+ let rotationQuaternion;
+ if (!space || space === 0 /* Space.LOCAL */) {
+ rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache);
+ this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
+ }
+ else {
+ if (this.parent) {
+ const parentWorldMatrix = this.parent.getWorldMatrix();
+ const invertParentWorldMatrix = TmpVectors.Matrix[0];
+ parentWorldMatrix.invertToRef(invertParentWorldMatrix);
+ axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
+ if (parentWorldMatrix.determinant() < 0) {
+ amount *= -1;
+ }
+ }
+ rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache);
+ rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
+ }
+ return this;
+ }
+ /**
+ * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
+ * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
+ * The passed axis is also normalized. .
+ * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
+ * @param point the point to rotate around
+ * @param axis the axis to rotate around
+ * @param amount the amount to rotate in radians
+ * @returns the TransformNode
+ */
+ rotateAround(point, axis, amount) {
+ axis.normalize();
+ if (!this.rotationQuaternion) {
+ this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
+ this.rotation.setAll(0);
+ }
+ const tmpVector = TmpVectors.Vector3[0];
+ const finalScale = TmpVectors.Vector3[1];
+ const finalTranslation = TmpVectors.Vector3[2];
+ const finalRotation = TmpVectors.Quaternion[0];
+ const translationMatrix = TmpVectors.Matrix[0]; // T
+ const translationMatrixInv = TmpVectors.Matrix[1]; // T'
+ const rotationMatrix = TmpVectors.Matrix[2]; // R
+ const finalMatrix = TmpVectors.Matrix[3]; // T' x R x T
+ point.subtractToRef(this.position, tmpVector);
+ Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
+ Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
+ Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
+ translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
+ finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
+ finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
+ this.position.addInPlace(finalTranslation);
+ finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
+ return this;
+ }
+ /**
+ * Translates the mesh along the axis vector for the passed distance in the given space.
+ * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD.
+ * @param axis the axis to translate in
+ * @param distance the distance to translate
+ * @param space Space to rotate in (Default: local)
+ * @returns the TransformNode.
+ */
+ translate(axis, distance, space) {
+ const displacementVector = axis.scale(distance);
+ if (!space || space === 0 /* Space.LOCAL */) {
+ const tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
+ this.setPositionWithLocalVector(tempV3);
+ }
+ else {
+ this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
+ }
+ return this;
+ }
+ /**
+ * Adds a rotation step to the mesh current rotation.
+ * x, y, z are Euler angles expressed in radians.
+ * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
+ * This means this rotation is made in the mesh local space only.
+ * It's useful to set a custom rotation order different from the BJS standard one YXZ.
+ * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
+ * ```javascript
+ * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
+ * ```
+ * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
+ * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
+ * @param x Rotation to add
+ * @param y Rotation to add
+ * @param z Rotation to add
+ * @returns the TransformNode.
+ */
+ addRotation(x, y, z) {
+ let rotationQuaternion;
+ if (this.rotationQuaternion) {
+ rotationQuaternion = this.rotationQuaternion;
+ }
+ else {
+ rotationQuaternion = TmpVectors.Quaternion[1];
+ Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
+ }
+ const accumulation = TmpVectors.Quaternion[0];
+ Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
+ rotationQuaternion.multiplyInPlace(accumulation);
+ if (!this.rotationQuaternion) {
+ rotationQuaternion.toEulerAnglesToRef(this.rotation);
+ }
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _getEffectiveParent() {
+ return this.parent;
+ }
+ /**
+ * Returns whether the transform node world matrix computation needs the camera information to be computed.
+ * This is the case when the node is a billboard or has an infinite distance for instance.
+ * @returns true if the world matrix computation needs the camera information to be computed
+ */
+ isWorldMatrixCameraDependent() {
+ return (this._infiniteDistance && !this.parent) || (this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard);
+ }
+ /**
+ * Computes the world matrix of the node
+ * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
+ * @param camera defines the camera used if different from the scene active camera (This is used with modes like Billboard or infinite distance)
+ * @returns the world matrix
+ */
+ computeWorldMatrix(force = false, camera = null) {
+ if (this._isWorldMatrixFrozen && !this._isDirty) {
+ return this._worldMatrix;
+ }
+ const currentRenderId = this.getScene().getRenderId();
+ if (!this._isDirty && !force && (this._currentRenderId === currentRenderId || this.isSynchronized())) {
+ this._currentRenderId = currentRenderId;
+ return this._worldMatrix;
+ }
+ camera = camera || this.getScene().activeCamera;
+ this._updateCache();
+ const cache = this._cache;
+ cache.pivotMatrixUpdated = false;
+ cache.billboardMode = this.billboardMode;
+ cache.infiniteDistance = this.infiniteDistance;
+ cache.parent = this._parentNode;
+ this._currentRenderId = currentRenderId;
+ this._childUpdateId += 1;
+ this._isDirty = false;
+ this._position._isDirty = false;
+ this._rotation._isDirty = false;
+ this._scaling._isDirty = false;
+ const parent = this._getEffectiveParent();
+ // Scaling
+ const scaling = TransformNode._TmpScaling;
+ let translation = this._position;
+ // Translation
+ if (this._infiniteDistance) {
+ if (!this.parent && camera) {
+ const cameraWorldMatrix = camera.getWorldMatrix();
+ const cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
+ translation = TransformNode._TmpTranslation;
+ translation.copyFromFloats(this._position.x + cameraGlobalPosition.x, this._position.y + cameraGlobalPosition.y, this._position.z + cameraGlobalPosition.z);
+ }
+ }
+ // Scaling
+ scaling.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant);
+ // Rotation
+ let rotation;
+ if (this._rotationQuaternion) {
+ this._rotationQuaternion._isDirty = false;
+ rotation = this._rotationQuaternion;
+ if (this.reIntegrateRotationIntoRotationQuaternion) {
+ const len = this.rotation.lengthSquared();
+ if (len) {
+ this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z));
+ this._rotation.copyFromFloats(0, 0, 0);
+ }
+ }
+ }
+ else {
+ rotation = TransformNode._TmpRotation;
+ Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, rotation);
+ }
+ // Compose
+ if (this._usePivotMatrix) {
+ const scaleMatrix = TmpVectors.Matrix[1];
+ Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, scaleMatrix);
+ // Rotation
+ const rotationMatrix = TmpVectors.Matrix[0];
+ rotation.toRotationMatrix(rotationMatrix);
+ // Composing transformations
+ this._pivotMatrix.multiplyToRef(scaleMatrix, TmpVectors.Matrix[4]);
+ TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, this._localMatrix);
+ // Post multiply inverse of pivotMatrix
+ if (this._postMultiplyPivotMatrix) {
+ this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix);
+ }
+ this._localMatrix.addTranslationFromFloats(translation.x, translation.y, translation.z);
+ }
+ else {
+ Matrix.ComposeToRef(scaling, rotation, translation, this._localMatrix);
+ }
+ // Parent
+ if (parent && parent.getWorldMatrix) {
+ if (force) {
+ parent.computeWorldMatrix(force);
+ }
+ if (cache.useBillboardPath) {
+ if (this._transformToBoneReferal) {
+ const bone = this.parent;
+ bone.getSkeleton().prepare();
+ bone.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]);
+ }
+ else {
+ TmpVectors.Matrix[7].copyFrom(parent.getWorldMatrix());
+ }
+ // Extract scaling and translation from parent
+ const translation = TmpVectors.Vector3[5];
+ const scale = TmpVectors.Vector3[6];
+ const orientation = TmpVectors.Quaternion[0];
+ TmpVectors.Matrix[7].decompose(scale, orientation, translation);
+ Matrix.ScalingToRef(scale.x, scale.y, scale.z, TmpVectors.Matrix[7]);
+ TmpVectors.Matrix[7].setTranslation(translation);
+ if (TransformNode.BillboardUseParentOrientation) {
+ // set localMatrix translation to be transformed against parent's orientation.
+ this._position.applyRotationQuaternionToRef(orientation, translation);
+ this._localMatrix.setTranslation(translation);
+ }
+ this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix);
+ }
+ else {
+ if (this._transformToBoneReferal) {
+ const bone = this.parent;
+ bone.getSkeleton().prepare();
+ this._localMatrix.multiplyToRef(bone.getFinalMatrix(), TmpVectors.Matrix[6]);
+ TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
+ }
+ else {
+ this._localMatrix.multiplyToRef(parent.getWorldMatrix(), this._worldMatrix);
+ }
+ }
+ this._markSyncedWithParent();
+ }
+ else {
+ this._worldMatrix.copyFrom(this._localMatrix);
+ }
+ // Billboarding based on camera orientation (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
+ if (cache.useBillboardPath && camera && this.billboardMode && !cache.useBillboardPosition) {
+ const storedTranslation = TmpVectors.Vector3[0];
+ this._worldMatrix.getTranslationToRef(storedTranslation); // Save translation
+ // Cancel camera rotation
+ TmpVectors.Matrix[1].copyFrom(camera.getViewMatrix());
+ if (this._scene.useRightHandedSystem) {
+ TmpVectors.Matrix[1].multiplyToRef(convertRHSToLHS, TmpVectors.Matrix[1]);
+ }
+ TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0);
+ TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]);
+ if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
+ TmpVectors.Matrix[0].decompose(undefined, TmpVectors.Quaternion[0], undefined);
+ const eulerAngles = TmpVectors.Vector3[1];
+ TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);
+ if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {
+ eulerAngles.x = 0;
+ }
+ if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {
+ eulerAngles.y = 0;
+ }
+ if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {
+ eulerAngles.z = 0;
+ }
+ Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);
+ }
+ this._worldMatrix.setTranslationFromFloats(0, 0, 0);
+ this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);
+ // Restore translation
+ this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);
+ }
+ // Billboarding based on camera position
+ else if (cache.useBillboardPath && camera && cache.useBillboardPosition) {
+ const storedTranslation = TmpVectors.Vector3[0];
+ // Save translation
+ this._worldMatrix.getTranslationToRef(storedTranslation);
+ // Compute camera position in local space
+ const cameraPosition = camera.globalPosition;
+ this._worldMatrix.invertToRef(TmpVectors.Matrix[1]);
+ const camInObjSpace = TmpVectors.Vector3[1];
+ Vector3.TransformCoordinatesToRef(cameraPosition, TmpVectors.Matrix[1], camInObjSpace);
+ camInObjSpace.normalize();
+ // Find the lookAt info in local space
+ const yaw = -Math.atan2(camInObjSpace.z, camInObjSpace.x) + Math.PI / 2;
+ const len = Math.sqrt(camInObjSpace.x * camInObjSpace.x + camInObjSpace.z * camInObjSpace.z);
+ const pitch = -Math.atan2(camInObjSpace.y, len);
+ Quaternion.RotationYawPitchRollToRef(yaw, pitch, 0, TmpVectors.Quaternion[0]);
+ if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
+ const eulerAngles = TmpVectors.Vector3[1];
+ TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);
+ if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {
+ eulerAngles.x = 0;
+ }
+ if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {
+ eulerAngles.y = 0;
+ }
+ if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {
+ eulerAngles.z = 0;
+ }
+ Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);
+ }
+ else {
+ Matrix.FromQuaternionToRef(TmpVectors.Quaternion[0], TmpVectors.Matrix[0]);
+ }
+ // Cancel translation
+ this._worldMatrix.setTranslationFromFloats(0, 0, 0);
+ // Rotate according to lookat (diff from local to lookat)
+ this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);
+ // Restore translation
+ this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);
+ }
+ // Normal matrix
+ if (!this.ignoreNonUniformScaling) {
+ if (this._scaling.isNonUniformWithinEpsilon(0.000001)) {
+ this._updateNonUniformScalingState(true);
+ }
+ else if (parent && parent._nonUniformScaling) {
+ this._updateNonUniformScalingState(parent._nonUniformScaling);
+ }
+ else {
+ this._updateNonUniformScalingState(false);
+ }
+ }
+ else {
+ this._updateNonUniformScalingState(false);
+ }
+ this._afterComputeWorldMatrix();
+ // Absolute position
+ this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
+ this._isAbsoluteSynced = false;
+ // Callbacks
+ this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
+ if (!this._poseMatrix) {
+ this._poseMatrix = Matrix.Invert(this._worldMatrix);
+ }
+ // Cache the determinant
+ this._worldMatrixDeterminantIsDirty = true;
+ return this._worldMatrix;
+ }
+ /**
+ * Resets this nodeTransform's local matrix to Matrix.Identity().
+ * @param independentOfChildren indicates if all child nodeTransform's world-space transform should be preserved.
+ */
+ resetLocalMatrix(independentOfChildren = true) {
+ this.computeWorldMatrix();
+ if (independentOfChildren) {
+ const children = this.getChildren();
+ for (let i = 0; i < children.length; ++i) {
+ const child = children[i];
+ if (child) {
+ child.computeWorldMatrix();
+ const bakedMatrix = TmpVectors.Matrix[0];
+ child._localMatrix.multiplyToRef(this._localMatrix, bakedMatrix);
+ const tmpRotationQuaternion = TmpVectors.Quaternion[0];
+ bakedMatrix.decompose(child.scaling, tmpRotationQuaternion, child.position);
+ if (child.rotationQuaternion) {
+ child.rotationQuaternion.copyFrom(tmpRotationQuaternion);
+ }
+ else {
+ tmpRotationQuaternion.toEulerAnglesToRef(child.rotation);
+ }
+ }
+ }
+ }
+ this.scaling.copyFromFloats(1, 1, 1);
+ this.position.copyFromFloats(0, 0, 0);
+ this.rotation.copyFromFloats(0, 0, 0);
+ //only if quaternion is already set
+ if (this.rotationQuaternion) {
+ this.rotationQuaternion = Quaternion.Identity();
+ }
+ this._worldMatrix = Matrix.Identity();
+ }
+ _afterComputeWorldMatrix() { }
+ /**
+ * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
+ * @param func callback function to add
+ *
+ * @returns the TransformNode.
+ */
+ registerAfterWorldMatrixUpdate(func) {
+ this.onAfterWorldMatrixUpdateObservable.add(func);
+ return this;
+ }
+ /**
+ * Removes a registered callback function.
+ * @param func callback function to remove
+ * @returns the TransformNode.
+ */
+ unregisterAfterWorldMatrixUpdate(func) {
+ this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
+ return this;
+ }
+ /**
+ * Gets the position of the current mesh in camera space
+ * @param camera defines the camera to use
+ * @returns a position
+ */
+ getPositionInCameraSpace(camera = null) {
+ if (!camera) {
+ camera = this.getScene().activeCamera;
+ }
+ return Vector3.TransformCoordinates(this.getAbsolutePosition(), camera.getViewMatrix());
+ }
+ /**
+ * Returns the distance from the mesh to the active camera
+ * @param camera defines the camera to use
+ * @returns the distance
+ */
+ getDistanceToCamera(camera = null) {
+ if (!camera) {
+ camera = this.getScene().activeCamera;
+ }
+ return this.getAbsolutePosition().subtract(camera.globalPosition).length();
+ }
+ /**
+ * Clone the current transform node
+ * @param name Name of the new clone
+ * @param newParent New parent for the clone
+ * @param doNotCloneChildren Do not clone children hierarchy
+ * @returns the new transform node
+ */
+ clone(name, newParent, doNotCloneChildren) {
+ const result = SerializationHelper.Clone(() => new TransformNode(name, this.getScene()), this);
+ result.name = name;
+ result.id = name;
+ if (newParent) {
+ result.parent = newParent;
+ }
+ if (!doNotCloneChildren) {
+ // Children
+ const directDescendants = this.getDescendants(true);
+ for (let index = 0; index < directDescendants.length; index++) {
+ const child = directDescendants[index];
+ if (child.clone) {
+ child.clone(name + "." + child.name, result);
+ }
+ }
+ }
+ return result;
+ }
+ /**
+ * Serializes the objects information.
+ * @param currentSerializationObject defines the object to serialize in
+ * @returns the serialized object
+ */
+ serialize(currentSerializationObject) {
+ const serializationObject = SerializationHelper.Serialize(this, currentSerializationObject);
+ serializationObject.type = this.getClassName();
+ serializationObject.uniqueId = this.uniqueId;
+ // Parent
+ if (this.parent) {
+ this.parent._serializeAsParent(serializationObject);
+ }
+ serializationObject.localMatrix = this.getPivotMatrix().asArray();
+ serializationObject.isEnabled = this.isEnabled();
+ // Animations
+ SerializationHelper.AppendSerializedAnimations(this, serializationObject);
+ serializationObject.ranges = this.serializeAnimationRanges();
+ return serializationObject;
+ }
+ // Statics
+ /**
+ * Returns a new TransformNode object parsed from the source provided.
+ * @param parsedTransformNode is the source.
+ * @param scene the scene the object belongs to
+ * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
+ * @returns a new TransformNode object parsed from the source provided.
+ */
+ static Parse(parsedTransformNode, scene, rootUrl) {
+ const transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl);
+ if (parsedTransformNode.localMatrix) {
+ transformNode.setPreTransformMatrix(Matrix.FromArray(parsedTransformNode.localMatrix));
+ }
+ else if (parsedTransformNode.pivotMatrix) {
+ transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix));
+ }
+ transformNode.setEnabled(parsedTransformNode.isEnabled);
+ transformNode._waitingParsedUniqueId = parsedTransformNode.uniqueId;
+ // Parent
+ if (parsedTransformNode.parentId !== undefined) {
+ transformNode._waitingParentId = parsedTransformNode.parentId;
+ }
+ if (parsedTransformNode.parentInstanceIndex !== undefined) {
+ transformNode._waitingParentInstanceIndex = parsedTransformNode.parentInstanceIndex;
+ }
+ // Animations
+ if (parsedTransformNode.animations) {
+ for (let animationIndex = 0; animationIndex < parsedTransformNode.animations.length; animationIndex++) {
+ const parsedAnimation = parsedTransformNode.animations[animationIndex];
+ const internalClass = GetClass("BABYLON.Animation");
+ if (internalClass) {
+ transformNode.animations.push(internalClass.Parse(parsedAnimation));
+ }
+ }
+ Node$2.ParseAnimationRanges(transformNode, parsedTransformNode, scene);
+ }
+ if (parsedTransformNode.autoAnimate) {
+ scene.beginAnimation(transformNode, parsedTransformNode.autoAnimateFrom, parsedTransformNode.autoAnimateTo, parsedTransformNode.autoAnimateLoop, parsedTransformNode.autoAnimateSpeed || 1.0);
+ }
+ return transformNode;
+ }
+ /**
+ * Get all child-transformNodes of this node
+ * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
+ * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
+ * @returns an array of TransformNode
+ */
+ getChildTransformNodes(directDescendantsOnly, predicate) {
+ const results = [];
+ this._getDescendants(results, directDescendantsOnly, (node) => {
+ return (!predicate || predicate(node)) && node instanceof TransformNode;
+ });
+ return results;
+ }
+ /**
+ * Releases resources associated with this transform node.
+ * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
+ * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
+ */
+ dispose(doNotRecurse, disposeMaterialAndTextures = false) {
+ // Animations
+ this.getScene().stopAnimation(this);
+ // Remove from scene
+ this.getScene().removeTransformNode(this);
+ if (this._parentContainer) {
+ const index = this._parentContainer.transformNodes.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.transformNodes.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ this.onAfterWorldMatrixUpdateObservable.clear();
+ if (doNotRecurse) {
+ const transformNodes = this.getChildTransformNodes(true);
+ for (const transformNode of transformNodes) {
+ transformNode.parent = null;
+ transformNode.computeWorldMatrix(true);
+ }
+ }
+ super.dispose(doNotRecurse, disposeMaterialAndTextures);
+ }
+ /**
+ * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
+ * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false
+ * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false
+ * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling
+ * @returns the current mesh
+ */
+ normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) {
+ let storedRotation = null;
+ let storedRotationQuaternion = null;
+ if (ignoreRotation) {
+ if (this.rotationQuaternion) {
+ storedRotationQuaternion = this.rotationQuaternion.clone();
+ this.rotationQuaternion.copyFromFloats(0, 0, 0, 1);
+ }
+ else if (this.rotation) {
+ storedRotation = this.rotation.clone();
+ this.rotation.copyFromFloats(0, 0, 0);
+ }
+ }
+ const boundingVectors = this.getHierarchyBoundingVectors(includeDescendants, predicate);
+ const sizeVec = boundingVectors.max.subtract(boundingVectors.min);
+ const maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
+ if (maxDimension === 0) {
+ return this;
+ }
+ const scale = 1 / maxDimension;
+ this.scaling.scaleInPlace(scale);
+ if (ignoreRotation) {
+ if (this.rotationQuaternion && storedRotationQuaternion) {
+ this.rotationQuaternion.copyFrom(storedRotationQuaternion);
+ }
+ else if (this.rotation && storedRotation) {
+ this.rotation.copyFrom(storedRotation);
+ }
+ }
+ return this;
+ }
+ _syncAbsoluteScalingAndRotation() {
+ if (!this._isAbsoluteSynced) {
+ this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion);
+ this._isAbsoluteSynced = true;
+ }
+ }
+}
+// Statics
+/**
+ * Object will not rotate to face the camera
+ */
+TransformNode.BILLBOARDMODE_NONE = 0;
+/**
+ * Object will rotate to face the camera but only on the x axis
+ */
+TransformNode.BILLBOARDMODE_X = 1;
+/**
+ * Object will rotate to face the camera but only on the y axis
+ */
+TransformNode.BILLBOARDMODE_Y = 2;
+/**
+ * Object will rotate to face the camera but only on the z axis
+ */
+TransformNode.BILLBOARDMODE_Z = 4;
+/**
+ * Object will rotate to face the camera
+ */
+TransformNode.BILLBOARDMODE_ALL = 7;
+/**
+ * Object will rotate to face the camera's position instead of orientation
+ */
+TransformNode.BILLBOARDMODE_USE_POSITION = 128;
+/**
+ * Child transform with Billboard flags should or should not apply parent rotation (default if off)
+ */
+TransformNode.BillboardUseParentOrientation = false;
+TransformNode._TmpRotation = Quaternion.Zero();
+TransformNode._TmpScaling = Vector3.Zero();
+TransformNode._TmpTranslation = Vector3.Zero();
+TransformNode._LookAtVectorCache = new Vector3(0, 0, 0);
+TransformNode._RotationAxisCache = new Quaternion();
+__decorate([
+ serializeAsVector3("position")
+], TransformNode.prototype, "_position", void 0);
+__decorate([
+ serializeAsVector3("rotation")
+], TransformNode.prototype, "_rotation", void 0);
+__decorate([
+ serializeAsQuaternion("rotationQuaternion")
+], TransformNode.prototype, "_rotationQuaternion", void 0);
+__decorate([
+ serializeAsVector3("scaling")
+], TransformNode.prototype, "_scaling", void 0);
+__decorate([
+ serialize("billboardMode")
+], TransformNode.prototype, "_billboardMode", void 0);
+__decorate([
+ serialize()
+], TransformNode.prototype, "scalingDeterminant", void 0);
+__decorate([
+ serialize("infiniteDistance")
+], TransformNode.prototype, "_infiniteDistance", void 0);
+__decorate([
+ serialize()
+], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
+__decorate([
+ serialize()
+], TransformNode.prototype, "reIntegrateRotationIntoRotationQuaternion", void 0);
+
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+class _MeshCollisionData {
+ constructor() {
+ this._checkCollisions = false;
+ this._collisionMask = -1;
+ this._collisionGroup = -1;
+ this._surroundingMeshes = null;
+ this._collider = null;
+ this._oldPositionForCollisions = new Vector3(0, 0, 0);
+ this._diffPositionForCollisions = new Vector3(0, 0, 0);
+ this._collisionResponse = true;
+ }
+}
+
+function applyMorph(data, kind, morphTargetManager) {
+ let getTargetData = null;
+ switch (kind) {
+ case VertexBuffer.PositionKind:
+ getTargetData = (target) => target.getPositions();
+ break;
+ case VertexBuffer.NormalKind:
+ getTargetData = (target) => target.getNormals();
+ break;
+ case VertexBuffer.TangentKind:
+ getTargetData = (target) => target.getTangents();
+ break;
+ case VertexBuffer.UVKind:
+ getTargetData = (target) => target.getUVs();
+ break;
+ case VertexBuffer.UV2Kind:
+ getTargetData = (target) => target.getUV2s();
+ break;
+ case VertexBuffer.ColorKind:
+ getTargetData = (target) => target.getColors();
+ break;
+ default:
+ return;
+ }
+ for (let index = 0; index < data.length; index++) {
+ let value = data[index];
+ for (let targetCount = 0; targetCount < morphTargetManager.numTargets; targetCount++) {
+ const target = morphTargetManager.getTarget(targetCount);
+ const influence = target.influence;
+ if (influence !== 0) {
+ const targetData = getTargetData(target);
+ if (targetData) {
+ value += (targetData[index] - data[index]) * influence;
+ }
+ }
+ }
+ data[index] = value;
+ }
+}
+function applySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData) {
+ const tempVector = TmpVectors.Vector3[0];
+ const finalMatrix = TmpVectors.Matrix[0];
+ const tempMatrix = TmpVectors.Matrix[1];
+ const transformFromFloatsToRef = kind === VertexBuffer.NormalKind ? Vector3.TransformNormalFromFloatsToRef : Vector3.TransformCoordinatesFromFloatsToRef;
+ for (let index = 0, matWeightIdx = 0; index < data.length; index += 3, matWeightIdx += 4) {
+ finalMatrix.reset();
+ let inf;
+ let weight;
+ for (inf = 0; inf < 4; inf++) {
+ weight = matricesWeightsData[matWeightIdx + inf];
+ if (weight > 0) {
+ Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
+ finalMatrix.addToSelf(tempMatrix);
+ }
+ }
+ if (matricesIndicesExtraData && matricesWeightsExtraData) {
+ for (inf = 0; inf < 4; inf++) {
+ weight = matricesWeightsExtraData[matWeightIdx + inf];
+ if (weight > 0) {
+ Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
+ finalMatrix.addToSelf(tempMatrix);
+ }
+ }
+ }
+ transformFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
+ tempVector.toArray(data, index);
+ }
+}
+/** @internal */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+class _FacetDataStorage {
+ constructor() {
+ this.facetNb = 0; // facet number
+ this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partitioning space
+ this.partitioningBBoxRatio = 1.01; // the partitioning array space is by default 1% bigger than the bounding box
+ this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
+ this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
+ this.bbSize = Vector3.Zero(); // bbox size approximated for facet data
+ this.subDiv = {
+ // actual number of subdivisions per axis for ComputeNormals()
+ max: 1,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ X: 1,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ Y: 1,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ Z: 1,
+ };
+ this.facetDepthSort = false; // is the facet depth sort to be computed
+ this.facetDepthSortEnabled = false; // is the facet depth sort initialized
+ }
+}
+/**
+ * @internal
+ **/
+// eslint-disable-next-line @typescript-eslint/naming-convention
+class _InternalAbstractMeshDataInfo {
+ constructor() {
+ this._hasVertexAlpha = false;
+ this._useVertexColors = true;
+ this._numBoneInfluencers = 4;
+ this._applyFog = true;
+ this._receiveShadows = false;
+ this._facetData = new _FacetDataStorage();
+ this._visibility = 1.0;
+ this._skeleton = null;
+ this._layerMask = 0x0fffffff;
+ this._computeBonesUsingShaders = true;
+ this._isActive = false;
+ this._onlyForInstances = false;
+ this._isActiveIntermediate = false;
+ this._onlyForInstancesIntermediate = false;
+ this._actAsRegularMesh = false;
+ this._currentLOD = new Map();
+ this._collisionRetryCount = 3;
+ this._morphTargetManager = null;
+ this._renderingGroupId = 0;
+ this._bakedVertexAnimationManager = null;
+ this._material = null;
+ this._positions = null;
+ this._pointerOverDisableMeshTesting = false;
+ // Collisions
+ this._meshCollisionData = new _MeshCollisionData();
+ this._enableDistantPicking = false;
+ /** @internal
+ * Bounding info that is unnafected by the addition of thin instances
+ */
+ this._rawBoundingInfo = null;
+ /** @internal
+ * This value will indicate us that at some point, the mesh was specifically used with the opposite winding order
+ * We use that as a clue to force the material to sideOrientation = null
+ */
+ this._sideOrientationHint = false;
+ /**
+ * @internal
+ * if this is set to true, the mesh will be visible only if its parent(s) are also visible
+ */
+ this._inheritVisibility = false;
+ }
+}
+/**
+ * Class used to store all common mesh properties
+ */
+class AbstractMesh extends TransformNode {
+ /**
+ * No billboard
+ */
+ static get BILLBOARDMODE_NONE() {
+ return TransformNode.BILLBOARDMODE_NONE;
+ }
+ /** Billboard on X axis */
+ static get BILLBOARDMODE_X() {
+ return TransformNode.BILLBOARDMODE_X;
+ }
+ /** Billboard on Y axis */
+ static get BILLBOARDMODE_Y() {
+ return TransformNode.BILLBOARDMODE_Y;
+ }
+ /** Billboard on Z axis */
+ static get BILLBOARDMODE_Z() {
+ return TransformNode.BILLBOARDMODE_Z;
+ }
+ /** Billboard on all axes */
+ static get BILLBOARDMODE_ALL() {
+ return TransformNode.BILLBOARDMODE_ALL;
+ }
+ /** Billboard on using position instead of orientation */
+ static get BILLBOARDMODE_USE_POSITION() {
+ return TransformNode.BILLBOARDMODE_USE_POSITION;
+ }
+ /**
+ * Gets the number of facets in the mesh
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet
+ */
+ get facetNb() {
+ return this._internalAbstractMeshDataInfo._facetData.facetNb;
+ }
+ /**
+ * Gets or set the number (integer) of subdivisions per axis in the partitioning space
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning
+ */
+ get partitioningSubdivisions() {
+ return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions;
+ }
+ set partitioningSubdivisions(nb) {
+ this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = nb;
+ }
+ /**
+ * The ratio (float) to apply to the bounding box size to set to the partitioning space.
+ * Ex : 1.01 (default) the partitioning space is 1% bigger than the bounding box
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning
+ */
+ get partitioningBBoxRatio() {
+ return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio;
+ }
+ set partitioningBBoxRatio(ratio) {
+ this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = ratio;
+ }
+ /**
+ * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
+ * Works only for updatable meshes.
+ * Doesn't work with multi-materials
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort
+ */
+ get mustDepthSortFacets() {
+ return this._internalAbstractMeshDataInfo._facetData.facetDepthSort;
+ }
+ set mustDepthSortFacets(sort) {
+ this._internalAbstractMeshDataInfo._facetData.facetDepthSort = sort;
+ }
+ /**
+ * The location (Vector3) where the facet depth sort must be computed from.
+ * By default, the active camera position.
+ * Used only when facet depth sort is enabled
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort
+ */
+ get facetDepthSortFrom() {
+ return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom;
+ }
+ set facetDepthSortFrom(location) {
+ this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = location;
+ }
+ /** number of collision detection tries. Change this value if not all collisions are detected and handled properly */
+ get collisionRetryCount() {
+ return this._internalAbstractMeshDataInfo._collisionRetryCount;
+ }
+ set collisionRetryCount(retryCount) {
+ this._internalAbstractMeshDataInfo._collisionRetryCount = retryCount;
+ }
+ /**
+ * gets a boolean indicating if facetData is enabled
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet
+ */
+ get isFacetDataEnabled() {
+ return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled;
+ }
+ /**
+ * Gets or sets the morph target manager
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets
+ */
+ get morphTargetManager() {
+ return this._internalAbstractMeshDataInfo._morphTargetManager;
+ }
+ set morphTargetManager(value) {
+ if (this._internalAbstractMeshDataInfo._morphTargetManager === value) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._morphTargetManager = value;
+ this._syncGeometryWithMorphTargetManager();
+ }
+ /**
+ * Gets or sets the baked vertex animation manager
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations
+ */
+ get bakedVertexAnimationManager() {
+ return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager;
+ }
+ set bakedVertexAnimationManager(value) {
+ if (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager === value) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = value;
+ this._markSubMeshesAsAttributesDirty();
+ }
+ /** @internal */
+ _syncGeometryWithMorphTargetManager() { }
+ /**
+ * @internal
+ */
+ _updateNonUniformScalingState(value) {
+ if (!super._updateNonUniformScalingState(value)) {
+ return false;
+ }
+ this._markSubMeshesAsMiscDirty();
+ return true;
+ }
+ /** @internal */
+ get rawBoundingInfo() {
+ return this._internalAbstractMeshDataInfo._rawBoundingInfo;
+ }
+ set rawBoundingInfo(boundingInfo) {
+ this._internalAbstractMeshDataInfo._rawBoundingInfo = boundingInfo;
+ }
+ /** Set a function to call when this mesh collides with another one */
+ set onCollide(callback) {
+ if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver) {
+ this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver);
+ }
+ this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(callback);
+ }
+ /** Set a function to call when the collision's position changes */
+ set onCollisionPositionChange(callback) {
+ if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver) {
+ this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver);
+ }
+ this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
+ }
+ /**
+ * Gets or sets mesh visibility between 0 and 1 (default is 1)
+ */
+ get visibility() {
+ return this._internalAbstractMeshDataInfo._visibility;
+ }
+ /**
+ * Gets or sets mesh visibility between 0 and 1 (default is 1)
+ */
+ set visibility(value) {
+ if (this._internalAbstractMeshDataInfo._visibility === value) {
+ return;
+ }
+ const oldValue = this._internalAbstractMeshDataInfo._visibility;
+ this._internalAbstractMeshDataInfo._visibility = value;
+ if ((oldValue === 1 && value !== 1) || (oldValue !== 1 && value === 1)) {
+ this._markSubMeshesAsDirty((defines) => {
+ defines.markAsMiscDirty();
+ defines.markAsPrePassDirty();
+ });
+ }
+ }
+ /**
+ * If set to true, a mesh will only be visible only if its parent(s) are also visible (default is false)
+ */
+ get inheritVisibility() {
+ return this._internalAbstractMeshDataInfo._inheritVisibility;
+ }
+ set inheritVisibility(value) {
+ this._internalAbstractMeshDataInfo._inheritVisibility = value;
+ }
+ /**
+ * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
+ */
+ get isVisible() {
+ if (!this._isVisible || !this.inheritVisibility || !this._parentNode) {
+ return this._isVisible;
+ }
+ if (this._isVisible) {
+ let parent = this._parentNode;
+ while (parent) {
+ const parentVisible = parent.isVisible;
+ if (typeof parentVisible !== "undefined") {
+ return parentVisible;
+ }
+ parent = parent.parent;
+ }
+ }
+ return this._isVisible;
+ }
+ set isVisible(value) {
+ this._isVisible = value;
+ }
+ /**
+ * Gets or sets the property which disables the test that is checking that the mesh under the pointer is the same than the previous time we tested for it (default: false).
+ * Set this property to true if you want thin instances picking to be reported accurately when moving over the mesh.
+ * Note that setting this property to true will incur some performance penalties when dealing with pointer events for this mesh so use it sparingly.
+ */
+ get pointerOverDisableMeshTesting() {
+ return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting;
+ }
+ set pointerOverDisableMeshTesting(disable) {
+ this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting = disable;
+ }
+ /**
+ * Specifies the rendering group id for this mesh (0 by default)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#rendering-groups
+ */
+ get renderingGroupId() {
+ return this._internalAbstractMeshDataInfo._renderingGroupId;
+ }
+ set renderingGroupId(value) {
+ this._internalAbstractMeshDataInfo._renderingGroupId = value;
+ }
+ /** Gets or sets current material */
+ get material() {
+ return this._internalAbstractMeshDataInfo._material;
+ }
+ set material(value) {
+ this._setMaterial(value);
+ }
+ /** @internal */
+ _setMaterial(value) {
+ if (this._internalAbstractMeshDataInfo._material === value) {
+ return;
+ }
+ // remove from material mesh map id needed
+ if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) {
+ this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined;
+ }
+ this._internalAbstractMeshDataInfo._material = value;
+ if (value && value.meshMap) {
+ value.meshMap[this.uniqueId] = this;
+ }
+ if (this.onMaterialChangedObservable.hasObservers()) {
+ this.onMaterialChangedObservable.notifyObservers(this);
+ }
+ if (!this.subMeshes) {
+ return;
+ }
+ this.resetDrawCache(undefined, value == null);
+ this._unBindEffect();
+ }
+ /**
+ * Gets the material used to render the mesh in a specific render pass
+ * @param renderPassId render pass id
+ * @returns material used for the render pass. If no specific material is used for this render pass, undefined is returned (meaning mesh.material is used for this pass)
+ */
+ getMaterialForRenderPass(renderPassId) {
+ return this._internalAbstractMeshDataInfo._materialForRenderPass?.[renderPassId];
+ }
+ /**
+ * Sets the material to be used to render the mesh in a specific render pass
+ * @param renderPassId render pass id
+ * @param material material to use for this render pass. If undefined is passed, no specific material will be used for this render pass but the regular material will be used instead (mesh.material)
+ */
+ setMaterialForRenderPass(renderPassId, material) {
+ this.resetDrawCache(renderPassId);
+ if (!this._internalAbstractMeshDataInfo._materialForRenderPass) {
+ this._internalAbstractMeshDataInfo._materialForRenderPass = [];
+ }
+ const currentMaterial = this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId];
+ if (currentMaterial?.meshMap?.[this.uniqueId]) {
+ currentMaterial.meshMap[this.uniqueId] = undefined;
+ }
+ this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId] = material;
+ if (material && material.meshMap) {
+ material.meshMap[this.uniqueId] = this;
+ }
+ }
+ /**
+ * Gets or sets a boolean indicating that this mesh can receive realtime shadows
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows
+ */
+ get receiveShadows() {
+ return this._internalAbstractMeshDataInfo._receiveShadows;
+ }
+ set receiveShadows(value) {
+ if (this._internalAbstractMeshDataInfo._receiveShadows === value) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._receiveShadows = value;
+ this._markSubMeshesAsLightDirty();
+ }
+ /**
+ * Gets or sets a boolean indicating that this mesh needs to use vertex alpha data to render.
+ * This property is misnamed and should be `useVertexAlpha`. Note that the mesh will be rendered
+ * with alpha blending when this flag is set even if vertex alpha data is missing from the geometry.
+ */
+ get hasVertexAlpha() {
+ return this._internalAbstractMeshDataInfo._hasVertexAlpha;
+ }
+ set hasVertexAlpha(value) {
+ if (this._internalAbstractMeshDataInfo._hasVertexAlpha === value) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._hasVertexAlpha = value;
+ this._markSubMeshesAsAttributesDirty();
+ this._markSubMeshesAsMiscDirty();
+ }
+ /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
+ get useVertexColors() {
+ return this._internalAbstractMeshDataInfo._useVertexColors;
+ }
+ set useVertexColors(value) {
+ if (this._internalAbstractMeshDataInfo._useVertexColors === value) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._useVertexColors = value;
+ this._markSubMeshesAsAttributesDirty();
+ }
+ /**
+ * Gets or sets a boolean indicating that bone animations must be computed by the GPU (true by default)
+ */
+ get computeBonesUsingShaders() {
+ return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;
+ }
+ set computeBonesUsingShaders(value) {
+ if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value;
+ this._markSubMeshesAsAttributesDirty();
+ }
+ /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
+ get numBoneInfluencers() {
+ return this._internalAbstractMeshDataInfo._numBoneInfluencers;
+ }
+ set numBoneInfluencers(value) {
+ if (this._internalAbstractMeshDataInfo._numBoneInfluencers === value) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._numBoneInfluencers = value;
+ this._markSubMeshesAsAttributesDirty();
+ }
+ /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
+ get applyFog() {
+ return this._internalAbstractMeshDataInfo._applyFog;
+ }
+ set applyFog(value) {
+ if (this._internalAbstractMeshDataInfo._applyFog === value) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._applyFog = value;
+ this._markSubMeshesAsMiscDirty();
+ }
+ /** When enabled, decompose picking matrices for better precision with large values for mesh position and scling */
+ get enableDistantPicking() {
+ return this._internalAbstractMeshDataInfo._enableDistantPicking;
+ }
+ set enableDistantPicking(value) {
+ this._internalAbstractMeshDataInfo._enableDistantPicking = value;
+ }
+ /**
+ * Gets or sets the current layer mask (default is 0x0FFFFFFF)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/layerMasksAndMultiCam
+ */
+ get layerMask() {
+ return this._internalAbstractMeshDataInfo._layerMask;
+ }
+ set layerMask(value) {
+ if (value === this._internalAbstractMeshDataInfo._layerMask) {
+ return;
+ }
+ this._internalAbstractMeshDataInfo._layerMask = value;
+ this._resyncLightSources();
+ }
+ /**
+ * Gets or sets a collision mask used to mask collisions (default is -1).
+ * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
+ */
+ get collisionMask() {
+ return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask;
+ }
+ set collisionMask(mask) {
+ this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = !isNaN(mask) ? mask : -1;
+ }
+ /**
+ * Gets or sets a collision response flag (default is true).
+ * when collisionResponse is false, events are still triggered but colliding entity has no response
+ * This helps creating trigger volume when user wants collision feedback events but not position/velocity
+ * to respond to the collision.
+ */
+ get collisionResponse() {
+ return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse;
+ }
+ set collisionResponse(response) {
+ this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = response;
+ }
+ /**
+ * Gets or sets the current collision group mask (-1 by default).
+ * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
+ */
+ get collisionGroup() {
+ return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup;
+ }
+ set collisionGroup(mask) {
+ this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = !isNaN(mask) ? mask : -1;
+ }
+ /**
+ * Gets or sets current surrounding meshes (null by default).
+ *
+ * By default collision detection is tested against every mesh in the scene.
+ * It is possible to set surroundingMeshes to a defined list of meshes and then only these specified
+ * meshes will be tested for the collision.
+ *
+ * Note: if set to an empty array no collision will happen when this mesh is moved.
+ */
+ get surroundingMeshes() {
+ return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes;
+ }
+ set surroundingMeshes(meshes) {
+ this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = meshes;
+ }
+ /** Gets the list of lights affecting that mesh */
+ get lightSources() {
+ return this._lightSources;
+ }
+ /**
+ * Gets or sets a skeleton to apply skinning transformations
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons
+ */
+ set skeleton(value) {
+ const skeleton = this._internalAbstractMeshDataInfo._skeleton;
+ if (skeleton && skeleton.needInitialSkinMatrix) {
+ skeleton._unregisterMeshWithPoseMatrix(this);
+ }
+ if (value && value.needInitialSkinMatrix) {
+ value._registerMeshWithPoseMatrix(this);
+ }
+ this._internalAbstractMeshDataInfo._skeleton = value;
+ if (!this._internalAbstractMeshDataInfo._skeleton) {
+ this._bonesTransformMatrices = null;
+ }
+ this._markSubMeshesAsAttributesDirty();
+ }
+ get skeleton() {
+ return this._internalAbstractMeshDataInfo._skeleton;
+ }
+ // Constructor
+ /**
+ * Creates a new AbstractMesh
+ * @param name defines the name of the mesh
+ * @param scene defines the hosting scene
+ */
+ constructor(name, scene = null) {
+ super(name, scene, false);
+ // Internal data
+ /** @internal */
+ this._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo();
+ /** @internal */
+ this._waitingMaterialId = null;
+ /** @internal */
+ this._waitingMorphTargetManagerId = null;
+ /**
+ * The culling strategy to use to check whether the mesh must be rendered or not.
+ * This value can be changed at any time and will be used on the next render mesh selection.
+ * The possible values are :
+ * - AbstractMesh.CULLINGSTRATEGY_STANDARD
+ * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY
+ * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION
+ * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY
+ * Please read each static variable documentation to get details about the culling process.
+ * */
+ this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY;
+ // Events
+ /**
+ * An event triggered when this mesh collides with another one
+ */
+ this.onCollideObservable = new Observable();
+ /**
+ * An event triggered when the collision's position changes
+ */
+ this.onCollisionPositionChangeObservable = new Observable();
+ /**
+ * An event triggered when material is changed
+ */
+ this.onMaterialChangedObservable = new Observable();
+ // Properties
+ /**
+ * Gets or sets the orientation for POV movement & rotation
+ */
+ this.definedFacingForward = true;
+ /** @internal */
+ this._occlusionQuery = null;
+ /** @internal */
+ this._renderingGroup = null;
+ /** Gets or sets the alpha index used to sort transparent meshes
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#alpha-index
+ */
+ this.alphaIndex = Number.MAX_VALUE;
+ this._isVisible = true;
+ /**
+ * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
+ */
+ this.isPickable = true;
+ /**
+ * Gets or sets a boolean indicating if the mesh can be near picked (touched by the XR controller or hands). Default is false
+ */
+ this.isNearPickable = false;
+ /**
+ * Gets or sets a boolean indicating if the mesh can be grabbed. Default is false.
+ * Setting this to true, while using the XR near interaction feature, will trigger a pointer event when the mesh is grabbed.
+ * Grabbing means that the controller is using the squeeze or main trigger button to grab the mesh.
+ * This is different from nearPickable which only triggers the event when the mesh is touched by the controller
+ */
+ this.isNearGrabbable = false;
+ /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
+ this.showSubMeshesBoundingBox = false;
+ /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare
+ */
+ this.isBlocker = false;
+ /**
+ * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
+ */
+ this.enablePointerMoveEvents = false;
+ /** Defines color to use when rendering outline */
+ this.outlineColor = Color3.Red();
+ /** Define width to use when rendering outline */
+ this.outlineWidth = 0.02;
+ /** Defines color to use when rendering overlay */
+ this.overlayColor = Color3.Red();
+ /** Defines alpha to use when rendering overlay */
+ this.overlayAlpha = 0.5;
+ /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
+ this.useOctreeForRenderingSelection = true;
+ /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
+ this.useOctreeForPicking = true;
+ /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
+ this.useOctreeForCollisions = true;
+ /**
+ * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
+ */
+ this.alwaysSelectAsActiveMesh = false;
+ /**
+ * Gets or sets a boolean indicating that the bounding info does not need to be kept in sync (for performance reason)
+ */
+ this.doNotSyncBoundingInfo = false;
+ /**
+ * Gets or sets the current action manager
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions
+ */
+ this.actionManager = null;
+ /**
+ * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions
+ */
+ this.ellipsoid = new Vector3(0.5, 1, 0.5);
+ /**
+ * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions
+ */
+ this.ellipsoidOffset = new Vector3(0, 0, 0);
+ // Edges
+ /**
+ * Defines edge width used when edgesRenderer is enabled
+ * @see https://www.babylonjs-playground.com/#10OJSG#13
+ */
+ this.edgesWidth = 1;
+ /**
+ * Defines edge color used when edgesRenderer is enabled
+ * @see https://www.babylonjs-playground.com/#10OJSG#13
+ */
+ this.edgesColor = new Color4(1, 0, 0, 1);
+ /** @internal */
+ this._edgesRenderer = null;
+ /** @internal */
+ this._masterMesh = null;
+ this._boundingInfo = null;
+ this._boundingInfoIsDirty = true;
+ /** @internal */
+ this._renderId = 0;
+ /** @internal */
+ this._intersectionsInProgress = new Array();
+ /** @internal */
+ this._unIndexed = false;
+ /** @internal */
+ this._lightSources = new Array();
+ // Loading properties
+ /** @internal */
+ this._waitingData = {
+ lods: null,
+ actions: null,
+ freezeWorldMatrix: null,
+ };
+ /** @internal */
+ this._bonesTransformMatrices = null;
+ /** @internal */
+ this._transformMatrixTexture = null;
+ /**
+ * An event triggered when the mesh is rebuilt.
+ */
+ this.onRebuildObservable = new Observable();
+ this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {
+ newPosition.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions);
+ if (this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > AbstractEngine.CollisionsEpsilon) {
+ this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions);
+ }
+ if (collidedMesh) {
+ this.onCollideObservable.notifyObservers(collidedMesh);
+ }
+ this.onCollisionPositionChangeObservable.notifyObservers(this.position);
+ };
+ scene = this.getScene();
+ scene.addMesh(this);
+ this._resyncLightSources();
+ // Mesh Uniform Buffer.
+ this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name, !this.getScene().getEngine().isWebGPU);
+ this._buildUniformLayout();
+ switch (scene.performancePriority) {
+ case 2 /* ScenePerformancePriority.Aggressive */:
+ this.doNotSyncBoundingInfo = true;
+ // eslint-disable-next-line no-fallthrough
+ case 1 /* ScenePerformancePriority.Intermediate */:
+ this.alwaysSelectAsActiveMesh = true;
+ this.isPickable = false;
+ break;
+ }
+ }
+ _buildUniformLayout() {
+ this._uniformBuffer.addUniform("world", 16);
+ this._uniformBuffer.addUniform("visibility", 1);
+ this._uniformBuffer.create();
+ }
+ /**
+ * Transfer the mesh values to its UBO.
+ * @param world The world matrix associated with the mesh
+ */
+ transferToEffect(world) {
+ const ubo = this._uniformBuffer;
+ ubo.updateMatrix("world", world);
+ ubo.updateFloat("visibility", this._internalAbstractMeshDataInfo._visibility);
+ ubo.update();
+ }
+ /**
+ * Gets the mesh uniform buffer.
+ * @returns the uniform buffer of the mesh.
+ */
+ getMeshUniformBuffer() {
+ return this._uniformBuffer;
+ }
+ /**
+ * Returns the string "AbstractMesh"
+ * @returns "AbstractMesh"
+ */
+ getClassName() {
+ return "AbstractMesh";
+ }
+ /**
+ * Gets a string representation of the current mesh
+ * @param fullDetails defines a boolean indicating if full details must be included
+ * @returns a string representation of the current mesh
+ */
+ toString(fullDetails) {
+ let ret = "Name: " + this.name + ", isInstance: " + (this.getClassName() !== "InstancedMesh" ? "YES" : "NO");
+ ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
+ const skeleton = this._internalAbstractMeshDataInfo._skeleton;
+ if (skeleton) {
+ ret += ", skeleton: " + skeleton.name;
+ }
+ if (fullDetails) {
+ ret += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode];
+ ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? "YES" : "NO");
+ }
+ return ret;
+ }
+ /**
+ * @internal
+ */
+ _getEffectiveParent() {
+ if (this._masterMesh && this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
+ return this._masterMesh;
+ }
+ return super._getEffectiveParent();
+ }
+ /**
+ * @internal
+ */
+ _getActionManagerForTrigger(trigger, initialCall = true) {
+ if (this.actionManager && (initialCall || this.actionManager.isRecursive)) {
+ if (trigger) {
+ if (this.actionManager.hasSpecificTrigger(trigger)) {
+ return this.actionManager;
+ }
+ }
+ else {
+ return this.actionManager;
+ }
+ }
+ if (!this.parent) {
+ return null;
+ }
+ return this.parent._getActionManagerForTrigger(trigger, false);
+ }
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _rebuild(dispose = false) {
+ this.onRebuildObservable.notifyObservers(this);
+ if (this._occlusionQuery !== null) {
+ this._occlusionQuery = null;
+ }
+ if (!this.subMeshes) {
+ return;
+ }
+ for (const subMesh of this.subMeshes) {
+ subMesh._rebuild();
+ }
+ this.resetDrawCache();
+ }
+ /** @internal */
+ _resyncLightSources() {
+ this._lightSources.length = 0;
+ for (const light of this.getScene().lights) {
+ if (!light.isEnabled()) {
+ continue;
+ }
+ if (light.canAffectMesh(this)) {
+ this._lightSources.push(light);
+ }
+ }
+ this._markSubMeshesAsLightDirty();
+ }
+ /**
+ * @internal
+ */
+ _resyncLightSource(light) {
+ const isIn = light.isEnabled() && light.canAffectMesh(this);
+ const index = this._lightSources.indexOf(light);
+ let removed = false;
+ if (index === -1) {
+ if (!isIn) {
+ return;
+ }
+ this._lightSources.push(light);
+ }
+ else {
+ if (isIn) {
+ return;
+ }
+ removed = true;
+ this._lightSources.splice(index, 1);
+ }
+ this._markSubMeshesAsLightDirty(removed);
+ }
+ /** @internal */
+ _unBindEffect() {
+ for (const subMesh of this.subMeshes) {
+ subMesh.setEffect(null);
+ }
+ }
+ /**
+ * @internal
+ */
+ _removeLightSource(light, dispose) {
+ const index = this._lightSources.indexOf(light);
+ if (index === -1) {
+ return;
+ }
+ this._lightSources.splice(index, 1);
+ this._markSubMeshesAsLightDirty(dispose);
+ }
+ _markSubMeshesAsDirty(func) {
+ if (!this.subMeshes) {
+ return;
+ }
+ for (const subMesh of this.subMeshes) {
+ for (let i = 0; i < subMesh._drawWrappers.length; ++i) {
+ const drawWrapper = subMesh._drawWrappers[i];
+ if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) {
+ continue;
+ }
+ func(drawWrapper.defines);
+ }
+ }
+ }
+ /**
+ * @internal
+ */
+ _markSubMeshesAsLightDirty(dispose = false) {
+ this._markSubMeshesAsDirty((defines) => defines.markAsLightDirty(dispose));
+ }
+ /** @internal */
+ _markSubMeshesAsAttributesDirty() {
+ this._markSubMeshesAsDirty((defines) => defines.markAsAttributesDirty());
+ }
+ /** @internal */
+ _markSubMeshesAsMiscDirty() {
+ this._markSubMeshesAsDirty((defines) => defines.markAsMiscDirty());
+ }
+ /**
+ * Flag the AbstractMesh as dirty (Forcing it to update everything)
+ * @param property if set to "rotation" the objects rotationQuaternion will be set to null
+ * @returns this AbstractMesh
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ markAsDirty(property) {
+ this._currentRenderId = Number.MAX_VALUE;
+ super.markAsDirty(property);
+ this._isDirty = true;
+ return this;
+ }
+ /**
+ * Resets the draw wrappers cache for all submeshes of this abstract mesh
+ * @param passId If provided, releases only the draw wrapper corresponding to this render pass id
+ * @param immediate If true, the effect will be released immediately, otherwise it will be released at the next frame
+ */
+ resetDrawCache(passId, immediate = false) {
+ if (!this.subMeshes) {
+ return;
+ }
+ for (const subMesh of this.subMeshes) {
+ subMesh.resetDrawCache(passId, immediate);
+ }
+ }
+ // Methods
+ /**
+ * Returns true if the mesh is blocked. Implemented by child classes
+ */
+ get isBlocked() {
+ return false;
+ }
+ /**
+ * Returns the mesh itself by default. Implemented by child classes
+ * @param camera defines the camera to use to pick the right LOD level
+ * @returns the currentAbstractMesh
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getLOD(camera) {
+ return this;
+ }
+ /**
+ * Returns 0 by default. Implemented by child classes
+ * @returns an integer
+ */
+ getTotalVertices() {
+ return 0;
+ }
+ /**
+ * Returns a positive integer : the total number of indices in this mesh geometry.
+ * @returns the number of indices or zero if the mesh has no geometry.
+ */
+ getTotalIndices() {
+ return 0;
+ }
+ /**
+ * Returns null by default. Implemented by child classes
+ * @returns null
+ */
+ getIndices() {
+ return null;
+ }
+ /**
+ * Returns the array of the requested vertex data kind. Implemented by child classes
+ * @param kind defines the vertex data kind to use
+ * @returns null
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getVerticesData(kind) {
+ return null;
+ }
+ /**
+ * Sets the vertex data of the mesh geometry for the requested `kind`.
+ * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
+ * Note that a new underlying VertexBuffer object is created each call.
+ * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
+ * @param kind defines vertex data kind:
+ * * VertexBuffer.PositionKind
+ * * VertexBuffer.UVKind
+ * * VertexBuffer.UV2Kind
+ * * VertexBuffer.UV3Kind
+ * * VertexBuffer.UV4Kind
+ * * VertexBuffer.UV5Kind
+ * * VertexBuffer.UV6Kind
+ * * VertexBuffer.ColorKind
+ * * VertexBuffer.MatricesIndicesKind
+ * * VertexBuffer.MatricesIndicesExtraKind
+ * * VertexBuffer.MatricesWeightsKind
+ * * VertexBuffer.MatricesWeightsExtraKind
+ * @param data defines the data source
+ * @param updatable defines if the data must be flagged as updatable (or static)
+ * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
+ * @returns the current mesh
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ setVerticesData(kind, data, updatable, stride) {
+ return this;
+ }
+ /**
+ * Updates the existing vertex data of the mesh geometry for the requested `kind`.
+ * If the mesh has no geometry, it is simply returned as it is.
+ * @param kind defines vertex data kind:
+ * * VertexBuffer.PositionKind
+ * * VertexBuffer.UVKind
+ * * VertexBuffer.UV2Kind
+ * * VertexBuffer.UV3Kind
+ * * VertexBuffer.UV4Kind
+ * * VertexBuffer.UV5Kind
+ * * VertexBuffer.UV6Kind
+ * * VertexBuffer.ColorKind
+ * * VertexBuffer.MatricesIndicesKind
+ * * VertexBuffer.MatricesIndicesExtraKind
+ * * VertexBuffer.MatricesWeightsKind
+ * * VertexBuffer.MatricesWeightsExtraKind
+ * @param data defines the data source
+ * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
+ * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
+ * @returns the current mesh
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ updateVerticesData(kind, data, updateExtends, makeItUnique) {
+ return this;
+ }
+ /**
+ * Sets the mesh indices,
+ * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
+ * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
+ * @param totalVertices Defines the total number of vertices
+ * @returns the current mesh
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ setIndices(indices, totalVertices) {
+ return this;
+ }
+ /**
+ * Gets a boolean indicating if specific vertex data is present
+ * @param kind defines the vertex data kind to use
+ * @returns true is data kind is present
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ isVerticesDataPresent(kind) {
+ return false;
+ }
+ /**
+ * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined.
+ * Note that it returns a shallow bounding of the mesh (i.e. it does not include children).
+ * However, if the mesh contains thin instances, it will be expanded to include them. If you want the "raw" bounding data instead, then use `getRawBoundingInfo()`.
+ * To get the full bounding of all children, call `getHierarchyBoundingVectors` instead.
+ * @returns a BoundingInfo
+ */
+ getBoundingInfo() {
+ if (this._masterMesh) {
+ return this._masterMesh.getBoundingInfo();
+ }
+ if (this._boundingInfoIsDirty) {
+ this._boundingInfoIsDirty = false;
+ // this._boundingInfo is being created if undefined
+ this._updateBoundingInfo();
+ }
+ // cannot be null.
+ return this._boundingInfo;
+ }
+ /**
+ * Returns the bounding info unnafected by instance data.
+ * @returns the bounding info of the mesh unaffected by instance data.
+ */
+ getRawBoundingInfo() {
+ return this.rawBoundingInfo ?? this.getBoundingInfo();
+ }
+ /**
+ * Overwrite the current bounding info
+ * @param boundingInfo defines the new bounding info
+ * @returns the current mesh
+ */
+ setBoundingInfo(boundingInfo) {
+ this._boundingInfo = boundingInfo;
+ return this;
+ }
+ /**
+ * Returns true if there is already a bounding info
+ */
+ get hasBoundingInfo() {
+ return this._boundingInfo !== null;
+ }
+ /**
+ * Creates a new bounding info for the mesh
+ * @param minimum min vector of the bounding box/sphere
+ * @param maximum max vector of the bounding box/sphere
+ * @param worldMatrix defines the new world matrix
+ * @returns the new bounding info
+ */
+ buildBoundingInfo(minimum, maximum, worldMatrix) {
+ this._boundingInfo = new BoundingInfo(minimum, maximum, worldMatrix);
+ return this._boundingInfo;
+ }
+ /**
+ * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
+ * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false
+ * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false
+ * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling
+ * @returns the current mesh
+ */
+ normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) {
+ return super.normalizeToUnitCube(includeDescendants, ignoreRotation, predicate);
+ }
+ /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
+ get useBones() {
+ return ((this.skeleton &&
+ this.getScene().skeletonsEnabled &&
+ this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) &&
+ this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)));
+ }
+ /** @internal */
+ _preActivate() { }
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _preActivateForIntermediateRendering(renderId) { }
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _activate(renderId, intermediateRendering) {
+ this._renderId = renderId;
+ return true;
+ }
+ /** @internal */
+ _postActivate() {
+ // Do nothing
+ }
+ /** @internal */
+ _freeze() {
+ // Do nothing
+ }
+ /** @internal */
+ _unFreeze() {
+ // Do nothing
+ }
+ /**
+ * Gets the current world matrix
+ * @returns a Matrix
+ */
+ getWorldMatrix() {
+ if (this._masterMesh && this.billboardMode === TransformNode.BILLBOARDMODE_NONE) {
+ return this._masterMesh.getWorldMatrix();
+ }
+ return super.getWorldMatrix();
+ }
+ /** @internal */
+ _getWorldMatrixDeterminant() {
+ if (this._masterMesh) {
+ return this._masterMesh._getWorldMatrixDeterminant();
+ }
+ return super._getWorldMatrixDeterminant();
+ }
+ /**
+ * Gets a boolean indicating if this mesh is an instance or a regular mesh
+ */
+ get isAnInstance() {
+ return false;
+ }
+ /**
+ * Gets a boolean indicating if this mesh has instances
+ */
+ get hasInstances() {
+ return false;
+ }
+ /**
+ * Gets a boolean indicating if this mesh has thin instances
+ */
+ get hasThinInstances() {
+ return false;
+ }
+ // ================================== Point of View Movement =================================
+ /**
+ * Perform relative position change from the point of view of behind the front of the mesh.
+ * This is performed taking into account the meshes current rotation, so you do not have to care.
+ * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.
+ * @param amountRight defines the distance on the right axis
+ * @param amountUp defines the distance on the up axis
+ * @param amountForward defines the distance on the forward axis
+ * @returns the current mesh
+ */
+ movePOV(amountRight, amountUp, amountForward) {
+ this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
+ return this;
+ }
+ /**
+ * Calculate relative position change from the point of view of behind the front of the mesh.
+ * This is performed taking into account the meshes current rotation, so you do not have to care.
+ * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.
+ * @param amountRight defines the distance on the right axis
+ * @param amountUp defines the distance on the up axis
+ * @param amountForward defines the distance on the forward axis
+ * @returns the new displacement vector
+ */
+ calcMovePOV(amountRight, amountUp, amountForward) {
+ const rotMatrix = new Matrix();
+ const rotQuaternion = this.rotationQuaternion ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
+ rotQuaternion.toRotationMatrix(rotMatrix);
+ const translationDelta = Vector3.Zero();
+ const defForwardMult = this.definedFacingForward ? -1 : 1;
+ Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
+ return translationDelta;
+ }
+ // ================================== Point of View Rotation =================================
+ /**
+ * Perform relative rotation change from the point of view of behind the front of the mesh.
+ * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.
+ * @param flipBack defines the flip
+ * @param twirlClockwise defines the twirl
+ * @param tiltRight defines the tilt
+ * @returns the current mesh
+ */
+ rotatePOV(flipBack, twirlClockwise, tiltRight) {
+ this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
+ return this;
+ }
+ /**
+ * Calculate relative rotation change from the point of view of behind the front of the mesh.
+ * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.
+ * @param flipBack defines the flip
+ * @param twirlClockwise defines the twirl
+ * @param tiltRight defines the tilt
+ * @returns the new rotation vector
+ */
+ calcRotatePOV(flipBack, twirlClockwise, tiltRight) {
+ const defForwardMult = this.definedFacingForward ? 1 : -1;
+ return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
+ }
+ /**
+ * @internal
+ */
+ _refreshBoundingInfo(data, bias) {
+ if (data) {
+ const extend = extractMinAndMax(data, 0, this.getTotalVertices(), bias);
+ if (this._boundingInfo) {
+ this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
+ }
+ else {
+ this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
+ }
+ }
+ if (this.subMeshes) {
+ for (let index = 0; index < this.subMeshes.length; index++) {
+ this.subMeshes[index].refreshBoundingInfo(data);
+ }
+ }
+ this._updateBoundingInfo();
+ }
+ /**
+ * @internal
+ */
+ _refreshBoundingInfoDirect(extend) {
+ if (this._boundingInfo) {
+ this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
+ }
+ else {
+ this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
+ }
+ if (this.subMeshes) {
+ for (let index = 0; index < this.subMeshes.length; index++) {
+ this.subMeshes[index].refreshBoundingInfo(null);
+ }
+ }
+ this._updateBoundingInfo();
+ }
+ // This function is only here so we can apply the nativeOverride decorator.
+ static _ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData) {
+ applySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData);
+ }
+ /** @internal */
+ _getData(options, data, kind = VertexBuffer.PositionKind) {
+ const cache = options.cache;
+ const getVertexData = (kind) => {
+ if (cache) {
+ const vertexData = (cache._vertexData || (cache._vertexData = {}));
+ if (!vertexData[kind]) {
+ this.copyVerticesData(kind, vertexData);
+ }
+ return vertexData[kind];
+ }
+ return this.getVerticesData(kind);
+ };
+ data || (data = getVertexData(kind));
+ if (!data) {
+ return null;
+ }
+ if (cache) {
+ if (cache._outputData) {
+ cache._outputData.set(data);
+ }
+ else {
+ cache._outputData = new Float32Array(data);
+ }
+ data = cache._outputData;
+ }
+ else if ((options.applyMorph && this.morphTargetManager) || (options.applySkeleton && this.skeleton)) {
+ data = data.slice();
+ }
+ if (options.applyMorph && this.morphTargetManager) {
+ applyMorph(data, kind, this.morphTargetManager);
+ }
+ if (options.applySkeleton && this.skeleton) {
+ const matricesIndicesData = getVertexData(VertexBuffer.MatricesIndicesKind);
+ const matricesWeightsData = getVertexData(VertexBuffer.MatricesWeightsKind);
+ if (matricesWeightsData && matricesIndicesData) {
+ const needExtras = this.numBoneInfluencers > 4;
+ const matricesIndicesExtraData = needExtras ? getVertexData(VertexBuffer.MatricesIndicesExtraKind) : null;
+ const matricesWeightsExtraData = needExtras ? getVertexData(VertexBuffer.MatricesWeightsExtraKind) : null;
+ const skeletonMatrices = this.skeleton.getTransformMatrices(this);
+ AbstractMesh._ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData);
+ }
+ }
+ if (options.updatePositionsArray !== false && kind === VertexBuffer.PositionKind) {
+ const positions = this._internalAbstractMeshDataInfo._positions || [];
+ const previousLength = positions.length;
+ positions.length = data.length / 3;
+ if (previousLength < positions.length) {
+ for (let positionIndex = previousLength; positionIndex < positions.length; positionIndex++) {
+ positions[positionIndex] = new Vector3();
+ }
+ }
+ for (let positionIndex = 0, dataIndex = 0; positionIndex < positions.length; positionIndex++, dataIndex += 3) {
+ positions[positionIndex].copyFromFloats(data[dataIndex], data[dataIndex + 1], data[dataIndex + 2]);
+ }
+ this._internalAbstractMeshDataInfo._positions = positions;
+ }
+ return data;
+ }
+ /**
+ * Get the normals vertex data and optionally apply skeleton and morphing.
+ * @param applySkeleton defines whether to apply the skeleton
+ * @param applyMorph defines whether to apply the morph target
+ * @returns the normals data
+ */
+ getNormalsData(applySkeleton = false, applyMorph = false) {
+ return this._getData({ applySkeleton, applyMorph, updatePositionsArray: false }, null, VertexBuffer.NormalKind);
+ }
+ /**
+ * Get the position vertex data and optionally apply skeleton and morphing.
+ * @param applySkeleton defines whether to apply the skeleton
+ * @param applyMorph defines whether to apply the morph target
+ * @param data defines the position data to apply the skeleton and morph to
+ * @returns the position data
+ */
+ getPositionData(applySkeleton = false, applyMorph = false, data = null) {
+ return this._getData({ applySkeleton, applyMorph, updatePositionsArray: false }, data, VertexBuffer.PositionKind);
+ }
+ /** @internal */
+ _updateBoundingInfo() {
+ if (this._boundingInfo) {
+ this._boundingInfo.update(this.worldMatrixFromCache);
+ }
+ else {
+ this._boundingInfo = new BoundingInfo(Vector3.Zero(), Vector3.Zero(), this.worldMatrixFromCache);
+ }
+ this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _updateSubMeshesBoundingInfo(matrix) {
+ if (!this.subMeshes) {
+ return this;
+ }
+ const count = this.subMeshes.length;
+ for (let subIndex = 0; subIndex < count; subIndex++) {
+ const subMesh = this.subMeshes[subIndex];
+ if (count > 1 || !subMesh.IsGlobal) {
+ subMesh.updateBoundingInfo(matrix);
+ }
+ }
+ return this;
+ }
+ /** @internal */
+ _afterComputeWorldMatrix() {
+ if (this.doNotSyncBoundingInfo) {
+ return;
+ }
+ // Bounding info
+ this._boundingInfoIsDirty = true;
+ }
+ /**
+ * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
+ * A mesh is in the frustum if its bounding box intersects the frustum
+ * @param frustumPlanes defines the frustum to test
+ * @returns true if the mesh is in the frustum planes
+ */
+ isInFrustum(frustumPlanes) {
+ return this.getBoundingInfo().isInFrustum(frustumPlanes, this.cullingStrategy);
+ }
+ /**
+ * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
+ * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
+ * @param frustumPlanes defines the frustum to test
+ * @returns true if the mesh is completely in the frustum planes
+ */
+ isCompletelyInFrustum(frustumPlanes) {
+ return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
+ }
+ /**
+ * True if the mesh intersects another mesh or a SolidParticle object
+ * @param mesh defines a target mesh or SolidParticle to test
+ * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
+ * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
+ * @returns true if there is an intersection
+ */
+ intersectsMesh(mesh, precise = false, includeDescendants) {
+ const boundingInfo = this.getBoundingInfo();
+ const otherBoundingInfo = mesh.getBoundingInfo();
+ if (boundingInfo.intersects(otherBoundingInfo, precise)) {
+ return true;
+ }
+ if (includeDescendants) {
+ for (const child of this.getChildMeshes()) {
+ if (child.intersectsMesh(mesh, precise, true)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ /**
+ * Returns true if the passed point (Vector3) is inside the mesh bounding box
+ * @param point defines the point to test
+ * @returns true if there is an intersection
+ */
+ intersectsPoint(point) {
+ return this.getBoundingInfo().intersectsPoint(point);
+ }
+ // Collisions
+ /**
+ * Gets or sets a boolean indicating that this mesh can be used in the collision engine
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions
+ */
+ get checkCollisions() {
+ return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions;
+ }
+ set checkCollisions(collisionEnabled) {
+ this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = collisionEnabled;
+ }
+ /**
+ * Gets Collider object used to compute collisions (not physics)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions
+ */
+ get collider() {
+ return this._internalAbstractMeshDataInfo._meshCollisionData._collider;
+ }
+ /**
+ * Move the mesh using collision engine
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions
+ * @param displacement defines the requested displacement vector
+ * @returns the current mesh
+ */
+ moveWithCollisions(displacement) {
+ const globalPosition = this.getAbsolutePosition();
+ globalPosition.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);
+ const coordinator = this.getScene().collisionCoordinator;
+ if (!this._internalAbstractMeshDataInfo._meshCollisionData._collider) {
+ this._internalAbstractMeshDataInfo._meshCollisionData._collider = coordinator.createCollider();
+ }
+ this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid;
+ coordinator.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, displacement, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId);
+ return this;
+ }
+ // Collisions
+ /**
+ * @internal
+ */
+ _collideForSubMesh(subMesh, transformMatrix, collider) {
+ this._generatePointsArray();
+ if (!this._positions) {
+ return this;
+ }
+ // Transformation
+ if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
+ subMesh._lastColliderTransformMatrix = transformMatrix.clone();
+ subMesh._lastColliderWorldVertices = [];
+ subMesh._trianglePlanes = [];
+ const start = subMesh.verticesStart;
+ const end = subMesh.verticesStart + subMesh.verticesCount;
+ for (let i = start; i < end; i++) {
+ subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));
+ }
+ }
+ // Collide
+ collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial(), this, this._shouldConvertRHS(), subMesh.getMaterial()?.fillMode === 7);
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _processCollisionsForSubMeshes(collider, transformMatrix) {
+ const subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
+ const len = subMeshes.length;
+ for (let index = 0; index < len; index++) {
+ const subMesh = subMeshes.data[index];
+ // Bounding test
+ if (len > 1 && !subMesh._checkCollision(collider)) {
+ continue;
+ }
+ this._collideForSubMesh(subMesh, transformMatrix, collider);
+ }
+ return this;
+ }
+ /** @internal */
+ _shouldConvertRHS() {
+ return false;
+ }
+ /**
+ * @internal
+ */
+ _checkCollision(collider) {
+ // Bounding box test
+ if (!this.getBoundingInfo()._checkCollision(collider)) {
+ return this;
+ }
+ // Transformation matrix
+ const collisionsScalingMatrix = TmpVectors.Matrix[0];
+ const collisionsTransformMatrix = TmpVectors.Matrix[1];
+ Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
+ this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
+ this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
+ return this;
+ }
+ // Picking
+ /** @internal */
+ _generatePointsArray() {
+ return false;
+ }
+ /**
+ * Checks if the passed Ray intersects with the mesh. A mesh triangle can be picked both from its front and back sides,
+ * irrespective of orientation.
+ * @param ray defines the ray to use. It should be in the mesh's LOCAL coordinate space.
+ * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
+ * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
+ * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)
+ * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point
+ * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check
+ * @returns the picking info
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect
+ */
+ intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {
+ const pickingInfo = new PickingInfo();
+ const className = this.getClassName();
+ const intersectionThreshold = className === "InstancedLinesMesh" || className === "LinesMesh" || className === "GreasedLineMesh" ? this.intersectionThreshold : 0;
+ const boundingInfo = this.getBoundingInfo();
+ if (!this.subMeshes) {
+ return pickingInfo;
+ }
+ if (!skipBoundingInfo &&
+ (!ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold))) {
+ return pickingInfo;
+ }
+ if (onlyBoundingInfo) {
+ pickingInfo.hit = skipBoundingInfo ? false : true;
+ pickingInfo.pickedMesh = skipBoundingInfo ? null : this;
+ pickingInfo.distance = skipBoundingInfo ? 0 : Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center);
+ pickingInfo.subMeshId = 0;
+ return pickingInfo;
+ }
+ if (!this._generatePointsArray()) {
+ return pickingInfo;
+ }
+ let intersectInfo = null;
+ const subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
+ const len = subMeshes.length;
+ // Check if all submeshes are using a material that don't allow picking (point/lines rendering)
+ // if no submesh can be picked that way, then fallback to BBox picking
+ let anySubmeshSupportIntersect = false;
+ for (let index = 0; index < len; index++) {
+ const subMesh = subMeshes.data[index];
+ const material = subMesh.getMaterial();
+ if (!material) {
+ continue;
+ }
+ if (material.fillMode == 7 ||
+ material.fillMode == 0 ||
+ material.fillMode == 1 ||
+ material.fillMode == 2 ||
+ material.fillMode == 4) {
+ anySubmeshSupportIntersect = true;
+ break;
+ }
+ }
+ // no sub mesh support intersection, fallback to BBox that has already be done
+ if (!anySubmeshSupportIntersect) {
+ pickingInfo.hit = true;
+ pickingInfo.pickedMesh = this;
+ pickingInfo.distance = Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center);
+ pickingInfo.subMeshId = -1;
+ return pickingInfo;
+ }
+ // at least 1 submesh supports intersection, keep going
+ for (let index = 0; index < len; index++) {
+ const subMesh = subMeshes.data[index];
+ // Bounding test
+ if (len > 1 && !skipBoundingInfo && !subMesh.canIntersects(ray)) {
+ continue;
+ }
+ const currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck, trianglePredicate);
+ if (currentIntersectInfo) {
+ if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
+ intersectInfo = currentIntersectInfo;
+ intersectInfo.subMeshId = index;
+ if (fastCheck) {
+ break;
+ }
+ }
+ }
+ }
+ if (intersectInfo) {
+ // Get picked point
+ const world = worldToUse ?? this.getWorldMatrix();
+ const worldOrigin = TmpVectors.Vector3[0];
+ const direction = TmpVectors.Vector3[1];
+ Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin);
+ ray.direction.scaleToRef(intersectInfo.distance, direction);
+ const worldDirection = Vector3.TransformNormal(direction, world);
+ const pickedPoint = worldDirection.addInPlace(worldOrigin);
+ // Return result
+ pickingInfo.hit = true;
+ pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
+ pickingInfo.pickedPoint = pickedPoint;
+ pickingInfo.pickedMesh = this;
+ pickingInfo.bu = intersectInfo.bu || 0;
+ pickingInfo.bv = intersectInfo.bv || 0;
+ pickingInfo.subMeshFaceId = intersectInfo.faceId;
+ pickingInfo.faceId = intersectInfo.faceId + subMeshes.data[intersectInfo.subMeshId].indexStart / (this.getClassName().indexOf("LinesMesh") !== -1 ? 2 : 3);
+ pickingInfo.subMeshId = intersectInfo.subMeshId;
+ return pickingInfo;
+ }
+ return pickingInfo;
+ }
+ /**
+ * Clones the current mesh
+ * @param name defines the mesh name
+ * @param newParent defines the new mesh parent
+ * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
+ * @returns the new mesh
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ clone(name, newParent, doNotCloneChildren) {
+ return null;
+ }
+ /**
+ * Disposes all the submeshes of the current mesh
+ * @param immediate should dispose the effects immediately or not
+ * @returns the current mesh
+ */
+ releaseSubMeshes(immediate = false) {
+ if (this.subMeshes) {
+ while (this.subMeshes.length) {
+ this.subMeshes[0].dispose(immediate);
+ }
+ }
+ else {
+ this.subMeshes = [];
+ }
+ return this;
+ }
+ /**
+ * Releases resources associated with this abstract mesh.
+ * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
+ * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
+ */
+ dispose(doNotRecurse, disposeMaterialAndTextures = false) {
+ let index;
+ const scene = this.getScene();
+ // mesh map release.
+ if (this._scene.useMaterialMeshMap) {
+ // remove from material mesh map id needed
+ if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) {
+ this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined;
+ }
+ }
+ // Smart Array Retainers.
+ scene.freeActiveMeshes();
+ scene.freeRenderingGroups();
+ if (scene.renderingManager.maintainStateBetweenFrames) {
+ scene.renderingManager.restoreDispachedFlags();
+ }
+ // Action manager
+ if (this.actionManager !== undefined && this.actionManager !== null) {
+ // If we are the only mesh using the action manager, dispose of the action manager too unless it has opted out from that behavior
+ if (this.actionManager.disposeWhenUnowned && !this._scene.meshes.some((m) => m !== this && m.actionManager === this.actionManager)) {
+ this.actionManager.dispose();
+ }
+ this.actionManager = null;
+ }
+ // Skeleton
+ this._internalAbstractMeshDataInfo._skeleton = null;
+ if (this._transformMatrixTexture) {
+ this._transformMatrixTexture.dispose();
+ this._transformMatrixTexture = null;
+ }
+ // Intersections in progress
+ for (index = 0; index < this._intersectionsInProgress.length; index++) {
+ const other = this._intersectionsInProgress[index];
+ const pos = other._intersectionsInProgress.indexOf(this);
+ other._intersectionsInProgress.splice(pos, 1);
+ }
+ this._intersectionsInProgress.length = 0;
+ // Lights
+ const lights = scene.lights;
+ lights.forEach((light) => {
+ let meshIndex = light.includedOnlyMeshes.indexOf(this);
+ if (meshIndex !== -1) {
+ light.includedOnlyMeshes.splice(meshIndex, 1);
+ }
+ meshIndex = light.excludedMeshes.indexOf(this);
+ if (meshIndex !== -1) {
+ light.excludedMeshes.splice(meshIndex, 1);
+ }
+ // Shadow generators
+ const generators = light.getShadowGenerators();
+ if (generators) {
+ const iterator = generators.values();
+ for (let key = iterator.next(); key.done !== true; key = iterator.next()) {
+ const generator = key.value;
+ const shadowMap = generator.getShadowMap();
+ if (shadowMap && shadowMap.renderList) {
+ meshIndex = shadowMap.renderList.indexOf(this);
+ if (meshIndex !== -1) {
+ shadowMap.renderList.splice(meshIndex, 1);
+ }
+ }
+ }
+ }
+ });
+ // SubMeshes
+ if (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") {
+ this.releaseSubMeshes(true);
+ }
+ // Query
+ const engine = scene.getEngine();
+ if (this._occlusionQuery !== null) {
+ this.isOcclusionQueryInProgress = false;
+ engine.deleteQuery(this._occlusionQuery);
+ this._occlusionQuery = null;
+ }
+ // Engine
+ engine.wipeCaches();
+ // Remove from scene
+ scene.removeMesh(this);
+ if (this._parentContainer) {
+ const index = this._parentContainer.meshes.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.meshes.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ if (disposeMaterialAndTextures) {
+ if (this.material) {
+ if (this.material.getClassName() === "MultiMaterial") {
+ this.material.dispose(false, true, true);
+ }
+ else {
+ this.material.dispose(false, true);
+ }
+ }
+ }
+ if (!doNotRecurse) {
+ // Particles
+ for (index = 0; index < scene.particleSystems.length; index++) {
+ if (scene.particleSystems[index].emitter === this) {
+ scene.particleSystems[index].dispose();
+ index--;
+ }
+ }
+ }
+ // facet data
+ if (this._internalAbstractMeshDataInfo._facetData.facetDataEnabled) {
+ this.disableFacetData();
+ }
+ this._uniformBuffer.dispose();
+ this.onAfterWorldMatrixUpdateObservable.clear();
+ this.onCollideObservable.clear();
+ this.onCollisionPositionChangeObservable.clear();
+ this.onRebuildObservable.clear();
+ super.dispose(doNotRecurse, disposeMaterialAndTextures);
+ }
+ // Facet data
+ /** @internal */
+ _initFacetData() {
+ const data = this._internalAbstractMeshDataInfo._facetData;
+ if (!data.facetNormals) {
+ data.facetNormals = [];
+ }
+ if (!data.facetPositions) {
+ data.facetPositions = [];
+ }
+ if (!data.facetPartitioning) {
+ data.facetPartitioning = new Array();
+ }
+ data.facetNb = (this.getIndices().length / 3) | 0;
+ data.partitioningSubdivisions = data.partitioningSubdivisions ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
+ data.partitioningBBoxRatio = data.partitioningBBoxRatio ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
+ for (let f = 0; f < data.facetNb; f++) {
+ data.facetNormals[f] = Vector3.Zero();
+ data.facetPositions[f] = Vector3.Zero();
+ }
+ data.facetDataEnabled = true;
+ return this;
+ }
+ /**
+ * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
+ * This method can be called within the render loop.
+ * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation
+ * @returns the current mesh
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ updateFacetData() {
+ const data = this._internalAbstractMeshDataInfo._facetData;
+ if (!data.facetDataEnabled) {
+ this._initFacetData();
+ }
+ const positions = this.getVerticesData(VertexBuffer.PositionKind);
+ const indices = this.getIndices();
+ const normals = this.getVerticesData(VertexBuffer.NormalKind);
+ const bInfo = this.getBoundingInfo();
+ if (data.facetDepthSort && !data.facetDepthSortEnabled) {
+ // init arrays, matrix and sort function on first call
+ data.facetDepthSortEnabled = true;
+ if (indices instanceof Uint16Array) {
+ data.depthSortedIndices = new Uint16Array(indices);
+ }
+ else if (indices instanceof Uint32Array) {
+ data.depthSortedIndices = new Uint32Array(indices);
+ }
+ else {
+ let needs32bits = false;
+ for (let i = 0; i < indices.length; i++) {
+ if (indices[i] > 65535) {
+ needs32bits = true;
+ break;
+ }
+ }
+ if (needs32bits) {
+ data.depthSortedIndices = new Uint32Array(indices);
+ }
+ else {
+ data.depthSortedIndices = new Uint16Array(indices);
+ }
+ }
+ data.facetDepthSortFunction = function (f1, f2) {
+ return f2.sqDistance - f1.sqDistance;
+ };
+ if (!data.facetDepthSortFrom) {
+ const camera = this.getScene().activeCamera;
+ data.facetDepthSortFrom = camera ? camera.position : Vector3.Zero();
+ }
+ data.depthSortedFacets = [];
+ for (let f = 0; f < data.facetNb; f++) {
+ const depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
+ data.depthSortedFacets.push(depthSortedFacet);
+ }
+ data.invertedMatrix = Matrix.Identity();
+ data.facetDepthSortOrigin = Vector3.Zero();
+ }
+ data.bbSize.x = bInfo.maximum.x - bInfo.minimum.x > Epsilon ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;
+ data.bbSize.y = bInfo.maximum.y - bInfo.minimum.y > Epsilon ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;
+ data.bbSize.z = bInfo.maximum.z - bInfo.minimum.z > Epsilon ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;
+ let bbSizeMax = data.bbSize.x > data.bbSize.y ? data.bbSize.x : data.bbSize.y;
+ bbSizeMax = bbSizeMax > data.bbSize.z ? bbSizeMax : data.bbSize.z;
+ data.subDiv.max = data.partitioningSubdivisions;
+ data.subDiv.X = Math.floor((data.subDiv.max * data.bbSize.x) / bbSizeMax); // adjust the number of subdivisions per axis
+ data.subDiv.Y = Math.floor((data.subDiv.max * data.bbSize.y) / bbSizeMax); // according to each bbox size per axis
+ data.subDiv.Z = Math.floor((data.subDiv.max * data.bbSize.z) / bbSizeMax);
+ data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
+ data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
+ data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
+ // set the parameters for ComputeNormals()
+ data.facetParameters.facetNormals = this.getFacetLocalNormals();
+ data.facetParameters.facetPositions = this.getFacetLocalPositions();
+ data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
+ data.facetParameters.bInfo = bInfo;
+ data.facetParameters.bbSize = data.bbSize;
+ data.facetParameters.subDiv = data.subDiv;
+ data.facetParameters.ratio = this.partitioningBBoxRatio;
+ data.facetParameters.depthSort = data.facetDepthSort;
+ if (data.facetDepthSort && data.facetDepthSortEnabled) {
+ this.computeWorldMatrix(true);
+ this._worldMatrix.invertToRef(data.invertedMatrix);
+ Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
+ data.facetParameters.distanceTo = data.facetDepthSortOrigin;
+ }
+ data.facetParameters.depthSortedFacets = data.depthSortedFacets;
+ if (normals) {
+ VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
+ }
+ if (data.facetDepthSort && data.facetDepthSortEnabled) {
+ data.depthSortedFacets.sort(data.facetDepthSortFunction);
+ const l = (data.depthSortedIndices.length / 3) | 0;
+ for (let f = 0; f < l; f++) {
+ const sind = data.depthSortedFacets[f].ind;
+ data.depthSortedIndices[f * 3] = indices[sind];
+ data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
+ data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
+ }
+ this.updateIndices(data.depthSortedIndices, undefined, true);
+ }
+ return this;
+ }
+ /**
+ * Returns the facetLocalNormals array.
+ * The normals are expressed in the mesh local spac
+ * @returns an array of Vector3
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetLocalNormals() {
+ const facetData = this._internalAbstractMeshDataInfo._facetData;
+ if (!facetData.facetNormals) {
+ this.updateFacetData();
+ }
+ return facetData.facetNormals;
+ }
+ /**
+ * Returns the facetLocalPositions array.
+ * The facet positions are expressed in the mesh local space
+ * @returns an array of Vector3
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetLocalPositions() {
+ const facetData = this._internalAbstractMeshDataInfo._facetData;
+ if (!facetData.facetPositions) {
+ this.updateFacetData();
+ }
+ return facetData.facetPositions;
+ }
+ /**
+ * Returns the facetLocalPartitioning array
+ * @returns an array of array of numbers
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetLocalPartitioning() {
+ const facetData = this._internalAbstractMeshDataInfo._facetData;
+ if (!facetData.facetPartitioning) {
+ this.updateFacetData();
+ }
+ return facetData.facetPartitioning;
+ }
+ /**
+ * Returns the i-th facet position in the world system.
+ * This method allocates a new Vector3 per call
+ * @param i defines the facet index
+ * @returns a new Vector3
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetPosition(i) {
+ const pos = Vector3.Zero();
+ this.getFacetPositionToRef(i, pos);
+ return pos;
+ }
+ /**
+ * Sets the reference Vector3 with the i-th facet position in the world system
+ * @param i defines the facet index
+ * @param ref defines the target vector
+ * @returns the current mesh
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetPositionToRef(i, ref) {
+ const localPos = this.getFacetLocalPositions()[i];
+ const world = this.getWorldMatrix();
+ Vector3.TransformCoordinatesToRef(localPos, world, ref);
+ return this;
+ }
+ /**
+ * Returns the i-th facet normal in the world system.
+ * This method allocates a new Vector3 per call
+ * @param i defines the facet index
+ * @returns a new Vector3
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetNormal(i) {
+ const norm = Vector3.Zero();
+ this.getFacetNormalToRef(i, norm);
+ return norm;
+ }
+ /**
+ * Sets the reference Vector3 with the i-th facet normal in the world system
+ * @param i defines the facet index
+ * @param ref defines the target vector
+ * @returns the current mesh
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetNormalToRef(i, ref) {
+ const localNorm = this.getFacetLocalNormals()[i];
+ Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
+ return this;
+ }
+ /**
+ * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)
+ * @param x defines x coordinate
+ * @param y defines y coordinate
+ * @param z defines z coordinate
+ * @returns the array of facet indexes
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetsAtLocalCoordinates(x, y, z) {
+ const bInfo = this.getBoundingInfo();
+ const data = this._internalAbstractMeshDataInfo._facetData;
+ const ox = Math.floor(((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio) / data.bbSize.x);
+ const oy = Math.floor(((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio) / data.bbSize.y);
+ const oz = Math.floor(((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio) / data.bbSize.z);
+ if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
+ return null;
+ }
+ return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
+ }
+ /**
+ * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
+ * @param x defines x coordinate
+ * @param y defines y coordinate
+ * @param z defines z coordinate
+ * @param projected sets as the (x,y,z) world projection on the facet
+ * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
+ * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
+ * @returns the face index if found (or null instead)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getClosestFacetAtCoordinates(x, y, z, projected, checkFace = false, facing = true) {
+ const world = this.getWorldMatrix();
+ const invMat = TmpVectors.Matrix[5];
+ world.invertToRef(invMat);
+ const invVect = TmpVectors.Vector3[8];
+ Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
+ const closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
+ if (projected) {
+ // transform the local computed projected vector to world coordinates
+ Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
+ }
+ return closest;
+ }
+ /**
+ * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
+ * @param x defines x coordinate
+ * @param y defines y coordinate
+ * @param z defines z coordinate
+ * @param projected sets as the (x,y,z) local projection on the facet
+ * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
+ * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
+ * @returns the face index if found (or null instead)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getClosestFacetAtLocalCoordinates(x, y, z, projected, checkFace = false, facing = true) {
+ let closest = null;
+ let tmpx = 0.0;
+ let tmpy = 0.0;
+ let tmpz = 0.0;
+ let d = 0.0; // tmp dot facet normal * facet position
+ let t0 = 0.0;
+ let projx = 0.0;
+ let projy = 0.0;
+ let projz = 0.0;
+ // Get all the facets in the same partitioning block than (x, y, z)
+ const facetPositions = this.getFacetLocalPositions();
+ const facetNormals = this.getFacetLocalNormals();
+ const facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
+ if (!facetsInBlock) {
+ return null;
+ }
+ // Get the closest facet to (x, y, z)
+ let shortest = Number.MAX_VALUE; // init distance vars
+ let tmpDistance = shortest;
+ let fib; // current facet in the block
+ let norm; // current facet normal
+ let p0; // current facet barycenter position
+ // loop on all the facets in the current partitioning block
+ for (let idx = 0; idx < facetsInBlock.length; idx++) {
+ fib = facetsInBlock[idx];
+ norm = facetNormals[fib];
+ p0 = facetPositions[fib];
+ d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
+ if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
+ // compute (x,y,z) projection on the facet = (projx, projy, projz)
+ d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
+ t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
+ projx = x + norm.x * t0;
+ projy = y + norm.y * t0;
+ projz = z + norm.z * t0;
+ tmpx = projx - x;
+ tmpy = projy - y;
+ tmpz = projz - z;
+ tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
+ if (tmpDistance < shortest) {
+ // just keep the closest facet to (x, y, z)
+ shortest = tmpDistance;
+ closest = fib;
+ if (projected) {
+ projected.x = projx;
+ projected.y = projy;
+ projected.z = projz;
+ }
+ }
+ }
+ }
+ return closest;
+ }
+ /**
+ * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
+ * @returns the parameters
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ getFacetDataParameters() {
+ return this._internalAbstractMeshDataInfo._facetData.facetParameters;
+ }
+ /**
+ * Disables the feature FacetData and frees the related memory
+ * @returns the current mesh
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
+ */
+ disableFacetData() {
+ const facetData = this._internalAbstractMeshDataInfo._facetData;
+ if (facetData.facetDataEnabled) {
+ facetData.facetDataEnabled = false;
+ facetData.facetPositions = [];
+ facetData.facetNormals = [];
+ facetData.facetPartitioning = new Array();
+ facetData.facetParameters = {};
+ facetData.depthSortedIndices = new Uint32Array(0);
+ }
+ return this;
+ }
+ /**
+ * Updates the AbstractMesh indices array
+ * @param indices defines the data source
+ * @param offset defines the offset in the index buffer where to store the new data (can be null)
+ * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)
+ * @returns the current mesh
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ updateIndices(indices, offset, gpuMemoryOnly = false) {
+ return this;
+ }
+ /**
+ * Creates new normals data for the mesh
+ * @param updatable defines if the normal vertex buffer must be flagged as updatable
+ * @returns the current mesh
+ */
+ createNormals(updatable) {
+ const positions = this.getVerticesData(VertexBuffer.PositionKind);
+ const indices = this.getIndices();
+ let normals;
+ if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+ normals = this.getVerticesData(VertexBuffer.NormalKind);
+ }
+ else {
+ normals = [];
+ }
+ VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
+ this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);
+ return this;
+ }
+ /**
+ * Optimize the indices order so that we keep the faces with similar indices together
+ * @returns the current mesh
+ */
+ async optimizeIndicesAsync() {
+ const indices = this.getIndices();
+ if (!indices) {
+ return this;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const { OptimizeIndices } = await Promise.resolve().then(() => mesh_vertexData_functions);
+ OptimizeIndices(indices);
+ this.setIndices(indices, this.getTotalVertices());
+ return this;
+ }
+ /**
+ * Align the mesh with a normal
+ * @param normal defines the normal to use
+ * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
+ * @returns the current mesh
+ */
+ alignWithNormal(normal, upDirection) {
+ if (!upDirection) {
+ upDirection = Axis.Y;
+ }
+ const axisX = TmpVectors.Vector3[0];
+ const axisZ = TmpVectors.Vector3[1];
+ Vector3.CrossToRef(upDirection, normal, axisZ);
+ Vector3.CrossToRef(normal, axisZ, axisX);
+ if (this.rotationQuaternion) {
+ Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
+ }
+ else {
+ Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
+ }
+ return this;
+ }
+ /** @internal */
+ _checkOcclusionQuery() {
+ // Will be replaced by correct code if Occlusion queries are referenced
+ return false;
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Disables the mesh edge rendering mode
+ * @returns the currentAbstractMesh
+ */
+ disableEdgesRendering() {
+ throw _WarnImport("EdgesRenderer");
+ }
+ // eslint-disable-next-line jsdoc/require-returns-check
+ /**
+ * Enables the edge rendering mode on the mesh.
+ * This mode makes the mesh edges visible
+ * @param epsilon defines the maximal distance between two angles to detect a face
+ * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
+ * @param options options to the edge renderer
+ * @returns the currentAbstractMesh
+ * @see https://www.babylonjs-playground.com/#19O9TU#0
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ enableEdgesRendering(epsilon, checkVerticesInsteadOfIndices, options) {
+ throw _WarnImport("EdgesRenderer");
+ }
+ /**
+ * This function returns all of the particle systems in the scene that use the mesh as an emitter.
+ * @returns an array of particle systems in the scene that use the mesh as an emitter
+ */
+ getConnectedParticleSystems() {
+ return this._scene.particleSystems.filter((particleSystem) => particleSystem.emitter === this);
+ }
+}
+/** No occlusion */
+AbstractMesh.OCCLUSION_TYPE_NONE = 0;
+/** Occlusion set to optimistic */
+AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
+/** Occlusion set to strict */
+AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
+/** Use an accurate occlusion algorithm */
+AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
+/** Use a conservative occlusion algorithm */
+AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
+/** Default culling strategy : this is an exclusion test and it's the more accurate.
+ * Test order :
+ * Is the bounding sphere outside the frustum ?
+ * If not, are the bounding box vertices outside the frustum ?
+ * It not, then the cullable object is in the frustum.
+ */
+AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
+/** Culling strategy : Bounding Sphere Only.
+ * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested.
+ * It's also less accurate than the standard because some not visible objects can still be selected.
+ * Test : is the bounding sphere outside the frustum ?
+ * If not, then the cullable object is in the frustum.
+ */
+AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
+/** Culling strategy : Optimistic Inclusion.
+ * This in an inclusion test first, then the standard exclusion test.
+ * This can be faster when a cullable object is expected to be almost always in the camera frustum.
+ * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside.
+ * Anyway, it's as accurate as the standard strategy.
+ * Test :
+ * Is the cullable object bounding sphere center in the frustum ?
+ * If not, apply the default culling strategy.
+ */
+AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;
+/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only.
+ * This in an inclusion test first, then the bounding sphere only exclusion test.
+ * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum.
+ * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it.
+ * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy.
+ * Test :
+ * Is the cullable object bounding sphere center in the frustum ?
+ * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here.
+ */
+AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;
+__decorate([
+ nativeOverride.filter((...[data, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData]) => !Array.isArray(data) &&
+ !Array.isArray(matricesIndicesData) &&
+ !Array.isArray(matricesWeightsData) &&
+ !Array.isArray(matricesIndicesExtraData) &&
+ !Array.isArray(matricesWeightsExtraData))
+], AbstractMesh, "_ApplySkeleton", null);
+RegisterClass("BABYLON.AbstractMesh", AbstractMesh);
+
+/**
+ * Class that holds the different stencil states of a material
+ * Usage example: https://playground.babylonjs.com/#CW5PRI#10
+ */
+class MaterialStencilState {
+ /**
+ * Creates a material stencil state instance
+ */
+ constructor() {
+ this.reset();
+ }
+ /**
+ * Resets all the stencil states to default values
+ */
+ reset() {
+ this.enabled = false;
+ this.mask = 0xff;
+ this.func = 519;
+ this.funcRef = 1;
+ this.funcMask = 0xff;
+ this.opStencilFail = 7680;
+ this.opDepthFail = 7680;
+ this.opStencilDepthPass = 7681;
+ }
+ /**
+ * Gets or sets the stencil function
+ */
+ get func() {
+ return this._func;
+ }
+ set func(value) {
+ this._func = value;
+ }
+ /**
+ * Gets or sets the stencil function reference
+ */
+ get funcRef() {
+ return this._funcRef;
+ }
+ set funcRef(value) {
+ this._funcRef = value;
+ }
+ /**
+ * Gets or sets the stencil function mask
+ */
+ get funcMask() {
+ return this._funcMask;
+ }
+ set funcMask(value) {
+ this._funcMask = value;
+ }
+ /**
+ * Gets or sets the operation when the stencil test fails
+ */
+ get opStencilFail() {
+ return this._opStencilFail;
+ }
+ set opStencilFail(value) {
+ this._opStencilFail = value;
+ }
+ /**
+ * Gets or sets the operation when the depth test fails
+ */
+ get opDepthFail() {
+ return this._opDepthFail;
+ }
+ set opDepthFail(value) {
+ this._opDepthFail = value;
+ }
+ /**
+ * Gets or sets the operation when the stencil+depth test succeeds
+ */
+ get opStencilDepthPass() {
+ return this._opStencilDepthPass;
+ }
+ set opStencilDepthPass(value) {
+ this._opStencilDepthPass = value;
+ }
+ /**
+ * Gets or sets the stencil mask
+ */
+ get mask() {
+ return this._mask;
+ }
+ set mask(value) {
+ this._mask = value;
+ }
+ /**
+ * Enables or disables the stencil test
+ */
+ get enabled() {
+ return this._enabled;
+ }
+ set enabled(value) {
+ this._enabled = value;
+ }
+ /**
+ * Get the current class name, useful for serialization or dynamic coding.
+ * @returns "MaterialStencilState"
+ */
+ getClassName() {
+ return "MaterialStencilState";
+ }
+ /**
+ * Makes a duplicate of the current configuration into another one.
+ * @param stencilState defines stencil state where to copy the info
+ */
+ copyTo(stencilState) {
+ SerializationHelper.Clone(() => stencilState, this);
+ }
+ /**
+ * Serializes this stencil configuration.
+ * @returns - An object with the serialized config.
+ */
+ serialize() {
+ return SerializationHelper.Serialize(this);
+ }
+ /**
+ * Parses a stencil state configuration from a serialized object.
+ * @param source - Serialized object.
+ * @param scene Defines the scene we are parsing for
+ * @param rootUrl Defines the rootUrl to load from
+ */
+ parse(source, scene, rootUrl) {
+ SerializationHelper.Parse(() => this, source, scene, rootUrl);
+ }
+}
+__decorate([
+ serialize()
+], MaterialStencilState.prototype, "func", null);
+__decorate([
+ serialize()
+], MaterialStencilState.prototype, "funcRef", null);
+__decorate([
+ serialize()
+], MaterialStencilState.prototype, "funcMask", null);
+__decorate([
+ serialize()
+], MaterialStencilState.prototype, "opStencilFail", null);
+__decorate([
+ serialize()
+], MaterialStencilState.prototype, "opDepthFail", null);
+__decorate([
+ serialize()
+], MaterialStencilState.prototype, "opStencilDepthPass", null);
+__decorate([
+ serialize()
+], MaterialStencilState.prototype, "mask", null);
+__decorate([
+ serialize()
+], MaterialStencilState.prototype, "enabled", null);
+
+/** @internal */
+function addClipPlaneUniforms(uniforms) {
+ if (uniforms.indexOf("vClipPlane") === -1) {
+ uniforms.push("vClipPlane");
+ }
+ if (uniforms.indexOf("vClipPlane2") === -1) {
+ uniforms.push("vClipPlane2");
+ }
+ if (uniforms.indexOf("vClipPlane3") === -1) {
+ uniforms.push("vClipPlane3");
+ }
+ if (uniforms.indexOf("vClipPlane4") === -1) {
+ uniforms.push("vClipPlane4");
+ }
+ if (uniforms.indexOf("vClipPlane5") === -1) {
+ uniforms.push("vClipPlane5");
+ }
+ if (uniforms.indexOf("vClipPlane6") === -1) {
+ uniforms.push("vClipPlane6");
+ }
+}
+/** @internal */
+function prepareStringDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) {
+ const clipPlane = !!(primaryHolder.clipPlane ?? secondaryHolder.clipPlane);
+ const clipPlane2 = !!(primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2);
+ const clipPlane3 = !!(primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3);
+ const clipPlane4 = !!(primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4);
+ const clipPlane5 = !!(primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5);
+ const clipPlane6 = !!(primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6);
+ if (clipPlane)
+ defines.push("#define CLIPPLANE");
+ if (clipPlane2)
+ defines.push("#define CLIPPLANE2");
+ if (clipPlane3)
+ defines.push("#define CLIPPLANE3");
+ if (clipPlane4)
+ defines.push("#define CLIPPLANE4");
+ if (clipPlane5)
+ defines.push("#define CLIPPLANE5");
+ if (clipPlane6)
+ defines.push("#define CLIPPLANE6");
+}
+/** @internal */
+function prepareDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) {
+ let changed = false;
+ const clipPlane = !!(primaryHolder.clipPlane ?? secondaryHolder.clipPlane);
+ const clipPlane2 = !!(primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2);
+ const clipPlane3 = !!(primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3);
+ const clipPlane4 = !!(primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4);
+ const clipPlane5 = !!(primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5);
+ const clipPlane6 = !!(primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6);
+ // Do not factorize this code, it breaks browsers optimizations.
+ if (defines["CLIPPLANE"] !== clipPlane) {
+ defines["CLIPPLANE"] = clipPlane;
+ changed = true;
+ }
+ if (defines["CLIPPLANE2"] !== clipPlane2) {
+ defines["CLIPPLANE2"] = clipPlane2;
+ changed = true;
+ }
+ if (defines["CLIPPLANE3"] !== clipPlane3) {
+ defines["CLIPPLANE3"] = clipPlane3;
+ changed = true;
+ }
+ if (defines["CLIPPLANE4"] !== clipPlane4) {
+ defines["CLIPPLANE4"] = clipPlane4;
+ changed = true;
+ }
+ if (defines["CLIPPLANE5"] !== clipPlane5) {
+ defines["CLIPPLANE5"] = clipPlane5;
+ changed = true;
+ }
+ if (defines["CLIPPLANE6"] !== clipPlane6) {
+ defines["CLIPPLANE6"] = clipPlane6;
+ changed = true;
+ }
+ return changed;
+}
+/** @internal */
+function bindClipPlane(effect, primaryHolder, secondaryHolder) {
+ let clipPlane = primaryHolder.clipPlane ?? secondaryHolder.clipPlane;
+ setClipPlane(effect, "vClipPlane", clipPlane);
+ clipPlane = primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2;
+ setClipPlane(effect, "vClipPlane2", clipPlane);
+ clipPlane = primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3;
+ setClipPlane(effect, "vClipPlane3", clipPlane);
+ clipPlane = primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4;
+ setClipPlane(effect, "vClipPlane4", clipPlane);
+ clipPlane = primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5;
+ setClipPlane(effect, "vClipPlane5", clipPlane);
+ clipPlane = primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6;
+ setClipPlane(effect, "vClipPlane6", clipPlane);
+}
+function setClipPlane(effect, uniformName, clipPlane) {
+ if (clipPlane) {
+ effect.setFloat4(uniformName, clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
+ }
+}
+
+// Temps
+const _TempFogColor = Color3.Black();
+const _TmpMorphInfluencers = {
+ NUM_MORPH_INFLUENCERS: 0,
+ NORMAL: false,
+ TANGENT: false,
+ UV: false,
+ UV2: false,
+ COLOR: false,
+};
+/**
+ * Binds the logarithmic depth information from the scene to the effect for the given defines.
+ * @param defines The generated defines used in the effect
+ * @param effect The effect we are binding the data to
+ * @param scene The scene we are willing to render with logarithmic scale for
+ */
+function BindLogDepth(defines, effect, scene) {
+ if (!defines || defines["LOGARITHMICDEPTH"] || (defines.indexOf && defines.indexOf("LOGARITHMICDEPTH") >= 0)) {
+ const camera = scene.activeCamera;
+ if (camera.mode === 1) {
+ Logger.Error("Logarithmic depth is not compatible with orthographic cameras!", 20);
+ }
+ effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(camera.maxZ + 1.0) / Math.LN2));
+ }
+}
+/**
+ * Binds the fog information from the scene to the effect for the given mesh.
+ * @param scene The scene the lights belongs to
+ * @param mesh The mesh we are binding the information to render
+ * @param effect The effect we are binding the data to
+ * @param linearSpace Defines if the fog effect is applied in linear space
+ */
+function BindFogParameters(scene, mesh, effect, linearSpace = false) {
+ if (effect && scene.fogEnabled && (!mesh || mesh.applyFog) && scene.fogMode !== 0) {
+ effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
+ // Convert fog color to linear space if used in a linear space computed shader.
+ if (linearSpace) {
+ scene.fogColor.toLinearSpaceToRef(_TempFogColor, scene.getEngine().useExactSrgbConversions);
+ effect.setColor3("vFogColor", _TempFogColor);
+ }
+ else {
+ effect.setColor3("vFogColor", scene.fogColor);
+ }
+ }
+}
+/**
+ * Prepares the list of attributes and defines required for morph targets.
+ * @param morphTargetManager The manager for the morph targets
+ * @param defines The current list of defines
+ * @param attribs The current list of attributes
+ * @param mesh The mesh to prepare the defines and attributes for
+ * @param usePositionMorph Whether the position morph target is used
+ * @param useNormalMorph Whether the normal morph target is used
+ * @param useTangentMorph Whether the tangent morph target is used
+ * @param useUVMorph Whether the UV morph target is used
+ * @param useUV2Morph Whether the UV2 morph target is used
+ * @param useColorMorph Whether the color morph target is used
+ * @returns The maxSimultaneousMorphTargets for the effect
+ */
+function PrepareDefinesAndAttributesForMorphTargets(morphTargetManager, defines, attribs, mesh, usePositionMorph, useNormalMorph, useTangentMorph, useUVMorph, useUV2Morph, useColorMorph) {
+ const numMorphInfluencers = morphTargetManager.numMaxInfluencers || morphTargetManager.numInfluencers;
+ if (numMorphInfluencers <= 0) {
+ return 0;
+ }
+ defines.push("#define MORPHTARGETS");
+ if (morphTargetManager.hasPositions)
+ defines.push("#define MORPHTARGETTEXTURE_HASPOSITIONS");
+ if (morphTargetManager.hasNormals)
+ defines.push("#define MORPHTARGETTEXTURE_HASNORMALS");
+ if (morphTargetManager.hasTangents)
+ defines.push("#define MORPHTARGETTEXTURE_HASTANGENTS");
+ if (morphTargetManager.hasUVs)
+ defines.push("#define MORPHTARGETTEXTURE_HASUVS");
+ if (morphTargetManager.hasUV2s)
+ defines.push("#define MORPHTARGETTEXTURE_HASUV2S");
+ if (morphTargetManager.hasColors)
+ defines.push("#define MORPHTARGETTEXTURE_HASCOLORS");
+ if (morphTargetManager.supportsPositions && usePositionMorph)
+ defines.push("#define MORPHTARGETS_POSITION");
+ if (morphTargetManager.supportsNormals && useNormalMorph)
+ defines.push("#define MORPHTARGETS_NORMAL");
+ if (morphTargetManager.supportsTangents && useTangentMorph)
+ defines.push("#define MORPHTARGETS_TANGENT");
+ if (morphTargetManager.supportsUVs && useUVMorph)
+ defines.push("#define MORPHTARGETS_UV");
+ if (morphTargetManager.supportsUV2s && useUV2Morph)
+ defines.push("#define MORPHTARGETS_UV2");
+ if (morphTargetManager.supportsColors && useColorMorph)
+ defines.push("#define MORPHTARGETS_COLOR");
+ defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers);
+ if (morphTargetManager.isUsingTextureForTargets) {
+ defines.push("#define MORPHTARGETS_TEXTURE");
+ }
+ _TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = numMorphInfluencers;
+ _TmpMorphInfluencers.NORMAL = useNormalMorph;
+ _TmpMorphInfluencers.TANGENT = useTangentMorph;
+ _TmpMorphInfluencers.UV = useUVMorph;
+ _TmpMorphInfluencers.UV2 = useUV2Morph;
+ _TmpMorphInfluencers.COLOR = useColorMorph;
+ PrepareAttributesForMorphTargets(attribs, mesh, _TmpMorphInfluencers, usePositionMorph);
+ return numMorphInfluencers;
+}
+/**
+ * Prepares the list of attributes required for morph targets according to the effect defines.
+ * @param attribs The current list of supported attribs
+ * @param mesh The mesh to prepare the morph targets attributes for
+ * @param defines The current Defines of the effect
+ * @param usePositionMorph Whether the position morph target is used
+ */
+function PrepareAttributesForMorphTargets(attribs, mesh, defines, usePositionMorph = true) {
+ const influencers = defines["NUM_MORPH_INFLUENCERS"];
+ if (influencers > 0 && EngineStore.LastCreatedEngine) {
+ const maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;
+ const manager = mesh.morphTargetManager;
+ if (manager?.isUsingTextureForTargets) {
+ return;
+ }
+ const position = manager && manager.supportsPositions && usePositionMorph;
+ const normal = manager && manager.supportsNormals && defines["NORMAL"];
+ const tangent = manager && manager.supportsTangents && defines["TANGENT"];
+ const uv = manager && manager.supportsUVs && defines["UV1"];
+ const uv2 = manager && manager.supportsUV2s && defines["UV2"];
+ const color = manager && manager.supportsColors && defines["COLOR"];
+ for (let index = 0; index < influencers; index++) {
+ if (position) {
+ attribs.push(`position` + index);
+ }
+ if (normal) {
+ attribs.push(`normal` + index);
+ }
+ if (tangent) {
+ attribs.push(`tangent` + index);
+ }
+ if (uv) {
+ attribs.push(`uv` + "_" + index);
+ }
+ if (uv2) {
+ attribs.push(`uv2` + "_" + index);
+ }
+ if (color) {
+ attribs.push(`color` + index);
+ }
+ if (attribs.length > maxAttributesCount) {
+ Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name);
+ }
+ }
+ }
+}
+/**
+ * Add the list of attributes required for instances to the attribs array.
+ * @param attribs The current list of supported attribs
+ * @param needsPreviousMatrices If the shader needs previous matrices
+ */
+function PushAttributesForInstances(attribs, needsPreviousMatrices = false) {
+ attribs.push("world0");
+ attribs.push("world1");
+ attribs.push("world2");
+ attribs.push("world3");
+ if (needsPreviousMatrices) {
+ attribs.push("previousWorld0");
+ attribs.push("previousWorld1");
+ attribs.push("previousWorld2");
+ attribs.push("previousWorld3");
+ }
+}
+/**
+ * Binds the morph targets information from the mesh to the effect.
+ * @param abstractMesh The mesh we are binding the information to render
+ * @param effect The effect we are binding the data to
+ */
+function BindMorphTargetParameters(abstractMesh, effect) {
+ const manager = abstractMesh.morphTargetManager;
+ if (!abstractMesh || !manager) {
+ return;
+ }
+ effect.setFloatArray("morphTargetInfluences", manager.influences);
+}
+/**
+ * Binds the scene's uniform buffer to the effect.
+ * @param effect defines the effect to bind to the scene uniform buffer
+ * @param sceneUbo defines the uniform buffer storing scene data
+ */
+function BindSceneUniformBuffer(effect, sceneUbo) {
+ sceneUbo.bindToEffect(effect, "Scene");
+}
+/**
+ * Helps preparing the defines values about the UVs in used in the effect.
+ * UVs are shared as much as we can across channels in the shaders.
+ * @param texture The texture we are preparing the UVs for
+ * @param defines The defines to update
+ * @param key The channel key "diffuse", "specular"... used in the shader
+ */
+function PrepareDefinesForMergedUV(texture, defines, key) {
+ defines._needUVs = true;
+ defines[key] = true;
+ if (texture.optimizeUVAllocation && texture.getTextureMatrix().isIdentityAs3x2()) {
+ defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
+ defines["MAINUV" + (texture.coordinatesIndex + 1)] = true;
+ }
+ else {
+ defines[key + "DIRECTUV"] = 0;
+ }
+}
+/**
+ * Binds a texture matrix value to its corresponding uniform
+ * @param texture The texture to bind the matrix for
+ * @param uniformBuffer The uniform buffer receiving the data
+ * @param key The channel key "diffuse", "specular"... used in the shader
+ */
+function BindTextureMatrix(texture, uniformBuffer, key) {
+ const matrix = texture.getTextureMatrix();
+ uniformBuffer.updateMatrix(key + "Matrix", matrix);
+}
+/**
+ * Prepares the list of attributes required for baked vertex animations according to the effect defines.
+ * @param attribs The current list of supported attribs
+ * @param mesh The mesh to prepare for baked vertex animations
+ * @param defines The current Defines of the effect
+ */
+function PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) {
+ const enabled = defines["BAKED_VERTEX_ANIMATION_TEXTURE"] && defines["INSTANCES"];
+ if (enabled) {
+ attribs.push("bakedVertexAnimationSettingsInstanced");
+ }
+}
+// Copies the bones transformation matrices into the target array and returns the target's reference
+function _CopyBonesTransformationMatrices(source, target) {
+ target.set(source);
+ return target;
+}
+/**
+ * Binds the bones information from the mesh to the effect.
+ * @param mesh The mesh we are binding the information to render
+ * @param effect The effect we are binding the data to
+ * @param prePassConfiguration Configuration for the prepass, in case prepass is activated
+ */
+function BindBonesParameters(mesh, effect, prePassConfiguration) {
+ if (!effect || !mesh) {
+ return;
+ }
+ if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
+ mesh.computeBonesUsingShaders = false;
+ }
+ if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
+ const skeleton = mesh.skeleton;
+ if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
+ const boneTexture = skeleton.getTransformMatrixTexture(mesh);
+ effect.setTexture("boneSampler", boneTexture);
+ effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
+ }
+ else {
+ const matrices = skeleton.getTransformMatrices(mesh);
+ if (matrices) {
+ effect.setMatrices("mBones", matrices);
+ if (prePassConfiguration && mesh.getScene().prePassRenderer && mesh.getScene().prePassRenderer.getIndex(2)) {
+ if (!prePassConfiguration.previousBones[mesh.uniqueId]) {
+ prePassConfiguration.previousBones[mesh.uniqueId] = matrices.slice();
+ }
+ effect.setMatrices("mPreviousBones", prePassConfiguration.previousBones[mesh.uniqueId]);
+ _CopyBonesTransformationMatrices(matrices, prePassConfiguration.previousBones[mesh.uniqueId]);
+ }
+ }
+ }
+ }
+}
+/**
+ * Binds the lights information from the scene to the effect for the given mesh.
+ * @param light Light to bind
+ * @param lightIndex Light index
+ * @param scene The scene where the light belongs to
+ * @param effect The effect we are binding the data to
+ * @param useSpecular Defines if specular is supported
+ * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows
+ */
+function BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) {
+ light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows);
+}
+/**
+ * Binds the lights information from the scene to the effect for the given mesh.
+ * @param scene The scene the lights belongs to
+ * @param mesh The mesh we are binding the information to render
+ * @param effect The effect we are binding the data to
+ * @param defines The generated defines for the effect
+ * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
+ */
+function BindLights(scene, mesh, effect, defines, maxSimultaneousLights = 4) {
+ const len = Math.min(mesh.lightSources.length, maxSimultaneousLights);
+ for (let i = 0; i < len; i++) {
+ const light = mesh.lightSources[i];
+ BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], mesh.receiveShadows);
+ }
+}
+/**
+ * Prepares the list of attributes required for bones according to the effect defines.
+ * @param attribs The current list of supported attribs
+ * @param mesh The mesh to prepare the bones attributes for
+ * @param defines The current Defines of the effect
+ * @param fallbacks The current effect fallback strategy
+ */
+function PrepareAttributesForBones(attribs, mesh, defines, fallbacks) {
+ if (defines["NUM_BONE_INFLUENCERS"] > 0) {
+ fallbacks.addCPUSkinningFallback(0, mesh);
+ attribs.push(`matricesIndices`);
+ attribs.push(`matricesWeights`);
+ if (defines["NUM_BONE_INFLUENCERS"] > 4) {
+ attribs.push(`matricesIndicesExtra`);
+ attribs.push(`matricesWeightsExtra`);
+ }
+ }
+}
+/**
+ * Check and prepare the list of attributes required for instances according to the effect defines.
+ * @param attribs The current list of supported attribs
+ * @param defines The current MaterialDefines of the effect
+ */
+function PrepareAttributesForInstances(attribs, defines) {
+ if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) {
+ PushAttributesForInstances(attribs, !!defines["PREPASS_VELOCITY"]);
+ }
+ if (defines.INSTANCESCOLOR) {
+ attribs.push(`instanceColor`);
+ }
+}
+/**
+ * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
+ * @param defines The defines to update while falling back
+ * @param fallbacks The authorized effect fallbacks
+ * @param maxSimultaneousLights The maximum number of lights allowed
+ * @param rank the current rank of the Effect
+ * @returns The newly affected rank
+ */
+function HandleFallbacksForShadows(defines, fallbacks, maxSimultaneousLights = 4, rank = 0) {
+ let lightFallbackRank = 0;
+ for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
+ if (!defines["LIGHT" + lightIndex]) {
+ break;
+ }
+ if (lightIndex > 0) {
+ lightFallbackRank = rank + lightIndex;
+ fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
+ }
+ if (!defines["SHADOWS"]) {
+ if (defines["SHADOW" + lightIndex]) {
+ fallbacks.addFallback(rank, "SHADOW" + lightIndex);
+ }
+ if (defines["SHADOWPCF" + lightIndex]) {
+ fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
+ }
+ if (defines["SHADOWPCSS" + lightIndex]) {
+ fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
+ }
+ if (defines["SHADOWPOISSON" + lightIndex]) {
+ fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
+ }
+ if (defines["SHADOWESM" + lightIndex]) {
+ fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
+ }
+ if (defines["SHADOWCLOSEESM" + lightIndex]) {
+ fallbacks.addFallback(rank, "SHADOWCLOSEESM" + lightIndex);
+ }
+ }
+ }
+ return lightFallbackRank++;
+}
+/**
+ * Gets the current status of the fog (should it be enabled?)
+ * @param mesh defines the mesh to evaluate for fog support
+ * @param scene defines the hosting scene
+ * @returns true if fog must be enabled
+ */
+function GetFogState(mesh, scene) {
+ return scene.fogEnabled && mesh.applyFog && scene.fogMode !== 0;
+}
+/**
+ * Helper used to prepare the list of defines associated with misc. values for shader compilation
+ * @param mesh defines the current mesh
+ * @param scene defines the current scene
+ * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
+ * @param pointsCloud defines if point cloud rendering has to be turned on
+ * @param fogEnabled defines if fog has to be turned on
+ * @param alphaTest defines if alpha testing has to be turned on
+ * @param defines defines the current list of defines
+ * @param applyDecalAfterDetail Defines if the decal is applied after or before the detail
+ */
+function PrepareDefinesForMisc(mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines, applyDecalAfterDetail = false) {
+ if (defines._areMiscDirty) {
+ defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
+ defines["POINTSIZE"] = pointsCloud;
+ defines["FOG"] = fogEnabled && GetFogState(mesh, scene);
+ defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
+ defines["ALPHATEST"] = alphaTest;
+ defines["DECAL_AFTER_DETAIL"] = applyDecalAfterDetail;
+ }
+}
+/**
+ * Prepares the defines related to the light information passed in parameter
+ * @param scene The scene we are intending to draw
+ * @param mesh The mesh the effect is compiling for
+ * @param defines The defines to update
+ * @param specularSupported Specifies whether specular is supported or not (override lights data)
+ * @param maxSimultaneousLights Specifies how manuy lights can be added to the effect at max
+ * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
+ * @returns true if normals will be required for the rest of the effect
+ */
+function PrepareDefinesForLights(scene, mesh, defines, specularSupported, maxSimultaneousLights = 4, disableLighting = false) {
+ if (!defines._areLightsDirty) {
+ return defines._needNormals;
+ }
+ let lightIndex = 0;
+ const state = {
+ needNormals: defines._needNormals, // prevents overriding previous reflection or other needs for normals
+ needRebuild: false,
+ lightmapMode: false,
+ shadowEnabled: false,
+ specularEnabled: false,
+ };
+ if (scene.lightsEnabled && !disableLighting) {
+ for (const light of mesh.lightSources) {
+ PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);
+ lightIndex++;
+ if (lightIndex === maxSimultaneousLights) {
+ break;
+ }
+ }
+ }
+ defines["SPECULARTERM"] = state.specularEnabled;
+ defines["SHADOWS"] = state.shadowEnabled;
+ // Resetting all other lights if any
+ for (let index = lightIndex; index < maxSimultaneousLights; index++) {
+ if (defines["LIGHT" + index] !== undefined) {
+ defines["LIGHT" + index] = false;
+ defines["HEMILIGHT" + index] = false;
+ defines["POINTLIGHT" + index] = false;
+ defines["DIRLIGHT" + index] = false;
+ defines["SPOTLIGHT" + index] = false;
+ defines["AREALIGHT" + index] = false;
+ defines["SHADOW" + index] = false;
+ defines["SHADOWCSM" + index] = false;
+ defines["SHADOWCSMDEBUG" + index] = false;
+ defines["SHADOWCSMNUM_CASCADES" + index] = false;
+ defines["SHADOWCSMUSESHADOWMAXZ" + index] = false;
+ defines["SHADOWCSMNOBLEND" + index] = false;
+ defines["SHADOWCSM_RIGHTHANDED" + index] = false;
+ defines["SHADOWPCF" + index] = false;
+ defines["SHADOWPCSS" + index] = false;
+ defines["SHADOWPOISSON" + index] = false;
+ defines["SHADOWESM" + index] = false;
+ defines["SHADOWCLOSEESM" + index] = false;
+ defines["SHADOWCUBE" + index] = false;
+ defines["SHADOWLOWQUALITY" + index] = false;
+ defines["SHADOWMEDIUMQUALITY" + index] = false;
+ }
+ }
+ const caps = scene.getEngine().getCaps();
+ if (defines["SHADOWFLOAT"] === undefined) {
+ state.needRebuild = true;
+ }
+ defines["SHADOWFLOAT"] =
+ state.shadowEnabled && ((caps.textureFloatRender && caps.textureFloatLinearFiltering) || (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
+ defines["LIGHTMAPEXCLUDED"] = state.lightmapMode;
+ if (state.needRebuild) {
+ defines.rebuild();
+ }
+ return state.needNormals;
+}
+/**
+ * Prepares the defines related to the light information passed in parameter
+ * @param scene The scene we are intending to draw
+ * @param mesh The mesh the effect is compiling for
+ * @param light The light the effect is compiling for
+ * @param lightIndex The index of the light
+ * @param defines The defines to update
+ * @param specularSupported Specifies whether specular is supported or not (override lights data)
+ * @param state Defines the current state regarding what is needed (normals, etc...)
+ * @param state.needNormals
+ * @param state.needRebuild
+ * @param state.shadowEnabled
+ * @param state.specularEnabled
+ * @param state.lightmapMode
+ */
+function PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state) {
+ state.needNormals = true;
+ if (defines["LIGHT" + lightIndex] === undefined) {
+ state.needRebuild = true;
+ }
+ defines["LIGHT" + lightIndex] = true;
+ defines["SPOTLIGHT" + lightIndex] = false;
+ defines["HEMILIGHT" + lightIndex] = false;
+ defines["POINTLIGHT" + lightIndex] = false;
+ defines["DIRLIGHT" + lightIndex] = false;
+ defines["AREALIGHT" + lightIndex] = false;
+ light.prepareLightSpecificDefines(defines, lightIndex);
+ // FallOff.
+ defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
+ defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
+ defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
+ switch (light.falloffType) {
+ case LightConstants.FALLOFF_GLTF:
+ defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
+ break;
+ case LightConstants.FALLOFF_PHYSICAL:
+ defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
+ break;
+ case LightConstants.FALLOFF_STANDARD:
+ defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
+ break;
+ }
+ // Specular
+ if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
+ state.specularEnabled = true;
+ }
+ // Shadows
+ defines["SHADOW" + lightIndex] = false;
+ defines["SHADOWCSM" + lightIndex] = false;
+ defines["SHADOWCSMDEBUG" + lightIndex] = false;
+ defines["SHADOWCSMNUM_CASCADES" + lightIndex] = false;
+ defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = false;
+ defines["SHADOWCSMNOBLEND" + lightIndex] = false;
+ defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = false;
+ defines["SHADOWPCF" + lightIndex] = false;
+ defines["SHADOWPCSS" + lightIndex] = false;
+ defines["SHADOWPOISSON" + lightIndex] = false;
+ defines["SHADOWESM" + lightIndex] = false;
+ defines["SHADOWCLOSEESM" + lightIndex] = false;
+ defines["SHADOWCUBE" + lightIndex] = false;
+ defines["SHADOWLOWQUALITY" + lightIndex] = false;
+ defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
+ if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
+ const shadowGenerator = light.getShadowGenerator(scene.activeCamera) ?? light.getShadowGenerator();
+ if (shadowGenerator) {
+ const shadowMap = shadowGenerator.getShadowMap();
+ if (shadowMap) {
+ if (shadowMap.renderList && shadowMap.renderList.length > 0) {
+ state.shadowEnabled = true;
+ shadowGenerator.prepareDefines(defines, lightIndex);
+ }
+ }
+ }
+ }
+ if (light.lightmapMode != LightConstants.LIGHTMAP_DEFAULT) {
+ state.lightmapMode = true;
+ defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
+ defines["LIGHTMAPNOSPECULAR" + lightIndex] = light.lightmapMode == LightConstants.LIGHTMAP_SHADOWSONLY;
+ }
+ else {
+ defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
+ defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
+ }
+}
+/**
+ * Helper used to prepare the list of defines associated with frame values for shader compilation
+ * @param scene defines the current scene
+ * @param engine defines the current engine
+ * @param material defines the material we are compiling the shader for
+ * @param defines specifies the list of active defines
+ * @param useInstances defines if instances have to be turned on
+ * @param useClipPlane defines if clip plane have to be turned on
+ * @param useThinInstances defines if thin instances have to be turned on
+ */
+function PrepareDefinesForFrameBoundValues(scene, engine, material, defines, useInstances, useClipPlane = null, useThinInstances = false) {
+ let changed = PrepareDefinesForCamera(scene, defines);
+ if (useClipPlane !== false) {
+ changed = prepareDefinesForClipPlanes(material, scene, defines);
+ }
+ if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
+ defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
+ changed = true;
+ }
+ if (defines["INSTANCES"] !== useInstances) {
+ defines["INSTANCES"] = useInstances;
+ changed = true;
+ }
+ if (defines["THIN_INSTANCES"] !== useThinInstances) {
+ defines["THIN_INSTANCES"] = useThinInstances;
+ changed = true;
+ }
+ if (changed) {
+ defines.markAsUnprocessed();
+ }
+}
+/**
+ * Prepares the defines for bones
+ * @param mesh The mesh containing the geometry data we will draw
+ * @param defines The defines to update
+ */
+function PrepareDefinesForBones(mesh, defines) {
+ if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
+ defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
+ const materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
+ if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
+ defines["BONETEXTURE"] = true;
+ }
+ else {
+ defines["BonesPerMesh"] = mesh.skeleton.bones.length + 1;
+ defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
+ const prePassRenderer = mesh.getScene().prePassRenderer;
+ if (prePassRenderer && prePassRenderer.enabled) {
+ const nonExcluded = prePassRenderer.excludedSkinnedMesh.indexOf(mesh) === -1;
+ defines["BONES_VELOCITY_ENABLED"] = nonExcluded;
+ }
+ }
+ }
+ else {
+ defines["NUM_BONE_INFLUENCERS"] = 0;
+ defines["BonesPerMesh"] = 0;
+ if (defines["BONETEXTURE"] !== undefined) {
+ defines["BONETEXTURE"] = false;
+ }
+ }
+}
+/**
+ * Prepares the defines for morph targets
+ * @param mesh The mesh containing the geometry data we will draw
+ * @param defines The defines to update
+ */
+function PrepareDefinesForMorphTargets(mesh, defines) {
+ const manager = mesh.morphTargetManager;
+ if (manager) {
+ defines["MORPHTARGETS_UV"] = manager.supportsUVs && defines["UV1"];
+ defines["MORPHTARGETS_UV2"] = manager.supportsUV2s && defines["UV2"];
+ defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
+ defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
+ defines["MORPHTARGETS_POSITION"] = manager.supportsPositions;
+ defines["MORPHTARGETS_COLOR"] = manager.supportsColors;
+ defines["MORPHTARGETTEXTURE_HASUVS"] = manager.hasUVs;
+ defines["MORPHTARGETTEXTURE_HASUV2S"] = manager.hasUV2s;
+ defines["MORPHTARGETTEXTURE_HASTANGENTS"] = manager.hasTangents;
+ defines["MORPHTARGETTEXTURE_HASNORMALS"] = manager.hasNormals;
+ defines["MORPHTARGETTEXTURE_HASPOSITIONS"] = manager.hasPositions;
+ defines["MORPHTARGETTEXTURE_HASCOLORS"] = manager.hasColors;
+ defines["NUM_MORPH_INFLUENCERS"] = manager.numMaxInfluencers || manager.numInfluencers;
+ defines["MORPHTARGETS"] = defines["NUM_MORPH_INFLUENCERS"] > 0;
+ defines["MORPHTARGETS_TEXTURE"] = manager.isUsingTextureForTargets;
+ }
+ else {
+ defines["MORPHTARGETS_UV"] = false;
+ defines["MORPHTARGETS_UV2"] = false;
+ defines["MORPHTARGETS_TANGENT"] = false;
+ defines["MORPHTARGETS_NORMAL"] = false;
+ defines["MORPHTARGETS_POSITION"] = false;
+ defines["MORPHTARGETS_COLOR"] = false;
+ defines["MORPHTARGETTEXTURE_HASUVS"] = false;
+ defines["MORPHTARGETTEXTURE_HASUV2S"] = false;
+ defines["MORPHTARGETTEXTURE_HASTANGENTS"] = false;
+ defines["MORPHTARGETTEXTURE_HASNORMALS"] = false;
+ defines["MORPHTARGETTEXTURE_HASPOSITIONS"] = false;
+ defines["MORPHTARGETTEXTURE_HAS_COLORS"] = false;
+ defines["MORPHTARGETS"] = false;
+ defines["NUM_MORPH_INFLUENCERS"] = 0;
+ }
+}
+/**
+ * Prepares the defines for baked vertex animation
+ * @param mesh The mesh containing the geometry data we will draw
+ * @param defines The defines to update
+ */
+function PrepareDefinesForBakedVertexAnimation(mesh, defines) {
+ const manager = mesh.bakedVertexAnimationManager;
+ defines["BAKED_VERTEX_ANIMATION_TEXTURE"] = manager && manager.isEnabled ? true : false;
+}
+/**
+ * Prepares the defines used in the shader depending on the attributes data available in the mesh
+ * @param mesh The mesh containing the geometry data we will draw
+ * @param defines The defines to update
+ * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
+ * @param useBones Precise whether bones should be used or not (override mesh info)
+ * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
+ * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
+ * @param useBakedVertexAnimation Precise whether baked vertex animation should be used or not (override mesh info)
+ * @returns false if defines are considered not dirty and have not been checked
+ */
+function PrepareDefinesForAttributes(mesh, defines, useVertexColor, useBones, useMorphTargets = false, useVertexAlpha = true, useBakedVertexAnimation = true) {
+ if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
+ return false;
+ }
+ defines._normals = defines._needNormals;
+ defines._uvs = defines._needUVs;
+ defines["NORMAL"] = defines._needNormals && mesh.isVerticesDataPresent(`normal`);
+ if (defines._needNormals && mesh.isVerticesDataPresent(`tangent`)) {
+ defines["TANGENT"] = true;
+ }
+ for (let i = 1; i <= 6; ++i) {
+ defines["UV" + i] = defines._needUVs ? mesh.isVerticesDataPresent(`uv${i === 1 ? "" : i}`) : false;
+ }
+ if (useVertexColor) {
+ const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(`color`);
+ defines["VERTEXCOLOR"] = hasVertexColors;
+ defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
+ }
+ if (mesh.isVerticesDataPresent(`instanceColor`) && (mesh.hasInstances || mesh.hasThinInstances)) {
+ defines["INSTANCESCOLOR"] = true;
+ }
+ if (useBones) {
+ PrepareDefinesForBones(mesh, defines);
+ }
+ if (useMorphTargets) {
+ PrepareDefinesForMorphTargets(mesh, defines);
+ }
+ if (useBakedVertexAnimation) {
+ PrepareDefinesForBakedVertexAnimation(mesh, defines);
+ }
+ return true;
+}
+/**
+ * Prepares the defines related to multiview
+ * @param scene The scene we are intending to draw
+ * @param defines The defines to update
+ */
+function PrepareDefinesForMultiview(scene, defines) {
+ if (scene.activeCamera) {
+ const previousMultiview = defines.MULTIVIEW;
+ defines.MULTIVIEW = scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1;
+ if (defines.MULTIVIEW != previousMultiview) {
+ defines.markAsUnprocessed();
+ }
+ }
+}
+/**
+ * Prepares the defines related to order independant transparency
+ * @param scene The scene we are intending to draw
+ * @param defines The defines to update
+ * @param needAlphaBlending Determines if the material needs alpha blending
+ */
+function PrepareDefinesForOIT(scene, defines, needAlphaBlending) {
+ const previousDefine = defines.ORDER_INDEPENDENT_TRANSPARENCY;
+ const previousDefine16Bits = defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;
+ defines.ORDER_INDEPENDENT_TRANSPARENCY = scene.useOrderIndependentTransparency && needAlphaBlending;
+ defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !scene.getEngine().getCaps().textureFloatLinearFiltering;
+ if (previousDefine !== defines.ORDER_INDEPENDENT_TRANSPARENCY || previousDefine16Bits !== defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) {
+ defines.markAsUnprocessed();
+ }
+}
+/**
+ * Prepares the defines related to the prepass
+ * @param scene The scene we are intending to draw
+ * @param defines The defines to update
+ * @param canRenderToMRT Indicates if this material renders to several textures in the prepass
+ */
+function PrepareDefinesForPrePass(scene, defines, canRenderToMRT) {
+ const previousPrePass = defines.PREPASS;
+ if (!defines._arePrePassDirty) {
+ return;
+ }
+ const texturesList = [
+ {
+ type: 1,
+ define: "PREPASS_POSITION",
+ index: "PREPASS_POSITION_INDEX",
+ },
+ {
+ type: 9,
+ define: "PREPASS_LOCAL_POSITION",
+ index: "PREPASS_LOCAL_POSITION_INDEX",
+ },
+ {
+ type: 2,
+ define: "PREPASS_VELOCITY",
+ index: "PREPASS_VELOCITY_INDEX",
+ },
+ {
+ type: 11,
+ define: "PREPASS_VELOCITY_LINEAR",
+ index: "PREPASS_VELOCITY_LINEAR_INDEX",
+ },
+ {
+ type: 3,
+ define: "PREPASS_REFLECTIVITY",
+ index: "PREPASS_REFLECTIVITY_INDEX",
+ },
+ {
+ type: 0,
+ define: "PREPASS_IRRADIANCE",
+ index: "PREPASS_IRRADIANCE_INDEX",
+ },
+ {
+ type: 7,
+ define: "PREPASS_ALBEDO_SQRT",
+ index: "PREPASS_ALBEDO_SQRT_INDEX",
+ },
+ {
+ type: 5,
+ define: "PREPASS_DEPTH",
+ index: "PREPASS_DEPTH_INDEX",
+ },
+ {
+ type: 10,
+ define: "PREPASS_SCREENSPACE_DEPTH",
+ index: "PREPASS_SCREENSPACE_DEPTH_INDEX",
+ },
+ {
+ type: 6,
+ define: "PREPASS_NORMAL",
+ index: "PREPASS_NORMAL_INDEX",
+ },
+ {
+ type: 8,
+ define: "PREPASS_WORLD_NORMAL",
+ index: "PREPASS_WORLD_NORMAL_INDEX",
+ },
+ ];
+ if (scene.prePassRenderer && scene.prePassRenderer.enabled && canRenderToMRT) {
+ defines.PREPASS = true;
+ defines.SCENE_MRT_COUNT = scene.prePassRenderer.mrtCount;
+ defines.PREPASS_NORMAL_WORLDSPACE = scene.prePassRenderer.generateNormalsInWorldSpace;
+ defines.PREPASS_COLOR = true;
+ defines.PREPASS_COLOR_INDEX = 0;
+ for (let i = 0; i < texturesList.length; i++) {
+ const index = scene.prePassRenderer.getIndex(texturesList[i].type);
+ if (index !== -1) {
+ defines[texturesList[i].define] = true;
+ defines[texturesList[i].index] = index;
+ }
+ else {
+ defines[texturesList[i].define] = false;
+ }
+ }
+ }
+ else {
+ defines.PREPASS = false;
+ for (let i = 0; i < texturesList.length; i++) {
+ defines[texturesList[i].define] = false;
+ }
+ }
+ if (defines.PREPASS != previousPrePass) {
+ defines.markAsUnprocessed();
+ defines.markAsImageProcessingDirty();
+ }
+}
+/**
+ * Helper used to prepare the defines relative to the active camera
+ * @param scene defines the current scene
+ * @param defines specifies the list of active defines
+ * @returns true if the defines have been updated, else false
+ */
+function PrepareDefinesForCamera(scene, defines) {
+ let changed = false;
+ if (scene.activeCamera) {
+ const wasOrtho = defines["CAMERA_ORTHOGRAPHIC"] ? 1 : 0;
+ const wasPersp = defines["CAMERA_PERSPECTIVE"] ? 1 : 0;
+ const isOrtho = scene.activeCamera.mode === 1 ? 1 : 0;
+ const isPersp = scene.activeCamera.mode === 0 ? 1 : 0;
+ if (wasOrtho ^ isOrtho || wasPersp ^ isPersp) {
+ defines["CAMERA_ORTHOGRAPHIC"] = isOrtho === 1;
+ defines["CAMERA_PERSPECTIVE"] = isPersp === 1;
+ changed = true;
+ }
+ }
+ return changed;
+}
+/**
+ * Prepares the uniforms and samplers list to be used in the effect (for a specific light)
+ * @param lightIndex defines the light index
+ * @param uniformsList The uniform list
+ * @param samplersList The sampler list
+ * @param projectedLightTexture defines if projected texture must be used
+ * @param uniformBuffersList defines an optional list of uniform buffers
+ * @param updateOnlyBuffersList True to only update the uniformBuffersList array
+ * @param iesLightTexture defines if IES texture must be used
+ */
+function PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, projectedLightTexture, uniformBuffersList = null, updateOnlyBuffersList = false, iesLightTexture = false) {
+ if (uniformBuffersList) {
+ uniformBuffersList.push("Light" + lightIndex);
+ }
+ if (updateOnlyBuffersList) {
+ return;
+ }
+ uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightWidth" + lightIndex, "vLightHeight" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
+ samplersList.push("shadowTexture" + lightIndex);
+ samplersList.push("depthTexture" + lightIndex);
+ uniformsList.push("viewFrustumZ" + lightIndex, "cascadeBlendFactor" + lightIndex, "lightSizeUVCorrection" + lightIndex, "depthCorrection" + lightIndex, "penumbraDarkness" + lightIndex, "frustumLengths" + lightIndex);
+ if (projectedLightTexture) {
+ samplersList.push("projectionLightTexture" + lightIndex);
+ uniformsList.push("textureProjectionMatrix" + lightIndex);
+ }
+ if (iesLightTexture) {
+ samplersList.push("iesLightTexture" + lightIndex);
+ }
+}
+/**
+ * Prepares the uniforms and samplers list to be used in the effect
+ * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the list and extra information
+ * @param samplersList The sampler list
+ * @param defines The defines helping in the list generation
+ * @param maxSimultaneousLights The maximum number of simultaneous light allowed in the effect
+ */
+function PrepareUniformsAndSamplersList(uniformsListOrOptions, samplersList, defines, maxSimultaneousLights = 4) {
+ let uniformsList;
+ let uniformBuffersList;
+ if (uniformsListOrOptions.uniformsNames) {
+ const options = uniformsListOrOptions;
+ uniformsList = options.uniformsNames;
+ uniformBuffersList = options.uniformBuffersNames;
+ samplersList = options.samplers;
+ defines = options.defines;
+ maxSimultaneousLights = options.maxSimultaneousLights || 0;
+ }
+ else {
+ uniformsList = uniformsListOrOptions;
+ if (!samplersList) {
+ samplersList = [];
+ }
+ }
+ for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
+ if (!defines["LIGHT" + lightIndex]) {
+ break;
+ }
+ PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList, false, defines["IESLIGHTTEXTURE" + lightIndex]);
+ }
+ if (defines["NUM_MORPH_INFLUENCERS"]) {
+ uniformsList.push("morphTargetInfluences");
+ uniformsList.push("morphTargetCount");
+ }
+ if (defines["BAKED_VERTEX_ANIMATION_TEXTURE"]) {
+ uniformsList.push("bakedVertexAnimationSettings");
+ uniformsList.push("bakedVertexAnimationTextureSizeInverted");
+ uniformsList.push("bakedVertexAnimationTime");
+ samplersList.push("bakedVertexAnimationTexture");
+ }
+}
+
+/**
+ * Base class for the main features of a material in Babylon.js
+ */
+class Material {
+ /** @internal */
+ get _supportGlowLayer() {
+ return false;
+ }
+ /** @internal */
+ set _glowModeEnabled(value) {
+ // Do nothing here
+ }
+ /**
+ * Gets the shader language used in this material.
+ */
+ get shaderLanguage() {
+ return this._shaderLanguage;
+ }
+ /**
+ * If the material can be rendered to several textures with MRT extension
+ */
+ get canRenderToMRT() {
+ // By default, shaders are not compatible with MRTs
+ // Base classes should override that if their shader supports MRT
+ return false;
+ }
+ /**
+ * Sets the alpha value of the material
+ */
+ set alpha(value) {
+ if (this._alpha === value) {
+ return;
+ }
+ const oldValue = this._alpha;
+ this._alpha = value;
+ // Only call dirty when there is a state change (no alpha / alpha)
+ if (oldValue === 1 || value === 1) {
+ this.markAsDirty(Material.MiscDirtyFlag + Material.PrePassDirtyFlag);
+ }
+ }
+ /**
+ * Gets the alpha value of the material
+ */
+ get alpha() {
+ return this._alpha;
+ }
+ /**
+ * Sets the culling state (true to enable culling, false to disable)
+ */
+ set backFaceCulling(value) {
+ if (this._backFaceCulling === value) {
+ return;
+ }
+ this._backFaceCulling = value;
+ this.markAsDirty(Material.TextureDirtyFlag);
+ }
+ /**
+ * Gets the culling state
+ */
+ get backFaceCulling() {
+ return this._backFaceCulling;
+ }
+ /**
+ * Sets the type of faces that should be culled (true for back faces, false for front faces)
+ */
+ set cullBackFaces(value) {
+ if (this._cullBackFaces === value) {
+ return;
+ }
+ this._cullBackFaces = value;
+ this.markAsDirty(Material.TextureDirtyFlag);
+ }
+ /**
+ * Gets the type of faces that should be culled
+ */
+ get cullBackFaces() {
+ return this._cullBackFaces;
+ }
+ /**
+ * Block the dirty-mechanism for this specific material
+ * When set to false after being true the material will be marked as dirty.
+ */
+ get blockDirtyMechanism() {
+ return this._blockDirtyMechanism;
+ }
+ set blockDirtyMechanism(value) {
+ if (this._blockDirtyMechanism === value) {
+ return;
+ }
+ this._blockDirtyMechanism = value;
+ if (!value) {
+ this.markDirty();
+ }
+ }
+ /**
+ * This allows you to modify the material without marking it as dirty after every change.
+ * This function should be used if you need to make more than one dirty-enabling change to the material - adding a texture, setting a new fill mode and so on.
+ * The callback will pass the material as an argument, so you can make your changes to it.
+ * @param callback the callback to be executed that will update the material
+ */
+ atomicMaterialsUpdate(callback) {
+ this.blockDirtyMechanism = true;
+ try {
+ callback(this);
+ }
+ finally {
+ this.blockDirtyMechanism = false;
+ }
+ }
+ /**
+ * Gets a boolean indicating that current material needs to register RTT
+ */
+ get hasRenderTargetTextures() {
+ this._eventInfo.hasRenderTargetTextures = false;
+ this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);
+ return this._eventInfo.hasRenderTargetTextures;
+ }
+ /**
+ * Called during a dispose event
+ */
+ set onDispose(callback) {
+ if (this._onDisposeObserver) {
+ this.onDisposeObservable.remove(this._onDisposeObserver);
+ }
+ this._onDisposeObserver = this.onDisposeObservable.add(callback);
+ }
+ /**
+ * An event triggered when the material is bound
+ */
+ get onBindObservable() {
+ if (!this._onBindObservable) {
+ this._onBindObservable = new Observable();
+ }
+ return this._onBindObservable;
+ }
+ /**
+ * Called during a bind event
+ */
+ set onBind(callback) {
+ if (this._onBindObserver) {
+ this.onBindObservable.remove(this._onBindObserver);
+ }
+ this._onBindObserver = this.onBindObservable.add(callback);
+ }
+ /**
+ * An event triggered when the material is unbound
+ */
+ get onUnBindObservable() {
+ if (!this._onUnBindObservable) {
+ this._onUnBindObservable = new Observable();
+ }
+ return this._onUnBindObservable;
+ }
+ /**
+ * An event triggered when the effect is (re)created
+ */
+ get onEffectCreatedObservable() {
+ if (!this._onEffectCreatedObservable) {
+ this._onEffectCreatedObservable = new Observable();
+ }
+ return this._onEffectCreatedObservable;
+ }
+ /**
+ * Sets the value of the alpha mode.
+ *
+ * | Value | Type | Description |
+ * | --- | --- | --- |
+ * | 0 | ALPHA_DISABLE | |
+ * | 1 | ALPHA_ADD | |
+ * | 2 | ALPHA_COMBINE | |
+ * | 3 | ALPHA_SUBTRACT | |
+ * | 4 | ALPHA_MULTIPLY | |
+ * | 5 | ALPHA_MAXIMIZED | |
+ * | 6 | ALPHA_ONEONE | |
+ * | 7 | ALPHA_PREMULTIPLIED | |
+ * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
+ * | 9 | ALPHA_INTERPOLATE | |
+ * | 10 | ALPHA_SCREENMODE | |
+ *
+ */
+ set alphaMode(value) {
+ if (this._alphaMode === value) {
+ return;
+ }
+ this._alphaMode = value;
+ this.markAsDirty(Material.TextureDirtyFlag);
+ }
+ /**
+ * Gets the value of the alpha mode
+ */
+ get alphaMode() {
+ return this._alphaMode;
+ }
+ /**
+ * Sets the need depth pre-pass value
+ */
+ set needDepthPrePass(value) {
+ if (this._needDepthPrePass === value) {
+ return;
+ }
+ this._needDepthPrePass = value;
+ if (this._needDepthPrePass) {
+ this.checkReadyOnEveryCall = true;
+ }
+ }
+ /**
+ * Gets the depth pre-pass value
+ */
+ get needDepthPrePass() {
+ return this._needDepthPrePass;
+ }
+ /**
+ * Can this material render to prepass
+ */
+ get isPrePassCapable() {
+ return false;
+ }
+ /**
+ * Sets the state for enabling fog
+ */
+ set fogEnabled(value) {
+ if (this._fogEnabled === value) {
+ return;
+ }
+ this._fogEnabled = value;
+ this.markAsDirty(Material.MiscDirtyFlag);
+ }
+ /**
+ * Gets the value of the fog enabled state
+ */
+ get fogEnabled() {
+ return this._fogEnabled;
+ }
+ get wireframe() {
+ switch (this._fillMode) {
+ case Material.WireFrameFillMode:
+ case Material.LineListDrawMode:
+ case Material.LineLoopDrawMode:
+ case Material.LineStripDrawMode:
+ return true;
+ }
+ return this._scene.forceWireframe;
+ }
+ /**
+ * Sets the state of wireframe mode
+ */
+ set wireframe(value) {
+ this.fillMode = value ? Material.WireFrameFillMode : Material.TriangleFillMode;
+ }
+ /**
+ * Gets the value specifying if point clouds are enabled
+ */
+ get pointsCloud() {
+ switch (this._fillMode) {
+ case Material.PointFillMode:
+ case Material.PointListDrawMode:
+ return true;
+ }
+ return this._scene.forcePointsCloud;
+ }
+ /**
+ * Sets the state of point cloud mode
+ */
+ set pointsCloud(value) {
+ this.fillMode = value ? Material.PointFillMode : Material.TriangleFillMode;
+ }
+ /**
+ * Gets the material fill mode
+ */
+ get fillMode() {
+ return this._fillMode;
+ }
+ /**
+ * Sets the material fill mode
+ */
+ set fillMode(value) {
+ if (this._fillMode === value) {
+ return;
+ }
+ this._fillMode = value;
+ this.markAsDirty(Material.MiscDirtyFlag);
+ }
+ /**
+ * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
+ * You can try switching to logarithmic depth.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/logarithmicDepthBuffer
+ */
+ get useLogarithmicDepth() {
+ return this._useLogarithmicDepth;
+ }
+ set useLogarithmicDepth(value) {
+ const fragmentDepthSupported = this.getScene().getEngine().getCaps().fragmentDepthSupported;
+ if (value && !fragmentDepthSupported) {
+ Logger.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it.");
+ }
+ this._useLogarithmicDepth = value && fragmentDepthSupported;
+ this._markAllSubMeshesAsMiscDirty();
+ }
+ /** @internal */
+ _getDrawWrapper() {
+ return this._drawWrapper;
+ }
+ /**
+ * @internal
+ */
+ _setDrawWrapper(drawWrapper) {
+ this._drawWrapper = drawWrapper;
+ }
+ /**
+ * Creates a material instance
+ * @param name defines the name of the material
+ * @param scene defines the scene to reference
+ * @param doNotAdd specifies if the material should be added to the scene
+ * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false
+ */
+ constructor(name, scene, doNotAdd, forceGLSL = false) {
+ /**
+ * Custom shadow depth material to use for shadow rendering instead of the in-built one
+ */
+ this.shadowDepthWrapper = null;
+ /**
+ * Gets or sets a boolean indicating that the material is allowed (if supported) to do shader hot swapping.
+ * This means that the material can keep using a previous shader while a new one is being compiled.
+ * This is mostly used when shader parallel compilation is supported (true by default)
+ */
+ this.allowShaderHotSwapping = true;
+ /** Shader language used by the material */
+ this._shaderLanguage = 0 /* ShaderLanguage.GLSL */;
+ this._forceGLSL = false;
+ /**
+ * Gets or sets user defined metadata
+ */
+ this.metadata = null;
+ /**
+ * For internal use only. Please do not use.
+ */
+ this.reservedDataStore = null;
+ /**
+ * Specifies if the ready state should be checked on each call
+ */
+ this.checkReadyOnEveryCall = false;
+ /**
+ * Specifies if the ready state should be checked once
+ */
+ this.checkReadyOnlyOnce = false;
+ /**
+ * The state of the material
+ */
+ this.state = "";
+ /**
+ * The alpha value of the material
+ */
+ this._alpha = 1.0;
+ /**
+ * Specifies if back face culling is enabled
+ */
+ this._backFaceCulling = true;
+ /**
+ * Specifies if back or front faces should be culled (when culling is enabled)
+ */
+ this._cullBackFaces = true;
+ this._blockDirtyMechanism = false;
+ /**
+ * Stores the value for side orientation
+ */
+ this.sideOrientation = null;
+ /**
+ * Callback triggered when the material is compiled
+ */
+ this.onCompiled = null;
+ /**
+ * Callback triggered when an error occurs
+ */
+ this.onError = null;
+ /**
+ * Callback triggered to get the render target textures
+ */
+ this.getRenderTargetTextures = null;
+ /**
+ * Specifies if the material should be serialized
+ */
+ this.doNotSerialize = false;
+ /**
+ * @internal
+ */
+ this._storeEffectOnSubMeshes = false;
+ /**
+ * Stores the animations for the material
+ */
+ this.animations = null;
+ /**
+ * An event triggered when the material is disposed
+ */
+ this.onDisposeObservable = new Observable();
+ /**
+ * An observer which watches for dispose events
+ */
+ this._onDisposeObserver = null;
+ this._onUnBindObservable = null;
+ /**
+ * An observer which watches for bind events
+ */
+ this._onBindObserver = null;
+ /**
+ * Stores the value of the alpha mode
+ */
+ this._alphaMode = 2;
+ /**
+ * Stores the state of the need depth pre-pass value
+ */
+ this._needDepthPrePass = false;
+ /**
+ * Specifies if depth writing should be disabled
+ */
+ this.disableDepthWrite = false;
+ /**
+ * Specifies if color writing should be disabled
+ */
+ this.disableColorWrite = false;
+ /**
+ * Specifies if depth writing should be forced
+ */
+ this.forceDepthWrite = false;
+ /**
+ * Specifies the depth function that should be used. 0 means the default engine function
+ */
+ this.depthFunction = 0;
+ /**
+ * Specifies if there should be a separate pass for culling
+ */
+ this.separateCullingPass = false;
+ /**
+ * Stores the state specifying if fog should be enabled
+ */
+ this._fogEnabled = true;
+ /**
+ * Stores the size of points
+ */
+ this.pointSize = 1.0;
+ /**
+ * Stores the z offset Factor value
+ */
+ this.zOffset = 0;
+ /**
+ * Stores the z offset Units value
+ */
+ this.zOffsetUnits = 0;
+ /**
+ * Gives access to the stencil properties of the material
+ */
+ this.stencil = new MaterialStencilState();
+ /**
+ * Specifies if uniform buffers should be used
+ */
+ this._useUBO = false;
+ /**
+ * Stores the fill mode state
+ */
+ this._fillMode = Material.TriangleFillMode;
+ /**
+ * Specifies if the depth write state should be cached
+ */
+ this._cachedDepthWriteState = false;
+ /**
+ * Specifies if the color write state should be cached
+ */
+ this._cachedColorWriteState = false;
+ /**
+ * Specifies if the depth function state should be cached
+ */
+ this._cachedDepthFunctionState = 0;
+ /** @internal */
+ this._indexInSceneMaterialArray = -1;
+ /** @internal */
+ this.meshMap = null;
+ /** @internal */
+ this._parentContainer = null;
+ /** @internal */
+ this._uniformBufferLayoutBuilt = false;
+ this._eventInfo = {}; // will be initialized before each event notification
+ /** @internal */
+ this._callbackPluginEventGeneric = () => void 0;
+ /** @internal */
+ this._callbackPluginEventIsReadyForSubMesh = () => void 0;
+ /** @internal */
+ this._callbackPluginEventPrepareDefines = () => void 0;
+ /** @internal */
+ this._callbackPluginEventPrepareDefinesBeforeAttributes = () => void 0;
+ /** @internal */
+ this._callbackPluginEventHardBindForSubMesh = () => void 0;
+ /** @internal */
+ this._callbackPluginEventBindForSubMesh = () => void 0;
+ /** @internal */
+ this._callbackPluginEventHasRenderTargetTextures = () => void 0;
+ /** @internal */
+ this._callbackPluginEventFillRenderTargetTextures = () => void 0;
+ /**
+ * The transparency mode of the material.
+ */
+ this._transparencyMode = null;
+ this.name = name;
+ const setScene = scene || EngineStore.LastCreatedScene;
+ if (!setScene) {
+ return;
+ }
+ this._scene = setScene;
+ this._dirtyCallbacks = {};
+ this._forceGLSL = forceGLSL;
+ this._dirtyCallbacks[1] = this._markAllSubMeshesAsTexturesDirty.bind(this);
+ this._dirtyCallbacks[2] = this._markAllSubMeshesAsLightsDirty.bind(this);
+ this._dirtyCallbacks[4] = this._markAllSubMeshesAsFresnelDirty.bind(this);
+ this._dirtyCallbacks[8] = this._markAllSubMeshesAsAttributesDirty.bind(this);
+ this._dirtyCallbacks[16] = this._markAllSubMeshesAsMiscDirty.bind(this);
+ this._dirtyCallbacks[32] = this._markAllSubMeshesAsPrePassDirty.bind(this);
+ this._dirtyCallbacks[127] = this._markAllSubMeshesAsAllDirty.bind(this);
+ this.id = name || Tools.RandomId();
+ this.uniqueId = this._scene.getUniqueId();
+ this._materialContext = this._scene.getEngine().createMaterialContext();
+ this._drawWrapper = new DrawWrapper(this._scene.getEngine(), false);
+ this._drawWrapper.materialContext = this._materialContext;
+ this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, name);
+ this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
+ this._createUniformBuffer();
+ if (!doNotAdd) {
+ this._scene.addMaterial(this);
+ }
+ if (this._scene.useMaterialMeshMap) {
+ this.meshMap = {};
+ }
+ Material.OnEventObservable.notifyObservers(this, 1 /* MaterialPluginEvent.Created */);
+ }
+ /** @internal */
+ _createUniformBuffer() {
+ const engine = this.getScene().getEngine();
+ this._uniformBuffer?.dispose();
+ if (engine.isWebGPU && !this._forceGLSL) {
+ // Switch main UBO to non UBO to connect to leftovers UBO in webgpu
+ this._uniformBuffer = new UniformBuffer(engine, undefined, undefined, this.name, true);
+ this._shaderLanguage = 1 /* ShaderLanguage.WGSL */;
+ }
+ else {
+ this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, this.name);
+ }
+ this._uniformBufferLayoutBuilt = false;
+ }
+ /**
+ * Returns a string representation of the current material
+ * @param fullDetails defines a boolean indicating which levels of logging is desired
+ * @returns a string with material information
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ toString(fullDetails) {
+ const ret = "Name: " + this.name;
+ return ret;
+ }
+ /**
+ * Gets the class name of the material
+ * @returns a string with the class name of the material
+ */
+ getClassName() {
+ return "Material";
+ }
+ /** @internal */
+ get _isMaterial() {
+ return true;
+ }
+ /**
+ * Specifies if updates for the material been locked
+ */
+ get isFrozen() {
+ return this.checkReadyOnlyOnce;
+ }
+ /**
+ * Locks updates for the material
+ */
+ freeze() {
+ this.markDirty();
+ this.checkReadyOnlyOnce = true;
+ }
+ /**
+ * Unlocks updates for the material
+ */
+ unfreeze() {
+ this.markDirty();
+ this.checkReadyOnlyOnce = false;
+ }
+ /**
+ * Specifies if the material is ready to be used
+ * @param mesh defines the mesh to check
+ * @param useInstances specifies if instances should be used
+ * @returns a boolean indicating if the material is ready to be used
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ isReady(mesh, useInstances) {
+ return true;
+ }
+ /**
+ * Specifies that the submesh is ready to be used
+ * @param mesh defines the mesh to check
+ * @param subMesh defines which submesh to check
+ * @param useInstances specifies that instances should be used
+ * @returns a boolean indicating that the submesh is ready or not
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ isReadyForSubMesh(mesh, subMesh, useInstances) {
+ const defines = subMesh.materialDefines;
+ if (!defines) {
+ return false;
+ }
+ this._eventInfo.isReadyForSubMesh = true;
+ this._eventInfo.defines = defines;
+ this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);
+ return this._eventInfo.isReadyForSubMesh;
+ }
+ /**
+ * Returns the material effect
+ * @returns the effect associated with the material
+ */
+ getEffect() {
+ return this._drawWrapper.effect;
+ }
+ /**
+ * Returns the current scene
+ * @returns a Scene
+ */
+ getScene() {
+ return this._scene;
+ }
+ /** @internal */
+ _getEffectiveOrientation(mesh) {
+ return this.sideOrientation !== null ? this.sideOrientation : mesh.sideOrientation;
+ }
+ /**
+ * Gets the current transparency mode.
+ */
+ get transparencyMode() {
+ return this._transparencyMode;
+ }
+ /**
+ * Sets the transparency mode of the material.
+ *
+ * | Value | Type | Description |
+ * | ----- | ----------------------------------- | ----------- |
+ * | 0 | OPAQUE | |
+ * | 1 | ALPHATEST | |
+ * | 2 | ALPHABLEND | |
+ * | 3 | ALPHATESTANDBLEND | |
+ *
+ */
+ set transparencyMode(value) {
+ if (this._transparencyMode === value) {
+ return;
+ }
+ this._transparencyMode = value;
+ this._markAllSubMeshesAsTexturesAndMiscDirty();
+ }
+ get _hasTransparencyMode() {
+ return this._transparencyMode != null;
+ }
+ get _transparencyModeIsBlend() {
+ return this._transparencyMode === Material.MATERIAL_ALPHABLEND || this._transparencyMode === Material.MATERIAL_ALPHATESTANDBLEND;
+ }
+ get _transparencyModeIsTest() {
+ return this._transparencyMode === Material.MATERIAL_ALPHATEST || this._transparencyMode === Material.MATERIAL_ALPHATESTANDBLEND;
+ }
+ /**
+ * Returns true if alpha blending should be disabled.
+ */
+ get _disableAlphaBlending() {
+ return this._transparencyMode === Material.MATERIAL_OPAQUE || this._transparencyMode === Material.MATERIAL_ALPHATEST;
+ }
+ /**
+ * Specifies whether or not this material should be rendered in alpha blend mode.
+ * @returns a boolean specifying if alpha blending is needed
+ * @deprecated Please use needAlphaBlendingForMesh instead
+ */
+ needAlphaBlending() {
+ if (this._hasTransparencyMode) {
+ return this._transparencyModeIsBlend;
+ }
+ if (this._disableAlphaBlending) {
+ return false;
+ }
+ return this.alpha < 1.0;
+ }
+ /**
+ * Specifies if the mesh will require alpha blending
+ * @param mesh defines the mesh to check
+ * @returns a boolean specifying if alpha blending is needed for the mesh
+ */
+ needAlphaBlendingForMesh(mesh) {
+ if (this._hasTransparencyMode) {
+ return this._transparencyModeIsBlend;
+ }
+ if (mesh.visibility < 1.0) {
+ return true;
+ }
+ if (this._disableAlphaBlending) {
+ return false;
+ }
+ return mesh.hasVertexAlpha || this.needAlphaBlending();
+ }
+ /**
+ * Specifies whether or not this material should be rendered in alpha test mode.
+ * @returns a boolean specifying if an alpha test is needed.
+ * @deprecated Please use needAlphaTestingForMesh instead
+ */
+ needAlphaTesting() {
+ if (this._hasTransparencyMode) {
+ return this._transparencyModeIsTest;
+ }
+ return false;
+ }
+ /**
+ * Specifies if material alpha testing should be turned on for the mesh
+ * @param mesh defines the mesh to check
+ * @returns a boolean specifying if alpha testing should be turned on for the mesh
+ */
+ needAlphaTestingForMesh(mesh) {
+ if (this._hasTransparencyMode) {
+ return this._transparencyModeIsTest;
+ }
+ return !this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting();
+ }
+ /**
+ * Gets the texture used for the alpha test
+ * @returns the texture to use for alpha testing
+ */
+ getAlphaTestTexture() {
+ return null;
+ }
+ /**
+ * Marks the material to indicate that it needs to be re-calculated
+ * @param forceMaterialDirty - Forces the material to be marked as dirty for all components (same as this.markAsDirty(Material.AllDirtyFlag)). You should use this flag if the material is frozen and you want to force a recompilation.
+ */
+ markDirty(forceMaterialDirty = false) {
+ const meshes = this.getScene().meshes;
+ for (const mesh of meshes) {
+ if (!mesh.subMeshes) {
+ continue;
+ }
+ for (const subMesh of mesh.subMeshes) {
+ if (subMesh.getMaterial() !== this) {
+ continue;
+ }
+ for (const drawWrapper of subMesh._drawWrappers) {
+ if (!drawWrapper) {
+ continue;
+ }
+ if (this._materialContext === drawWrapper.materialContext) {
+ drawWrapper._wasPreviouslyReady = false;
+ drawWrapper._wasPreviouslyUsingInstances = null;
+ drawWrapper._forceRebindOnNextCall = forceMaterialDirty;
+ }
+ }
+ }
+ }
+ if (forceMaterialDirty) {
+ this.markAsDirty(Material.AllDirtyFlag);
+ }
+ }
+ /**
+ * @internal
+ */
+ _preBind(effect, overrideOrientation = null) {
+ const engine = this._scene.getEngine();
+ const orientation = overrideOrientation == null ? this.sideOrientation : overrideOrientation;
+ const reverse = orientation === Material.ClockWiseSideOrientation;
+ engine.enableEffect(effect ? effect : this._getDrawWrapper());
+ engine.setState(this.backFaceCulling, this.zOffset, false, reverse, this._scene._mirroredCameraPosition ? !this.cullBackFaces : this.cullBackFaces, this.stencil, this.zOffsetUnits);
+ return reverse;
+ }
+ /**
+ * Binds the material to the mesh
+ * @param world defines the world transformation matrix
+ * @param mesh defines the mesh to bind the material to
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ bind(world, mesh) { }
+ /**
+ * Initializes the uniform buffer layout for the shader.
+ */
+ buildUniformLayout() {
+ const ubo = this._uniformBuffer;
+ this._eventInfo.ubo = ubo;
+ this._callbackPluginEventGeneric(8 /* MaterialPluginEvent.PrepareUniformBuffer */, this._eventInfo);
+ ubo.create();
+ this._uniformBufferLayoutBuilt = true;
+ }
+ /**
+ * Binds the submesh to the material
+ * @param world defines the world transformation matrix
+ * @param mesh defines the mesh containing the submesh
+ * @param subMesh defines the submesh to bind the material to
+ */
+ bindForSubMesh(world, mesh, subMesh) {
+ const drawWrapper = subMesh._drawWrapper;
+ this._eventInfo.subMesh = subMesh;
+ this._callbackPluginEventBindForSubMesh(this._eventInfo);
+ drawWrapper._forceRebindOnNextCall = false;
+ }
+ /**
+ * Binds the world matrix to the material
+ * @param world defines the world transformation matrix
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ bindOnlyWorldMatrix(world) { }
+ /**
+ * Binds the view matrix to the effect
+ * @param effect defines the effect to bind the view matrix to
+ */
+ bindView(effect) {
+ if (!this._useUBO) {
+ effect.setMatrix("view", this.getScene().getViewMatrix());
+ }
+ else {
+ this._needToBindSceneUbo = true;
+ }
+ }
+ /**
+ * Binds the view projection and projection matrices to the effect
+ * @param effect defines the effect to bind the view projection and projection matrices to
+ */
+ bindViewProjection(effect) {
+ if (!this._useUBO) {
+ effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
+ effect.setMatrix("projection", this.getScene().getProjectionMatrix());
+ }
+ else {
+ this._needToBindSceneUbo = true;
+ }
+ }
+ /**
+ * Binds the view matrix to the effect
+ * @param effect defines the effect to bind the view matrix to
+ * @param variableName name of the shader variable that will hold the eye position
+ */
+ bindEyePosition(effect, variableName) {
+ if (!this._useUBO) {
+ this._scene.bindEyePosition(effect, variableName);
+ }
+ else {
+ this._needToBindSceneUbo = true;
+ }
+ }
+ /**
+ * Processes to execute after binding the material to a mesh
+ * @param mesh defines the rendered mesh
+ * @param effect defines the effect used to bind the material
+ * @param _subMesh defines the subMesh that the material has been bound for
+ */
+ _afterBind(mesh, effect = null, _subMesh) {
+ this._scene._cachedMaterial = this;
+ if (this._needToBindSceneUbo) {
+ if (effect) {
+ this._needToBindSceneUbo = false;
+ BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
+ this._scene.finalizeSceneUbo();
+ }
+ }
+ if (mesh) {
+ this._scene._cachedVisibility = mesh.visibility;
+ }
+ else {
+ this._scene._cachedVisibility = 1;
+ }
+ if (this._onBindObservable && mesh) {
+ this._onBindObservable.notifyObservers(mesh);
+ }
+ if (this.disableDepthWrite) {
+ const engine = this._scene.getEngine();
+ this._cachedDepthWriteState = engine.getDepthWrite();
+ engine.setDepthWrite(false);
+ }
+ if (this.disableColorWrite) {
+ const engine = this._scene.getEngine();
+ this._cachedColorWriteState = engine.getColorWrite();
+ engine.setColorWrite(false);
+ }
+ if (this.depthFunction !== 0) {
+ const engine = this._scene.getEngine();
+ this._cachedDepthFunctionState = engine.getDepthFunction() || 0;
+ engine.setDepthFunction(this.depthFunction);
+ }
+ }
+ /**
+ * Unbinds the material from the mesh
+ */
+ unbind() {
+ this._scene.getSceneUniformBuffer().unbindEffect();
+ if (this._onUnBindObservable) {
+ this._onUnBindObservable.notifyObservers(this);
+ }
+ if (this.depthFunction !== 0) {
+ const engine = this._scene.getEngine();
+ engine.setDepthFunction(this._cachedDepthFunctionState);
+ }
+ if (this.disableDepthWrite) {
+ const engine = this._scene.getEngine();
+ engine.setDepthWrite(this._cachedDepthWriteState);
+ }
+ if (this.disableColorWrite) {
+ const engine = this._scene.getEngine();
+ engine.setColorWrite(this._cachedColorWriteState);
+ }
+ }
+ /**
+ * Returns the animatable textures.
+ * @returns - Array of animatable textures.
+ */
+ getAnimatables() {
+ this._eventInfo.animatables = [];
+ this._callbackPluginEventGeneric(256 /* MaterialPluginEvent.GetAnimatables */, this._eventInfo);
+ return this._eventInfo.animatables;
+ }
+ /**
+ * Gets the active textures from the material
+ * @returns an array of textures
+ */
+ getActiveTextures() {
+ this._eventInfo.activeTextures = [];
+ this._callbackPluginEventGeneric(512 /* MaterialPluginEvent.GetActiveTextures */, this._eventInfo);
+ return this._eventInfo.activeTextures;
+ }
+ /**
+ * Specifies if the material uses a texture
+ * @param texture defines the texture to check against the material
+ * @returns a boolean specifying if the material uses the texture
+ */
+ hasTexture(texture) {
+ this._eventInfo.hasTexture = false;
+ this._eventInfo.texture = texture;
+ this._callbackPluginEventGeneric(1024 /* MaterialPluginEvent.HasTexture */, this._eventInfo);
+ return this._eventInfo.hasTexture;
+ }
+ /**
+ * Makes a duplicate of the material, and gives it a new name
+ * @param name defines the new name for the duplicated material
+ * @returns the cloned material
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ clone(name) {
+ return null;
+ }
+ _clonePlugins(targetMaterial, rootUrl) {
+ const serializationObject = {};
+ // Create plugins in targetMaterial in case they don't exist
+ this._serializePlugins(serializationObject);
+ Material._ParsePlugins(serializationObject, targetMaterial, this._scene, rootUrl);
+ // Copy the properties of the current plugins to the cloned material's plugins
+ if (this.pluginManager) {
+ for (const plugin of this.pluginManager._plugins) {
+ const targetPlugin = targetMaterial.pluginManager.getPlugin(plugin.name);
+ if (targetPlugin) {
+ plugin.copyTo(targetPlugin);
+ }
+ }
+ }
+ }
+ /**
+ * Gets the meshes bound to the material
+ * @returns an array of meshes bound to the material
+ */
+ getBindedMeshes() {
+ if (this.meshMap) {
+ const result = [];
+ for (const meshId in this.meshMap) {
+ const mesh = this.meshMap[meshId];
+ if (mesh) {
+ result.push(mesh);
+ }
+ }
+ return result;
+ }
+ else {
+ const meshes = this._scene.meshes;
+ return meshes.filter((mesh) => mesh.material === this);
+ }
+ }
+ /**
+ * Force shader compilation
+ * @param mesh defines the mesh associated with this material
+ * @param onCompiled defines a function to execute once the material is compiled
+ * @param options defines the options to configure the compilation
+ * @param onError defines a function to execute if the material fails compiling
+ */
+ forceCompilation(mesh, onCompiled, options, onError) {
+ const localOptions = {
+ clipPlane: false,
+ useInstances: false,
+ ...options,
+ };
+ const scene = this.getScene();
+ const currentHotSwapingState = this.allowShaderHotSwapping;
+ this.allowShaderHotSwapping = false; // Turned off to let us evaluate the real compilation state
+ const checkReady = () => {
+ if (!this._scene || !this._scene.getEngine()) {
+ return;
+ }
+ const clipPlaneState = scene.clipPlane;
+ if (localOptions.clipPlane) {
+ scene.clipPlane = new Plane(0, 0, 0, 1);
+ }
+ if (this._storeEffectOnSubMeshes) {
+ let allDone = true, lastError = null;
+ if (mesh.subMeshes) {
+ const tempSubMesh = new SubMesh(0, 0, 0, 0, 0, mesh, undefined, false, false);
+ if (tempSubMesh.materialDefines) {
+ tempSubMesh.materialDefines._renderId = -1;
+ }
+ if (!this.isReadyForSubMesh(mesh, tempSubMesh, localOptions.useInstances)) {
+ if (tempSubMesh.effect && tempSubMesh.effect.getCompilationError() && tempSubMesh.effect.allFallbacksProcessed()) {
+ lastError = tempSubMesh.effect.getCompilationError();
+ }
+ else {
+ allDone = false;
+ setTimeout(checkReady, 16);
+ }
+ }
+ }
+ if (allDone) {
+ this.allowShaderHotSwapping = currentHotSwapingState;
+ if (lastError) {
+ if (onError) {
+ onError(lastError);
+ }
+ }
+ if (onCompiled) {
+ onCompiled(this);
+ }
+ }
+ }
+ else {
+ if (this.isReady()) {
+ this.allowShaderHotSwapping = currentHotSwapingState;
+ if (onCompiled) {
+ onCompiled(this);
+ }
+ }
+ else {
+ setTimeout(checkReady, 16);
+ }
+ }
+ if (localOptions.clipPlane) {
+ scene.clipPlane = clipPlaneState;
+ }
+ };
+ checkReady();
+ }
+ /**
+ * Force shader compilation
+ * @param mesh defines the mesh that will use this material
+ * @param options defines additional options for compiling the shaders
+ * @returns a promise that resolves when the compilation completes
+ */
+ forceCompilationAsync(mesh, options) {
+ return new Promise((resolve, reject) => {
+ this.forceCompilation(mesh, () => {
+ resolve();
+ }, options, (reason) => {
+ reject(reason);
+ });
+ });
+ }
+ /**
+ * Marks a define in the material to indicate that it needs to be re-computed
+ * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
+ */
+ markAsDirty(flag) {
+ if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {
+ return;
+ }
+ Material._DirtyCallbackArray.length = 0;
+ if (flag & Material.ImageProcessingDirtyFlag) {
+ Material._DirtyCallbackArray.push(Material._ImageProcessingDirtyCallBack);
+ }
+ if (flag & Material.TextureDirtyFlag) {
+ Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
+ }
+ if (flag & Material.LightDirtyFlag) {
+ Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
+ }
+ if (flag & Material.FresnelDirtyFlag) {
+ Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
+ }
+ if (flag & Material.AttributesDirtyFlag) {
+ Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
+ }
+ if (flag & Material.MiscDirtyFlag) {
+ Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
+ }
+ if (flag & Material.PrePassDirtyFlag) {
+ Material._DirtyCallbackArray.push(Material._PrePassDirtyCallBack);
+ }
+ if (Material._DirtyCallbackArray.length) {
+ this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
+ }
+ this.getScene().resetCachedMaterial();
+ }
+ /**
+ * Resets the draw wrappers cache for all submeshes that are using this material
+ */
+ resetDrawCache() {
+ const meshes = this.getScene().meshes;
+ for (const mesh of meshes) {
+ if (!mesh.subMeshes) {
+ continue;
+ }
+ for (const subMesh of mesh.subMeshes) {
+ if (subMesh.getMaterial() !== this) {
+ continue;
+ }
+ subMesh.resetDrawCache();
+ }
+ }
+ }
+ /**
+ * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
+ * @param func defines a function which checks material defines against the submeshes
+ */
+ _markAllSubMeshesAsDirty(func) {
+ const scene = this.getScene();
+ if (scene.blockMaterialDirtyMechanism || this._blockDirtyMechanism) {
+ return;
+ }
+ const meshes = scene.meshes;
+ for (const mesh of meshes) {
+ if (!mesh.subMeshes) {
+ continue;
+ }
+ for (const subMesh of mesh.subMeshes) {
+ // We want to skip the submeshes which are not using this material or which have not yet rendered at least once
+ const material = subMesh.getMaterial() || (scene._hasDefaultMaterial ? scene.defaultMaterial : null);
+ if (material !== this) {
+ continue;
+ }
+ for (const drawWrapper of subMesh._drawWrappers) {
+ if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) {
+ continue;
+ }
+ if (this._materialContext === drawWrapper.materialContext) {
+ func(drawWrapper.defines);
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Indicates that the scene should check if the rendering now needs a prepass
+ */
+ _markScenePrePassDirty() {
+ if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {
+ return;
+ }
+ const prePassRenderer = this.getScene().enablePrePassRenderer();
+ if (prePassRenderer) {
+ prePassRenderer.markAsDirty();
+ }
+ }
+ /**
+ * Indicates that we need to re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsAllDirty() {
+ this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack);
+ }
+ /**
+ * Indicates that image processing needs to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsImageProcessingDirty() {
+ this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
+ }
+ /**
+ * Indicates that textures need to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsTexturesDirty() {
+ this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
+ }
+ /**
+ * Indicates that fresnel needs to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsFresnelDirty() {
+ this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
+ }
+ /**
+ * Indicates that fresnel and misc need to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsFresnelAndMiscDirty() {
+ this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
+ }
+ /**
+ * Indicates that lights need to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsLightsDirty() {
+ this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
+ }
+ /**
+ * Indicates that attributes need to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsAttributesDirty() {
+ this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
+ }
+ /**
+ * Indicates that misc needs to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsMiscDirty() {
+ this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
+ }
+ /**
+ * Indicates that prepass needs to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsPrePassDirty() {
+ this._markAllSubMeshesAsDirty(Material._PrePassDirtyCallBack);
+ }
+ /**
+ * Indicates that textures and misc need to be re-calculated for all submeshes
+ */
+ _markAllSubMeshesAsTexturesAndMiscDirty() {
+ this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
+ }
+ _checkScenePerformancePriority() {
+ if (this._scene.performancePriority !== 0 /* ScenePerformancePriority.BackwardCompatible */) {
+ this.checkReadyOnlyOnce = true;
+ // re-set the flag when the perf priority changes
+ const observer = this._scene.onScenePerformancePriorityChangedObservable.addOnce(() => {
+ this.checkReadyOnlyOnce = false;
+ });
+ // if this material is disposed before the scene is disposed, cleanup the observer
+ this.onDisposeObservable.add(() => {
+ this._scene.onScenePerformancePriorityChangedObservable.remove(observer);
+ });
+ }
+ }
+ /**
+ * Sets the required values to the prepass renderer.
+ * @param prePassRenderer defines the prepass renderer to setup.
+ * @returns true if the pre pass is needed.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ setPrePassRenderer(prePassRenderer) {
+ // Do Nothing by default
+ return false;
+ }
+ /**
+ * Disposes the material
+ * @param _forceDisposeEffect kept for backward compat. We reference count the effect now.
+ * @param forceDisposeTextures specifies if textures should be forcefully disposed
+ * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
+ */
+ dispose(_forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
+ const scene = this.getScene();
+ // Animations
+ scene.stopAnimation(this);
+ scene.freeProcessedMaterials();
+ // Remove from scene
+ scene.removeMaterial(this);
+ this._eventInfo.forceDisposeTextures = forceDisposeTextures;
+ this._callbackPluginEventGeneric(2 /* MaterialPluginEvent.Disposed */, this._eventInfo);
+ if (this._parentContainer) {
+ const index = this._parentContainer.materials.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.materials.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ if (notBoundToMesh !== true) {
+ // Remove from meshes
+ if (this.meshMap) {
+ for (const meshId in this.meshMap) {
+ const mesh = this.meshMap[meshId];
+ this._disposeMeshResources(mesh);
+ }
+ }
+ else {
+ const meshes = scene.meshes;
+ for (const mesh of meshes) {
+ this._disposeMeshResources(mesh);
+ }
+ }
+ }
+ this._uniformBuffer.dispose();
+ // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
+ if (this._drawWrapper.effect) {
+ if (!this._storeEffectOnSubMeshes) {
+ this._drawWrapper.effect.dispose();
+ }
+ this._drawWrapper.effect = null;
+ }
+ this.metadata = null;
+ // Callback
+ this.onDisposeObservable.notifyObservers(this);
+ this.onDisposeObservable.clear();
+ if (this._onBindObservable) {
+ this._onBindObservable.clear();
+ }
+ if (this._onUnBindObservable) {
+ this._onUnBindObservable.clear();
+ }
+ if (this._onEffectCreatedObservable) {
+ this._onEffectCreatedObservable.clear();
+ }
+ if (this._eventInfo) {
+ this._eventInfo = {};
+ }
+ }
+ _disposeMeshResources(mesh) {
+ if (!mesh) {
+ return;
+ }
+ const geometry = mesh.geometry;
+ const materialForRenderPass = mesh._internalAbstractMeshDataInfo._materialForRenderPass;
+ if (this._storeEffectOnSubMeshes) {
+ if (mesh.subMeshes && materialForRenderPass) {
+ for (const subMesh of mesh.subMeshes) {
+ const drawWrappers = subMesh._drawWrappers;
+ for (let renderPassIndex = 0; renderPassIndex < drawWrappers.length; renderPassIndex++) {
+ const effect = drawWrappers[renderPassIndex]?.effect;
+ if (!effect) {
+ continue;
+ }
+ const material = materialForRenderPass[renderPassIndex];
+ if (material === this) {
+ geometry?._releaseVertexArrayObject(effect);
+ subMesh._removeDrawWrapper(renderPassIndex, true, true);
+ }
+ }
+ }
+ }
+ }
+ else {
+ geometry?._releaseVertexArrayObject(this._drawWrapper.effect);
+ }
+ if (mesh.material === this && !mesh.sourceMesh) {
+ mesh.material = null;
+ }
+ }
+ /**
+ * Serializes this material
+ * @returns the serialized material object
+ */
+ serialize() {
+ const serializationObject = SerializationHelper.Serialize(this);
+ serializationObject.stencil = this.stencil.serialize();
+ serializationObject.uniqueId = this.uniqueId;
+ this._serializePlugins(serializationObject);
+ return serializationObject;
+ }
+ _serializePlugins(serializationObject) {
+ serializationObject.plugins = {};
+ if (this.pluginManager) {
+ for (const plugin of this.pluginManager._plugins) {
+ if (!plugin.doNotSerialize) {
+ serializationObject.plugins[plugin.getClassName()] = plugin.serialize();
+ }
+ }
+ }
+ }
+ /**
+ * Creates a material from parsed material data
+ * @param parsedMaterial defines parsed material data
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root URL to use to load textures
+ * @returns a new material
+ */
+ static Parse(parsedMaterial, scene, rootUrl) {
+ if (!parsedMaterial.customType) {
+ parsedMaterial.customType = "BABYLON.StandardMaterial";
+ }
+ else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
+ parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
+ if (!BABYLON.LegacyPBRMaterial) {
+ Logger.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
+ return null;
+ }
+ }
+ const materialType = Tools.Instantiate(parsedMaterial.customType);
+ const material = materialType.Parse(parsedMaterial, scene, rootUrl);
+ material._loadedUniqueId = parsedMaterial.uniqueId;
+ return material;
+ }
+ static _ParsePlugins(serializationObject, material, scene, rootUrl) {
+ if (!serializationObject.plugins) {
+ return;
+ }
+ for (const pluginClassName in serializationObject.plugins) {
+ const pluginData = serializationObject.plugins[pluginClassName];
+ let plugin = material.pluginManager?.getPlugin(pluginData.name);
+ if (!plugin) {
+ const pluginClassType = Tools.Instantiate("BABYLON." + pluginClassName);
+ if (pluginClassType) {
+ plugin = new pluginClassType(material);
+ }
+ }
+ plugin?.parse(pluginData, scene, rootUrl);
+ }
+ }
+}
+/**
+ * Returns the triangle fill mode
+ */
+Material.TriangleFillMode = 0;
+/**
+ * Returns the wireframe mode
+ */
+Material.WireFrameFillMode = 1;
+/**
+ * Returns the point fill mode
+ */
+Material.PointFillMode = 2;
+/**
+ * Returns the point list draw mode
+ */
+Material.PointListDrawMode = 3;
+/**
+ * Returns the line list draw mode
+ */
+Material.LineListDrawMode = 4;
+/**
+ * Returns the line loop draw mode
+ */
+Material.LineLoopDrawMode = 5;
+/**
+ * Returns the line strip draw mode
+ */
+Material.LineStripDrawMode = 6;
+/**
+ * Returns the triangle strip draw mode
+ */
+Material.TriangleStripDrawMode = 7;
+/**
+ * Returns the triangle fan draw mode
+ */
+Material.TriangleFanDrawMode = 8;
+/**
+ * Stores the clock-wise side orientation
+ */
+Material.ClockWiseSideOrientation = 0;
+/**
+ * Stores the counter clock-wise side orientation
+ */
+Material.CounterClockWiseSideOrientation = 1;
+/**
+ * The dirty image processing flag value
+ */
+Material.ImageProcessingDirtyFlag = 64;
+/**
+ * The dirty texture flag value
+ */
+Material.TextureDirtyFlag = 1;
+/**
+ * The dirty light flag value
+ */
+Material.LightDirtyFlag = 2;
+/**
+ * The dirty fresnel flag value
+ */
+Material.FresnelDirtyFlag = 4;
+/**
+ * The dirty attribute flag value
+ */
+Material.AttributesDirtyFlag = 8;
+/**
+ * The dirty misc flag value
+ */
+Material.MiscDirtyFlag = 16;
+/**
+ * The dirty prepass flag value
+ */
+Material.PrePassDirtyFlag = 32;
+/**
+ * The all dirty flag value
+ */
+Material.AllDirtyFlag = 127;
+/**
+ * MaterialTransparencyMode: No transparency mode, Alpha channel is not use.
+ */
+Material.MATERIAL_OPAQUE = 0;
+/**
+ * MaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
+ */
+Material.MATERIAL_ALPHATEST = 1;
+/**
+ * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
+ */
+Material.MATERIAL_ALPHABLEND = 2;
+/**
+ * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
+ * They are also discarded below the alpha cutoff threshold to improve performances.
+ */
+Material.MATERIAL_ALPHATESTANDBLEND = 3;
+/**
+ * The Whiteout method is used to blend normals.
+ * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/
+ */
+Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0;
+/**
+ * The Reoriented Normal Mapping method is used to blend normals.
+ * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/
+ */
+Material.MATERIAL_NORMALBLENDMETHOD_RNM = 1;
+/**
+ * Event observable which raises global events common to all materials (like MaterialPluginEvent.Created)
+ */
+Material.OnEventObservable = new Observable();
+Material._AllDirtyCallBack = (defines) => defines.markAllAsDirty();
+Material._ImageProcessingDirtyCallBack = (defines) => defines.markAsImageProcessingDirty();
+Material._TextureDirtyCallBack = (defines) => defines.markAsTexturesDirty();
+Material._FresnelDirtyCallBack = (defines) => defines.markAsFresnelDirty();
+Material._MiscDirtyCallBack = (defines) => defines.markAsMiscDirty();
+Material._PrePassDirtyCallBack = (defines) => defines.markAsPrePassDirty();
+Material._LightsDirtyCallBack = (defines) => defines.markAsLightDirty();
+Material._AttributeDirtyCallBack = (defines) => defines.markAsAttributesDirty();
+Material._FresnelAndMiscDirtyCallBack = (defines) => {
+ Material._FresnelDirtyCallBack(defines);
+ Material._MiscDirtyCallBack(defines);
+};
+Material._TextureAndMiscDirtyCallBack = (defines) => {
+ Material._TextureDirtyCallBack(defines);
+ Material._MiscDirtyCallBack(defines);
+};
+Material._DirtyCallbackArray = [];
+Material._RunDirtyCallBacks = (defines) => {
+ for (const cb of Material._DirtyCallbackArray) {
+ cb(defines);
+ }
+};
+__decorate([
+ serialize()
+], Material.prototype, "id", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "uniqueId", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "name", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "metadata", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "checkReadyOnEveryCall", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "checkReadyOnlyOnce", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "state", void 0);
+__decorate([
+ serialize("alpha")
+], Material.prototype, "_alpha", void 0);
+__decorate([
+ serialize("backFaceCulling")
+], Material.prototype, "_backFaceCulling", void 0);
+__decorate([
+ serialize("cullBackFaces")
+], Material.prototype, "_cullBackFaces", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "sideOrientation", void 0);
+__decorate([
+ serialize("alphaMode")
+], Material.prototype, "_alphaMode", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "_needDepthPrePass", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "disableDepthWrite", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "disableColorWrite", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "forceDepthWrite", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "depthFunction", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "separateCullingPass", void 0);
+__decorate([
+ serialize("fogEnabled")
+], Material.prototype, "_fogEnabled", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "pointSize", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "zOffset", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "zOffsetUnits", void 0);
+__decorate([
+ serialize()
+], Material.prototype, "pointsCloud", null);
+__decorate([
+ serialize()
+], Material.prototype, "fillMode", null);
+__decorate([
+ serialize()
+], Material.prototype, "useLogarithmicDepth", null);
+__decorate([
+ serialize()
+], Material.prototype, "transparencyMode", null);
+
+/**
+ * A multi-material is used to apply different materials to different parts of the same object without the need of
+ * separate meshes. This can be use to improve performances.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials
+ */
+class MultiMaterial extends Material {
+ /**
+ * Gets or Sets the list of Materials used within the multi material.
+ * They need to be ordered according to the submeshes order in the associated mesh
+ */
+ get subMaterials() {
+ return this._subMaterials;
+ }
+ set subMaterials(value) {
+ this._subMaterials = value;
+ this._hookArray(value);
+ }
+ /**
+ * Function used to align with Node.getChildren()
+ * @returns the list of Materials used within the multi material
+ */
+ getChildren() {
+ return this.subMaterials;
+ }
+ /**
+ * Instantiates a new Multi Material
+ * A multi-material is used to apply different materials to different parts of the same object without the need of
+ * separate meshes. This can be use to improve performances.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials
+ * @param name Define the name in the scene
+ * @param scene Define the scene the material belongs to
+ */
+ constructor(name, scene) {
+ super(name, scene, true);
+ /** @internal */
+ this._waitingSubMaterialsUniqueIds = [];
+ this.getScene().addMultiMaterial(this);
+ this.subMaterials = [];
+ this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
+ }
+ _hookArray(array) {
+ const oldPush = array.push;
+ array.push = (...items) => {
+ const result = oldPush.apply(array, items);
+ this._markAllSubMeshesAsTexturesDirty();
+ return result;
+ };
+ const oldSplice = array.splice;
+ array.splice = (index, deleteCount) => {
+ const deleted = oldSplice.apply(array, [index, deleteCount]);
+ this._markAllSubMeshesAsTexturesDirty();
+ return deleted;
+ };
+ }
+ /**
+ * Get one of the submaterial by its index in the submaterials array
+ * @param index The index to look the sub material at
+ * @returns The Material if the index has been defined
+ */
+ getSubMaterial(index) {
+ if (index < 0 || index >= this.subMaterials.length) {
+ return this.getScene().defaultMaterial;
+ }
+ return this.subMaterials[index];
+ }
+ /**
+ * Get the list of active textures for the whole sub materials list.
+ * @returns All the textures that will be used during the rendering
+ */
+ getActiveTextures() {
+ return super.getActiveTextures().concat(...this.subMaterials.map((subMaterial) => {
+ if (subMaterial) {
+ return subMaterial.getActiveTextures();
+ }
+ else {
+ return [];
+ }
+ }));
+ }
+ /**
+ * Specifies if any sub-materials of this multi-material use a given texture.
+ * @param texture Defines the texture to check against this multi-material's sub-materials.
+ * @returns A boolean specifying if any sub-material of this multi-material uses the texture.
+ */
+ hasTexture(texture) {
+ if (super.hasTexture(texture)) {
+ return true;
+ }
+ for (let i = 0; i < this.subMaterials.length; i++) {
+ if (this.subMaterials[i]?.hasTexture(texture)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * Gets the current class name of the material e.g. "MultiMaterial"
+ * Mainly use in serialization.
+ * @returns the class name
+ */
+ getClassName() {
+ return "MultiMaterial";
+ }
+ /**
+ * Checks if the material is ready to render the requested sub mesh
+ * @param mesh Define the mesh the submesh belongs to
+ * @param subMesh Define the sub mesh to look readiness for
+ * @param useInstances Define whether or not the material is used with instances
+ * @returns true if ready, otherwise false
+ */
+ isReadyForSubMesh(mesh, subMesh, useInstances) {
+ for (let index = 0; index < this.subMaterials.length; index++) {
+ const subMaterial = this.subMaterials[index];
+ if (subMaterial) {
+ if (subMaterial._storeEffectOnSubMeshes) {
+ if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
+ return false;
+ }
+ continue;
+ }
+ if (!subMaterial.isReady(mesh)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ /**
+ * Clones the current material and its related sub materials
+ * @param name Define the name of the newly cloned material
+ * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
+ * @returns the cloned material
+ */
+ clone(name, cloneChildren) {
+ const newMultiMaterial = new MultiMaterial(name, this.getScene());
+ for (let index = 0; index < this.subMaterials.length; index++) {
+ let subMaterial = null;
+ const current = this.subMaterials[index];
+ if (cloneChildren && current) {
+ subMaterial = current.clone(name + "-" + current.name);
+ }
+ else {
+ subMaterial = this.subMaterials[index];
+ }
+ newMultiMaterial.subMaterials.push(subMaterial);
+ }
+ return newMultiMaterial;
+ }
+ /**
+ * Serializes the materials into a JSON representation.
+ * @returns the JSON representation
+ */
+ serialize() {
+ const serializationObject = {};
+ serializationObject.name = this.name;
+ serializationObject.id = this.id;
+ serializationObject.uniqueId = this.uniqueId;
+ if (Tags) {
+ serializationObject.tags = Tags.GetTags(this);
+ }
+ serializationObject.materialsUniqueIds = [];
+ serializationObject.materials = [];
+ for (let matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
+ const subMat = this.subMaterials[matIndex];
+ if (subMat) {
+ serializationObject.materialsUniqueIds.push(subMat.uniqueId);
+ serializationObject.materials.push(subMat.id);
+ }
+ else {
+ serializationObject.materialsUniqueIds.push(null);
+ serializationObject.materials.push(null);
+ }
+ }
+ return serializationObject;
+ }
+ /**
+ * Dispose the material and release its associated resources
+ * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
+ * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
+ * @param forceDisposeChildren Define if we want to force disposing the associated submaterials (if false, they will not be disposed and can still be use elsewhere in the app)
+ */
+ dispose(forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) {
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ if (forceDisposeChildren) {
+ for (let index = 0; index < this.subMaterials.length; index++) {
+ const subMaterial = this.subMaterials[index];
+ if (subMaterial) {
+ subMaterial.dispose(forceDisposeEffect, forceDisposeTextures);
+ }
+ }
+ }
+ const index = scene.multiMaterials.indexOf(this);
+ if (index >= 0) {
+ scene.multiMaterials.splice(index, 1);
+ }
+ super.dispose(forceDisposeEffect, forceDisposeTextures);
+ }
+ /**
+ * Creates a MultiMaterial from parsed MultiMaterial data.
+ * @param parsedMultiMaterial defines parsed MultiMaterial data.
+ * @param scene defines the hosting scene
+ * @returns a new MultiMaterial
+ */
+ static ParseMultiMaterial(parsedMultiMaterial, scene) {
+ const multiMaterial = new MultiMaterial(parsedMultiMaterial.name, scene);
+ multiMaterial.id = parsedMultiMaterial.id;
+ multiMaterial._loadedUniqueId = parsedMultiMaterial.uniqueId;
+ if (Tags) {
+ Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
+ }
+ if (parsedMultiMaterial.materialsUniqueIds) {
+ multiMaterial._waitingSubMaterialsUniqueIds = parsedMultiMaterial.materialsUniqueIds;
+ }
+ else {
+ parsedMultiMaterial.materials.forEach((subMatId) => multiMaterial.subMaterials.push(scene.getLastMaterialById(subMatId)));
+ }
+ return multiMaterial;
+ }
+}
+RegisterClass("BABYLON.MultiMaterial", MultiMaterial);
+
+/**
+ * Class used to represent a specific level of detail of a mesh
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
+ */
+class MeshLODLevel {
+ /**
+ * Creates a new LOD level
+ * @param distanceOrScreenCoverage defines either the distance or the screen coverage where this level should start being displayed
+ * @param mesh defines the mesh to use to render this level
+ */
+ constructor(
+ /** Either distance from the center of the object to show this level or the screen coverage if `useLODScreenCoverage` is set to `true` on the mesh*/
+ distanceOrScreenCoverage,
+ /** Defines the mesh to use to render this level */
+ mesh) {
+ this.distanceOrScreenCoverage = distanceOrScreenCoverage;
+ this.mesh = mesh;
+ }
+}
+
+/**
+ * @internal
+ **/
+class _CreationDataStorage {
+}
+/**
+ * @internal
+ **/
+class _InstanceDataStorage {
+ constructor() {
+ this.visibleInstances = {};
+ this.batchCache = new _InstancesBatch();
+ this.batchCacheReplacementModeInFrozenMode = new _InstancesBatch();
+ this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
+ }
+}
+/**
+ * @internal
+ **/
+class _InstancesBatch {
+ constructor() {
+ /**
+ *
+ */
+ this.mustReturn = false;
+ /**
+ *
+ */
+ this.visibleInstances = new Array();
+ /**
+ *
+ */
+ this.renderSelf = [];
+ /**
+ *
+ */
+ this.hardwareInstancedRendering = [];
+ }
+}
+/**
+ * @internal
+ **/
+class _ThinInstanceDataStorage {
+ constructor() {
+ this.instancesCount = 0;
+ this.matrixBuffer = null;
+ this.previousMatrixBuffer = null;
+ this.matrixBufferSize = 32 * 16; // let's start with a maximum of 32 thin instances
+ this.matrixData = null;
+ this.boundingVectors = [];
+ this.worldMatrices = null;
+ }
+}
+/**
+ * @internal
+ **/
+class _InternalMeshDataInfo {
+ constructor() {
+ this._areNormalsFrozen = false; // Will be used by ribbons mainly
+ // Will be used to save a source mesh reference, If any
+ this._source = null;
+ // Will be used to for fast cloned mesh lookup
+ this.meshMap = null;
+ this._preActivateId = -1;
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ this._LODLevels = new Array();
+ /** Alternative definition of LOD level, using screen coverage instead of distance */
+ this._useLODScreenCoverage = false;
+ this._effectiveMaterial = null;
+ this._forcedInstanceCount = 0;
+ this._overrideRenderingFillMode = null;
+ }
+}
+const meshCreationOptions = {
+ source: null,
+ parent: null,
+ doNotCloneChildren: false,
+ clonePhysicsImpostor: true,
+ cloneThinInstances: false,
+};
+/**
+ * Class used to represent renderable models
+ */
+class Mesh extends AbstractMesh {
+ /**
+ * Gets the default side orientation.
+ * @param orientation the orientation to value to attempt to get
+ * @returns the default orientation
+ * @internal
+ */
+ static _GetDefaultSideOrientation(orientation) {
+ return orientation || Mesh.FRONTSIDE; // works as Mesh.FRONTSIDE is 0
+ }
+ /**
+ * Determines if the LOD levels are intended to be calculated using screen coverage (surface area ratio) instead of distance.
+ */
+ get useLODScreenCoverage() {
+ return this._internalMeshDataInfo._useLODScreenCoverage;
+ }
+ set useLODScreenCoverage(value) {
+ this._internalMeshDataInfo._useLODScreenCoverage = value;
+ this._sortLODLevels();
+ }
+ get computeBonesUsingShaders() {
+ return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;
+ }
+ set computeBonesUsingShaders(value) {
+ if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) {
+ return;
+ }
+ if (value && this._internalMeshDataInfo._sourcePositions) {
+ // switch from software to GPU computation: we need to reset the vertex and normal buffers that have been updated by the software process
+ this.setVerticesData(VertexBuffer.PositionKind, this._internalMeshDataInfo._sourcePositions, true);
+ if (this._internalMeshDataInfo._sourceNormals) {
+ this.setVerticesData(VertexBuffer.NormalKind, this._internalMeshDataInfo._sourceNormals, true);
+ }
+ this._internalMeshDataInfo._sourcePositions = null;
+ this._internalMeshDataInfo._sourceNormals = null;
+ }
+ this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value;
+ this._markSubMeshesAsAttributesDirty();
+ }
+ /**
+ * An event triggered before rendering the mesh
+ */
+ get onBeforeRenderObservable() {
+ if (!this._internalMeshDataInfo._onBeforeRenderObservable) {
+ this._internalMeshDataInfo._onBeforeRenderObservable = new Observable();
+ }
+ return this._internalMeshDataInfo._onBeforeRenderObservable;
+ }
+ /**
+ * An event triggered before binding the mesh
+ */
+ get onBeforeBindObservable() {
+ if (!this._internalMeshDataInfo._onBeforeBindObservable) {
+ this._internalMeshDataInfo._onBeforeBindObservable = new Observable();
+ }
+ return this._internalMeshDataInfo._onBeforeBindObservable;
+ }
+ /**
+ * An event triggered after rendering the mesh
+ */
+ get onAfterRenderObservable() {
+ if (!this._internalMeshDataInfo._onAfterRenderObservable) {
+ this._internalMeshDataInfo._onAfterRenderObservable = new Observable();
+ }
+ return this._internalMeshDataInfo._onAfterRenderObservable;
+ }
+ /**
+ * An event triggeredbetween rendering pass when using separateCullingPass = true
+ */
+ get onBetweenPassObservable() {
+ if (!this._internalMeshDataInfo._onBetweenPassObservable) {
+ this._internalMeshDataInfo._onBetweenPassObservable = new Observable();
+ }
+ return this._internalMeshDataInfo._onBetweenPassObservable;
+ }
+ /**
+ * An event triggered before drawing the mesh
+ */
+ get onBeforeDrawObservable() {
+ if (!this._internalMeshDataInfo._onBeforeDrawObservable) {
+ this._internalMeshDataInfo._onBeforeDrawObservable = new Observable();
+ }
+ return this._internalMeshDataInfo._onBeforeDrawObservable;
+ }
+ /**
+ * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
+ */
+ set onBeforeDraw(callback) {
+ if (this._onBeforeDrawObserver) {
+ this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
+ }
+ this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
+ }
+ get hasInstances() {
+ return this.instances.length > 0;
+ }
+ get hasThinInstances() {
+ return (this.forcedInstanceCount || this._thinInstanceDataStorage.instancesCount || 0) > 0;
+ }
+ /**
+ * Gets or sets the forced number of instances to display.
+ * If 0 (default value), the number of instances is not forced and depends on the draw type
+ * (regular / instance / thin instances mesh)
+ */
+ get forcedInstanceCount() {
+ return this._internalMeshDataInfo._forcedInstanceCount;
+ }
+ set forcedInstanceCount(count) {
+ this._internalMeshDataInfo._forcedInstanceCount = count;
+ }
+ /**
+ * Use this property to change the original side orientation defined at construction time
+ * Material.sideOrientation will override this value if set
+ * User will still be able to change the material sideOrientation afterwards if they really need it
+ */
+ get sideOrientation() {
+ return this._internalMeshDataInfo._sideOrientation;
+ }
+ set sideOrientation(value) {
+ this._internalMeshDataInfo._sideOrientation = value;
+ this._internalAbstractMeshDataInfo._sideOrientationHint =
+ (this._scene.useRightHandedSystem && value === 1) ||
+ (!this._scene.useRightHandedSystem && value === 0);
+ }
+ /**
+ * @deprecated Please use sideOrientation instead.
+ * @see https://doc.babylonjs.com/breaking-changes#7110
+ */
+ get overrideMaterialSideOrientation() {
+ return this.sideOrientation;
+ }
+ set overrideMaterialSideOrientation(value) {
+ this.sideOrientation = value;
+ if (this.material) {
+ this.material.sideOrientation = null;
+ }
+ }
+ /**
+ * Use this property to override the Material's fillMode value
+ */
+ get overrideRenderingFillMode() {
+ return this._internalMeshDataInfo._overrideRenderingFillMode;
+ }
+ set overrideRenderingFillMode(fillMode) {
+ this._internalMeshDataInfo._overrideRenderingFillMode = fillMode;
+ }
+ get material() {
+ return this._internalAbstractMeshDataInfo._material;
+ }
+ set material(value) {
+ if (value && ((this.material && this.material.sideOrientation === null) || this._internalAbstractMeshDataInfo._sideOrientationHint)) {
+ value.sideOrientation = null;
+ }
+ this._setMaterial(value);
+ }
+ /**
+ * Gets the source mesh (the one used to clone this one from)
+ */
+ get source() {
+ return this._internalMeshDataInfo._source;
+ }
+ /**
+ * Gets the list of clones of this mesh
+ * The scene must have been constructed with useClonedMeshMap=true for this to work!
+ * Note that useClonedMeshMap=true is the default setting
+ */
+ get cloneMeshMap() {
+ return this._internalMeshDataInfo.meshMap;
+ }
+ /**
+ * Gets or sets a boolean indicating that this mesh does not use index buffer
+ */
+ get isUnIndexed() {
+ return this._unIndexed;
+ }
+ set isUnIndexed(value) {
+ if (this._unIndexed !== value) {
+ this._unIndexed = value;
+ this._markSubMeshesAsAttributesDirty();
+ }
+ }
+ /** Gets the array buffer used to store the instanced buffer used for instances' world matrices */
+ get worldMatrixInstancedBuffer() {
+ return this._instanceDataStorage.instancesData;
+ }
+ /** Gets the array buffer used to store the instanced buffer used for instances' previous world matrices */
+ get previousWorldMatrixInstancedBuffer() {
+ return this._instanceDataStorage.instancesPreviousData;
+ }
+ /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */
+ get manualUpdateOfWorldMatrixInstancedBuffer() {
+ return this._instanceDataStorage.manualUpdate;
+ }
+ set manualUpdateOfWorldMatrixInstancedBuffer(value) {
+ this._instanceDataStorage.manualUpdate = value;
+ }
+ /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */
+ get manualUpdateOfPreviousWorldMatrixInstancedBuffer() {
+ return this._instanceDataStorage.previousManualUpdate;
+ }
+ set manualUpdateOfPreviousWorldMatrixInstancedBuffer(value) {
+ this._instanceDataStorage.previousManualUpdate = value;
+ }
+ /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices must be performed in all cases (and notably even in frozen mode) */
+ get forceWorldMatrixInstancedBufferUpdate() {
+ return this._instanceDataStorage.forceMatrixUpdates;
+ }
+ set forceWorldMatrixInstancedBufferUpdate(value) {
+ this._instanceDataStorage.forceMatrixUpdates = value;
+ }
+ _copySource(source, doNotCloneChildren, clonePhysicsImpostor = true, cloneThinInstances = false) {
+ const scene = this.getScene();
+ // Geometry
+ if (source._geometry) {
+ source._geometry.applyToMesh(this);
+ }
+ // Deep copy
+ DeepCopier.DeepCopy(source, this, [
+ "name",
+ "material",
+ "skeleton",
+ "instances",
+ "parent",
+ "uniqueId",
+ "source",
+ "metadata",
+ "morphTargetManager",
+ "hasInstances",
+ "worldMatrixInstancedBuffer",
+ "previousWorldMatrixInstancedBuffer",
+ "hasLODLevels",
+ "geometry",
+ "isBlocked",
+ "areNormalsFrozen",
+ "facetNb",
+ "isFacetDataEnabled",
+ "lightSources",
+ "useBones",
+ "isAnInstance",
+ "collider",
+ "edgesRenderer",
+ "forward",
+ "up",
+ "right",
+ "absolutePosition",
+ "absoluteScaling",
+ "absoluteRotationQuaternion",
+ "isWorldMatrixFrozen",
+ "nonUniformScaling",
+ "behaviors",
+ "worldMatrixFromCache",
+ "hasThinInstances",
+ "cloneMeshMap",
+ "hasBoundingInfo",
+ "physicsBody",
+ "physicsImpostor",
+ ], ["_poseMatrix"]);
+ // Source mesh
+ this._internalMeshDataInfo._source = source;
+ if (scene.useClonedMeshMap) {
+ if (!source._internalMeshDataInfo.meshMap) {
+ source._internalMeshDataInfo.meshMap = {};
+ }
+ source._internalMeshDataInfo.meshMap[this.uniqueId] = this;
+ }
+ // Construction Params
+ // Clone parameters allowing mesh to be updated in case of parametric shapes.
+ this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
+ this._creationDataStorage = source._creationDataStorage;
+ // Animation ranges
+ if (source._ranges) {
+ const ranges = source._ranges;
+ for (const name in ranges) {
+ if (!Object.prototype.hasOwnProperty.call(ranges, name)) {
+ continue;
+ }
+ if (!ranges[name]) {
+ continue;
+ }
+ this.createAnimationRange(name, ranges[name].from, ranges[name].to);
+ }
+ }
+ // Metadata
+ if (source.metadata && source.metadata.clone) {
+ this.metadata = source.metadata.clone();
+ }
+ else {
+ this.metadata = source.metadata;
+ }
+ this._internalMetadata = source._internalMetadata;
+ // Tags
+ if (Tags && Tags.HasTags(source)) {
+ Tags.AddTagsTo(this, Tags.GetTags(source, true));
+ }
+ // Enabled. We shouldn't need to check the source's ancestors, as this mesh
+ // will have the same ones.
+ this.setEnabled(source.isEnabled(false));
+ // Parent
+ this.parent = source.parent;
+ // Pivot
+ this.setPivotMatrix(source.getPivotMatrix(), this._postMultiplyPivotMatrix);
+ this.id = this.name + "." + source.id;
+ // Material
+ this.material = source.material;
+ if (!doNotCloneChildren) {
+ // Children
+ const directDescendants = source.getDescendants(true);
+ for (let index = 0; index < directDescendants.length; index++) {
+ const child = directDescendants[index];
+ if (child._isMesh) {
+ meshCreationOptions.parent = this;
+ meshCreationOptions.doNotCloneChildren = doNotCloneChildren;
+ meshCreationOptions.clonePhysicsImpostor = clonePhysicsImpostor;
+ meshCreationOptions.cloneThinInstances = cloneThinInstances;
+ child.clone(this.name + "." + child.name, meshCreationOptions);
+ }
+ else if (child.clone) {
+ child.clone(this.name + "." + child.name, this);
+ }
+ }
+ }
+ // Morphs
+ if (source.morphTargetManager) {
+ this.morphTargetManager = source.morphTargetManager;
+ }
+ // Physics clone
+ if (scene.getPhysicsEngine) {
+ const physicsEngine = scene.getPhysicsEngine();
+ if (clonePhysicsImpostor && physicsEngine) {
+ if (physicsEngine.getPluginVersion() === 1) {
+ const impostor = physicsEngine.getImpostorForPhysicsObject(source);
+ if (impostor) {
+ this.physicsImpostor = impostor.clone(this);
+ }
+ }
+ else if (physicsEngine.getPluginVersion() === 2) {
+ if (source.physicsBody) {
+ source.physicsBody.clone(this);
+ }
+ }
+ }
+ }
+ // Particles
+ for (let index = 0; index < scene.particleSystems.length; index++) {
+ const system = scene.particleSystems[index];
+ if (system.emitter === source) {
+ system.clone(system.name, this);
+ }
+ }
+ // Skeleton
+ this.skeleton = source.skeleton;
+ // Thin instances
+ if (cloneThinInstances) {
+ if (source._thinInstanceDataStorage.matrixData) {
+ this.thinInstanceSetBuffer("matrix", new Float32Array(source._thinInstanceDataStorage.matrixData), 16, !source._thinInstanceDataStorage.matrixBuffer.isUpdatable());
+ this._thinInstanceDataStorage.matrixBufferSize = source._thinInstanceDataStorage.matrixBufferSize;
+ this._thinInstanceDataStorage.instancesCount = source._thinInstanceDataStorage.instancesCount;
+ }
+ else {
+ this._thinInstanceDataStorage.matrixBufferSize = source._thinInstanceDataStorage.matrixBufferSize;
+ }
+ if (source._userThinInstanceBuffersStorage) {
+ const userThinInstance = source._userThinInstanceBuffersStorage;
+ for (const kind in userThinInstance.data) {
+ this.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], !userThinInstance.vertexBuffers?.[kind]?.isUpdatable());
+ this._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind];
+ }
+ }
+ }
+ this.refreshBoundingInfo(true, true);
+ this.computeWorldMatrix(true);
+ }
+ /** @internal */
+ constructor(name, scene = null, parentOrOptions = null, source = null, doNotCloneChildren, clonePhysicsImpostor = true) {
+ super(name, scene);
+ // Internal data
+ this._internalMeshDataInfo = new _InternalMeshDataInfo();
+ // Members
+ /**
+ * Gets the delay loading state of the mesh (when delay loading is turned on)
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/incrementalLoading
+ */
+ this.delayLoadState = 0;
+ /**
+ * Gets the list of instances created from this mesh
+ * it is not supposed to be modified manually.
+ * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances
+ */
+ this.instances = [];
+ // Private
+ /** @internal */
+ this._creationDataStorage = null;
+ /** @internal */
+ this._geometry = null;
+ /** @internal */
+ this._instanceDataStorage = new _InstanceDataStorage();
+ /** @internal */
+ this._thinInstanceDataStorage = new _ThinInstanceDataStorage();
+ /** @internal */
+ this._shouldGenerateFlatShading = false;
+ // Use by builder only to know what orientation were the mesh build in.
+ /** @internal */
+ this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
+ /**
+ * Gets or sets a boolean indicating whether to render ignoring the active camera's max z setting. (false by default)
+ * You should not mix meshes that have this property set to true with meshes that have it set to false if they all write
+ * to the depth buffer, because the z-values are not comparable in the two cases and you will get rendering artifacts if you do.
+ * You can set the property to true for meshes that do not write to the depth buffer, or set the same value (either false or true) otherwise.
+ * Note this will reduce performance when set to true.
+ */
+ this.ignoreCameraMaxZ = false;
+ scene = this.getScene();
+ if (this._scene.useRightHandedSystem) {
+ this.sideOrientation = 0;
+ }
+ else {
+ this.sideOrientation = 1;
+ }
+ this._onBeforeDraw = (isInstance, world, effectiveMaterial) => {
+ if (isInstance && effectiveMaterial) {
+ if (this._uniformBuffer) {
+ this.transferToEffect(world);
+ }
+ else {
+ effectiveMaterial.bindOnlyWorldMatrix(world);
+ }
+ }
+ };
+ let parent = null;
+ let cloneThinInstances = false;
+ if (parentOrOptions && parentOrOptions._addToSceneRootNodes === undefined) {
+ const options = parentOrOptions;
+ parent = options.parent ?? null;
+ source = options.source ?? null;
+ doNotCloneChildren = options.doNotCloneChildren ?? false;
+ clonePhysicsImpostor = options.clonePhysicsImpostor ?? true;
+ cloneThinInstances = options.cloneThinInstances ?? false;
+ }
+ else {
+ parent = parentOrOptions;
+ }
+ if (source) {
+ this._copySource(source, doNotCloneChildren, clonePhysicsImpostor, cloneThinInstances);
+ }
+ // Parent
+ if (parent !== null) {
+ this.parent = parent;
+ }
+ this._instanceDataStorage.hardwareInstancedRendering = this.getEngine().getCaps().instancedArrays;
+ this._internalMeshDataInfo._onMeshReadyObserverAdded = (observer) => {
+ // only notify once! then unregister the observer
+ observer.unregisterOnNextCall = true;
+ if (this.isReady(true)) {
+ this.onMeshReadyObservable.notifyObservers(this);
+ }
+ else {
+ if (!this._internalMeshDataInfo._checkReadinessObserver) {
+ this._internalMeshDataInfo._checkReadinessObserver = this._scene.onBeforeRenderObservable.add(() => {
+ // check for complete readiness
+ if (this.isReady(true)) {
+ this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver);
+ this._internalMeshDataInfo._checkReadinessObserver = null;
+ this.onMeshReadyObservable.notifyObservers(this);
+ }
+ });
+ }
+ }
+ };
+ this.onMeshReadyObservable = new Observable(this._internalMeshDataInfo._onMeshReadyObserverAdded);
+ if (source) {
+ source.onClonedObservable.notifyObservers(this);
+ }
+ }
+ instantiateHierarchy(newParent = null, options, onNewNodeCreated) {
+ const instance = this.getTotalVertices() === 0 || (options && options.doNotInstantiate && (options.doNotInstantiate === true || options.doNotInstantiate(this)))
+ ? this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true)
+ : this.createInstance("instance of " + (this.name || this.id));
+ instance.parent = newParent || this.parent;
+ instance.position = this.position.clone();
+ instance.scaling = this.scaling.clone();
+ if (this.rotationQuaternion) {
+ instance.rotationQuaternion = this.rotationQuaternion.clone();
+ }
+ else {
+ instance.rotation = this.rotation.clone();
+ }
+ if (onNewNodeCreated) {
+ onNewNodeCreated(this, instance);
+ }
+ for (const child of this.getChildTransformNodes(true)) {
+ // instancedMesh should have a different sourced mesh
+ if (child.getClassName() === "InstancedMesh" && instance.getClassName() === "Mesh" && child.sourceMesh === this) {
+ child.instantiateHierarchy(instance, {
+ doNotInstantiate: (options && options.doNotInstantiate) || false,
+ newSourcedMesh: instance,
+ }, onNewNodeCreated);
+ }
+ else {
+ child.instantiateHierarchy(instance, options, onNewNodeCreated);
+ }
+ }
+ return instance;
+ }
+ /**
+ * Gets the class name
+ * @returns the string "Mesh".
+ */
+ getClassName() {
+ return "Mesh";
+ }
+ /** @internal */
+ get _isMesh() {
+ return true;
+ }
+ /**
+ * Returns a description of this mesh
+ * @param fullDetails define if full details about this mesh must be used
+ * @returns a descriptive string representing this mesh
+ */
+ toString(fullDetails) {
+ let ret = super.toString(fullDetails);
+ ret += ", n vertices: " + this.getTotalVertices();
+ ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE");
+ if (this.animations) {
+ for (let i = 0; i < this.animations.length; i++) {
+ ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
+ }
+ }
+ if (fullDetails) {
+ if (this._geometry) {
+ const ib = this.getIndices();
+ const vb = this.getVerticesData(VertexBuffer.PositionKind);
+ if (vb && ib) {
+ ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
+ }
+ }
+ else {
+ ret += ", flat shading: UNKNOWN";
+ }
+ }
+ return ret;
+ }
+ /** @internal */
+ _unBindEffect() {
+ super._unBindEffect();
+ for (const instance of this.instances) {
+ instance._unBindEffect();
+ }
+ }
+ /**
+ * Gets a boolean indicating if this mesh has LOD
+ */
+ get hasLODLevels() {
+ return this._internalMeshDataInfo._LODLevels.length > 0;
+ }
+ /**
+ * Gets the list of MeshLODLevel associated with the current mesh
+ * @returns an array of MeshLODLevel
+ */
+ getLODLevels() {
+ return this._internalMeshDataInfo._LODLevels;
+ }
+ _sortLODLevels() {
+ const sortingOrderFactor = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1;
+ this._internalMeshDataInfo._LODLevels.sort((a, b) => {
+ if (a.distanceOrScreenCoverage < b.distanceOrScreenCoverage) {
+ return sortingOrderFactor;
+ }
+ if (a.distanceOrScreenCoverage > b.distanceOrScreenCoverage) {
+ return -sortingOrderFactor;
+ }
+ return 0;
+ });
+ }
+ /**
+ * Add a mesh as LOD level triggered at the given distance.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
+ * @param distanceOrScreenCoverage Either distance from the center of the object to show this level or the screen coverage if `useScreenCoverage` is set to `true`.
+ * If screen coverage, value is a fraction of the screen's total surface, between 0 and 1.
+ * Example Playground for distance https://playground.babylonjs.com/#QE7KM#197
+ * Example Playground for screen coverage https://playground.babylonjs.com/#QE7KM#196
+ * @param mesh The mesh to be added as LOD level (can be null)
+ * @returns This mesh (for chaining)
+ */
+ addLODLevel(distanceOrScreenCoverage, mesh) {
+ if (mesh && mesh._masterMesh) {
+ Logger.Warn("You cannot use a mesh as LOD level twice");
+ return this;
+ }
+ const level = new MeshLODLevel(distanceOrScreenCoverage, mesh);
+ this._internalMeshDataInfo._LODLevels.push(level);
+ if (mesh) {
+ mesh._masterMesh = this;
+ }
+ this._sortLODLevels();
+ return this;
+ }
+ /**
+ * Returns the LOD level mesh at the passed distance or null if not found.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
+ * @param distance The distance from the center of the object to show this level
+ * @returns a Mesh or `null`
+ */
+ getLODLevelAtDistance(distance) {
+ const internalDataInfo = this._internalMeshDataInfo;
+ for (let index = 0; index < internalDataInfo._LODLevels.length; index++) {
+ const level = internalDataInfo._LODLevels[index];
+ if (level.distanceOrScreenCoverage === distance) {
+ return level.mesh;
+ }
+ }
+ return null;
+ }
+ /**
+ * Remove a mesh from the LOD array
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
+ * @param mesh defines the mesh to be removed
+ * @returns This mesh (for chaining)
+ */
+ removeLODLevel(mesh) {
+ const internalDataInfo = this._internalMeshDataInfo;
+ for (let index = 0; index < internalDataInfo._LODLevels.length; index++) {
+ if (internalDataInfo._LODLevels[index].mesh === mesh) {
+ internalDataInfo._LODLevels.splice(index, 1);
+ if (mesh) {
+ mesh._masterMesh = null;
+ }
+ }
+ }
+ this._sortLODLevels();
+ return this;
+ }
+ /**
+ * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
+ * @param camera defines the camera to use to compute distance
+ * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
+ * @returns This mesh (for chaining)
+ */
+ getLOD(camera, boundingSphere) {
+ const internalDataInfo = this._internalMeshDataInfo;
+ if (!internalDataInfo._LODLevels || internalDataInfo._LODLevels.length === 0) {
+ return this;
+ }
+ const bSphere = boundingSphere || this.getBoundingInfo().boundingSphere;
+ const distanceToCamera = camera.mode === Camera.ORTHOGRAPHIC_CAMERA ? camera.minZ : bSphere.centerWorld.subtract(camera.globalPosition).length();
+ let compareValue = distanceToCamera;
+ let compareSign = 1;
+ if (internalDataInfo._useLODScreenCoverage) {
+ const screenArea = camera.screenArea;
+ let meshArea = (bSphere.radiusWorld * camera.minZ) / distanceToCamera;
+ meshArea = meshArea * meshArea * Math.PI;
+ compareValue = meshArea / screenArea;
+ compareSign = -1;
+ }
+ if (compareSign * internalDataInfo._LODLevels[internalDataInfo._LODLevels.length - 1].distanceOrScreenCoverage > compareSign * compareValue) {
+ if (this.onLODLevelSelection) {
+ this.onLODLevelSelection(compareValue, this, this);
+ }
+ return this;
+ }
+ for (let index = 0; index < internalDataInfo._LODLevels.length; index++) {
+ const level = internalDataInfo._LODLevels[index];
+ if (compareSign * level.distanceOrScreenCoverage < compareSign * compareValue) {
+ if (level.mesh) {
+ if (level.mesh.delayLoadState === 4) {
+ level.mesh._checkDelayState();
+ return this;
+ }
+ if (level.mesh.delayLoadState === 2) {
+ return this;
+ }
+ level.mesh._preActivate();
+ level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
+ }
+ if (this.onLODLevelSelection) {
+ this.onLODLevelSelection(compareValue, this, level.mesh);
+ }
+ return level.mesh;
+ }
+ }
+ if (this.onLODLevelSelection) {
+ this.onLODLevelSelection(compareValue, this, this);
+ }
+ return this;
+ }
+ /**
+ * Gets the mesh internal Geometry object
+ */
+ get geometry() {
+ return this._geometry;
+ }
+ /**
+ * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
+ * @returns the total number of vertices
+ */
+ getTotalVertices() {
+ if (this._geometry === null || this._geometry === undefined) {
+ return 0;
+ }
+ return this._geometry.getTotalVertices();
+ }
+ /**
+ * Returns the content of an associated vertex buffer
+ * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
+ * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
+ * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false
+ * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
+ */
+ getVerticesData(kind, copyWhenShared, forceCopy, bypassInstanceData) {
+ if (!this._geometry) {
+ return null;
+ }
+ let data = bypassInstanceData
+ ? undefined
+ : this._userInstancedBuffersStorage?.vertexBuffers[kind]?.getFloatData(this.instances.length + 1, // +1 because the master mesh is not included in the instances array
+ forceCopy || (copyWhenShared && this._geometry.meshes.length !== 1));
+ if (!data) {
+ data = this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
+ }
+ return data;
+ }
+ copyVerticesData(kind, vertexData) {
+ if (this._geometry) {
+ this._geometry.copyVerticesData(kind, vertexData);
+ }
+ }
+ /**
+ * Returns the mesh VertexBuffer object from the requested `kind`
+ * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.NormalKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false
+ * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
+ */
+ getVertexBuffer(kind, bypassInstanceData) {
+ if (!this._geometry) {
+ return null;
+ }
+ return (bypassInstanceData ? undefined : this._userInstancedBuffersStorage?.vertexBuffers[kind]) ?? this._geometry.getVertexBuffer(kind);
+ }
+ /**
+ * Tests if a specific vertex buffer is associated with this mesh
+ * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.NormalKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false
+ * @returns a boolean
+ */
+ isVerticesDataPresent(kind, bypassInstanceData) {
+ if (!this._geometry) {
+ if (this._delayInfo) {
+ return this._delayInfo.indexOf(kind) !== -1;
+ }
+ return false;
+ }
+ return (!bypassInstanceData && this._userInstancedBuffersStorage?.vertexBuffers[kind] !== undefined) || this._geometry.isVerticesDataPresent(kind);
+ }
+ /**
+ * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
+ * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false
+ * @returns a boolean
+ */
+ isVertexBufferUpdatable(kind, bypassInstanceData) {
+ if (!this._geometry) {
+ if (this._delayInfo) {
+ return this._delayInfo.indexOf(kind) !== -1;
+ }
+ return false;
+ }
+ if (!bypassInstanceData) {
+ const buffer = this._userInstancedBuffersStorage?.vertexBuffers[kind];
+ if (buffer) {
+ return buffer.isUpdatable();
+ }
+ }
+ return this._geometry.isVertexBufferUpdatable(kind);
+ }
+ /**
+ * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
+ * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false
+ * @returns an array of strings
+ */
+ getVerticesDataKinds(bypassInstanceData) {
+ if (!this._geometry) {
+ const result = [];
+ if (this._delayInfo) {
+ this._delayInfo.forEach(function (kind) {
+ result.push(kind);
+ });
+ }
+ return result;
+ }
+ const kinds = this._geometry.getVerticesDataKinds();
+ if (!bypassInstanceData && this._userInstancedBuffersStorage) {
+ for (const kind in this._userInstancedBuffersStorage.vertexBuffers) {
+ if (kinds.indexOf(kind) === -1) {
+ kinds.push(kind);
+ }
+ }
+ }
+ return kinds;
+ }
+ /**
+ * Returns a positive integer : the total number of indices in this mesh geometry.
+ * @returns the numner of indices or zero if the mesh has no geometry.
+ */
+ getTotalIndices() {
+ if (!this._geometry) {
+ return 0;
+ }
+ return this._geometry.getTotalIndices();
+ }
+ /**
+ * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
+ * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
+ * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
+ * @returns the indices array or an empty array if the mesh has no geometry
+ */
+ getIndices(copyWhenShared, forceCopy) {
+ if (!this._geometry) {
+ return [];
+ }
+ return this._geometry.getIndices(copyWhenShared, forceCopy);
+ }
+ get isBlocked() {
+ return this._masterMesh !== null && this._masterMesh !== undefined;
+ }
+ /**
+ * Determine if the current mesh is ready to be rendered
+ * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
+ * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
+ * @returns true if all associated assets are ready (material, textures, shaders)
+ */
+ isReady(completeCheck = false, forceInstanceSupport = false) {
+ if (this.delayLoadState === 2) {
+ return false;
+ }
+ if (!super.isReady(completeCheck)) {
+ return false;
+ }
+ if (!this.subMeshes || this.subMeshes.length === 0) {
+ return true;
+ }
+ if (!completeCheck) {
+ return true;
+ }
+ const engine = this.getEngine();
+ const scene = this.getScene();
+ const hardwareInstancedRendering = forceInstanceSupport || (engine.getCaps().instancedArrays && (this.instances.length > 0 || this.hasThinInstances));
+ this.computeWorldMatrix();
+ const mat = this.material || scene.defaultMaterial;
+ if (mat) {
+ if (mat._storeEffectOnSubMeshes) {
+ for (const subMesh of this.subMeshes) {
+ const effectiveMaterial = subMesh.getMaterial();
+ if (effectiveMaterial) {
+ if (effectiveMaterial._storeEffectOnSubMeshes) {
+ if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
+ return false;
+ }
+ }
+ else {
+ if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
+ return false;
+ }
+ }
+ }
+ }
+ }
+ else {
+ if (!mat.isReady(this, hardwareInstancedRendering)) {
+ return false;
+ }
+ }
+ }
+ // Shadows
+ const currentRenderPassId = engine.currentRenderPassId;
+ for (const light of this.lightSources) {
+ const generators = light.getShadowGenerators();
+ if (!generators) {
+ continue;
+ }
+ const iterator = generators.values();
+ for (let key = iterator.next(); key.done !== true; key = iterator.next()) {
+ const generator = key.value;
+ if (generator && (!generator.getShadowMap()?.renderList || (generator.getShadowMap()?.renderList && generator.getShadowMap()?.renderList?.indexOf(this) !== -1))) {
+ const shadowMap = generator.getShadowMap();
+ const renderPassIds = shadowMap.renderPassIds ?? [engine.currentRenderPassId];
+ for (let p = 0; p < renderPassIds.length; ++p) {
+ engine.currentRenderPassId = renderPassIds[p];
+ for (const subMesh of this.subMeshes) {
+ if (!generator.isReady(subMesh, hardwareInstancedRendering, subMesh.getMaterial()?.needAlphaBlendingForMesh(this) ?? false)) {
+ engine.currentRenderPassId = currentRenderPassId;
+ return false;
+ }
+ }
+ }
+ engine.currentRenderPassId = currentRenderPassId;
+ }
+ }
+ }
+ // LOD
+ for (const lod of this._internalMeshDataInfo._LODLevels) {
+ if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
+ */
+ get areNormalsFrozen() {
+ return this._internalMeshDataInfo._areNormalsFrozen;
+ }
+ /**
+ * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
+ * @returns the current mesh
+ */
+ freezeNormals() {
+ this._internalMeshDataInfo._areNormalsFrozen = true;
+ return this;
+ }
+ /**
+ * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
+ * @returns the current mesh
+ */
+ unfreezeNormals() {
+ this._internalMeshDataInfo._areNormalsFrozen = false;
+ return this;
+ }
+ /**
+ * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
+ */
+ set overridenInstanceCount(count) {
+ this._instanceDataStorage.overridenInstanceCount = count;
+ }
+ // Methods
+ /** @internal */
+ _preActivate() {
+ const internalDataInfo = this._internalMeshDataInfo;
+ const sceneRenderId = this.getScene().getRenderId();
+ if (internalDataInfo._preActivateId === sceneRenderId) {
+ return this;
+ }
+ internalDataInfo._preActivateId = sceneRenderId;
+ this._instanceDataStorage.visibleInstances = null;
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _preActivateForIntermediateRendering(renderId) {
+ if (this._instanceDataStorage.visibleInstances) {
+ this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
+ }
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _registerInstanceForRenderId(instance, renderId) {
+ if (!this._instanceDataStorage.visibleInstances) {
+ this._instanceDataStorage.visibleInstances = {
+ defaultRenderId: renderId,
+ selfDefaultRenderId: this._renderId,
+ };
+ }
+ if (!this._instanceDataStorage.visibleInstances[renderId]) {
+ if (this._instanceDataStorage.previousRenderId !== undefined && this._instanceDataStorage.isFrozen) {
+ this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId] = null;
+ }
+ this._instanceDataStorage.previousRenderId = renderId;
+ this._instanceDataStorage.visibleInstances[renderId] = new Array();
+ }
+ this._instanceDataStorage.visibleInstances[renderId].push(instance);
+ return this;
+ }
+ _afterComputeWorldMatrix() {
+ super._afterComputeWorldMatrix();
+ if (!this.hasThinInstances) {
+ return;
+ }
+ if (!this.doNotSyncBoundingInfo) {
+ this.thinInstanceRefreshBoundingInfo(false);
+ }
+ }
+ /** @internal */
+ _postActivate() {
+ if (this.edgesShareWithInstances && this.edgesRenderer && this.edgesRenderer.isEnabled && this._renderingGroup) {
+ this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer);
+ this.edgesRenderer.customInstances.push(this.getWorldMatrix());
+ }
+ }
+ /**
+ * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
+ * This means the mesh underlying bounding box and sphere are recomputed.
+ * @param applySkeletonOrOptions defines whether to apply the skeleton before computing the bounding info or a set of options
+ * @param applyMorph defines whether to apply the morph target before computing the bounding info
+ * @returns the current mesh
+ */
+ refreshBoundingInfo(applySkeletonOrOptions = false, applyMorph = false) {
+ if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) {
+ return this;
+ }
+ let options;
+ if (typeof applySkeletonOrOptions === "object") {
+ options = applySkeletonOrOptions;
+ }
+ else {
+ options = {
+ applySkeleton: applySkeletonOrOptions,
+ applyMorph: applyMorph,
+ };
+ }
+ const bias = this.geometry ? this.geometry.boundingBias : null;
+ this._refreshBoundingInfo(this._getData(options, null, VertexBuffer.PositionKind), bias);
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _createGlobalSubMesh(force) {
+ const totalVertices = this.getTotalVertices();
+ if (!totalVertices || !this.getIndices()) {
+ return null;
+ }
+ // Check if we need to recreate the submeshes
+ if (this.subMeshes && this.subMeshes.length > 0) {
+ const ib = this.getIndices();
+ if (!ib) {
+ return null;
+ }
+ const totalIndices = ib.length;
+ let needToRecreate = false;
+ if (force) {
+ needToRecreate = true;
+ }
+ else {
+ for (const submesh of this.subMeshes) {
+ if (submesh.indexStart + submesh.indexCount > totalIndices) {
+ needToRecreate = true;
+ break;
+ }
+ if (submesh.verticesStart + submesh.verticesCount > totalVertices) {
+ needToRecreate = true;
+ break;
+ }
+ }
+ }
+ if (!needToRecreate) {
+ return this.subMeshes[0];
+ }
+ }
+ this.releaseSubMeshes();
+ return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices() || totalVertices, this); // getTotalIndices() can be zero if the mesh is unindexed
+ }
+ /**
+ * This function will subdivide the mesh into multiple submeshes
+ * @param count defines the expected number of submeshes
+ */
+ subdivide(count) {
+ if (count < 1) {
+ return;
+ }
+ const totalIndices = this.getTotalIndices();
+ let subdivisionSize = (totalIndices / count) | 0;
+ let offset = 0;
+ // Ensure that subdivisionSize is a multiple of 3
+ while (subdivisionSize % 3 !== 0) {
+ subdivisionSize++;
+ }
+ this.releaseSubMeshes();
+ for (let index = 0; index < count; index++) {
+ if (offset >= totalIndices) {
+ break;
+ }
+ SubMesh.CreateFromIndices(0, offset, index === count - 1 ? totalIndices - offset : subdivisionSize, this, undefined, false);
+ offset += subdivisionSize;
+ }
+ this.refreshBoundingInfo();
+ this.synchronizeInstances();
+ }
+ /**
+ * Copy a FloatArray into a specific associated vertex buffer
+ * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ * @param data defines the data source
+ * @param updatable defines if the updated vertex buffer must be flagged as updatable
+ * @param stride defines the data stride size (can be null)
+ * @returns the current mesh
+ */
+ setVerticesData(kind, data, updatable = false, stride) {
+ if (!this._geometry) {
+ const vertexData = new VertexData();
+ vertexData.set(data, kind);
+ const scene = this.getScene();
+ new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
+ }
+ else {
+ this._geometry.setVerticesData(kind, data, updatable, stride);
+ }
+ return this;
+ }
+ /**
+ * Delete a vertex buffer associated with this mesh
+ * @param kind defines which buffer to delete (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ */
+ removeVerticesData(kind) {
+ if (!this._geometry) {
+ return;
+ }
+ this._geometry.removeVerticesData(kind);
+ }
+ /**
+ * Flags an associated vertex buffer as updatable
+ * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ * @param updatable defines if the updated vertex buffer must be flagged as updatable
+ */
+ markVerticesDataAsUpdatable(kind, updatable = true) {
+ const vb = this.getVertexBuffer(kind);
+ if (!vb || vb.isUpdatable() === updatable) {
+ return;
+ }
+ this.setVerticesData(kind, this.getVerticesData(kind), updatable);
+ }
+ /**
+ * Sets the mesh global Vertex Buffer
+ * @param buffer defines the buffer to use
+ * @param disposeExistingBuffer disposes the existing buffer, if any (default: true)
+ * @returns the current mesh
+ */
+ setVerticesBuffer(buffer, disposeExistingBuffer = true) {
+ if (!this._geometry) {
+ this._geometry = Geometry.CreateGeometryForMesh(this);
+ }
+ this._geometry.setVerticesBuffer(buffer, null, disposeExistingBuffer);
+ return this;
+ }
+ /**
+ * Update a specific associated vertex buffer
+ * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ * @param data defines the data source
+ * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
+ * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
+ * @returns the current mesh
+ */
+ updateVerticesData(kind, data, updateExtends, makeItUnique) {
+ if (!this._geometry) {
+ return this;
+ }
+ if (!makeItUnique) {
+ this._geometry.updateVerticesData(kind, data, updateExtends);
+ }
+ else {
+ this.makeGeometryUnique();
+ this.updateVerticesData(kind, data, updateExtends, false);
+ }
+ return this;
+ }
+ /**
+ * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#other-shapes-updatemeshpositions
+ * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
+ * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
+ * @returns the current mesh
+ */
+ updateMeshPositions(positionFunction, computeNormals = true) {
+ const positions = this.getVerticesData(VertexBuffer.PositionKind);
+ if (!positions) {
+ return this;
+ }
+ positionFunction(positions);
+ this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
+ if (computeNormals) {
+ const indices = this.getIndices();
+ const normals = this.getVerticesData(VertexBuffer.NormalKind);
+ if (!normals) {
+ return this;
+ }
+ VertexData.ComputeNormals(positions, indices, normals);
+ this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
+ }
+ return this;
+ }
+ /**
+ * Creates a un-shared specific occurence of the geometry for the mesh.
+ * @returns the current mesh
+ */
+ makeGeometryUnique() {
+ if (!this._geometry) {
+ return this;
+ }
+ if (this._geometry.meshes.length === 1) {
+ return this;
+ }
+ const oldGeometry = this._geometry;
+ const geometry = this._geometry.copy(Geometry.RandomId());
+ oldGeometry.releaseForMesh(this, true);
+ geometry.applyToMesh(this);
+ return this;
+ }
+ /**
+ * Sets the index buffer of this mesh.
+ * @param indexBuffer Defines the index buffer to use for this mesh
+ * @param totalVertices Defines the total number of vertices used by the buffer
+ * @param totalIndices Defines the total number of indices in the index buffer
+ * @param is32Bits Defines if the indices are 32 bits. If null (default), the value is guessed from the number of vertices
+ */
+ setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits = null) {
+ let geometry = this._geometry;
+ if (!geometry) {
+ geometry = new Geometry(Geometry.RandomId(), this.getScene(), undefined, undefined, this);
+ }
+ geometry.setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits);
+ }
+ /**
+ * Set the index buffer of this mesh
+ * @param indices defines the source data
+ * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
+ * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
+ * @param dontForceSubMeshRecreation defines a boolean indicating that we don't want to force the recreation of sub-meshes if we don't have to (false by default)
+ * @returns the current mesh
+ */
+ setIndices(indices, totalVertices = null, updatable = false, dontForceSubMeshRecreation = false) {
+ if (!this._geometry) {
+ const vertexData = new VertexData();
+ vertexData.indices = indices;
+ const scene = this.getScene();
+ new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
+ }
+ else {
+ this._geometry.setIndices(indices, totalVertices, updatable, dontForceSubMeshRecreation);
+ }
+ return this;
+ }
+ /**
+ * Update the current index buffer
+ * @param indices defines the source data
+ * @param offset defines the offset in the index buffer where to store the new data (can be null)
+ * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)
+ * @returns the current mesh
+ */
+ updateIndices(indices, offset, gpuMemoryOnly = false) {
+ if (!this._geometry) {
+ return this;
+ }
+ this._geometry.updateIndices(indices, offset, gpuMemoryOnly);
+ return this;
+ }
+ /**
+ * Invert the geometry to move from a right handed system to a left handed one.
+ * @returns the current mesh
+ */
+ toLeftHanded() {
+ if (!this._geometry) {
+ return this;
+ }
+ this._geometry.toLeftHanded();
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _bind(subMesh, effect, fillMode, allowInstancedRendering = true) {
+ if (!this._geometry) {
+ return this;
+ }
+ const engine = this.getScene().getEngine();
+ // Wireframe
+ let indexToBind;
+ if (this._unIndexed) {
+ switch (this._getRenderingFillMode(fillMode)) {
+ case Material.WireFrameFillMode:
+ indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
+ break;
+ default:
+ indexToBind = null;
+ break;
+ }
+ }
+ else {
+ switch (this._getRenderingFillMode(fillMode)) {
+ case Material.PointFillMode:
+ indexToBind = null;
+ break;
+ case Material.WireFrameFillMode:
+ indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
+ break;
+ default:
+ case Material.TriangleFillMode:
+ indexToBind = this._geometry.getIndexBuffer();
+ break;
+ }
+ }
+ return this._bindDirect(effect, indexToBind, allowInstancedRendering);
+ }
+ /**
+ * @internal
+ */
+ _bindDirect(effect, indexToBind, allowInstancedRendering = true) {
+ if (!this._geometry) {
+ return this;
+ }
+ // Morph targets
+ if (this.morphTargetManager && this.morphTargetManager.isUsingTextureForTargets) {
+ this.morphTargetManager._bind(effect);
+ }
+ // VBOs
+ if (!allowInstancedRendering || !this._userInstancedBuffersStorage || this.hasThinInstances) {
+ this._geometry._bind(effect, indexToBind);
+ }
+ else {
+ this._geometry._bind(effect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects);
+ }
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _draw(subMesh, fillMode, instancesCount) {
+ if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
+ return this;
+ }
+ if (this._internalMeshDataInfo._onBeforeDrawObservable) {
+ this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);
+ }
+ const scene = this.getScene();
+ const engine = scene.getEngine();
+ if ((this._unIndexed && fillMode !== Material.WireFrameFillMode) || fillMode == Material.PointFillMode) {
+ // or triangles as points
+ engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, this.forcedInstanceCount || instancesCount);
+ }
+ else if (fillMode == Material.WireFrameFillMode) {
+ // Triangles as wireframe
+ engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, this.forcedInstanceCount || instancesCount);
+ }
+ else {
+ engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, this.forcedInstanceCount || instancesCount);
+ }
+ return this;
+ }
+ /**
+ * Registers for this mesh a javascript function called just before the rendering process
+ * @param func defines the function to call before rendering this mesh
+ * @returns the current mesh
+ */
+ registerBeforeRender(func) {
+ this.onBeforeRenderObservable.add(func);
+ return this;
+ }
+ /**
+ * Disposes a previously registered javascript function called before the rendering
+ * @param func defines the function to remove
+ * @returns the current mesh
+ */
+ unregisterBeforeRender(func) {
+ this.onBeforeRenderObservable.removeCallback(func);
+ return this;
+ }
+ /**
+ * Registers for this mesh a javascript function called just after the rendering is complete
+ * @param func defines the function to call after rendering this mesh
+ * @returns the current mesh
+ */
+ registerAfterRender(func) {
+ this.onAfterRenderObservable.add(func);
+ return this;
+ }
+ /**
+ * Disposes a previously registered javascript function called after the rendering.
+ * @param func defines the function to remove
+ * @returns the current mesh
+ */
+ unregisterAfterRender(func) {
+ this.onAfterRenderObservable.removeCallback(func);
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _getInstancesRenderList(subMeshId, isReplacementMode = false) {
+ if (this._instanceDataStorage.isFrozen) {
+ if (isReplacementMode) {
+ this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[subMeshId] = false;
+ this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[subMeshId] = true;
+ return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;
+ }
+ if (this._instanceDataStorage.previousBatch) {
+ return this._instanceDataStorage.previousBatch;
+ }
+ }
+ const scene = this.getScene();
+ const isInIntermediateRendering = scene._isInIntermediateRendering();
+ const onlyForInstances = isInIntermediateRendering
+ ? this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate
+ : this._internalAbstractMeshDataInfo._onlyForInstances;
+ const batchCache = this._instanceDataStorage.batchCache;
+ batchCache.mustReturn = false;
+ batchCache.renderSelf[subMeshId] = isReplacementMode || (!onlyForInstances && this.isEnabled() && this.isVisible);
+ batchCache.visibleInstances[subMeshId] = null;
+ if (this._instanceDataStorage.visibleInstances && !isReplacementMode) {
+ const visibleInstances = this._instanceDataStorage.visibleInstances;
+ const currentRenderId = scene.getRenderId();
+ const defaultRenderId = isInIntermediateRendering ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId;
+ batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
+ if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
+ batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
+ }
+ }
+ batchCache.hardwareInstancedRendering[subMeshId] =
+ !isReplacementMode &&
+ this._instanceDataStorage.hardwareInstancedRendering &&
+ batchCache.visibleInstances[subMeshId] !== null &&
+ batchCache.visibleInstances[subMeshId] !== undefined;
+ this._instanceDataStorage.previousBatch = batchCache;
+ return batchCache;
+ }
+ /**
+ * This method will also draw the instances if fillMode and effect are passed
+ * @internal
+ */
+ _updateInstancedBuffers(subMesh, batch, currentInstancesBufferSize, engine, fillMode, effect) {
+ const visibleInstances = batch.visibleInstances[subMesh._id];
+ const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0;
+ const instanceStorage = this._instanceDataStorage;
+ let instancesBuffer = instanceStorage.instancesBuffer;
+ let instancesPreviousBuffer = instanceStorage.instancesPreviousBuffer;
+ let offset = 0;
+ let instancesCount = 0;
+ const renderSelf = batch.renderSelf[subMesh._id];
+ const needUpdateBuffer = !instancesBuffer ||
+ currentInstancesBufferSize !== instanceStorage.instancesBufferSize ||
+ (this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousBuffer);
+ if (!this._instanceDataStorage.manualUpdate && (!instanceStorage.isFrozen || needUpdateBuffer)) {
+ const world = this.getWorldMatrix();
+ if (renderSelf) {
+ if (this._scene.needsPreviousWorldMatrices) {
+ if (!instanceStorage.masterMeshPreviousWorldMatrix) {
+ instanceStorage.masterMeshPreviousWorldMatrix = world.clone();
+ instanceStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset);
+ }
+ else {
+ instanceStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset);
+ instanceStorage.masterMeshPreviousWorldMatrix.copyFrom(world);
+ }
+ }
+ world.copyToArray(instanceStorage.instancesData, offset);
+ offset += 16;
+ instancesCount++;
+ }
+ if (visibleInstances) {
+ if (Mesh.INSTANCEDMESH_SORT_TRANSPARENT && this._scene.activeCamera && subMesh.getMaterial()?.needAlphaBlendingForMesh(subMesh.getRenderingMesh())) {
+ const cameraPosition = this._scene.activeCamera.globalPosition;
+ for (let instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
+ const instanceMesh = visibleInstances[instanceIndex];
+ instanceMesh._distanceToCamera = Vector3.Distance(instanceMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition);
+ }
+ visibleInstances.sort((m1, m2) => {
+ return m1._distanceToCamera > m2._distanceToCamera ? -1 : m1._distanceToCamera < m2._distanceToCamera ? 1 : 0;
+ });
+ }
+ for (let instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
+ const instance = visibleInstances[instanceIndex];
+ const matrix = instance.getWorldMatrix();
+ matrix.copyToArray(instanceStorage.instancesData, offset);
+ if (this._scene.needsPreviousWorldMatrices) {
+ if (!instance._previousWorldMatrix) {
+ instance._previousWorldMatrix = matrix.clone();
+ instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset);
+ }
+ else {
+ instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset);
+ instance._previousWorldMatrix.copyFrom(matrix);
+ }
+ }
+ offset += 16;
+ instancesCount++;
+ }
+ }
+ }
+ else {
+ instancesCount = (renderSelf ? 1 : 0) + visibleInstanceCount;
+ }
+ if (needUpdateBuffer) {
+ if (instancesBuffer) {
+ instancesBuffer.dispose();
+ }
+ if (instancesPreviousBuffer) {
+ instancesPreviousBuffer.dispose();
+ }
+ instancesBuffer = new Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
+ instanceStorage.instancesBuffer = instancesBuffer;
+ if (!this._userInstancedBuffersStorage) {
+ this._userInstancedBuffersStorage = {
+ data: {},
+ vertexBuffers: {},
+ strides: {},
+ sizes: {},
+ vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined,
+ };
+ }
+ this._userInstancedBuffersStorage.vertexBuffers["world0"] = instancesBuffer.createVertexBuffer("world0", 0, 4);
+ this._userInstancedBuffersStorage.vertexBuffers["world1"] = instancesBuffer.createVertexBuffer("world1", 4, 4);
+ this._userInstancedBuffersStorage.vertexBuffers["world2"] = instancesBuffer.createVertexBuffer("world2", 8, 4);
+ this._userInstancedBuffersStorage.vertexBuffers["world3"] = instancesBuffer.createVertexBuffer("world3", 12, 4);
+ if (this._scene.needsPreviousWorldMatrices) {
+ instancesPreviousBuffer = new Buffer(engine, instanceStorage.instancesPreviousData, true, 16, false, true);
+ instanceStorage.instancesPreviousBuffer = instancesPreviousBuffer;
+ this._userInstancedBuffersStorage.vertexBuffers["previousWorld0"] = instancesPreviousBuffer.createVertexBuffer("previousWorld0", 0, 4);
+ this._userInstancedBuffersStorage.vertexBuffers["previousWorld1"] = instancesPreviousBuffer.createVertexBuffer("previousWorld1", 4, 4);
+ this._userInstancedBuffersStorage.vertexBuffers["previousWorld2"] = instancesPreviousBuffer.createVertexBuffer("previousWorld2", 8, 4);
+ this._userInstancedBuffersStorage.vertexBuffers["previousWorld3"] = instancesPreviousBuffer.createVertexBuffer("previousWorld3", 12, 4);
+ }
+ this._invalidateInstanceVertexArrayObject();
+ }
+ else {
+ if (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) {
+ instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
+ if (this._scene.needsPreviousWorldMatrices && (!this._instanceDataStorage.manualUpdate || this._instanceDataStorage.previousManualUpdate)) {
+ instancesPreviousBuffer.updateDirectly(instanceStorage.instancesPreviousData, 0, instancesCount);
+ }
+ }
+ }
+ this._processInstancedBuffers(visibleInstances, renderSelf);
+ if (effect && fillMode !== undefined) {
+ // Stats
+ this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false);
+ // Draw
+ if (engine._currentDrawContext) {
+ engine._currentDrawContext.useInstancing = true;
+ }
+ this._bind(subMesh, effect, fillMode);
+ this._draw(subMesh, fillMode, instancesCount);
+ }
+ // Write current matrices as previous matrices in case of manual update
+ // Default behaviour when previous matrices are not specified explicitly
+ // Will break if instances number/order changes
+ if (this._scene.needsPreviousWorldMatrices &&
+ !needUpdateBuffer &&
+ this._instanceDataStorage.manualUpdate &&
+ (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) &&
+ !this._instanceDataStorage.previousManualUpdate) {
+ instancesPreviousBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
+ }
+ }
+ /**
+ * @internal
+ */
+ _renderWithInstances(subMesh, fillMode, batch, effect, engine) {
+ const visibleInstances = batch.visibleInstances[subMesh._id];
+ const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0;
+ const instanceStorage = this._instanceDataStorage;
+ const currentInstancesBufferSize = instanceStorage.instancesBufferSize;
+ const matricesCount = visibleInstanceCount + 1;
+ const bufferSize = matricesCount * 16 * 4;
+ while (instanceStorage.instancesBufferSize < bufferSize) {
+ instanceStorage.instancesBufferSize *= 2;
+ }
+ if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
+ instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
+ }
+ if ((this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousData) || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
+ instanceStorage.instancesPreviousData = new Float32Array(instanceStorage.instancesBufferSize / 4);
+ }
+ this._updateInstancedBuffers(subMesh, batch, currentInstancesBufferSize, engine, fillMode, effect);
+ engine.unbindInstanceAttributes();
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _renderWithThinInstances(subMesh, fillMode, effect, engine) {
+ // Stats
+ const instancesCount = this._thinInstanceDataStorage?.instancesCount ?? 0;
+ this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false);
+ // Draw
+ if (engine._currentDrawContext) {
+ engine._currentDrawContext.useInstancing = true;
+ }
+ this._bind(subMesh, effect, fillMode);
+ this._draw(subMesh, fillMode, instancesCount);
+ // Write current matrices as previous matrices
+ // Default behaviour when previous matrices are not specified explicitly
+ // Will break if instances number/order changes
+ if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData && this._thinInstanceDataStorage.matrixData) {
+ if (!this._thinInstanceDataStorage.previousMatrixBuffer) {
+ this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.matrixData, false);
+ }
+ else {
+ this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, instancesCount);
+ }
+ }
+ engine.unbindInstanceAttributes();
+ }
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _processInstancedBuffers(visibleInstances, renderSelf) {
+ // Do nothing
+ }
+ /**
+ * @internal
+ */
+ _processRendering(renderingMesh, subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
+ const scene = this.getScene();
+ const engine = scene.getEngine();
+ fillMode = this._getRenderingFillMode(fillMode);
+ if (hardwareInstancedRendering && subMesh.getRenderingMesh().hasThinInstances) {
+ this._renderWithThinInstances(subMesh, fillMode, effect, engine);
+ return this;
+ }
+ if (hardwareInstancedRendering) {
+ this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
+ }
+ else {
+ if (engine._currentDrawContext) {
+ engine._currentDrawContext.useInstancing = false;
+ }
+ let instanceCount = 0;
+ if (batch.renderSelf[subMesh._id]) {
+ // Draw
+ if (onBeforeDraw) {
+ onBeforeDraw(false, renderingMesh.getWorldMatrix(), effectiveMaterial);
+ }
+ instanceCount++;
+ this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
+ }
+ const visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
+ if (visibleInstancesForSubMesh) {
+ const visibleInstanceCount = visibleInstancesForSubMesh.length;
+ instanceCount += visibleInstanceCount;
+ // Stats
+ for (let instanceIndex = 0; instanceIndex < visibleInstanceCount; instanceIndex++) {
+ const instance = visibleInstancesForSubMesh[instanceIndex];
+ // World
+ const world = instance.getWorldMatrix();
+ if (onBeforeDraw) {
+ onBeforeDraw(true, world, effectiveMaterial);
+ }
+ // Draw
+ this._draw(subMesh, fillMode);
+ }
+ }
+ // Stats
+ scene._activeIndices.addCount(subMesh.indexCount * instanceCount, false);
+ }
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _rebuild(dispose = false) {
+ if (this._instanceDataStorage.instancesBuffer) {
+ // Dispose instance buffer to be recreated in _renderWithInstances when rendered
+ if (dispose) {
+ this._instanceDataStorage.instancesBuffer.dispose();
+ }
+ this._instanceDataStorage.instancesBuffer = null;
+ }
+ if (this._userInstancedBuffersStorage) {
+ for (const kind in this._userInstancedBuffersStorage.vertexBuffers) {
+ const buffer = this._userInstancedBuffersStorage.vertexBuffers[kind];
+ if (buffer) {
+ // Dispose instance buffer to be recreated in _renderWithInstances when rendered
+ if (dispose) {
+ buffer.dispose();
+ }
+ this._userInstancedBuffersStorage.vertexBuffers[kind] = null;
+ }
+ }
+ if (this._userInstancedBuffersStorage.vertexArrayObjects) {
+ this._userInstancedBuffersStorage.vertexArrayObjects = {};
+ }
+ }
+ this._internalMeshDataInfo._effectiveMaterial = null;
+ super._rebuild(dispose);
+ }
+ /** @internal */
+ _freeze() {
+ if (!this.subMeshes) {
+ return;
+ }
+ // Prepare batches
+ for (let index = 0; index < this.subMeshes.length; index++) {
+ this._getInstancesRenderList(index);
+ }
+ this._internalMeshDataInfo._effectiveMaterial = null;
+ this._instanceDataStorage.isFrozen = true;
+ }
+ /** @internal */
+ _unFreeze() {
+ this._instanceDataStorage.isFrozen = false;
+ this._instanceDataStorage.previousBatch = null;
+ }
+ /**
+ * Triggers the draw call for the mesh (or a submesh), for a specific render pass id
+ * @param renderPassId defines the render pass id to use to draw the mesh / submesh. If not provided, use the current renderPassId of the engine.
+ * @param enableAlphaMode defines if alpha mode can be changed (default: false)
+ * @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering (default: undefined)
+ * @param subMesh defines the subMesh to render. If not provided, draw all mesh submeshes (default: undefined)
+ * @param checkFrustumCulling defines if frustum culling must be checked (default: true). If you know the mesh is in the frustum (or if you don't care!), you can pass false to optimize.
+ * @returns the current mesh
+ */
+ renderWithRenderPassId(renderPassId, enableAlphaMode, effectiveMeshReplacement, subMesh, checkFrustumCulling = true) {
+ const engine = this._scene.getEngine();
+ const currentRenderPassId = engine.currentRenderPassId;
+ if (renderPassId !== undefined) {
+ engine.currentRenderPassId = renderPassId;
+ }
+ if (subMesh) {
+ if (!checkFrustumCulling || (checkFrustumCulling && subMesh.isInFrustum(this._scene._frustumPlanes))) {
+ this.render(subMesh, !!enableAlphaMode, effectiveMeshReplacement);
+ }
+ }
+ else {
+ for (let s = 0; s < this.subMeshes.length; s++) {
+ const subMesh = this.subMeshes[s];
+ if (!checkFrustumCulling || (checkFrustumCulling && subMesh.isInFrustum(this._scene._frustumPlanes))) {
+ this.render(subMesh, !!enableAlphaMode, effectiveMeshReplacement);
+ }
+ }
+ }
+ if (renderPassId !== undefined) {
+ engine.currentRenderPassId = currentRenderPassId;
+ }
+ return this;
+ }
+ /**
+ * Render a complete mesh by going through all submeshes
+ * @returns the current mesh
+ * @see [simple test](https://playground.babylonjs.com/#5SPY1V#2)
+ * @see [perf test](https://playground.babylonjs.com/#5SPY1V#5)
+ */
+ directRender() {
+ if (!this.subMeshes) {
+ return this;
+ }
+ for (const submesh of this.subMeshes) {
+ this.render(submesh, false);
+ }
+ return this;
+ }
+ /**
+ * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
+ * @param subMesh defines the subMesh to render
+ * @param enableAlphaMode defines if alpha mode can be changed
+ * @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering
+ * @returns the current mesh
+ */
+ render(subMesh, enableAlphaMode, effectiveMeshReplacement) {
+ const scene = this.getScene();
+ if (this._internalAbstractMeshDataInfo._isActiveIntermediate) {
+ this._internalAbstractMeshDataInfo._isActiveIntermediate = false;
+ }
+ else {
+ this._internalAbstractMeshDataInfo._isActive = false;
+ }
+ const numActiveCameras = scene.activeCameras?.length ?? 0;
+ const canCheckOcclusionQuery = (numActiveCameras > 1 && scene.activeCamera === scene.activeCameras[0]) || numActiveCameras <= 1;
+ if (canCheckOcclusionQuery && this._checkOcclusionQuery() && !this._occlusionDataStorage.forceRenderingWhenOccluded) {
+ return this;
+ }
+ // Managing instances
+ const batch = this._getInstancesRenderList(subMesh._id, !!effectiveMeshReplacement);
+ if (batch.mustReturn) {
+ return this;
+ }
+ // Checking geometry state
+ if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
+ return this;
+ }
+ const engine = scene.getEngine();
+ let oldCameraMaxZ = 0;
+ let oldCamera = null;
+ if (this.ignoreCameraMaxZ && scene.activeCamera && !scene._isInIntermediateRendering()) {
+ oldCameraMaxZ = scene.activeCamera.maxZ;
+ oldCamera = scene.activeCamera;
+ scene.activeCamera.maxZ = 0;
+ scene.updateTransformMatrix(true);
+ }
+ if (this._internalMeshDataInfo._onBeforeRenderObservable) {
+ this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);
+ }
+ const renderingMesh = subMesh.getRenderingMesh();
+ const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] ||
+ renderingMesh.hasThinInstances ||
+ (!!this._userInstancedBuffersStorage && !subMesh.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh);
+ const instanceDataStorage = this._instanceDataStorage;
+ const material = subMesh.getMaterial();
+ if (!material) {
+ if (oldCamera) {
+ oldCamera.maxZ = oldCameraMaxZ;
+ scene.updateTransformMatrix(true);
+ }
+ return this;
+ }
+ // Material
+ if (!instanceDataStorage.isFrozen || !this._internalMeshDataInfo._effectiveMaterial || this._internalMeshDataInfo._effectiveMaterial !== material) {
+ if (material._storeEffectOnSubMeshes) {
+ if (!material.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
+ if (oldCamera) {
+ oldCamera.maxZ = oldCameraMaxZ;
+ scene.updateTransformMatrix(true);
+ }
+ return this;
+ }
+ }
+ else if (!material.isReady(this, hardwareInstancedRendering)) {
+ if (oldCamera) {
+ oldCamera.maxZ = oldCameraMaxZ;
+ scene.updateTransformMatrix(true);
+ }
+ return this;
+ }
+ this._internalMeshDataInfo._effectiveMaterial = material;
+ }
+ else if ((material._storeEffectOnSubMeshes && !subMesh._drawWrapper?._wasPreviouslyReady) ||
+ (!material._storeEffectOnSubMeshes && !material._getDrawWrapper()._wasPreviouslyReady)) {
+ if (oldCamera) {
+ oldCamera.maxZ = oldCameraMaxZ;
+ scene.updateTransformMatrix(true);
+ }
+ return this;
+ }
+ // Alpha mode
+ if (enableAlphaMode) {
+ engine.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);
+ }
+ let drawWrapper;
+ if (this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes) {
+ drawWrapper = subMesh._drawWrapper;
+ }
+ else {
+ drawWrapper = this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();
+ }
+ const effect = drawWrapper?.effect ?? null;
+ for (const step of scene._beforeRenderingMeshStage) {
+ step.action(this, subMesh, batch, effect);
+ }
+ if (!drawWrapper || !effect) {
+ if (oldCamera) {
+ oldCamera.maxZ = oldCameraMaxZ;
+ scene.updateTransformMatrix(true);
+ }
+ return this;
+ }
+ const effectiveMesh = effectiveMeshReplacement || this;
+ let sideOrientation;
+ if (!instanceDataStorage.isFrozen &&
+ (this._internalMeshDataInfo._effectiveMaterial.backFaceCulling ||
+ this._internalMeshDataInfo._effectiveMaterial.sideOrientation !== null ||
+ this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)) {
+ // Note: if two sided lighting is enabled, we need to ensure that the normal will point in the right direction even if the determinant of the world matrix is negative
+ const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant();
+ sideOrientation = this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this);
+ if (mainDeterminant < 0) {
+ sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
+ }
+ instanceDataStorage.sideOrientation = sideOrientation;
+ }
+ else {
+ sideOrientation = instanceDataStorage.sideOrientation;
+ }
+ const reverse = this._internalMeshDataInfo._effectiveMaterial._preBind(drawWrapper, sideOrientation);
+ if (this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite) {
+ engine.setDepthWrite(true);
+ }
+ // Bind
+ const effectiveMaterial = this._internalMeshDataInfo._effectiveMaterial;
+ const fillMode = effectiveMaterial.fillMode;
+ if (this._internalMeshDataInfo._onBeforeBindObservable) {
+ this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this);
+ }
+ if (!hardwareInstancedRendering) {
+ // Binding will be done later because we need to add more info to the VB
+ this._bind(subMesh, effect, fillMode, false);
+ }
+ const world = effectiveMesh.getWorldMatrix();
+ if (effectiveMaterial._storeEffectOnSubMeshes) {
+ effectiveMaterial.bindForSubMesh(world, this, subMesh);
+ }
+ else {
+ effectiveMaterial.bind(world, this);
+ }
+ if (!effectiveMaterial.backFaceCulling && effectiveMaterial.separateCullingPass) {
+ engine.setState(true, effectiveMaterial.zOffset, false, !reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits);
+ this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial);
+ engine.setState(true, effectiveMaterial.zOffset, false, reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits);
+ if (this._internalMeshDataInfo._onBetweenPassObservable) {
+ this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(subMesh);
+ }
+ }
+ // Draw
+ this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial);
+ // Unbind
+ this._internalMeshDataInfo._effectiveMaterial.unbind();
+ for (const step of scene._afterRenderingMeshStage) {
+ step.action(this, subMesh, batch, effect);
+ }
+ if (this._internalMeshDataInfo._onAfterRenderObservable) {
+ this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this);
+ }
+ if (oldCamera) {
+ oldCamera.maxZ = oldCameraMaxZ;
+ scene.updateTransformMatrix(true);
+ }
+ if (scene.performancePriority === 2 /* ScenePerformancePriority.Aggressive */ && !instanceDataStorage.isFrozen) {
+ this._freeze();
+ }
+ return this;
+ }
+ /**
+ * Renormalize the mesh and patch it up if there are no weights
+ * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
+ * However in the case of zero weights then we set just a single influence to 1.
+ * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
+ */
+ cleanMatrixWeights() {
+ if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
+ if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) {
+ this._normalizeSkinWeightsAndExtra();
+ }
+ else {
+ this._normalizeSkinFourWeights();
+ }
+ }
+ }
+ // faster 4 weight version.
+ _normalizeSkinFourWeights() {
+ const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
+ const numWeights = matricesWeights.length;
+ for (let a = 0; a < numWeights; a += 4) {
+ // accumulate weights
+ const t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
+ // check for invalid weight and just set it to 1.
+ if (t === 0) {
+ matricesWeights[a] = 1;
+ }
+ else {
+ // renormalize so everything adds to 1 use reciprocal
+ const recip = 1 / t;
+ matricesWeights[a] *= recip;
+ matricesWeights[a + 1] *= recip;
+ matricesWeights[a + 2] *= recip;
+ matricesWeights[a + 3] *= recip;
+ }
+ }
+ this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
+ }
+ // handle special case of extra verts. (in theory gltf can handle 12 influences)
+ _normalizeSkinWeightsAndExtra() {
+ const matricesWeightsExtra = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind);
+ const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
+ const numWeights = matricesWeights.length;
+ for (let a = 0; a < numWeights; a += 4) {
+ // accumulate weights
+ let t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
+ t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
+ // check for invalid weight and just set it to 1.
+ if (t === 0) {
+ matricesWeights[a] = 1;
+ }
+ else {
+ // renormalize so everything adds to 1 use reciprocal
+ const recip = 1 / t;
+ matricesWeights[a] *= recip;
+ matricesWeights[a + 1] *= recip;
+ matricesWeights[a + 2] *= recip;
+ matricesWeights[a + 3] *= recip;
+ // same goes for extras
+ matricesWeightsExtra[a] *= recip;
+ matricesWeightsExtra[a + 1] *= recip;
+ matricesWeightsExtra[a + 2] *= recip;
+ matricesWeightsExtra[a + 3] *= recip;
+ }
+ }
+ this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
+ this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
+ }
+ /**
+ * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
+ * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
+ * the user know there was an issue with importing the mesh
+ * @returns a validation object with skinned, valid and report string
+ */
+ validateSkinning() {
+ const matricesWeightsExtra = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind);
+ const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
+ if (matricesWeights === null || this.skeleton == null) {
+ return { skinned: false, valid: true, report: "not skinned" };
+ }
+ const numWeights = matricesWeights.length;
+ let numberNotSorted = 0;
+ let missingWeights = 0;
+ let maxUsedWeights = 0;
+ let numberNotNormalized = 0;
+ const numInfluences = matricesWeightsExtra === null ? 4 : 8;
+ const usedWeightCounts = [];
+ for (let a = 0; a <= numInfluences; a++) {
+ usedWeightCounts[a] = 0;
+ }
+ const toleranceEpsilon = 0.001;
+ for (let a = 0; a < numWeights; a += 4) {
+ let lastWeight = matricesWeights[a];
+ let t = lastWeight;
+ let usedWeights = t === 0 ? 0 : 1;
+ for (let b = 1; b < numInfluences; b++) {
+ const d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
+ if (d > lastWeight) {
+ numberNotSorted++;
+ }
+ if (d !== 0) {
+ usedWeights++;
+ }
+ t += d;
+ lastWeight = d;
+ }
+ // count the buffer weights usage
+ usedWeightCounts[usedWeights]++;
+ // max influences
+ if (usedWeights > maxUsedWeights) {
+ maxUsedWeights = usedWeights;
+ }
+ // check for invalid weight and just set it to 1.
+ if (t === 0) {
+ missingWeights++;
+ }
+ else {
+ // renormalize so everything adds to 1 use reciprocal
+ const recip = 1 / t;
+ let tolerance = 0;
+ for (let b = 0; b < numInfluences; b++) {
+ if (b < 4) {
+ tolerance += Math.abs(matricesWeights[a + b] - matricesWeights[a + b] * recip);
+ }
+ else {
+ tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - matricesWeightsExtra[a + b - 4] * recip);
+ }
+ }
+ // arbitrary epsilon value for dictating not normalized
+ if (tolerance > toleranceEpsilon) {
+ numberNotNormalized++;
+ }
+ }
+ }
+ // validate bone indices are in range of the skeleton
+ const numBones = this.skeleton.bones.length;
+ const matricesIndices = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
+ const matricesIndicesExtra = this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind);
+ let numBadBoneIndices = 0;
+ for (let a = 0; a < numWeights; a += 4) {
+ for (let b = 0; b < numInfluences; b++) {
+ const index = b < 4 ? matricesIndices[a + b] : matricesIndicesExtra[a + b - 4];
+ if (index >= numBones || index < 0) {
+ numBadBoneIndices++;
+ }
+ }
+ }
+ // log mesh stats
+ const output = "Number of Weights = " +
+ numWeights / 4 +
+ "\nMaximum influences = " +
+ maxUsedWeights +
+ "\nMissing Weights = " +
+ missingWeights +
+ "\nNot Sorted = " +
+ numberNotSorted +
+ "\nNot Normalized = " +
+ numberNotNormalized +
+ "\nWeightCounts = [" +
+ usedWeightCounts +
+ "]" +
+ "\nNumber of bones = " +
+ numBones +
+ "\nBad Bone Indices = " +
+ numBadBoneIndices;
+ return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
+ }
+ /** @internal */
+ _checkDelayState() {
+ const scene = this.getScene();
+ if (this._geometry) {
+ this._geometry.load(scene);
+ }
+ else if (this.delayLoadState === 4) {
+ this.delayLoadState = 2;
+ this._queueLoad(scene);
+ }
+ return this;
+ }
+ _queueLoad(scene) {
+ scene.addPendingData(this);
+ const getBinaryData = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1;
+ Tools.LoadFile(this.delayLoadingFile, (data) => {
+ if (data instanceof ArrayBuffer) {
+ this._delayLoadingFunction(data, this);
+ }
+ else {
+ this._delayLoadingFunction(JSON.parse(data), this);
+ }
+ this.instances.forEach((instance) => {
+ instance.refreshBoundingInfo();
+ instance._syncSubMeshes();
+ });
+ this.delayLoadState = 1;
+ scene.removePendingData(this);
+ }, () => { }, scene.offlineProvider, getBinaryData);
+ return this;
+ }
+ /**
+ * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
+ * A mesh is in the frustum if its bounding box intersects the frustum
+ * @param frustumPlanes defines the frustum to test
+ * @returns true if the mesh is in the frustum planes
+ */
+ isInFrustum(frustumPlanes) {
+ if (this.delayLoadState === 2) {
+ return false;
+ }
+ if (!super.isInFrustum(frustumPlanes)) {
+ return false;
+ }
+ this._checkDelayState();
+ return true;
+ }
+ /**
+ * Sets the mesh material by the material or multiMaterial `id` property
+ * @param id is a string identifying the material or the multiMaterial
+ * @returns the current mesh
+ */
+ setMaterialById(id) {
+ const materials = this.getScene().materials;
+ let index;
+ for (index = materials.length - 1; index > -1; index--) {
+ if (materials[index].id === id) {
+ this.material = materials[index];
+ return this;
+ }
+ }
+ // Multi
+ const multiMaterials = this.getScene().multiMaterials;
+ for (index = multiMaterials.length - 1; index > -1; index--) {
+ if (multiMaterials[index].id === id) {
+ this.material = multiMaterials[index];
+ return this;
+ }
+ }
+ return this;
+ }
+ /**
+ * Returns as a new array populated with the mesh material and/or skeleton, if any.
+ * @returns an array of IAnimatable
+ */
+ getAnimatables() {
+ const results = [];
+ if (this.material) {
+ results.push(this.material);
+ }
+ if (this.skeleton) {
+ results.push(this.skeleton);
+ }
+ return results;
+ }
+ /**
+ * Modifies the mesh geometry according to the passed transformation matrix.
+ * This method returns nothing, but it really modifies the mesh even if it's originally not set as updatable.
+ * The mesh normals are modified using the same transformation.
+ * Note that, under the hood, this method sets a new VertexBuffer each call.
+ * @param transform defines the transform matrix to use
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms
+ * @returns the current mesh
+ */
+ bakeTransformIntoVertices(transform) {
+ // Position
+ if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
+ return this;
+ }
+ const submeshes = this.subMeshes.splice(0);
+ this._resetPointsArrayCache();
+ let data = this.getVerticesData(VertexBuffer.PositionKind);
+ const temp = Vector3.Zero();
+ let index;
+ for (index = 0; index < data.length; index += 3) {
+ Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).toArray(data, index);
+ }
+ this.setVerticesData(VertexBuffer.PositionKind, data, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
+ // Normals
+ if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+ data = this.getVerticesData(VertexBuffer.NormalKind);
+ for (index = 0; index < data.length; index += 3) {
+ Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp)
+ .normalize()
+ .toArray(data, index);
+ }
+ this.setVerticesData(VertexBuffer.NormalKind, data, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
+ }
+ // Tangents
+ if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {
+ data = this.getVerticesData(VertexBuffer.TangentKind);
+ for (index = 0; index < data.length; index += 4) {
+ Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp)
+ .normalize()
+ .toArray(data, index);
+ }
+ this.setVerticesData(VertexBuffer.TangentKind, data, this.getVertexBuffer(VertexBuffer.TangentKind).isUpdatable());
+ }
+ // flip faces?
+ if (transform.determinant() < 0) {
+ this.flipFaces();
+ }
+ // Restore submeshes
+ this.releaseSubMeshes();
+ this.subMeshes = submeshes;
+ return this;
+ }
+ /**
+ * Modifies the mesh geometry according to its own current World Matrix.
+ * The mesh World Matrix is then reset.
+ * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
+ * Note that, under the hood, this method sets a new VertexBuffer each call.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms
+ * @param bakeIndependentlyOfChildren indicates whether to preserve all child nodes' World Matrix during baking
+ * @param forceUnique indicates whether to force the mesh geometry to be unique
+ * @returns the current mesh
+ */
+ bakeCurrentTransformIntoVertices(bakeIndependentlyOfChildren = true, forceUnique = false) {
+ if (forceUnique) {
+ this.makeGeometryUnique();
+ }
+ this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
+ this.resetLocalMatrix(bakeIndependentlyOfChildren);
+ return this;
+ }
+ // Cache
+ /** @internal */
+ get _positions() {
+ return this._internalAbstractMeshDataInfo._positions || (this._geometry && this._geometry._positions) || null;
+ }
+ /** @internal */
+ _resetPointsArrayCache() {
+ if (this._geometry) {
+ this._geometry._resetPointsArrayCache();
+ }
+ return this;
+ }
+ /** @internal */
+ _generatePointsArray() {
+ if (this._geometry) {
+ return this._geometry._generatePointsArray();
+ }
+ return false;
+ }
+ /**
+ * Returns a new Mesh object generated from the current mesh properties.
+ * This method must not get confused with createInstance()
+ * @param name is a string, the name given to the new mesh
+ * @param newParent can be any Node object (default `null`) or an instance of MeshCloneOptions. If the latter, doNotCloneChildren and clonePhysicsImpostor are unused.
+ * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
+ * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
+ * @returns a new mesh
+ */
+ clone(name = "", newParent = null, doNotCloneChildren, clonePhysicsImpostor = true) {
+ if (newParent && newParent._addToSceneRootNodes === undefined) {
+ const cloneOptions = newParent;
+ meshCreationOptions.source = this;
+ meshCreationOptions.doNotCloneChildren = cloneOptions.doNotCloneChildren;
+ meshCreationOptions.clonePhysicsImpostor = cloneOptions.clonePhysicsImpostor;
+ meshCreationOptions.cloneThinInstances = cloneOptions.cloneThinInstances;
+ return new Mesh(name, this.getScene(), meshCreationOptions);
+ }
+ return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
+ }
+ /**
+ * Releases resources associated with this mesh.
+ * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
+ * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
+ */
+ dispose(doNotRecurse, disposeMaterialAndTextures = false) {
+ this.morphTargetManager = null;
+ if (this._geometry) {
+ this._geometry.releaseForMesh(this, true);
+ }
+ const internalDataInfo = this._internalMeshDataInfo;
+ if (internalDataInfo._onBeforeDrawObservable) {
+ internalDataInfo._onBeforeDrawObservable.clear();
+ }
+ if (internalDataInfo._onBeforeBindObservable) {
+ internalDataInfo._onBeforeBindObservable.clear();
+ }
+ if (internalDataInfo._onBeforeRenderObservable) {
+ internalDataInfo._onBeforeRenderObservable.clear();
+ }
+ if (internalDataInfo._onAfterRenderObservable) {
+ internalDataInfo._onAfterRenderObservable.clear();
+ }
+ if (internalDataInfo._onBetweenPassObservable) {
+ internalDataInfo._onBetweenPassObservable.clear();
+ }
+ // Sources
+ if (this._scene.useClonedMeshMap) {
+ if (internalDataInfo.meshMap) {
+ for (const uniqueId in internalDataInfo.meshMap) {
+ const mesh = internalDataInfo.meshMap[uniqueId];
+ if (mesh) {
+ mesh._internalMeshDataInfo._source = null;
+ internalDataInfo.meshMap[uniqueId] = undefined;
+ }
+ }
+ }
+ if (internalDataInfo._source && internalDataInfo._source._internalMeshDataInfo.meshMap) {
+ internalDataInfo._source._internalMeshDataInfo.meshMap[this.uniqueId] = undefined;
+ }
+ }
+ else {
+ const meshes = this.getScene().meshes;
+ for (const abstractMesh of meshes) {
+ const mesh = abstractMesh;
+ if (mesh._internalMeshDataInfo && mesh._internalMeshDataInfo._source && mesh._internalMeshDataInfo._source === this) {
+ mesh._internalMeshDataInfo._source = null;
+ }
+ }
+ }
+ internalDataInfo._source = null;
+ this._instanceDataStorage.visibleInstances = {};
+ // Instances
+ this._disposeInstanceSpecificData();
+ // Thin instances
+ this._disposeThinInstanceSpecificData();
+ if (this._internalMeshDataInfo._checkReadinessObserver) {
+ this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver);
+ }
+ super.dispose(doNotRecurse, disposeMaterialAndTextures);
+ }
+ /** @internal */
+ _disposeInstanceSpecificData() {
+ // Do nothing
+ }
+ /** @internal */
+ _disposeThinInstanceSpecificData() {
+ // Do nothing
+ }
+ /** @internal */
+ _invalidateInstanceVertexArrayObject() {
+ // Do nothing
+ }
+ /**
+ * Modifies the mesh geometry according to a displacement map.
+ * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
+ * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
+ * @param url is a string, the URL from the image file is to be downloaded.
+ * @param minHeight is the lower limit of the displacement.
+ * @param maxHeight is the upper limit of the displacement.
+ * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
+ * @param uvOffset is an optional vector2 used to offset UV.
+ * @param uvScale is an optional vector2 used to scale UV.
+ * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
+ * @param onError defines a callback called when an error occurs during the processing of the request.
+ * @returns the Mesh.
+ */
+ applyDisplacementMap(url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate = false, onError) {
+ const scene = this.getScene();
+ const onload = (img) => {
+ // Getting height map data
+ const heightMapWidth = img.width;
+ const heightMapHeight = img.height;
+ const canvas = this.getEngine().createCanvas(heightMapWidth, heightMapHeight);
+ const context = canvas.getContext("2d");
+ context.drawImage(img, 0, 0);
+ // Create VertexData from map data
+ //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
+ const buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
+ this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
+ //execute success callback, if set
+ if (onSuccess) {
+ onSuccess(this);
+ }
+ };
+ Tools.LoadImage(url, onload, onError ? onError : () => { }, scene.offlineProvider);
+ return this;
+ }
+ /**
+ * Modifies the mesh geometry according to a displacementMap buffer.
+ * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
+ * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
+ * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
+ * @param heightMapWidth is the width of the buffer image.
+ * @param heightMapHeight is the height of the buffer image.
+ * @param minHeight is the lower limit of the displacement.
+ * @param maxHeight is the upper limit of the displacement.
+ * @param uvOffset is an optional vector2 used to offset UV.
+ * @param uvScale is an optional vector2 used to scale UV.
+ * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
+ * @returns the Mesh.
+ */
+ applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate = false) {
+ if (!this.isVerticesDataPresent(VertexBuffer.PositionKind) || !this.isVerticesDataPresent(VertexBuffer.NormalKind) || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
+ Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
+ return this;
+ }
+ const positions = this.getVerticesData(VertexBuffer.PositionKind, true, true);
+ const normals = this.getVerticesData(VertexBuffer.NormalKind);
+ const uvs = this.getVerticesData(VertexBuffer.UVKind);
+ let position = Vector3.Zero();
+ const normal = Vector3.Zero();
+ const uv = Vector2.Zero();
+ uvOffset = uvOffset || Vector2.Zero();
+ uvScale = uvScale || new Vector2(1, 1);
+ for (let index = 0; index < positions.length; index += 3) {
+ Vector3.FromArrayToRef(positions, index, position);
+ Vector3.FromArrayToRef(normals, index, normal);
+ Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
+ // Compute height
+ const u = (Math.abs(uv.x * uvScale.x + (uvOffset.x % 1)) * (heightMapWidth - 1)) % heightMapWidth | 0;
+ const v = (Math.abs(uv.y * uvScale.y + (uvOffset.y % 1)) * (heightMapHeight - 1)) % heightMapHeight | 0;
+ const pos = (u + v * heightMapWidth) * 4;
+ const r = buffer[pos] / 255.0;
+ const g = buffer[pos + 1] / 255.0;
+ const b = buffer[pos + 2] / 255.0;
+ const gradient = r * 0.3 + g * 0.59 + b * 0.11;
+ normal.normalize();
+ normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
+ position = position.add(normal);
+ position.toArray(positions, index);
+ }
+ VertexData.ComputeNormals(positions, this.getIndices(), normals);
+ if (forceUpdate) {
+ this.setVerticesData(VertexBuffer.PositionKind, positions);
+ this.setVerticesData(VertexBuffer.NormalKind, normals);
+ this.setVerticesData(VertexBuffer.UVKind, uvs);
+ }
+ else {
+ this.updateVerticesData(VertexBuffer.PositionKind, positions);
+ this.updateVerticesData(VertexBuffer.NormalKind, normals);
+ }
+ return this;
+ }
+ _getFlattenedNormals(indices, positions) {
+ const normals = new Float32Array(indices.length * 3);
+ let normalsCount = 0;
+ // Decide if normals should be flipped
+ const flipNormalGeneration = this.sideOrientation === (this._scene.useRightHandedSystem ? 1 : 0);
+ // Generate new normals
+ for (let index = 0; index < indices.length; index += 3) {
+ const p1 = Vector3.FromArray(positions, indices[index] * 3);
+ const p2 = Vector3.FromArray(positions, indices[index + 1] * 3);
+ const p3 = Vector3.FromArray(positions, indices[index + 2] * 3);
+ const p1p2 = p1.subtract(p2);
+ const p3p2 = p3.subtract(p2);
+ const normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
+ if (flipNormalGeneration) {
+ normal.scaleInPlace(-1);
+ }
+ // Store same normals for every vertex
+ for (let localIndex = 0; localIndex < 3; localIndex++) {
+ normals[normalsCount++] = normal.x;
+ normals[normalsCount++] = normal.y;
+ normals[normalsCount++] = normal.z;
+ }
+ }
+ return normals;
+ }
+ _convertToUnIndexedMesh(flattenNormals = false) {
+ const kinds = this.getVerticesDataKinds().filter((kind) => !this.getVertexBuffer(kind)?.getIsInstanced());
+ const indices = this.getIndices();
+ const data = {};
+ const separateVertices = (data, size) => {
+ const newData = new Float32Array(indices.length * size);
+ let count = 0;
+ for (let index = 0; index < indices.length; index++) {
+ for (let offset = 0; offset < size; offset++) {
+ newData[count++] = data[indices[index] * size + offset];
+ }
+ }
+ return newData;
+ };
+ // Save mesh bounding info
+ const meshBoundingInfo = this.getBoundingInfo();
+ // Save previous submeshes
+ const previousSubmeshes = this.geometry ? this.subMeshes.slice(0) : [];
+ // Cache vertex data
+ for (const kind of kinds) {
+ data[kind] = this.getVerticesData(kind);
+ }
+ // Update vertex data
+ for (const kind of kinds) {
+ const vertexBuffer = this.getVertexBuffer(kind);
+ const size = vertexBuffer.getSize();
+ if (flattenNormals && kind === VertexBuffer.NormalKind) {
+ const normals = this._getFlattenedNormals(indices, data[VertexBuffer.PositionKind]);
+ this.setVerticesData(VertexBuffer.NormalKind, normals, vertexBuffer.isUpdatable(), size);
+ }
+ else {
+ this.setVerticesData(kind, separateVertices(data[kind], size), vertexBuffer.isUpdatable(), size);
+ }
+ }
+ // Update morph targets
+ if (this.morphTargetManager) {
+ for (let targetIndex = 0; targetIndex < this.morphTargetManager.numTargets; targetIndex++) {
+ const target = this.morphTargetManager.getTarget(targetIndex);
+ const positions = target.getPositions();
+ target.setPositions(separateVertices(positions, 3));
+ const normals = target.getNormals();
+ if (normals) {
+ target.setNormals(flattenNormals ? this._getFlattenedNormals(indices, positions) : separateVertices(normals, 3));
+ }
+ const tangents = target.getTangents();
+ if (tangents) {
+ target.setTangents(separateVertices(tangents, 3));
+ }
+ const uvs = target.getUVs();
+ if (uvs) {
+ target.setUVs(separateVertices(uvs, 2));
+ }
+ const colors = target.getColors();
+ if (colors) {
+ target.setColors(separateVertices(colors, 4));
+ }
+ }
+ this.morphTargetManager.synchronize();
+ }
+ // Update indices
+ for (let index = 0; index < indices.length; index++) {
+ indices[index] = index;
+ }
+ this.setIndices(indices);
+ this._unIndexed = true;
+ // Update submeshes
+ this.releaseSubMeshes();
+ for (const previousOne of previousSubmeshes) {
+ const boundingInfo = previousOne.getBoundingInfo();
+ const subMesh = SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
+ subMesh.setBoundingInfo(boundingInfo);
+ }
+ this.setBoundingInfo(meshBoundingInfo);
+ this.synchronizeInstances();
+ return this;
+ }
+ /**
+ * Modify the mesh to get a flat shading rendering.
+ * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
+ * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
+ * @returns current mesh
+ */
+ convertToFlatShadedMesh() {
+ return this._convertToUnIndexedMesh(true);
+ }
+ /**
+ * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
+ * In other words, more vertices, no more indices and a single bigger VBO.
+ * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
+ * @returns current mesh
+ */
+ convertToUnIndexedMesh() {
+ return this._convertToUnIndexedMesh();
+ }
+ /**
+ * Inverses facet orientations.
+ * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
+ * @param flipNormals will also inverts the normals
+ * @returns current mesh
+ */
+ flipFaces(flipNormals = false) {
+ const vertex_data = VertexData.ExtractFromMesh(this);
+ let i;
+ if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind) && vertex_data.normals) {
+ for (i = 0; i < vertex_data.normals.length; i++) {
+ vertex_data.normals[i] *= -1;
+ }
+ this.setVerticesData(VertexBuffer.NormalKind, vertex_data.normals, this.isVertexBufferUpdatable(VertexBuffer.NormalKind));
+ }
+ if (vertex_data.indices) {
+ let temp;
+ for (i = 0; i < vertex_data.indices.length; i += 3) {
+ // reassign indices
+ temp = vertex_data.indices[i + 1];
+ vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
+ vertex_data.indices[i + 2] = temp;
+ }
+ this.setIndices(vertex_data.indices, null, this.isVertexBufferUpdatable(VertexBuffer.PositionKind), true);
+ }
+ return this;
+ }
+ /**
+ * Increase the number of facets and hence vertices in a mesh
+ * Vertex normals are interpolated from existing vertex normals
+ * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
+ * @param numberPerEdge the number of new vertices to add to each edge of a facet, optional default 1
+ */
+ increaseVertices(numberPerEdge = 1) {
+ const vertex_data = VertexData.ExtractFromMesh(this);
+ const currentIndices = vertex_data.indices && !Array.isArray(vertex_data.indices) && Array.from ? Array.from(vertex_data.indices) : vertex_data.indices;
+ const positions = vertex_data.positions && !Array.isArray(vertex_data.positions) && Array.from ? Array.from(vertex_data.positions) : vertex_data.positions;
+ const uvs = vertex_data.uvs && !Array.isArray(vertex_data.uvs) && Array.from ? Array.from(vertex_data.uvs) : vertex_data.uvs;
+ const normals = vertex_data.normals && !Array.isArray(vertex_data.normals) && Array.from ? Array.from(vertex_data.normals) : vertex_data.normals;
+ if (!currentIndices || !positions) {
+ Logger.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions");
+ }
+ else {
+ vertex_data.indices = currentIndices;
+ vertex_data.positions = positions;
+ if (uvs) {
+ vertex_data.uvs = uvs;
+ }
+ if (normals) {
+ vertex_data.normals = normals;
+ }
+ const segments = numberPerEdge + 1; //segments per current facet edge, become sides of new facets
+ const tempIndices = new Array();
+ for (let i = 0; i < segments + 1; i++) {
+ tempIndices[i] = new Array();
+ }
+ let a; //vertex index of one end of a side
+ let b; //vertex index of other end of the side
+ const deltaPosition = new Vector3(0, 0, 0);
+ const deltaNormal = new Vector3(0, 0, 0);
+ const deltaUV = new Vector2(0, 0);
+ const indices = new Array();
+ const vertexIndex = new Array();
+ const side = new Array();
+ let len;
+ let positionPtr = positions.length;
+ let uvPtr;
+ if (uvs) {
+ uvPtr = uvs.length;
+ }
+ let normalsPtr;
+ if (normals) {
+ normalsPtr = normals.length;
+ }
+ for (let i = 0; i < currentIndices.length; i += 3) {
+ vertexIndex[0] = currentIndices[i];
+ vertexIndex[1] = currentIndices[i + 1];
+ vertexIndex[2] = currentIndices[i + 2];
+ for (let j = 0; j < 3; j++) {
+ a = vertexIndex[j];
+ b = vertexIndex[(j + 1) % 3];
+ if (side[a] === undefined && side[b] === undefined) {
+ side[a] = new Array();
+ side[b] = new Array();
+ }
+ else {
+ if (side[a] === undefined) {
+ side[a] = new Array();
+ }
+ if (side[b] === undefined) {
+ side[b] = new Array();
+ }
+ }
+ if (side[a][b] === undefined && side[b][a] === undefined) {
+ side[a][b] = [];
+ deltaPosition.x = (positions[3 * b] - positions[3 * a]) / segments;
+ deltaPosition.y = (positions[3 * b + 1] - positions[3 * a + 1]) / segments;
+ deltaPosition.z = (positions[3 * b + 2] - positions[3 * a + 2]) / segments;
+ if (normals) {
+ deltaNormal.x = (normals[3 * b] - normals[3 * a]) / segments;
+ deltaNormal.y = (normals[3 * b + 1] - normals[3 * a + 1]) / segments;
+ deltaNormal.z = (normals[3 * b + 2] - normals[3 * a + 2]) / segments;
+ }
+ if (uvs) {
+ deltaUV.x = (uvs[2 * b] - uvs[2 * a]) / segments;
+ deltaUV.y = (uvs[2 * b + 1] - uvs[2 * a + 1]) / segments;
+ }
+ side[a][b].push(a);
+ for (let k = 1; k < segments; k++) {
+ side[a][b].push(positions.length / 3);
+ positions[positionPtr++] = positions[3 * a] + k * deltaPosition.x;
+ positions[positionPtr++] = positions[3 * a + 1] + k * deltaPosition.y;
+ positions[positionPtr++] = positions[3 * a + 2] + k * deltaPosition.z;
+ if (normals) {
+ normals[normalsPtr++] = normals[3 * a] + k * deltaNormal.x;
+ normals[normalsPtr++] = normals[3 * a + 1] + k * deltaNormal.y;
+ normals[normalsPtr++] = normals[3 * a + 2] + k * deltaNormal.z;
+ }
+ if (uvs) {
+ uvs[uvPtr++] = uvs[2 * a] + k * deltaUV.x;
+ uvs[uvPtr++] = uvs[2 * a + 1] + k * deltaUV.y;
+ }
+ }
+ side[a][b].push(b);
+ side[b][a] = new Array();
+ len = side[a][b].length;
+ for (let idx = 0; idx < len; idx++) {
+ side[b][a][idx] = side[a][b][len - 1 - idx];
+ }
+ }
+ }
+ //Calculate positions, normals and uvs of new internal vertices
+ tempIndices[0][0] = currentIndices[i];
+ tempIndices[1][0] = side[currentIndices[i]][currentIndices[i + 1]][1];
+ tempIndices[1][1] = side[currentIndices[i]][currentIndices[i + 2]][1];
+ for (let k = 2; k < segments; k++) {
+ tempIndices[k][0] = side[currentIndices[i]][currentIndices[i + 1]][k];
+ tempIndices[k][k] = side[currentIndices[i]][currentIndices[i + 2]][k];
+ deltaPosition.x = (positions[3 * tempIndices[k][k]] - positions[3 * tempIndices[k][0]]) / k;
+ deltaPosition.y = (positions[3 * tempIndices[k][k] + 1] - positions[3 * tempIndices[k][0] + 1]) / k;
+ deltaPosition.z = (positions[3 * tempIndices[k][k] + 2] - positions[3 * tempIndices[k][0] + 2]) / k;
+ if (normals) {
+ deltaNormal.x = (normals[3 * tempIndices[k][k]] - normals[3 * tempIndices[k][0]]) / k;
+ deltaNormal.y = (normals[3 * tempIndices[k][k] + 1] - normals[3 * tempIndices[k][0] + 1]) / k;
+ deltaNormal.z = (normals[3 * tempIndices[k][k] + 2] - normals[3 * tempIndices[k][0] + 2]) / k;
+ }
+ if (uvs) {
+ deltaUV.x = (uvs[2 * tempIndices[k][k]] - uvs[2 * tempIndices[k][0]]) / k;
+ deltaUV.y = (uvs[2 * tempIndices[k][k] + 1] - uvs[2 * tempIndices[k][0] + 1]) / k;
+ }
+ for (let j = 1; j < k; j++) {
+ tempIndices[k][j] = positions.length / 3;
+ positions[positionPtr++] = positions[3 * tempIndices[k][0]] + j * deltaPosition.x;
+ positions[positionPtr++] = positions[3 * tempIndices[k][0] + 1] + j * deltaPosition.y;
+ positions[positionPtr++] = positions[3 * tempIndices[k][0] + 2] + j * deltaPosition.z;
+ if (normals) {
+ normals[normalsPtr++] = normals[3 * tempIndices[k][0]] + j * deltaNormal.x;
+ normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 1] + j * deltaNormal.y;
+ normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 2] + j * deltaNormal.z;
+ }
+ if (uvs) {
+ uvs[uvPtr++] = uvs[2 * tempIndices[k][0]] + j * deltaUV.x;
+ uvs[uvPtr++] = uvs[2 * tempIndices[k][0] + 1] + j * deltaUV.y;
+ }
+ }
+ }
+ tempIndices[segments] = side[currentIndices[i + 1]][currentIndices[i + 2]];
+ // reform indices
+ indices.push(tempIndices[0][0], tempIndices[1][0], tempIndices[1][1]);
+ for (let k = 1; k < segments; k++) {
+ let j;
+ for (j = 0; j < k; j++) {
+ indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]);
+ indices.push(tempIndices[k][j], tempIndices[k + 1][j + 1], tempIndices[k][j + 1]);
+ }
+ indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]);
+ }
+ }
+ vertex_data.indices = indices;
+ vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind));
+ }
+ }
+ /**
+ * Force adjacent facets to share vertices and remove any facets that have all vertices in a line
+ * This will undo any application of covertToFlatShadedMesh
+ * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
+ */
+ forceSharedVertices() {
+ const vertex_data = VertexData.ExtractFromMesh(this);
+ const currentUVs = vertex_data.uvs;
+ const currentIndices = vertex_data.indices;
+ const currentPositions = vertex_data.positions;
+ const currentColors = vertex_data.colors;
+ const currentMatrixIndices = vertex_data.matricesIndices;
+ const currentMatrixWeights = vertex_data.matricesWeights;
+ const currentMatrixIndicesExtra = vertex_data.matricesIndicesExtra;
+ const currentMatrixWeightsExtra = vertex_data.matricesWeightsExtra;
+ if (currentIndices === void 0 || currentPositions === void 0 || currentIndices === null || currentPositions === null) {
+ Logger.Warn("VertexData contains empty entries");
+ }
+ else {
+ const positions = new Array();
+ const indices = new Array();
+ const uvs = new Array();
+ const colors = new Array();
+ const matrixIndices = new Array();
+ const matrixWeights = new Array();
+ const matrixIndicesExtra = new Array();
+ const matrixWeightsExtra = new Array();
+ let pstring = new Array(); //lists facet vertex positions (a,b,c) as string "a|b|c"
+ let indexPtr = 0; // pointer to next available index value
+ const uniquePositions = {}; // unique vertex positions
+ let ptr; // pointer to element in uniquePositions
+ let facet;
+ for (let i = 0; i < currentIndices.length; i += 3) {
+ facet = [currentIndices[i], currentIndices[i + 1], currentIndices[i + 2]]; //facet vertex indices
+ pstring = [];
+ for (let j = 0; j < 3; j++) {
+ pstring[j] = "";
+ for (let k = 0; k < 3; k++) {
+ //small values make 0
+ if (Math.abs(currentPositions[3 * facet[j] + k]) < 0.00000001) {
+ currentPositions[3 * facet[j] + k] = 0;
+ }
+ pstring[j] += currentPositions[3 * facet[j] + k] + "|";
+ }
+ }
+ //check facet vertices to see that none are repeated
+ // do not process any facet that has a repeated vertex, ie is a line
+ if (!(pstring[0] == pstring[1] || pstring[0] == pstring[2] || pstring[1] == pstring[2])) {
+ //for each facet position check if already listed in uniquePositions
+ // if not listed add to uniquePositions and set index pointer
+ // if listed use its index in uniquePositions and new index pointer
+ for (let j = 0; j < 3; j++) {
+ ptr = uniquePositions[pstring[j]];
+ if (ptr === undefined) {
+ uniquePositions[pstring[j]] = indexPtr;
+ ptr = indexPtr++;
+ //not listed so add individual x, y, z coordinates to positions
+ for (let k = 0; k < 3; k++) {
+ positions.push(currentPositions[3 * facet[j] + k]);
+ }
+ if (currentColors !== null && currentColors !== void 0) {
+ for (let k = 0; k < 4; k++) {
+ colors.push(currentColors[4 * facet[j] + k]);
+ }
+ }
+ if (currentUVs !== null && currentUVs !== void 0) {
+ for (let k = 0; k < 2; k++) {
+ uvs.push(currentUVs[2 * facet[j] + k]);
+ }
+ }
+ if (currentMatrixIndices !== null && currentMatrixIndices !== void 0) {
+ for (let k = 0; k < 4; k++) {
+ matrixIndices.push(currentMatrixIndices[4 * facet[j] + k]);
+ }
+ }
+ if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) {
+ for (let k = 0; k < 4; k++) {
+ matrixWeights.push(currentMatrixWeights[4 * facet[j] + k]);
+ }
+ }
+ if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== void 0) {
+ for (let k = 0; k < 4; k++) {
+ matrixIndicesExtra.push(currentMatrixIndicesExtra[4 * facet[j] + k]);
+ }
+ }
+ if (currentMatrixWeightsExtra !== null && currentMatrixWeightsExtra !== void 0) {
+ for (let k = 0; k < 4; k++) {
+ matrixWeightsExtra.push(currentMatrixWeightsExtra[4 * facet[j] + k]);
+ }
+ }
+ }
+ // add new index pointer to indices array
+ indices.push(ptr);
+ }
+ }
+ }
+ const normals = new Array();
+ VertexData.ComputeNormals(positions, indices, normals);
+ //create new vertex data object and update
+ vertex_data.positions = positions;
+ vertex_data.indices = indices;
+ vertex_data.normals = normals;
+ if (currentUVs !== null && currentUVs !== void 0) {
+ vertex_data.uvs = uvs;
+ }
+ if (currentColors !== null && currentColors !== void 0) {
+ vertex_data.colors = colors;
+ }
+ if (currentMatrixIndices !== null && currentMatrixIndices !== void 0) {
+ vertex_data.matricesIndices = matrixIndices;
+ }
+ if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) {
+ vertex_data.matricesWeights = matrixWeights;
+ }
+ if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== void 0) {
+ vertex_data.matricesIndicesExtra = matrixIndicesExtra;
+ }
+ if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) {
+ vertex_data.matricesWeightsExtra = matrixWeightsExtra;
+ }
+ vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind));
+ }
+ }
+ // Instances
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/naming-convention
+ static _instancedMeshFactory(name, mesh) {
+ throw _WarnImport("InstancedMesh");
+ }
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static _PhysicsImpostorParser(scene, physicObject, jsonObject) {
+ throw _WarnImport("PhysicsImpostor");
+ }
+ /**
+ * Creates a new InstancedMesh object from the mesh model.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances
+ * @param name defines the name of the new instance
+ * @returns a new InstancedMesh
+ */
+ createInstance(name) {
+ const instance = Mesh._instancedMeshFactory(name, this);
+ instance.parent = this.parent;
+ return instance;
+ }
+ /**
+ * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
+ * After this call, all the mesh instances have the same submeshes than the current mesh.
+ * @returns the current mesh
+ */
+ synchronizeInstances() {
+ for (let instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
+ const instance = this.instances[instanceIndex];
+ instance._syncSubMeshes();
+ }
+ return this;
+ }
+ /**
+ * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
+ * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
+ * This should be used together with the simplification to avoid disappearing triangles.
+ * @param successCallback an optional success callback to be called after the optimization finished.
+ * @returns the current mesh
+ */
+ optimizeIndices(successCallback) {
+ const indices = this.getIndices();
+ const positions = this.getVerticesData(VertexBuffer.PositionKind);
+ if (!positions || !indices) {
+ return this;
+ }
+ const vectorPositions = [];
+ for (let pos = 0; pos < positions.length; pos = pos + 3) {
+ vectorPositions.push(Vector3.FromArray(positions, pos));
+ }
+ const dupes = [];
+ AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
+ const realPos = vectorPositions.length - 1 - iteration;
+ const testedPosition = vectorPositions[realPos];
+ for (let j = 0; j < realPos; ++j) {
+ const againstPosition = vectorPositions[j];
+ if (testedPosition.equals(againstPosition)) {
+ dupes[realPos] = j;
+ break;
+ }
+ }
+ }, () => {
+ for (let i = 0; i < indices.length; ++i) {
+ indices[i] = dupes[indices[i]] || indices[i];
+ }
+ //indices are now reordered
+ const originalSubMeshes = this.subMeshes.slice(0);
+ this.setIndices(indices);
+ this.subMeshes = originalSubMeshes;
+ if (successCallback) {
+ successCallback(this);
+ }
+ });
+ return this;
+ }
+ /**
+ * Serialize current mesh
+ * @param serializationObject defines the object which will receive the serialization data
+ * @returns the serialized object
+ */
+ serialize(serializationObject = {}) {
+ serializationObject.name = this.name;
+ serializationObject.id = this.id;
+ serializationObject.uniqueId = this.uniqueId;
+ serializationObject.type = this.getClassName();
+ if (Tags && Tags.HasTags(this)) {
+ serializationObject.tags = Tags.GetTags(this);
+ }
+ serializationObject.position = this.position.asArray();
+ if (this.rotationQuaternion) {
+ serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
+ }
+ else if (this.rotation) {
+ serializationObject.rotation = this.rotation.asArray();
+ }
+ serializationObject.scaling = this.scaling.asArray();
+ if (this._postMultiplyPivotMatrix) {
+ serializationObject.pivotMatrix = this.getPivotMatrix().asArray();
+ }
+ else {
+ serializationObject.localMatrix = this.getPivotMatrix().asArray();
+ }
+ serializationObject.isEnabled = this.isEnabled(false);
+ serializationObject.isVisible = this.isVisible;
+ serializationObject.infiniteDistance = this.infiniteDistance;
+ serializationObject.pickable = this.isPickable;
+ serializationObject.receiveShadows = this.receiveShadows;
+ serializationObject.billboardMode = this.billboardMode;
+ serializationObject.visibility = this.visibility;
+ serializationObject.alwaysSelectAsActiveMesh = this.alwaysSelectAsActiveMesh;
+ serializationObject.checkCollisions = this.checkCollisions;
+ serializationObject.ellipsoid = this.ellipsoid.asArray();
+ serializationObject.ellipsoidOffset = this.ellipsoidOffset.asArray();
+ serializationObject.doNotSyncBoundingInfo = this.doNotSyncBoundingInfo;
+ serializationObject.isBlocker = this.isBlocker;
+ serializationObject.sideOrientation = this.sideOrientation;
+ // Parent
+ if (this.parent) {
+ this.parent._serializeAsParent(serializationObject);
+ }
+ // Geometry
+ serializationObject.isUnIndexed = this.isUnIndexed;
+ const geometry = this._geometry;
+ if (geometry && this.subMeshes) {
+ serializationObject.geometryUniqueId = geometry.uniqueId;
+ serializationObject.geometryId = geometry.id;
+ // SubMeshes
+ serializationObject.subMeshes = [];
+ for (let subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
+ const subMesh = this.subMeshes[subIndex];
+ serializationObject.subMeshes.push({
+ materialIndex: subMesh.materialIndex,
+ verticesStart: subMesh.verticesStart,
+ verticesCount: subMesh.verticesCount,
+ indexStart: subMesh.indexStart,
+ indexCount: subMesh.indexCount,
+ });
+ }
+ }
+ // Material
+ if (this.material) {
+ if (!this.material.doNotSerialize) {
+ serializationObject.materialUniqueId = this.material.uniqueId;
+ serializationObject.materialId = this.material.id; // back compat
+ }
+ }
+ else {
+ this.material = null;
+ serializationObject.materialUniqueId = this._scene.defaultMaterial.uniqueId;
+ serializationObject.materialId = this._scene.defaultMaterial.id; // back compat
+ }
+ // Morph targets
+ if (this.morphTargetManager) {
+ serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
+ }
+ // Skeleton
+ if (this.skeleton) {
+ serializationObject.skeletonId = this.skeleton.id;
+ serializationObject.numBoneInfluencers = this.numBoneInfluencers;
+ }
+ // Physics
+ //TODO implement correct serialization for physics impostors.
+ if (this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) {
+ const impostor = this.getPhysicsImpostor();
+ if (impostor) {
+ serializationObject.physicsMass = impostor.getParam("mass");
+ serializationObject.physicsFriction = impostor.getParam("friction");
+ serializationObject.physicsRestitution = impostor.getParam("mass");
+ serializationObject.physicsImpostor = impostor.type;
+ }
+ }
+ // Metadata
+ if (this.metadata) {
+ serializationObject.metadata = this.metadata;
+ }
+ // Instances
+ serializationObject.instances = [];
+ for (let index = 0; index < this.instances.length; index++) {
+ const instance = this.instances[index];
+ if (instance.doNotSerialize) {
+ continue;
+ }
+ const serializationInstance = {
+ name: instance.name,
+ id: instance.id,
+ isEnabled: instance.isEnabled(false),
+ isVisible: instance.isVisible,
+ isPickable: instance.isPickable,
+ checkCollisions: instance.checkCollisions,
+ position: instance.position.asArray(),
+ scaling: instance.scaling.asArray(),
+ };
+ if (instance.parent) {
+ instance.parent._serializeAsParent(serializationInstance);
+ }
+ if (instance.rotationQuaternion) {
+ serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
+ }
+ else if (instance.rotation) {
+ serializationInstance.rotation = instance.rotation.asArray();
+ }
+ // Physics
+ //TODO implement correct serialization for physics impostors.
+ if (this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) {
+ const impostor = instance.getPhysicsImpostor();
+ if (impostor) {
+ serializationInstance.physicsMass = impostor.getParam("mass");
+ serializationInstance.physicsFriction = impostor.getParam("friction");
+ serializationInstance.physicsRestitution = impostor.getParam("mass");
+ serializationInstance.physicsImpostor = impostor.type;
+ }
+ }
+ // Metadata
+ if (instance.metadata) {
+ serializationInstance.metadata = instance.metadata;
+ }
+ // Action Manager
+ if (instance.actionManager) {
+ serializationInstance.actions = instance.actionManager.serialize(instance.name);
+ }
+ serializationObject.instances.push(serializationInstance);
+ // Animations
+ SerializationHelper.AppendSerializedAnimations(instance, serializationInstance);
+ serializationInstance.ranges = instance.serializeAnimationRanges();
+ }
+ // Thin instances
+ if (this._thinInstanceDataStorage.instancesCount && this._thinInstanceDataStorage.matrixData) {
+ serializationObject.thinInstances = {
+ instancesCount: this._thinInstanceDataStorage.instancesCount,
+ matrixData: Array.from(this._thinInstanceDataStorage.matrixData),
+ matrixBufferSize: this._thinInstanceDataStorage.matrixBufferSize,
+ enablePicking: this.thinInstanceEnablePicking,
+ };
+ if (this._userThinInstanceBuffersStorage) {
+ const userThinInstance = {
+ data: {},
+ sizes: {},
+ strides: {},
+ };
+ for (const kind in this._userThinInstanceBuffersStorage.data) {
+ userThinInstance.data[kind] = Array.from(this._userThinInstanceBuffersStorage.data[kind]);
+ userThinInstance.sizes[kind] = this._userThinInstanceBuffersStorage.sizes[kind];
+ userThinInstance.strides[kind] = this._userThinInstanceBuffersStorage.strides[kind];
+ }
+ serializationObject.thinInstances.userThinInstance = userThinInstance;
+ }
+ }
+ // Animations
+ SerializationHelper.AppendSerializedAnimations(this, serializationObject);
+ serializationObject.ranges = this.serializeAnimationRanges();
+ // Layer mask
+ serializationObject.layerMask = this.layerMask;
+ // Alpha
+ serializationObject.alphaIndex = this.alphaIndex;
+ serializationObject.hasVertexAlpha = this.hasVertexAlpha;
+ // Overlay
+ serializationObject.overlayAlpha = this.overlayAlpha;
+ serializationObject.overlayColor = this.overlayColor.asArray();
+ serializationObject.renderOverlay = this.renderOverlay;
+ // Fog
+ serializationObject.applyFog = this.applyFog;
+ // Action Manager
+ if (this.actionManager) {
+ serializationObject.actions = this.actionManager.serialize(this.name);
+ }
+ return serializationObject;
+ }
+ /** @internal */
+ _syncGeometryWithMorphTargetManager() {
+ if (!this.geometry) {
+ return;
+ }
+ this._markSubMeshesAsAttributesDirty();
+ const morphTargetManager = this._internalAbstractMeshDataInfo._morphTargetManager;
+ if (morphTargetManager && morphTargetManager.vertexCount) {
+ if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
+ Logger.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
+ this.morphTargetManager = null;
+ return;
+ }
+ if (morphTargetManager.isUsingTextureForTargets) {
+ return;
+ }
+ for (let index = 0; index < morphTargetManager.numInfluencers; index++) {
+ const morphTarget = morphTargetManager.getActiveTarget(index);
+ const positions = morphTarget.getPositions();
+ if (!positions) {
+ Logger.Error("Invalid morph target. Target must have positions.");
+ return;
+ }
+ this.geometry.setVerticesData(VertexBuffer.PositionKind + index, positions, false, 3);
+ const normals = morphTarget.getNormals();
+ if (normals) {
+ this.geometry.setVerticesData(VertexBuffer.NormalKind + index, normals, false, 3);
+ }
+ const tangents = morphTarget.getTangents();
+ if (tangents) {
+ this.geometry.setVerticesData(VertexBuffer.TangentKind + index, tangents, false, 3);
+ }
+ const uvs = morphTarget.getUVs();
+ if (uvs) {
+ this.geometry.setVerticesData(VertexBuffer.UVKind + "_" + index, uvs, false, 2);
+ }
+ const uv2s = morphTarget.getUV2s();
+ if (uv2s) {
+ this.geometry.setVerticesData(VertexBuffer.UV2Kind + "_" + index, uv2s, false, 2);
+ }
+ const colors = morphTarget.getColors();
+ if (colors) {
+ this.geometry.setVerticesData(VertexBuffer.ColorKind + index, colors, false, 4);
+ }
+ }
+ }
+ else {
+ let index = 0;
+ // Positions
+ while (this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + index)) {
+ this.geometry.removeVerticesData(VertexBuffer.PositionKind + index);
+ if (this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + index)) {
+ this.geometry.removeVerticesData(VertexBuffer.NormalKind + index);
+ }
+ if (this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + index)) {
+ this.geometry.removeVerticesData(VertexBuffer.TangentKind + index);
+ }
+ if (this.geometry.isVerticesDataPresent(VertexBuffer.UVKind + index)) {
+ this.geometry.removeVerticesData(VertexBuffer.UVKind + "_" + index);
+ }
+ if (this.geometry.isVerticesDataPresent(VertexBuffer.UV2Kind + index)) {
+ this.geometry.removeVerticesData(VertexBuffer.UV2Kind + "_" + index);
+ }
+ if (this.geometry.isVerticesDataPresent(VertexBuffer.ColorKind + index)) {
+ this.geometry.removeVerticesData(VertexBuffer.ColorKind + index);
+ }
+ index++;
+ }
+ }
+ }
+ /**
+ * Returns a new Mesh object parsed from the source provided.
+ * @param parsedMesh is the source
+ * @param scene defines the hosting scene
+ * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
+ * @returns a new Mesh
+ */
+ static Parse(parsedMesh, scene, rootUrl) {
+ let mesh;
+ if (parsedMesh.type && parsedMesh.type === "LinesMesh") {
+ mesh = Mesh._LinesMeshParser(parsedMesh, scene);
+ }
+ else if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
+ mesh = Mesh._GroundMeshParser(parsedMesh, scene);
+ }
+ else if (parsedMesh.type && parsedMesh.type === "GoldbergMesh") {
+ mesh = Mesh._GoldbergMeshParser(parsedMesh, scene);
+ }
+ else if (parsedMesh.type && parsedMesh.type === "GreasedLineMesh") {
+ mesh = Mesh._GreasedLineMeshParser(parsedMesh, scene);
+ }
+ else if (parsedMesh.type && parsedMesh.type === "TrailMesh") {
+ mesh = Mesh._TrailMeshParser(parsedMesh, scene);
+ }
+ else {
+ mesh = new Mesh(parsedMesh.name, scene);
+ }
+ mesh.id = parsedMesh.id;
+ mesh._waitingParsedUniqueId = parsedMesh.uniqueId;
+ if (Tags) {
+ Tags.AddTagsTo(mesh, parsedMesh.tags);
+ }
+ mesh.position = Vector3.FromArray(parsedMesh.position);
+ if (parsedMesh.metadata !== undefined) {
+ mesh.metadata = parsedMesh.metadata;
+ }
+ if (parsedMesh.rotationQuaternion) {
+ mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
+ }
+ else if (parsedMesh.rotation) {
+ mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
+ }
+ mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
+ if (parsedMesh.localMatrix) {
+ mesh.setPreTransformMatrix(Matrix.FromArray(parsedMesh.localMatrix));
+ }
+ else if (parsedMesh.pivotMatrix) {
+ mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
+ }
+ mesh.setEnabled(parsedMesh.isEnabled);
+ mesh.isVisible = parsedMesh.isVisible;
+ mesh.infiniteDistance = parsedMesh.infiniteDistance;
+ mesh.alwaysSelectAsActiveMesh = !!parsedMesh.alwaysSelectAsActiveMesh;
+ mesh.showBoundingBox = parsedMesh.showBoundingBox;
+ mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
+ if (parsedMesh.applyFog !== undefined) {
+ mesh.applyFog = parsedMesh.applyFog;
+ }
+ if (parsedMesh.pickable !== undefined) {
+ mesh.isPickable = parsedMesh.pickable;
+ }
+ if (parsedMesh.alphaIndex !== undefined) {
+ mesh.alphaIndex = parsedMesh.alphaIndex;
+ }
+ mesh.receiveShadows = parsedMesh.receiveShadows;
+ if (parsedMesh.billboardMode !== undefined) {
+ mesh.billboardMode = parsedMesh.billboardMode;
+ }
+ if (parsedMesh.visibility !== undefined) {
+ mesh.visibility = parsedMesh.visibility;
+ }
+ mesh.checkCollisions = parsedMesh.checkCollisions;
+ mesh.doNotSyncBoundingInfo = !!parsedMesh.doNotSyncBoundingInfo;
+ if (parsedMesh.ellipsoid) {
+ mesh.ellipsoid = Vector3.FromArray(parsedMesh.ellipsoid);
+ }
+ if (parsedMesh.ellipsoidOffset) {
+ mesh.ellipsoidOffset = Vector3.FromArray(parsedMesh.ellipsoidOffset);
+ }
+ // For Backward compatibility ("!=" to exclude null and undefined)
+ if (parsedMesh.overrideMaterialSideOrientation != null) {
+ mesh.sideOrientation = parsedMesh.overrideMaterialSideOrientation;
+ }
+ if (parsedMesh.sideOrientation !== undefined) {
+ mesh.sideOrientation = parsedMesh.sideOrientation;
+ }
+ if (parsedMesh.isBlocker !== undefined) {
+ mesh.isBlocker = parsedMesh.isBlocker;
+ }
+ mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
+ // freezeWorldMatrix
+ if (parsedMesh.freezeWorldMatrix) {
+ mesh._waitingData.freezeWorldMatrix = parsedMesh.freezeWorldMatrix;
+ }
+ // Parent
+ if (parsedMesh.parentId !== undefined) {
+ mesh._waitingParentId = parsedMesh.parentId;
+ }
+ if (parsedMesh.parentInstanceIndex !== undefined) {
+ mesh._waitingParentInstanceIndex = parsedMesh.parentInstanceIndex;
+ }
+ // Actions
+ if (parsedMesh.actions !== undefined) {
+ mesh._waitingData.actions = parsedMesh.actions;
+ }
+ // Overlay
+ if (parsedMesh.overlayAlpha !== undefined) {
+ mesh.overlayAlpha = parsedMesh.overlayAlpha;
+ }
+ if (parsedMesh.overlayColor !== undefined) {
+ mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor);
+ }
+ if (parsedMesh.renderOverlay !== undefined) {
+ mesh.renderOverlay = parsedMesh.renderOverlay;
+ }
+ // Geometry
+ mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
+ mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
+ if (parsedMesh.delayLoadingFile) {
+ mesh.delayLoadState = 4;
+ mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
+ mesh.buildBoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
+ if (parsedMesh._binaryInfo) {
+ mesh._binaryInfo = parsedMesh._binaryInfo;
+ }
+ mesh._delayInfo = [];
+ if (parsedMesh.hasUVs) {
+ mesh._delayInfo.push(VertexBuffer.UVKind);
+ }
+ if (parsedMesh.hasUVs2) {
+ mesh._delayInfo.push(VertexBuffer.UV2Kind);
+ }
+ if (parsedMesh.hasUVs3) {
+ mesh._delayInfo.push(VertexBuffer.UV3Kind);
+ }
+ if (parsedMesh.hasUVs4) {
+ mesh._delayInfo.push(VertexBuffer.UV4Kind);
+ }
+ if (parsedMesh.hasUVs5) {
+ mesh._delayInfo.push(VertexBuffer.UV5Kind);
+ }
+ if (parsedMesh.hasUVs6) {
+ mesh._delayInfo.push(VertexBuffer.UV6Kind);
+ }
+ if (parsedMesh.hasColors) {
+ mesh._delayInfo.push(VertexBuffer.ColorKind);
+ }
+ if (parsedMesh.hasMatricesIndices) {
+ mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
+ }
+ if (parsedMesh.hasMatricesWeights) {
+ mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
+ }
+ mesh._delayLoadingFunction = Geometry._ImportGeometry;
+ if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) {
+ mesh._checkDelayState();
+ }
+ }
+ else {
+ Geometry._ImportGeometry(parsedMesh, mesh);
+ }
+ // Material
+ if (parsedMesh.materialUniqueId) {
+ mesh._waitingMaterialId = parsedMesh.materialUniqueId;
+ }
+ else if (parsedMesh.materialId) {
+ mesh._waitingMaterialId = parsedMesh.materialId;
+ }
+ // Morph targets
+ if (parsedMesh.morphTargetManagerId > -1) {
+ mesh._waitingMorphTargetManagerId = parsedMesh.morphTargetManagerId;
+ }
+ // Skeleton
+ if (parsedMesh.skeletonId !== undefined && parsedMesh.skeletonId !== null) {
+ mesh.skeleton = scene.getLastSkeletonById(parsedMesh.skeletonId);
+ if (parsedMesh.numBoneInfluencers) {
+ mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
+ }
+ }
+ // Animations
+ if (parsedMesh.animations) {
+ for (let animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
+ const parsedAnimation = parsedMesh.animations[animationIndex];
+ const internalClass = GetClass("BABYLON.Animation");
+ if (internalClass) {
+ mesh.animations.push(internalClass.Parse(parsedAnimation));
+ }
+ }
+ Node$2.ParseAnimationRanges(mesh, parsedMesh, scene);
+ }
+ if (parsedMesh.autoAnimate) {
+ scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
+ }
+ // Layer Mask
+ if (parsedMesh.layerMask && !isNaN(parsedMesh.layerMask)) {
+ mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
+ }
+ else {
+ mesh.layerMask = 0x0fffffff;
+ }
+ // Physics
+ if (parsedMesh.physicsImpostor) {
+ mesh.physicsImpostor = Mesh._PhysicsImpostorParser(scene, mesh, parsedMesh);
+ }
+ // Levels
+ if (parsedMesh.lodMeshIds) {
+ mesh._waitingData.lods = {
+ ids: parsedMesh.lodMeshIds,
+ distances: parsedMesh.lodDistances ? parsedMesh.lodDistances : null,
+ coverages: parsedMesh.lodCoverages ? parsedMesh.lodCoverages : null,
+ };
+ }
+ // Instances
+ if (parsedMesh.instances) {
+ for (let index = 0; index < parsedMesh.instances.length; index++) {
+ const parsedInstance = parsedMesh.instances[index];
+ const instance = mesh.createInstance(parsedInstance.name);
+ if (parsedInstance.id) {
+ instance.id = parsedInstance.id;
+ }
+ if (Tags) {
+ if (parsedInstance.tags) {
+ Tags.AddTagsTo(instance, parsedInstance.tags);
+ }
+ else {
+ Tags.AddTagsTo(instance, parsedMesh.tags);
+ }
+ }
+ instance.position = Vector3.FromArray(parsedInstance.position);
+ if (parsedInstance.metadata !== undefined) {
+ instance.metadata = parsedInstance.metadata;
+ }
+ if (parsedInstance.parentId !== undefined) {
+ instance._waitingParentId = parsedInstance.parentId;
+ }
+ if (parsedInstance.parentInstanceIndex !== undefined) {
+ instance._waitingParentInstanceIndex = parsedInstance.parentInstanceIndex;
+ }
+ if (parsedInstance.isEnabled !== undefined && parsedInstance.isEnabled !== null) {
+ instance.setEnabled(parsedInstance.isEnabled);
+ }
+ if (parsedInstance.isVisible !== undefined && parsedInstance.isVisible !== null) {
+ instance.isVisible = parsedInstance.isVisible;
+ }
+ if (parsedInstance.isPickable !== undefined && parsedInstance.isPickable !== null) {
+ instance.isPickable = parsedInstance.isPickable;
+ }
+ if (parsedInstance.rotationQuaternion) {
+ instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
+ }
+ else if (parsedInstance.rotation) {
+ instance.rotation = Vector3.FromArray(parsedInstance.rotation);
+ }
+ instance.scaling = Vector3.FromArray(parsedInstance.scaling);
+ if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
+ instance.checkCollisions = parsedInstance.checkCollisions;
+ }
+ if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
+ instance.isPickable = parsedInstance.pickable;
+ }
+ if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
+ instance.showBoundingBox = parsedInstance.showBoundingBox;
+ }
+ if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
+ instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
+ }
+ if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
+ instance.alphaIndex = parsedInstance.alphaIndex;
+ }
+ // Physics
+ if (parsedInstance.physicsImpostor) {
+ instance.physicsImpostor = Mesh._PhysicsImpostorParser(scene, instance, parsedInstance);
+ }
+ // Actions
+ if (parsedInstance.actions !== undefined) {
+ instance._waitingData.actions = parsedInstance.actions;
+ }
+ // Animation
+ if (parsedInstance.animations) {
+ for (let animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
+ const parsedAnimation = parsedInstance.animations[animationIndex];
+ const internalClass = GetClass("BABYLON.Animation");
+ if (internalClass) {
+ instance.animations.push(internalClass.Parse(parsedAnimation));
+ }
+ }
+ Node$2.ParseAnimationRanges(instance, parsedInstance, scene);
+ if (parsedInstance.autoAnimate) {
+ scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
+ }
+ }
+ }
+ }
+ // Thin instances
+ if (parsedMesh.thinInstances) {
+ const thinInstances = parsedMesh.thinInstances;
+ mesh.thinInstanceEnablePicking = !!thinInstances.enablePicking;
+ if (thinInstances.matrixData) {
+ mesh.thinInstanceSetBuffer("matrix", new Float32Array(thinInstances.matrixData), 16, false);
+ mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize;
+ mesh._thinInstanceDataStorage.instancesCount = thinInstances.instancesCount;
+ }
+ else {
+ mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize;
+ }
+ if (parsedMesh.thinInstances.userThinInstance) {
+ const userThinInstance = parsedMesh.thinInstances.userThinInstance;
+ for (const kind in userThinInstance.data) {
+ mesh.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], false);
+ mesh._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind];
+ }
+ }
+ }
+ return mesh;
+ }
+ // Skeletons
+ /**
+ * Prepare internal position array for software CPU skinning
+ * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
+ */
+ setPositionsForCPUSkinning() {
+ const internalDataInfo = this._internalMeshDataInfo;
+ if (!internalDataInfo._sourcePositions) {
+ const source = this.getVerticesData(VertexBuffer.PositionKind);
+ if (!source) {
+ return internalDataInfo._sourcePositions;
+ }
+ internalDataInfo._sourcePositions = new Float32Array(source);
+ if (!this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
+ this.setVerticesData(VertexBuffer.PositionKind, source, true);
+ }
+ }
+ return internalDataInfo._sourcePositions;
+ }
+ /**
+ * Prepare internal normal array for software CPU skinning
+ * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
+ */
+ setNormalsForCPUSkinning() {
+ const internalDataInfo = this._internalMeshDataInfo;
+ if (!internalDataInfo._sourceNormals) {
+ const source = this.getVerticesData(VertexBuffer.NormalKind);
+ if (!source) {
+ return internalDataInfo._sourceNormals;
+ }
+ internalDataInfo._sourceNormals = new Float32Array(source);
+ if (!this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
+ this.setVerticesData(VertexBuffer.NormalKind, source, true);
+ }
+ }
+ return internalDataInfo._sourceNormals;
+ }
+ /**
+ * Updates the vertex buffer by applying transformation from the bones
+ * @param skeleton defines the skeleton to apply to current mesh
+ * @returns the current mesh
+ */
+ applySkeleton(skeleton) {
+ if (!this.geometry) {
+ return this;
+ }
+ if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
+ return this;
+ }
+ this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
+ if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
+ return this;
+ }
+ if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
+ return this;
+ }
+ if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
+ return this;
+ }
+ const hasNormals = this.isVerticesDataPresent(VertexBuffer.NormalKind);
+ const internalDataInfo = this._internalMeshDataInfo;
+ if (!internalDataInfo._sourcePositions) {
+ const submeshes = this.subMeshes.slice();
+ this.setPositionsForCPUSkinning();
+ this.subMeshes = submeshes;
+ }
+ if (hasNormals && !internalDataInfo._sourceNormals) {
+ this.setNormalsForCPUSkinning();
+ }
+ // positionsData checks for not being Float32Array will only pass at most once
+ let positionsData = this.getVerticesData(VertexBuffer.PositionKind);
+ if (!positionsData) {
+ return this;
+ }
+ if (!(positionsData instanceof Float32Array)) {
+ positionsData = new Float32Array(positionsData);
+ }
+ // normalsData checks for not being Float32Array will only pass at most once
+ let normalsData = this.getVerticesData(VertexBuffer.NormalKind);
+ if (hasNormals) {
+ if (!normalsData) {
+ return this;
+ }
+ if (!(normalsData instanceof Float32Array)) {
+ normalsData = new Float32Array(normalsData);
+ }
+ }
+ const matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
+ const matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
+ if (!matricesWeightsData || !matricesIndicesData) {
+ return this;
+ }
+ const needExtras = this.numBoneInfluencers > 4;
+ const matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
+ const matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
+ const skeletonMatrices = skeleton.getTransformMatrices(this);
+ const tempVector3 = Vector3.Zero();
+ const finalMatrix = new Matrix();
+ const tempMatrix = new Matrix();
+ let matWeightIdx = 0;
+ let inf;
+ for (let index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
+ let weight;
+ for (inf = 0; inf < 4; inf++) {
+ weight = matricesWeightsData[matWeightIdx + inf];
+ if (weight > 0) {
+ Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
+ finalMatrix.addToSelf(tempMatrix);
+ }
+ }
+ if (needExtras) {
+ for (inf = 0; inf < 4; inf++) {
+ weight = matricesWeightsExtraData[matWeightIdx + inf];
+ if (weight > 0) {
+ Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
+ finalMatrix.addToSelf(tempMatrix);
+ }
+ }
+ }
+ Vector3.TransformCoordinatesFromFloatsToRef(internalDataInfo._sourcePositions[index], internalDataInfo._sourcePositions[index + 1], internalDataInfo._sourcePositions[index + 2], finalMatrix, tempVector3);
+ tempVector3.toArray(positionsData, index);
+ if (hasNormals) {
+ Vector3.TransformNormalFromFloatsToRef(internalDataInfo._sourceNormals[index], internalDataInfo._sourceNormals[index + 1], internalDataInfo._sourceNormals[index + 2], finalMatrix, tempVector3);
+ tempVector3.toArray(normalsData, index);
+ }
+ finalMatrix.reset();
+ }
+ this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
+ if (hasNormals) {
+ this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
+ }
+ return this;
+ }
+ // Tools
+ /**
+ * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
+ * @param meshes defines the list of meshes to scan
+ * @returns an object `{min:` Vector3`, max:` Vector3`}`
+ */
+ static MinMax(meshes) {
+ let minVector = null;
+ let maxVector = null;
+ meshes.forEach(function (mesh) {
+ const boundingInfo = mesh.getBoundingInfo();
+ const boundingBox = boundingInfo.boundingBox;
+ if (!minVector || !maxVector) {
+ minVector = boundingBox.minimumWorld;
+ maxVector = boundingBox.maximumWorld;
+ }
+ else {
+ minVector.minimizeInPlace(boundingBox.minimumWorld);
+ maxVector.maximizeInPlace(boundingBox.maximumWorld);
+ }
+ });
+ if (!minVector || !maxVector) {
+ return {
+ min: Vector3.Zero(),
+ max: Vector3.Zero(),
+ };
+ }
+ return {
+ min: minVector,
+ max: maxVector,
+ };
+ }
+ /**
+ * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
+ * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
+ * @returns a vector3
+ */
+ static Center(meshesOrMinMaxVector) {
+ const minMaxVector = meshesOrMinMaxVector instanceof Array ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
+ return Vector3.Center(minMaxVector.min, minMaxVector.max);
+ }
+ /**
+ * Merge the array of meshes into a single mesh for performance reasons.
+ * @param meshes array of meshes with the vertices to merge. Entries cannot be empty meshes.
+ * @param disposeSource when true (default), dispose of the vertices from the source meshes.
+ * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true.
+ * @param meshSubclass (optional) can be set to a Mesh where the merged vertices will be inserted.
+ * @param subdivideWithSubMeshes when true (false default), subdivide mesh into subMeshes.
+ * @param multiMultiMaterials when true (false default), subdivide mesh into subMeshes with multiple materials, ignores subdivideWithSubMeshes.
+ * @returns a new mesh
+ */
+ static MergeMeshes(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) {
+ return runCoroutineSync(Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, false));
+ }
+ /**
+ * Merge the array of meshes into a single mesh for performance reasons.
+ * @param meshes array of meshes with the vertices to merge. Entries cannot be empty meshes.
+ * @param disposeSource when true (default), dispose of the vertices from the source meshes.
+ * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true.
+ * @param meshSubclass (optional) can be set to a Mesh where the merged vertices will be inserted.
+ * @param subdivideWithSubMeshes when true (false default), subdivide mesh into subMeshes.
+ * @param multiMultiMaterials when true (false default), subdivide mesh into subMeshes with multiple materials, ignores subdivideWithSubMeshes.
+ * @returns a new mesh
+ */
+ static MergeMeshesAsync(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) {
+ return runCoroutineAsync(Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, true), createYieldingScheduler());
+ }
+ static *_MergeMeshesCoroutine(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, isAsync) {
+ // Remove any null/undefined entries from the mesh array
+ meshes = meshes.filter(Boolean);
+ if (meshes.length === 0) {
+ return null;
+ }
+ let index;
+ if (!allow32BitsIndices) {
+ let totalVertices = 0;
+ // Counting vertices
+ for (index = 0; index < meshes.length; index++) {
+ totalVertices += meshes[index].getTotalVertices();
+ if (totalVertices >= 65536) {
+ Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
+ return null;
+ }
+ }
+ }
+ if (multiMultiMaterials) {
+ subdivideWithSubMeshes = false;
+ }
+ const materialArray = new Array();
+ const materialIndexArray = new Array();
+ // Merge
+ const indiceArray = new Array();
+ const currentsideOrientation = meshes[0].sideOrientation;
+ for (index = 0; index < meshes.length; index++) {
+ const mesh = meshes[index];
+ if (mesh.isAnInstance) {
+ Logger.Warn("Cannot merge instance meshes.");
+ return null;
+ }
+ if (currentsideOrientation !== mesh.sideOrientation) {
+ Logger.Warn("Cannot merge meshes with different sideOrientation values.");
+ return null;
+ }
+ if (subdivideWithSubMeshes) {
+ indiceArray.push(mesh.getTotalIndices());
+ }
+ if (multiMultiMaterials) {
+ if (mesh.material) {
+ const material = mesh.material;
+ if (material instanceof MultiMaterial) {
+ for (let matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
+ if (materialArray.indexOf(material.subMaterials[matIndex]) < 0) {
+ materialArray.push(material.subMaterials[matIndex]);
+ }
+ }
+ for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+ materialIndexArray.push(materialArray.indexOf(material.subMaterials[mesh.subMeshes[subIndex].materialIndex]));
+ indiceArray.push(mesh.subMeshes[subIndex].indexCount);
+ }
+ }
+ else {
+ if (materialArray.indexOf(material) < 0) {
+ materialArray.push(material);
+ }
+ for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+ materialIndexArray.push(materialArray.indexOf(material));
+ indiceArray.push(mesh.subMeshes[subIndex].indexCount);
+ }
+ }
+ }
+ else {
+ for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
+ materialIndexArray.push(0);
+ indiceArray.push(mesh.subMeshes[subIndex].indexCount);
+ }
+ }
+ }
+ }
+ const source = meshes[0];
+ const getVertexDataFromMesh = (mesh) => {
+ const wm = mesh.computeWorldMatrix(true);
+ const vertexData = VertexData.ExtractFromMesh(mesh, false, false);
+ return { vertexData, transform: wm };
+ };
+ const { vertexData: sourceVertexData, transform: sourceTransform } = getVertexDataFromMesh(source);
+ if (isAsync) {
+ yield;
+ }
+ const meshVertexDatas = new Array(meshes.length - 1);
+ for (let i = 1; i < meshes.length; i++) {
+ meshVertexDatas[i - 1] = getVertexDataFromMesh(meshes[i]);
+ if (isAsync) {
+ yield;
+ }
+ }
+ const mergeCoroutine = sourceVertexData._mergeCoroutine(sourceTransform, meshVertexDatas, allow32BitsIndices, isAsync, !disposeSource);
+ let mergeCoroutineStep = mergeCoroutine.next();
+ while (!mergeCoroutineStep.done) {
+ if (isAsync) {
+ yield;
+ }
+ mergeCoroutineStep = mergeCoroutine.next();
+ }
+ const vertexData = mergeCoroutineStep.value;
+ if (!meshSubclass) {
+ meshSubclass = new Mesh(source.name + "_merged", source.getScene());
+ }
+ const applyToCoroutine = vertexData._applyToCoroutine(meshSubclass, undefined, isAsync);
+ let applyToCoroutineStep = applyToCoroutine.next();
+ while (!applyToCoroutineStep.done) {
+ if (isAsync) {
+ yield;
+ }
+ applyToCoroutineStep = applyToCoroutine.next();
+ }
+ // Setting properties
+ meshSubclass.checkCollisions = source.checkCollisions;
+ meshSubclass.sideOrientation = source.sideOrientation;
+ // Cleaning
+ if (disposeSource) {
+ for (index = 0; index < meshes.length; index++) {
+ meshes[index].dispose();
+ }
+ }
+ // Subdivide
+ if (subdivideWithSubMeshes || multiMultiMaterials) {
+ //-- removal of global submesh
+ meshSubclass.releaseSubMeshes();
+ index = 0;
+ let offset = 0;
+ //-- apply subdivision according to index table
+ while (index < indiceArray.length) {
+ SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass, undefined, false);
+ offset += indiceArray[index];
+ index++;
+ }
+ for (const subMesh of meshSubclass.subMeshes) {
+ subMesh.refreshBoundingInfo();
+ }
+ meshSubclass.computeWorldMatrix(true);
+ }
+ if (multiMultiMaterials) {
+ const newMultiMaterial = new MultiMaterial(source.name + "_merged", source.getScene());
+ newMultiMaterial.subMaterials = materialArray;
+ for (let subIndex = 0; subIndex < meshSubclass.subMeshes.length; subIndex++) {
+ meshSubclass.subMeshes[subIndex].materialIndex = materialIndexArray[subIndex];
+ }
+ meshSubclass.material = newMultiMaterial;
+ }
+ else {
+ meshSubclass.material = source.material;
+ }
+ return meshSubclass;
+ }
+ /**
+ * @internal
+ */
+ addInstance(instance) {
+ instance._indexInSourceMeshInstanceArray = this.instances.length;
+ this.instances.push(instance);
+ }
+ /**
+ * @internal
+ */
+ removeInstance(instance) {
+ // Remove from mesh
+ const index = instance._indexInSourceMeshInstanceArray;
+ if (index != -1) {
+ if (index !== this.instances.length - 1) {
+ const last = this.instances[this.instances.length - 1];
+ this.instances[index] = last;
+ last._indexInSourceMeshInstanceArray = index;
+ }
+ instance._indexInSourceMeshInstanceArray = -1;
+ this.instances.pop();
+ }
+ }
+ /** @internal */
+ _shouldConvertRHS() {
+ return this._scene.useRightHandedSystem && this.sideOrientation === Material.CounterClockWiseSideOrientation;
+ }
+ /** @internal */
+ _getRenderingFillMode(fillMode) {
+ const scene = this.getScene();
+ if (scene.forcePointsCloud)
+ return Material.PointFillMode;
+ if (scene.forceWireframe)
+ return Material.WireFrameFillMode;
+ return this.overrideRenderingFillMode ?? fillMode;
+ }
+ // deprecated methods
+ /**
+ * Sets the mesh material by the material or multiMaterial `id` property
+ * @param id is a string identifying the material or the multiMaterial
+ * @returns the current mesh
+ * @deprecated Please use MeshBuilder instead Please use setMaterialById instead
+ */
+ setMaterialByID(id) {
+ return this.setMaterialById(id);
+ }
+ /**
+ * Creates a ribbon mesh.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param
+ * @param name defines the name of the mesh to create
+ * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
+ * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
+ * @param closePath creates a seam between the first and the last points of each path of the path array
+ * @param offset is taken in account only if the `pathArray` is containing a single path
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateRibbon(name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a plane polygonal mesh. By default, this is a disc.
+ * @param name defines the name of the mesh to create
+ * @param radius sets the radius size (float) of the polygon (default 0.5)
+ * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateDisc(name, radius, tessellation, scene, updatable, sideOrientation) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a box mesh.
+ * @param name defines the name of the mesh to create
+ * @param size sets the size (float) of each box side (default 1)
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateBox(name, size, scene, updatable, sideOrientation) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a sphere mesh.
+ * @param name defines the name of the mesh to create
+ * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
+ * @param diameter sets the diameter size (float) of the sphere (default 1)
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateSphere(name, segments, diameter, scene, updatable, sideOrientation) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a hemisphere mesh.
+ * @param name defines the name of the mesh to create
+ * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
+ * @param diameter sets the diameter size (float) of the sphere (default 1)
+ * @param scene defines the hosting scene
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateHemisphere(name, segments, diameter, scene) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a cylinder or a cone mesh.
+ * @param name defines the name of the mesh to create
+ * @param height sets the height size (float) of the cylinder/cone (float, default 2)
+ * @param diameterTop set the top cap diameter (floats, default 1)
+ * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
+ * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
+ * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateCylinder(name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ // Torus (Code from SharpDX.org)
+ /**
+ * Creates a torus mesh.
+ * @param name defines the name of the mesh to create
+ * @param diameter sets the diameter size (float) of the torus (default 1)
+ * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
+ * @param tessellation sets the number of torus sides (positive integer, default 16)
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateTorus(name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a torus knot mesh.
+ * @param name defines the name of the mesh to create
+ * @param radius sets the global radius size (float) of the torus knot (default 2)
+ * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
+ * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
+ * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
+ * @param p the number of windings on X axis (positive integers, default 2)
+ * @param q the number of windings on Y axis (positive integers, default 3)
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateTorusKnot(name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a line mesh..
+ * @param name defines the name of the mesh to create
+ * @param points is an array successive Vector3
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateLines(name, points, scene, updatable, instance) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a dashed line mesh.
+ * @param name defines the name of the mesh to create
+ * @param points is an array successive Vector3
+ * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
+ * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
+ * @param dashNb is the intended total number of dashes (positive integer, default 200)
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateDashedLines(name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
+ * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
+ * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
+ * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
+ * Remember you can only change the shape positions, not their number when updating a polygon.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#non-regular-polygon
+ * @param name defines the name of the mesh to create
+ * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
+ * @param scene defines the hosting scene
+ * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @param earcutInjection can be used to inject your own earcut reference
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreatePolygon(name, shape, scene, holes, updatable, sideOrientation, earcutInjection) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates an extruded polygon mesh, with depth in the Y direction..
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-non-regular-polygon
+ * @param name defines the name of the mesh to create
+ * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
+ * @param depth defines the height of extrusion
+ * @param scene defines the hosting scene
+ * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @param earcutInjection can be used to inject your own earcut reference
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static ExtrudePolygon(name, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates an extruded shape mesh.
+ * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes
+ * @param name defines the name of the mesh to create
+ * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
+ * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
+ * @param scale is the value to scale the shape
+ * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
+ * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static ExtrudeShape(name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates an custom extruded shape mesh.
+ * The custom extrusion is a parametric shape.
+ * It has no predefined shape. Its final shape will depend on the input parameters.
+ *
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes
+ * @param name defines the name of the mesh to create
+ * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
+ * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
+ * @param scaleFunction is a custom Javascript function called on each path point
+ * @param rotationFunction is a custom Javascript function called on each path point
+ * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
+ * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
+ * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static ExtrudeShapeCustom(name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates lathe mesh.
+ * The lathe is a shape with a symmetry axis : a 2D model shape is rotated around this axis to design the lathe.
+ * @param name defines the name of the mesh to create
+ * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
+ * @param radius is the radius value of the lathe
+ * @param tessellation is the side number of the lathe.
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateLathe(name, shape, radius, tessellation, scene, updatable, sideOrientation) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a plane mesh.
+ * @param name defines the name of the mesh to create
+ * @param size sets the size (float) of both sides of the plane at once (default 1)
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreatePlane(name, size, scene, updatable, sideOrientation) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a ground mesh.
+ * @param name defines the name of the mesh to create
+ * @param width set the width of the ground
+ * @param height set the height of the ground
+ * @param subdivisions sets the number of subdivisions per side
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateGround(name, width, height, subdivisions, scene, updatable) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a tiled ground mesh.
+ * @param name defines the name of the mesh to create
+ * @param xmin set the ground minimum X coordinate
+ * @param zmin set the ground minimum Y coordinate
+ * @param xmax set the ground maximum X coordinate
+ * @param zmax set the ground maximum Z coordinate
+ * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
+ * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateTiledGround(name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a ground mesh from a height map.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/height_map
+ * @param name defines the name of the mesh to create
+ * @param url sets the URL of the height map image resource
+ * @param width set the ground width size
+ * @param height set the ground height size
+ * @param subdivisions sets the number of subdivision per side
+ * @param minHeight is the minimum altitude on the ground
+ * @param maxHeight is the maximum altitude on the ground
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
+ * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateGroundFromHeightMap(name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a tube mesh.
+ * The tube is a parametric shape.
+ * It has no predefined shape. Its final shape will depend on the input parameters.
+ *
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param
+ * @param name defines the name of the mesh to create
+ * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
+ * @param radius sets the tube radius size
+ * @param tessellation is the number of sides on the tubular surface
+ * @param radiusFunction is a custom function. If it is not null, it overrides the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
+ * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
+ * @param scene defines the hosting scene
+ * @param updatable defines if the mesh must be flagged as updatable
+ * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation)
+ * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateTube(name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a polyhedron mesh.
+ *.
+ * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embedded types. Please refer to the type sheet in the tutorial to choose the wanted type
+ * * The parameter `size` (positive float, default 1) sets the polygon size
+ * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
+ * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`
+ * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
+ * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)
+ * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace
+ * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored
+ * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation
+ * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
+ * @param name defines the name of the mesh to create
+ * @param options defines the options used to create the mesh
+ * @param scene defines the hosting scene
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreatePolyhedron(name, options, scene) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
+ * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
+ * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`)
+ * * The parameter `subdivisions` sets the number of subdivisions (positive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
+ * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface
+ * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
+ * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation
+ * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra#icosphere
+ * @param name defines the name of the mesh
+ * @param options defines the options used to create the mesh
+ * @param scene defines the hosting scene
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateIcoSphere(name, options, scene) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Creates a decal mesh.
+ *.
+ * A decal is a mesh usually applied as a model onto the surface of another mesh
+ * @param name defines the name of the mesh
+ * @param sourceMesh defines the mesh receiving the decal
+ * @param position sets the position of the decal in world coordinates
+ * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
+ * @param size sets the decal scaling
+ * @param angle sets the angle to rotate the decal
+ * @returns a new Mesh
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateDecal(name, sourceMesh, position, normal, size, angle) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /** Creates a Capsule Mesh
+ * @param name defines the name of the mesh.
+ * @param options the constructors options used to shape the mesh.
+ * @param scene defines the scene the mesh is scoped to.
+ * @returns the capsule mesh
+ * @see https://doc.babylonjs.com/how_to/capsule_shape
+ * @deprecated Please use MeshBuilder instead
+ */
+ static CreateCapsule(name, options, scene) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+ /**
+ * Extends a mesh to a Goldberg mesh
+ * Warning the mesh to convert MUST be an import of a perviously exported Goldberg mesh
+ * @param mesh the mesh to convert
+ * @returns the extended mesh
+ * @deprecated Please use ExtendMeshToGoldberg instead
+ */
+ static ExtendToGoldberg(mesh) {
+ throw new Error("Import MeshBuilder to populate this function");
+ }
+}
+// Consts
+/**
+ * Mesh side orientation : usually the external or front surface
+ */
+Mesh.FRONTSIDE = VertexData.FRONTSIDE;
+/**
+ * Mesh side orientation : usually the internal or back surface
+ */
+Mesh.BACKSIDE = VertexData.BACKSIDE;
+/**
+ * Mesh side orientation : both internal and external or front and back surfaces
+ */
+Mesh.DOUBLESIDE = VertexData.DOUBLESIDE;
+/**
+ * Mesh side orientation : by default, `FRONTSIDE`
+ */
+Mesh.DEFAULTSIDE = VertexData.DEFAULTSIDE;
+/**
+ * Mesh cap setting : no cap
+ */
+Mesh.NO_CAP = 0;
+/**
+ * Mesh cap setting : one cap at the beginning of the mesh
+ */
+Mesh.CAP_START = 1;
+/**
+ * Mesh cap setting : one cap at the end of the mesh
+ */
+Mesh.CAP_END = 2;
+/**
+ * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
+ */
+Mesh.CAP_ALL = 3;
+/**
+ * Mesh pattern setting : no flip or rotate
+ */
+Mesh.NO_FLIP = 0;
+/**
+ * Mesh pattern setting : flip (reflect in y axis) alternate tiles on each row or column
+ */
+Mesh.FLIP_TILE = 1;
+/**
+ * Mesh pattern setting : rotate (180degs) alternate tiles on each row or column
+ */
+Mesh.ROTATE_TILE = 2;
+/**
+ * Mesh pattern setting : flip (reflect in y axis) all tiles on alternate rows
+ */
+Mesh.FLIP_ROW = 3;
+/**
+ * Mesh pattern setting : rotate (180degs) all tiles on alternate rows
+ */
+Mesh.ROTATE_ROW = 4;
+/**
+ * Mesh pattern setting : flip and rotate alternate tiles on each row or column
+ */
+Mesh.FLIP_N_ROTATE_TILE = 5;
+/**
+ * Mesh pattern setting : rotate pattern and rotate
+ */
+Mesh.FLIP_N_ROTATE_ROW = 6;
+/**
+ * Mesh tile positioning : part tiles same on left/right or top/bottom
+ */
+Mesh.CENTER = 0;
+/**
+ * Mesh tile positioning : part tiles on left
+ */
+Mesh.LEFT = 1;
+/**
+ * Mesh tile positioning : part tiles on right
+ */
+Mesh.RIGHT = 2;
+/**
+ * Mesh tile positioning : part tiles on top
+ */
+Mesh.TOP = 3;
+/**
+ * Mesh tile positioning : part tiles on bottom
+ */
+Mesh.BOTTOM = 4;
+/**
+ * Indicates that the instanced meshes should be sorted from back to front before rendering if their material is transparent
+ */
+Mesh.INSTANCEDMESH_SORT_TRANSPARENT = false;
+// Statics
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Mesh._GroundMeshParser = (parsedMesh, scene) => {
+ throw _WarnImport("GroundMesh");
+};
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Mesh._GoldbergMeshParser = (parsedMesh, scene) => {
+ throw _WarnImport("GoldbergMesh");
+};
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Mesh._LinesMeshParser = (parsedMesh, scene) => {
+ throw _WarnImport("LinesMesh");
+};
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Mesh._GreasedLineMeshParser = (parsedMesh, scene) => {
+ throw _WarnImport("GreasedLineMesh");
+};
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Mesh._GreasedLineRibbonMeshParser = (parsedMesh, scene) => {
+ throw _WarnImport("GreasedLineRibbonMesh");
+};
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Mesh._TrailMeshParser = (parsedMesh, scene) => {
+ throw _WarnImport("TrailMesh");
+};
+RegisterClass("BABYLON.Mesh", Mesh);
+
+/**
+ * The autoRotation behavior (AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior
+ */
+class AutoRotationBehavior {
+ constructor() {
+ this._zoomStopsAnimation = false;
+ this._idleRotationSpeed = 0.05;
+ this._idleRotationWaitTime = 2000;
+ this._idleRotationSpinupTime = 2000;
+ /**
+ * Target alpha
+ */
+ this.targetAlpha = null;
+ this._isPointerDown = false;
+ this._lastFrameTime = null;
+ this._lastInteractionTime = -Infinity;
+ this._cameraRotationSpeed = 0;
+ this._lastFrameRadius = 0;
+ }
+ /**
+ * Gets the name of the behavior.
+ */
+ get name() {
+ return "AutoRotation";
+ }
+ /**
+ * Sets the flag that indicates if user zooming should stop animation.
+ */
+ set zoomStopsAnimation(flag) {
+ this._zoomStopsAnimation = flag;
+ }
+ /**
+ * Gets the flag that indicates if user zooming should stop animation.
+ */
+ get zoomStopsAnimation() {
+ return this._zoomStopsAnimation;
+ }
+ /**
+ * Sets the default speed at which the camera rotates around the model.
+ */
+ set idleRotationSpeed(speed) {
+ this._idleRotationSpeed = speed;
+ }
+ /**
+ * Gets the default speed at which the camera rotates around the model.
+ */
+ get idleRotationSpeed() {
+ return this._idleRotationSpeed;
+ }
+ /**
+ * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
+ */
+ set idleRotationWaitTime(time) {
+ this._idleRotationWaitTime = time;
+ }
+ /**
+ * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
+ */
+ get idleRotationWaitTime() {
+ return this._idleRotationWaitTime;
+ }
+ /**
+ * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
+ */
+ set idleRotationSpinupTime(time) {
+ this._idleRotationSpinupTime = time;
+ }
+ /**
+ * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
+ */
+ get idleRotationSpinupTime() {
+ return this._idleRotationSpinupTime;
+ }
+ /**
+ * Gets a value indicating if the camera is currently rotating because of this behavior
+ */
+ get rotationInProgress() {
+ return Math.abs(this._cameraRotationSpeed) > 0;
+ }
+ /**
+ * Initializes the behavior.
+ */
+ init() {
+ // Do nothing
+ }
+ /**
+ * Attaches the behavior to its arc rotate camera.
+ * @param camera Defines the camera to attach the behavior to
+ */
+ attach(camera) {
+ this._attachedCamera = camera;
+ const scene = this._attachedCamera.getScene();
+ this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => {
+ if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) {
+ this._isPointerDown = true;
+ return;
+ }
+ if (pointerInfoPre.type === PointerEventTypes.POINTERUP) {
+ this._isPointerDown = false;
+ }
+ });
+ this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {
+ if (this._reachTargetAlpha()) {
+ return;
+ }
+ const now = PrecisionDate.Now;
+ let dt = 0;
+ if (this._lastFrameTime != null) {
+ dt = now - this._lastFrameTime;
+ }
+ this._lastFrameTime = now;
+ // Stop the animation if there is user interaction and the animation should stop for this interaction
+ this._applyUserInteraction();
+ const timeToRotation = now - this._lastInteractionTime - this._idleRotationWaitTime;
+ const scale = Math.max(Math.min(timeToRotation / this._idleRotationSpinupTime, 1), 0);
+ this._cameraRotationSpeed = this._idleRotationSpeed * scale;
+ // Step camera rotation by rotation speed
+ if (this._attachedCamera) {
+ this._attachedCamera.alpha -= this._cameraRotationSpeed * (dt / 1000);
+ }
+ });
+ }
+ /**
+ * Detaches the behavior from its current arc rotate camera.
+ */
+ detach() {
+ if (!this._attachedCamera) {
+ return;
+ }
+ const scene = this._attachedCamera.getScene();
+ if (this._onPrePointerObservableObserver) {
+ scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
+ }
+ this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
+ this._attachedCamera = null;
+ this._lastFrameTime = null;
+ }
+ /**
+ * Force-reset the last interaction time
+ * @param customTime an optional time that will be used instead of the current last interaction time. For example `Date.now()`
+ */
+ resetLastInteractionTime(customTime) {
+ this._lastInteractionTime = customTime ?? PrecisionDate.Now;
+ }
+ /**
+ * Returns true if camera alpha reaches the target alpha
+ * @returns true if camera alpha reaches the target alpha
+ */
+ _reachTargetAlpha() {
+ if (this._attachedCamera && this.targetAlpha) {
+ return Math.abs(this._attachedCamera.alpha - this.targetAlpha) < Epsilon;
+ }
+ return false;
+ }
+ /**
+ * Returns true if user is scrolling.
+ * @returns true if user is scrolling.
+ */
+ _userIsZooming() {
+ if (!this._attachedCamera) {
+ return false;
+ }
+ return this._attachedCamera.inertialRadiusOffset !== 0;
+ }
+ _shouldAnimationStopForInteraction() {
+ if (!this._attachedCamera) {
+ return false;
+ }
+ let zoomHasHitLimit = false;
+ if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
+ zoomHasHitLimit = true;
+ }
+ // Update the record of previous radius - works as an approx. indicator of hitting radius limits
+ this._lastFrameRadius = this._attachedCamera.radius;
+ return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
+ }
+ /**
+ * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
+ */
+ _applyUserInteraction() {
+ if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
+ this._lastInteractionTime = PrecisionDate.Now;
+ }
+ }
+ // Tools
+ _userIsMoving() {
+ if (!this._attachedCamera) {
+ return false;
+ }
+ return (this._attachedCamera.inertialAlphaOffset !== 0 ||
+ this._attachedCamera.inertialBetaOffset !== 0 ||
+ this._attachedCamera.inertialRadiusOffset !== 0 ||
+ this._attachedCamera.inertialPanningX !== 0 ||
+ this._attachedCamera.inertialPanningY !== 0 ||
+ this._isPointerDown);
+ }
+}
+
+/**
+ * Base class used for every default easing function.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class EasingFunction {
+ constructor() {
+ this._easingMode = EasingFunction.EASINGMODE_EASEIN;
+ }
+ /**
+ * Sets the easing mode of the current function.
+ * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
+ */
+ setEasingMode(easingMode) {
+ const n = Math.min(Math.max(easingMode, 0), 2);
+ this._easingMode = n;
+ }
+ /**
+ * Gets the current easing mode.
+ * @returns the easing mode
+ */
+ getEasingMode() {
+ return this._easingMode;
+ }
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ easeInCore(gradient) {
+ throw new Error("You must implement this method");
+ }
+ /**
+ * Given an input gradient between 0 and 1, this returns the corresponding value
+ * of the easing function.
+ * @param gradient Defines the value between 0 and 1 we want the easing value for
+ * @returns the corresponding value on the curve defined by the easing function
+ */
+ ease(gradient) {
+ switch (this._easingMode) {
+ case EasingFunction.EASINGMODE_EASEIN:
+ return this.easeInCore(gradient);
+ case EasingFunction.EASINGMODE_EASEOUT:
+ return 1 - this.easeInCore(1 - gradient);
+ }
+ if (gradient >= 0.5) {
+ return (1 - this.easeInCore((1 - gradient) * 2)) * 0.5 + 0.5;
+ }
+ return this.easeInCore(gradient * 2) * 0.5;
+ }
+}
+/**
+ * Interpolation follows the mathematical formula associated with the easing function.
+ */
+EasingFunction.EASINGMODE_EASEIN = 0;
+/**
+ * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
+ */
+EasingFunction.EASINGMODE_EASEOUT = 1;
+/**
+ * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
+ */
+EasingFunction.EASINGMODE_EASEINOUT = 2;
+/**
+ * Easing function with a circle shape (see link below).
+ * @see https://easings.net/#easeInCirc
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class CircleEase extends EasingFunction {
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ gradient = Math.max(0, Math.min(1, gradient));
+ return 1.0 - Math.sqrt(1.0 - gradient * gradient);
+ }
+}
+/**
+ * Easing function with a ease back shape (see link below).
+ * @see https://easings.net/#easeInBack
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class BackEase extends EasingFunction {
+ /**
+ * Instantiates a back ease easing
+ * @see https://easings.net/#easeInBack
+ * @param amplitude Defines the amplitude of the function
+ */
+ constructor(
+ /** [1] Defines the amplitude of the function */
+ amplitude = 1) {
+ super();
+ this.amplitude = amplitude;
+ }
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ const num = Math.max(0, this.amplitude);
+ return Math.pow(gradient, 3.0) - gradient * num * Math.sin(3.1415926535897931 * gradient);
+ }
+}
+/**
+ * Easing function with a bouncing shape (see link below).
+ * @see https://easings.net/#easeInBounce
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class BounceEase extends EasingFunction {
+ /**
+ * Instantiates a bounce easing
+ * @see https://easings.net/#easeInBounce
+ * @param bounces Defines the number of bounces
+ * @param bounciness Defines the amplitude of the bounce
+ */
+ constructor(
+ /** [3] Defines the number of bounces */
+ bounces = 3,
+ /** [2] Defines the amplitude of the bounce */
+ bounciness = 2) {
+ super();
+ this.bounces = bounces;
+ this.bounciness = bounciness;
+ }
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ const y = Math.max(0.0, this.bounces);
+ let bounciness = this.bounciness;
+ if (bounciness <= 1.0) {
+ bounciness = 1.001;
+ }
+ const num9 = Math.pow(bounciness, y);
+ const num5 = 1.0 - bounciness;
+ const num4 = (1.0 - num9) / num5 + num9 * 0.5;
+ const num15 = gradient * num4;
+ const num65 = Math.log(-num15 * (1.0 - bounciness) + 1.0) / Math.log(bounciness);
+ const num3 = Math.floor(num65);
+ const num13 = num3 + 1.0;
+ const num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
+ const num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
+ const num7 = (num8 + num12) * 0.5;
+ const num6 = gradient - num7;
+ const num2 = num7 - num8;
+ return (-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2) * (num6 + num2);
+ }
+}
+/**
+ * Easing function with a power of 3 shape (see link below).
+ * @see https://easings.net/#easeInCubic
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class CubicEase extends EasingFunction {
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ return gradient * gradient * gradient;
+ }
+}
+/**
+ * Easing function with an elastic shape (see link below).
+ * @see https://easings.net/#easeInElastic
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class ElasticEase extends EasingFunction {
+ /**
+ * Instantiates an elastic easing function
+ * @see https://easings.net/#easeInElastic
+ * @param oscillations Defines the number of oscillations
+ * @param springiness Defines the amplitude of the oscillations
+ */
+ constructor(
+ /** [3] Defines the number of oscillations*/
+ oscillations = 3,
+ /** [3] Defines the amplitude of the oscillations*/
+ springiness = 3) {
+ super();
+ this.oscillations = oscillations;
+ this.springiness = springiness;
+ }
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ let num2;
+ const num3 = Math.max(0.0, this.oscillations);
+ const num = Math.max(0.0, this.springiness);
+ if (num == 0) {
+ num2 = gradient;
+ }
+ else {
+ num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
+ }
+ return num2 * Math.sin((6.2831853071795862 * num3 + 1.5707963267948966) * gradient);
+ }
+}
+/**
+ * Easing function with an exponential shape (see link below).
+ * @see https://easings.net/#easeInExpo
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class ExponentialEase extends EasingFunction {
+ /**
+ * Instantiates an exponential easing function
+ * @see https://easings.net/#easeInExpo
+ * @param exponent Defines the exponent of the function
+ */
+ constructor(
+ /** [3] Defines the exponent of the function */
+ exponent = 2) {
+ super();
+ this.exponent = exponent;
+ }
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ if (this.exponent <= 0) {
+ return gradient;
+ }
+ return (Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0);
+ }
+}
+/**
+ * Easing function with a power of 2 shape (see link below).
+ * @see https://easings.net/#easeInQuad
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class QuadraticEase extends EasingFunction {
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ return gradient * gradient;
+ }
+}
+/**
+ * Easing function with a power of 4 shape (see link below).
+ * @see https://easings.net/#easeInQuart
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class QuarticEase extends EasingFunction {
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ return gradient * gradient * gradient * gradient;
+ }
+}
+/**
+ * Easing function with a power of 5 shape (see link below).
+ * @see https://easings.net/#easeInQuint
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class QuinticEase extends EasingFunction {
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ return gradient * gradient * gradient * gradient * gradient;
+ }
+}
+/**
+ * Easing function with a sin shape (see link below).
+ * @see https://easings.net/#easeInSine
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class SineEase extends EasingFunction {
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ return 1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient));
+ }
+}
+/**
+ * Easing function with a bezier shape (see link below).
+ * @see http://cubic-bezier.com/#.17,.67,.83,.67
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions
+ */
+class BezierCurveEase extends EasingFunction {
+ /**
+ * Instantiates a bezier function
+ * @see http://cubic-bezier.com/#.17,.67,.83,.67
+ * @param x1 Defines the x component of the start tangent in the bezier curve
+ * @param y1 Defines the y component of the start tangent in the bezier curve
+ * @param x2 Defines the x component of the end tangent in the bezier curve
+ * @param y2 Defines the y component of the end tangent in the bezier curve
+ */
+ constructor(
+ /** [0] Defines the x component of the start tangent in the bezier curve */
+ x1 = 0,
+ /** [0] Defines the y component of the start tangent in the bezier curve */
+ y1 = 0,
+ /** [1] Defines the x component of the end tangent in the bezier curve */
+ x2 = 1,
+ /** [1] Defines the y component of the end tangent in the bezier curve */
+ y2 = 1) {
+ super();
+ this.x1 = x1;
+ this.y1 = y1;
+ this.x2 = x2;
+ this.y2 = y2;
+ }
+ /**
+ * @internal
+ */
+ easeInCore(gradient) {
+ return BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
+ }
+}
+
+/**
+ * Represents the range of an animation
+ */
+class AnimationRange {
+ /**
+ * Initializes the range of an animation
+ * @param name The name of the animation range
+ * @param from The starting frame of the animation
+ * @param to The ending frame of the animation
+ */
+ constructor(
+ /**The name of the animation range**/
+ name,
+ /**The starting frame of the animation */
+ from,
+ /**The ending frame of the animation*/
+ to) {
+ this.name = name;
+ this.from = from;
+ this.to = to;
+ }
+ /**
+ * Makes a copy of the animation range
+ * @returns A copy of the animation range
+ */
+ clone() {
+ return new AnimationRange(this.name, this.from, this.to);
+ }
+}
+
+// Static values to help the garbage collector
+// Quaternion
+const _staticOffsetValueQuaternion = Object.freeze(new Quaternion(0, 0, 0, 0));
+// Vector3
+const _staticOffsetValueVector3 = Object.freeze(Vector3.Zero());
+// Vector2
+const _staticOffsetValueVector2 = Object.freeze(Vector2.Zero());
+// Size
+const _staticOffsetValueSize = Object.freeze(Size.Zero());
+// Color3
+const _staticOffsetValueColor3 = Object.freeze(Color3.Black());
+// Color4
+const _staticOffsetValueColor4 = Object.freeze(new Color4(0, 0, 0, 0));
+const evaluateAnimationState = {
+ key: 0,
+ repeatCount: 0,
+ loopMode: 2 /*Animation.ANIMATIONLOOPMODE_CONSTANT*/,
+};
+/**
+ * Class used to store any kind of animation
+ */
+class Animation {
+ /**
+ * @internal Internal use
+ */
+ static _PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
+ let dataType = undefined;
+ if (!isNaN(parseFloat(from)) && isFinite(from)) {
+ dataType = Animation.ANIMATIONTYPE_FLOAT;
+ }
+ else if (from instanceof Quaternion) {
+ dataType = Animation.ANIMATIONTYPE_QUATERNION;
+ }
+ else if (from instanceof Vector3) {
+ dataType = Animation.ANIMATIONTYPE_VECTOR3;
+ }
+ else if (from instanceof Vector2) {
+ dataType = Animation.ANIMATIONTYPE_VECTOR2;
+ }
+ else if (from instanceof Color3) {
+ dataType = Animation.ANIMATIONTYPE_COLOR3;
+ }
+ else if (from instanceof Color4) {
+ dataType = Animation.ANIMATIONTYPE_COLOR4;
+ }
+ else if (from instanceof Size) {
+ dataType = Animation.ANIMATIONTYPE_SIZE;
+ }
+ if (dataType == undefined) {
+ return null;
+ }
+ const animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
+ const keys = [
+ { frame: 0, value: from },
+ { frame: totalFrame, value: to },
+ ];
+ animation.setKeys(keys);
+ if (easingFunction !== undefined) {
+ animation.setEasingFunction(easingFunction);
+ }
+ return animation;
+ }
+ /**
+ * Sets up an animation
+ * @param property The property to animate
+ * @param animationType The animation type to apply
+ * @param framePerSecond The frames per second of the animation
+ * @param easingFunction The easing function used in the animation
+ * @returns The created animation
+ */
+ static CreateAnimation(property, animationType, framePerSecond, easingFunction) {
+ const animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
+ animation.setEasingFunction(easingFunction);
+ return animation;
+ }
+ /**
+ * Create and start an animation on a node
+ * @param name defines the name of the global animation that will be run on all nodes
+ * @param target defines the target where the animation will take place
+ * @param targetProperty defines property to animate
+ * @param framePerSecond defines the number of frame per second yo use
+ * @param totalFrame defines the number of frames in total
+ * @param from defines the initial value
+ * @param to defines the final value
+ * @param loopMode defines which loop mode you want to use (off by default)
+ * @param easingFunction defines the easing function to use (linear by default)
+ * @param onAnimationEnd defines the callback to call when animation end
+ * @param scene defines the hosting scene
+ * @returns the animatable created for this animation
+ */
+ static CreateAndStartAnimation(name, target, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd, scene) {
+ const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
+ if (!animation) {
+ return null;
+ }
+ if (target.getScene) {
+ scene = target.getScene();
+ }
+ if (!scene) {
+ return null;
+ }
+ return scene.beginDirectAnimation(target, [animation], 0, totalFrame, animation.loopMode !== Animation.ANIMATIONLOOPMODE_CONSTANT, 1.0, onAnimationEnd);
+ }
+ /**
+ * Create and start an animation on a node and its descendants
+ * @param name defines the name of the global animation that will be run on all nodes
+ * @param node defines the root node where the animation will take place
+ * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
+ * @param targetProperty defines property to animate
+ * @param framePerSecond defines the number of frame per second to use
+ * @param totalFrame defines the number of frames in total
+ * @param from defines the initial value
+ * @param to defines the final value
+ * @param loopMode defines which loop mode you want to use (off by default)
+ * @param easingFunction defines the easing function to use (linear by default)
+ * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
+ * @returns the list of animatables created for all nodes
+ * @example https://www.babylonjs-playground.com/#MH0VLI
+ */
+ static CreateAndStartHierarchyAnimation(name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
+ const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
+ if (!animation) {
+ return null;
+ }
+ const scene = node.getScene();
+ return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd);
+ }
+ /**
+ * Creates a new animation, merges it with the existing animations and starts it
+ * @param name Name of the animation
+ * @param node Node which contains the scene that begins the animations
+ * @param targetProperty Specifies which property to animate
+ * @param framePerSecond The frames per second of the animation
+ * @param totalFrame The total number of frames
+ * @param from The frame at the beginning of the animation
+ * @param to The frame at the end of the animation
+ * @param loopMode Specifies the loop mode of the animation
+ * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
+ * @param onAnimationEnd Callback to run once the animation is complete
+ * @returns Nullable animation
+ */
+ static CreateMergeAndStartAnimation(name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
+ const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
+ if (!animation) {
+ return null;
+ }
+ node.animations.push(animation);
+ return node.getScene().beginAnimation(node, 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd);
+ }
+ /** @internal */
+ static MakeAnimationAdditive(sourceAnimation, referenceFrameOrOptions, range, cloneOriginal = false, clonedName) {
+ let options;
+ if (typeof referenceFrameOrOptions === "object") {
+ options = referenceFrameOrOptions;
+ }
+ else {
+ options = {
+ referenceFrame: referenceFrameOrOptions ?? 0,
+ range: range,
+ cloneOriginalAnimation: cloneOriginal,
+ clonedAnimationName: clonedName,
+ };
+ }
+ let animation = sourceAnimation;
+ if (options.cloneOriginalAnimation) {
+ animation = sourceAnimation.clone();
+ animation.name = options.clonedAnimationName || animation.name;
+ }
+ if (!animation._keys.length) {
+ return animation;
+ }
+ const referenceFrame = options.referenceFrame && options.referenceFrame >= 0 ? options.referenceFrame : 0;
+ let startIndex = 0;
+ const firstKey = animation._keys[0];
+ let endIndex = animation._keys.length - 1;
+ const lastKey = animation._keys[endIndex];
+ const valueStore = {
+ referenceValue: firstKey.value,
+ referencePosition: TmpVectors.Vector3[0],
+ referenceQuaternion: TmpVectors.Quaternion[0],
+ referenceScaling: TmpVectors.Vector3[1],
+ keyPosition: TmpVectors.Vector3[2],
+ keyQuaternion: TmpVectors.Quaternion[1],
+ keyScaling: TmpVectors.Vector3[3],
+ };
+ let from = firstKey.frame;
+ let to = lastKey.frame;
+ if (options.range) {
+ const rangeValue = animation.getRange(options.range);
+ if (rangeValue) {
+ from = rangeValue.from;
+ to = rangeValue.to;
+ }
+ }
+ else {
+ from = options.fromFrame ?? from;
+ to = options.toFrame ?? to;
+ }
+ if (from !== firstKey.frame) {
+ startIndex = animation.createKeyForFrame(from);
+ }
+ if (to !== lastKey.frame) {
+ endIndex = animation.createKeyForFrame(to);
+ }
+ // There's only one key, so use it
+ if (animation._keys.length === 1) {
+ const value = animation._getKeyValue(animation._keys[0]);
+ valueStore.referenceValue = value.clone ? value.clone() : value;
+ }
+ // Reference frame is before the first frame, so just use the first frame
+ else if (referenceFrame <= firstKey.frame) {
+ const value = animation._getKeyValue(firstKey.value);
+ valueStore.referenceValue = value.clone ? value.clone() : value;
+ }
+ // Reference frame is after the last frame, so just use the last frame
+ else if (referenceFrame >= lastKey.frame) {
+ const value = animation._getKeyValue(lastKey.value);
+ valueStore.referenceValue = value.clone ? value.clone() : value;
+ }
+ // Interpolate the reference value from the animation
+ else {
+ evaluateAnimationState.key = 0;
+ const value = animation._interpolate(referenceFrame, evaluateAnimationState);
+ valueStore.referenceValue = value.clone ? value.clone() : value;
+ }
+ // Conjugate the quaternion
+ if (animation.dataType === Animation.ANIMATIONTYPE_QUATERNION) {
+ valueStore.referenceValue.normalize().conjugateInPlace();
+ }
+ // Decompose matrix and conjugate the quaternion
+ else if (animation.dataType === Animation.ANIMATIONTYPE_MATRIX) {
+ valueStore.referenceValue.decompose(valueStore.referenceScaling, valueStore.referenceQuaternion, valueStore.referencePosition);
+ valueStore.referenceQuaternion.normalize().conjugateInPlace();
+ }
+ let startFrame = Number.MAX_VALUE;
+ const clippedKeys = options.clipKeys ? [] : null;
+ // Subtract the reference value from all of the key values
+ for (let index = startIndex; index <= endIndex; index++) {
+ let key = animation._keys[index];
+ if (clippedKeys || options.cloneOriginalAnimation) {
+ key = {
+ frame: key.frame,
+ value: key.value.clone ? key.value.clone() : key.value,
+ inTangent: key.inTangent,
+ outTangent: key.outTangent,
+ interpolation: key.interpolation,
+ lockedTangent: key.lockedTangent,
+ };
+ if (clippedKeys) {
+ if (startFrame === Number.MAX_VALUE) {
+ startFrame = key.frame;
+ }
+ key.frame -= startFrame;
+ clippedKeys.push(key);
+ }
+ }
+ // If this key was duplicated to create a frame 0 key, skip it because its value has already been updated
+ if (index && animation.dataType !== Animation.ANIMATIONTYPE_FLOAT && key.value === firstKey.value) {
+ continue;
+ }
+ switch (animation.dataType) {
+ case Animation.ANIMATIONTYPE_MATRIX:
+ key.value.decompose(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition);
+ valueStore.keyPosition.subtractInPlace(valueStore.referencePosition);
+ valueStore.keyScaling.divideInPlace(valueStore.referenceScaling);
+ valueStore.referenceQuaternion.multiplyToRef(valueStore.keyQuaternion, valueStore.keyQuaternion);
+ Matrix.ComposeToRef(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition, key.value);
+ break;
+ case Animation.ANIMATIONTYPE_QUATERNION:
+ valueStore.referenceValue.multiplyToRef(key.value, key.value);
+ break;
+ case Animation.ANIMATIONTYPE_VECTOR2:
+ case Animation.ANIMATIONTYPE_VECTOR3:
+ case Animation.ANIMATIONTYPE_COLOR3:
+ case Animation.ANIMATIONTYPE_COLOR4:
+ key.value.subtractToRef(valueStore.referenceValue, key.value);
+ break;
+ case Animation.ANIMATIONTYPE_SIZE:
+ key.value.width -= valueStore.referenceValue.width;
+ key.value.height -= valueStore.referenceValue.height;
+ break;
+ default:
+ key.value -= valueStore.referenceValue;
+ }
+ }
+ if (clippedKeys) {
+ animation.setKeys(clippedKeys, true);
+ }
+ return animation;
+ }
+ /**
+ * Transition property of an host to the target Value
+ * @param property The property to transition
+ * @param targetValue The target Value of the property
+ * @param host The object where the property to animate belongs
+ * @param scene Scene used to run the animation
+ * @param frameRate Framerate (in frame/s) to use
+ * @param transition The transition type we want to use
+ * @param duration The duration of the animation, in milliseconds
+ * @param onAnimationEnd Callback trigger at the end of the animation
+ * @returns Nullable animation
+ */
+ static TransitionTo(property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd = null) {
+ if (duration <= 0) {
+ host[property] = targetValue;
+ if (onAnimationEnd) {
+ onAnimationEnd();
+ }
+ return null;
+ }
+ const endFrame = frameRate * (duration / 1000);
+ transition.setKeys([
+ {
+ frame: 0,
+ value: host[property].clone ? host[property].clone() : host[property],
+ },
+ {
+ frame: endFrame,
+ value: targetValue,
+ },
+ ]);
+ if (!host.animations) {
+ host.animations = [];
+ }
+ host.animations.push(transition);
+ const animation = scene.beginAnimation(host, 0, endFrame, false);
+ animation.onAnimationEnd = onAnimationEnd;
+ return animation;
+ }
+ /**
+ * Return the array of runtime animations currently using this animation
+ */
+ get runtimeAnimations() {
+ return this._runtimeAnimations;
+ }
+ /**
+ * Specifies if any of the runtime animations are currently running
+ */
+ get hasRunningRuntimeAnimations() {
+ for (const runtimeAnimation of this._runtimeAnimations) {
+ if (!runtimeAnimation.isStopped()) {
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * Initializes the animation
+ * @param name Name of the animation
+ * @param targetProperty Property to animate
+ * @param framePerSecond The frames per second of the animation
+ * @param dataType The data type of the animation
+ * @param loopMode The loop mode of the animation
+ * @param enableBlending Specifies if blending should be enabled
+ */
+ constructor(
+ /**Name of the animation */
+ name,
+ /**Property to animate */
+ targetProperty,
+ /**The frames per second of the animation */
+ framePerSecond,
+ /**The data type of the animation */
+ dataType,
+ /**The loop mode of the animation */
+ loopMode,
+ /**Specifies if blending should be enabled */
+ enableBlending) {
+ this.name = name;
+ this.targetProperty = targetProperty;
+ this.framePerSecond = framePerSecond;
+ this.dataType = dataType;
+ this.loopMode = loopMode;
+ this.enableBlending = enableBlending;
+ /**
+ * Stores the easing function of the animation
+ */
+ this._easingFunction = null;
+ /**
+ * @internal Internal use only
+ */
+ this._runtimeAnimations = new Array();
+ /**
+ * The set of event that will be linked to this animation
+ */
+ this._events = new Array();
+ /**
+ * Stores the blending speed of the animation
+ */
+ this.blendingSpeed = 0.01;
+ /**
+ * Stores the animation ranges for the animation
+ */
+ this._ranges = {};
+ this.targetPropertyPath = targetProperty.split(".");
+ this.dataType = dataType;
+ this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
+ this.uniqueId = Animation._UniqueIdGenerator++;
+ }
+ // Methods
+ /**
+ * Converts the animation to a string
+ * @param fullDetails support for multiple levels of logging within scene loading
+ * @returns String form of the animation
+ */
+ toString(fullDetails) {
+ let ret = "Name: " + this.name + ", property: " + this.targetProperty;
+ ret += ", datatype: " + ["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"][this.dataType];
+ ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
+ ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
+ if (fullDetails) {
+ ret += ", Ranges: {";
+ let first = true;
+ for (const name in this._ranges) {
+ if (first) {
+ ret += ", ";
+ first = false;
+ }
+ ret += name;
+ }
+ ret += "}";
+ }
+ return ret;
+ }
+ /**
+ * Add an event to this animation
+ * @param event Event to add
+ */
+ addEvent(event) {
+ this._events.push(event);
+ this._events.sort((a, b) => a.frame - b.frame);
+ }
+ /**
+ * Remove all events found at the given frame
+ * @param frame The frame to remove events from
+ */
+ removeEvents(frame) {
+ for (let index = 0; index < this._events.length; index++) {
+ if (this._events[index].frame === frame) {
+ this._events.splice(index, 1);
+ index--;
+ }
+ }
+ }
+ /**
+ * Retrieves all the events from the animation
+ * @returns Events from the animation
+ */
+ getEvents() {
+ return this._events;
+ }
+ /**
+ * Creates an animation range
+ * @param name Name of the animation range
+ * @param from Starting frame of the animation range
+ * @param to Ending frame of the animation
+ */
+ createRange(name, from, to) {
+ // check name not already in use; could happen for bones after serialized
+ if (!this._ranges[name]) {
+ this._ranges[name] = new AnimationRange(name, from, to);
+ }
+ }
+ /**
+ * Deletes an animation range by name
+ * @param name Name of the animation range to delete
+ * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
+ */
+ deleteRange(name, deleteFrames = true) {
+ const range = this._ranges[name];
+ if (!range) {
+ return;
+ }
+ if (deleteFrames) {
+ const from = range.from;
+ const to = range.to;
+ // this loop MUST go high to low for multiple splices to work
+ for (let key = this._keys.length - 1; key >= 0; key--) {
+ if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
+ this._keys.splice(key, 1);
+ }
+ }
+ }
+ this._ranges[name] = null; // said much faster than 'delete this._range[name]'
+ }
+ /**
+ * Gets the animation range by name, or null if not defined
+ * @param name Name of the animation range
+ * @returns Nullable animation range
+ */
+ getRange(name) {
+ return this._ranges[name];
+ }
+ /**
+ * Gets the key frames from the animation
+ * @returns The key frames of the animation
+ */
+ getKeys() {
+ return this._keys;
+ }
+ /**
+ * Gets the highest frame of the animation
+ * @returns Highest frame of the animation
+ */
+ getHighestFrame() {
+ let ret = 0;
+ for (let key = 0, nKeys = this._keys.length; key < nKeys; key++) {
+ if (ret < this._keys[key].frame) {
+ ret = this._keys[key].frame;
+ }
+ }
+ return ret;
+ }
+ /**
+ * Gets the easing function of the animation
+ * @returns Easing function of the animation
+ */
+ getEasingFunction() {
+ return this._easingFunction;
+ }
+ /**
+ * Sets the easing function of the animation
+ * @param easingFunction A custom mathematical formula for animation
+ */
+ setEasingFunction(easingFunction) {
+ this._easingFunction = easingFunction;
+ }
+ /**
+ * Interpolates a scalar linearly
+ * @param startValue Start value of the animation curve
+ * @param endValue End value of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns Interpolated scalar value
+ */
+ floatInterpolateFunction(startValue, endValue, gradient) {
+ return Lerp(startValue, endValue, gradient);
+ }
+ /**
+ * Interpolates a scalar cubically
+ * @param startValue Start value of the animation curve
+ * @param outTangent End tangent of the animation
+ * @param endValue End value of the animation curve
+ * @param inTangent Start tangent of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns Interpolated scalar value
+ */
+ floatInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
+ return Hermite(startValue, outTangent, endValue, inTangent, gradient);
+ }
+ /**
+ * Interpolates a quaternion using a spherical linear interpolation
+ * @param startValue Start value of the animation curve
+ * @param endValue End value of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns Interpolated quaternion value
+ */
+ quaternionInterpolateFunction(startValue, endValue, gradient) {
+ return Quaternion.Slerp(startValue, endValue, gradient);
+ }
+ /**
+ * Interpolates a quaternion cubically
+ * @param startValue Start value of the animation curve
+ * @param outTangent End tangent of the animation curve
+ * @param endValue End value of the animation curve
+ * @param inTangent Start tangent of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns Interpolated quaternion value
+ */
+ quaternionInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
+ return Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
+ }
+ /**
+ * Interpolates a Vector3 linearly
+ * @param startValue Start value of the animation curve
+ * @param endValue End value of the animation curve
+ * @param gradient Scalar amount to interpolate (value between 0 and 1)
+ * @returns Interpolated scalar value
+ */
+ vector3InterpolateFunction(startValue, endValue, gradient) {
+ return Vector3.Lerp(startValue, endValue, gradient);
+ }
+ /**
+ * Interpolates a Vector3 cubically
+ * @param startValue Start value of the animation curve
+ * @param outTangent End tangent of the animation
+ * @param endValue End value of the animation curve
+ * @param inTangent Start tangent of the animation curve
+ * @param gradient Scalar amount to interpolate (value between 0 and 1)
+ * @returns InterpolatedVector3 value
+ */
+ vector3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
+ return Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
+ }
+ /**
+ * Interpolates a Vector2 linearly
+ * @param startValue Start value of the animation curve
+ * @param endValue End value of the animation curve
+ * @param gradient Scalar amount to interpolate (value between 0 and 1)
+ * @returns Interpolated Vector2 value
+ */
+ vector2InterpolateFunction(startValue, endValue, gradient) {
+ return Vector2.Lerp(startValue, endValue, gradient);
+ }
+ /**
+ * Interpolates a Vector2 cubically
+ * @param startValue Start value of the animation curve
+ * @param outTangent End tangent of the animation
+ * @param endValue End value of the animation curve
+ * @param inTangent Start tangent of the animation curve
+ * @param gradient Scalar amount to interpolate (value between 0 and 1)
+ * @returns Interpolated Vector2 value
+ */
+ vector2InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
+ return Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
+ }
+ /**
+ * Interpolates a size linearly
+ * @param startValue Start value of the animation curve
+ * @param endValue End value of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns Interpolated Size value
+ */
+ sizeInterpolateFunction(startValue, endValue, gradient) {
+ return Size.Lerp(startValue, endValue, gradient);
+ }
+ /**
+ * Interpolates a Color3 linearly
+ * @param startValue Start value of the animation curve
+ * @param endValue End value of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns Interpolated Color3 value
+ */
+ color3InterpolateFunction(startValue, endValue, gradient) {
+ return Color3.Lerp(startValue, endValue, gradient);
+ }
+ /**
+ * Interpolates a Color3 cubically
+ * @param startValue Start value of the animation curve
+ * @param outTangent End tangent of the animation
+ * @param endValue End value of the animation curve
+ * @param inTangent Start tangent of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns interpolated value
+ */
+ color3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
+ return Color3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
+ }
+ /**
+ * Interpolates a Color4 linearly
+ * @param startValue Start value of the animation curve
+ * @param endValue End value of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns Interpolated Color3 value
+ */
+ color4InterpolateFunction(startValue, endValue, gradient) {
+ return Color4.Lerp(startValue, endValue, gradient);
+ }
+ /**
+ * Interpolates a Color4 cubically
+ * @param startValue Start value of the animation curve
+ * @param outTangent End tangent of the animation
+ * @param endValue End value of the animation curve
+ * @param inTangent Start tangent of the animation curve
+ * @param gradient Scalar amount to interpolate
+ * @returns interpolated value
+ */
+ color4InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
+ return Color4.Hermite(startValue, outTangent, endValue, inTangent, gradient);
+ }
+ /**
+ * @internal Internal use only
+ */
+ _getKeyValue(value) {
+ if (typeof value === "function") {
+ return value();
+ }
+ return value;
+ }
+ /**
+ * Evaluate the animation value at a given frame
+ * @param currentFrame defines the frame where we want to evaluate the animation
+ * @returns the animation value
+ */
+ evaluate(currentFrame) {
+ evaluateAnimationState.key = 0;
+ return this._interpolate(currentFrame, evaluateAnimationState);
+ }
+ /**
+ * @internal Internal use only
+ */
+ _interpolate(currentFrame, state, searchClosestKeyOnly = false) {
+ if (state.loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && state.repeatCount > 0) {
+ return state.highLimitValue.clone ? state.highLimitValue.clone() : state.highLimitValue;
+ }
+ const keys = this._keys;
+ const keysLength = keys.length;
+ let key = state.key;
+ while (key >= 0 && currentFrame < keys[key].frame) {
+ --key;
+ }
+ while (key + 1 <= keysLength - 1 && currentFrame >= keys[key + 1].frame) {
+ ++key;
+ }
+ state.key = key;
+ if (key < 0) {
+ return searchClosestKeyOnly ? undefined : this._getKeyValue(keys[0].value);
+ }
+ else if (key + 1 > keysLength - 1) {
+ return searchClosestKeyOnly ? undefined : this._getKeyValue(keys[keysLength - 1].value);
+ }
+ const startKey = keys[key];
+ const endKey = keys[key + 1];
+ if (searchClosestKeyOnly && (currentFrame === startKey.frame || currentFrame === endKey.frame)) {
+ return undefined;
+ }
+ const startValue = this._getKeyValue(startKey.value);
+ const endValue = this._getKeyValue(endKey.value);
+ if (startKey.interpolation === 1 /* AnimationKeyInterpolation.STEP */) {
+ if (endKey.frame > currentFrame) {
+ return startValue;
+ }
+ else {
+ return endValue;
+ }
+ }
+ const useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
+ const frameDelta = endKey.frame - startKey.frame;
+ // gradient : percent of currentFrame between the frame inf and the frame sup
+ let gradient = (currentFrame - startKey.frame) / frameDelta;
+ // check for easingFunction and correction of gradient
+ const easingFunction = startKey.easingFunction || this.getEasingFunction();
+ // can also be undefined, if not provided
+ if (easingFunction) {
+ gradient = easingFunction.ease(gradient);
+ }
+ switch (this.dataType) {
+ // Float
+ case Animation.ANIMATIONTYPE_FLOAT: {
+ const floatValue = useTangent
+ ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient)
+ : this.floatInterpolateFunction(startValue, endValue, gradient);
+ switch (state.loopMode) {
+ case Animation.ANIMATIONLOOPMODE_CYCLE:
+ case Animation.ANIMATIONLOOPMODE_CONSTANT:
+ case Animation.ANIMATIONLOOPMODE_YOYO:
+ return floatValue;
+ case Animation.ANIMATIONLOOPMODE_RELATIVE:
+ case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:
+ return (state.offsetValue ?? 0) * state.repeatCount + floatValue;
+ }
+ break;
+ }
+ // Quaternion
+ case Animation.ANIMATIONTYPE_QUATERNION: {
+ const quatValue = useTangent
+ ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)
+ : this.quaternionInterpolateFunction(startValue, endValue, gradient);
+ switch (state.loopMode) {
+ case Animation.ANIMATIONLOOPMODE_CYCLE:
+ case Animation.ANIMATIONLOOPMODE_CONSTANT:
+ case Animation.ANIMATIONLOOPMODE_YOYO:
+ return quatValue;
+ case Animation.ANIMATIONLOOPMODE_RELATIVE:
+ case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:
+ return quatValue.addInPlace((state.offsetValue || _staticOffsetValueQuaternion).scale(state.repeatCount));
+ }
+ return quatValue;
+ }
+ // Vector3
+ case Animation.ANIMATIONTYPE_VECTOR3: {
+ const vec3Value = useTangent
+ ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)
+ : this.vector3InterpolateFunction(startValue, endValue, gradient);
+ switch (state.loopMode) {
+ case Animation.ANIMATIONLOOPMODE_CYCLE:
+ case Animation.ANIMATIONLOOPMODE_CONSTANT:
+ case Animation.ANIMATIONLOOPMODE_YOYO:
+ return vec3Value;
+ case Animation.ANIMATIONLOOPMODE_RELATIVE:
+ case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:
+ return vec3Value.add((state.offsetValue || _staticOffsetValueVector3).scale(state.repeatCount));
+ }
+ break;
+ }
+ // Vector2
+ case Animation.ANIMATIONTYPE_VECTOR2: {
+ const vec2Value = useTangent
+ ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)
+ : this.vector2InterpolateFunction(startValue, endValue, gradient);
+ switch (state.loopMode) {
+ case Animation.ANIMATIONLOOPMODE_CYCLE:
+ case Animation.ANIMATIONLOOPMODE_CONSTANT:
+ case Animation.ANIMATIONLOOPMODE_YOYO:
+ return vec2Value;
+ case Animation.ANIMATIONLOOPMODE_RELATIVE:
+ case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:
+ return vec2Value.add((state.offsetValue || _staticOffsetValueVector2).scale(state.repeatCount));
+ }
+ break;
+ }
+ // Size
+ case Animation.ANIMATIONTYPE_SIZE: {
+ switch (state.loopMode) {
+ case Animation.ANIMATIONLOOPMODE_CYCLE:
+ case Animation.ANIMATIONLOOPMODE_CONSTANT:
+ case Animation.ANIMATIONLOOPMODE_YOYO:
+ return this.sizeInterpolateFunction(startValue, endValue, gradient);
+ case Animation.ANIMATIONLOOPMODE_RELATIVE:
+ case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:
+ return this.sizeInterpolateFunction(startValue, endValue, gradient).add((state.offsetValue || _staticOffsetValueSize).scale(state.repeatCount));
+ }
+ break;
+ }
+ // Color3
+ case Animation.ANIMATIONTYPE_COLOR3: {
+ const color3Value = useTangent
+ ? this.color3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)
+ : this.color3InterpolateFunction(startValue, endValue, gradient);
+ switch (state.loopMode) {
+ case Animation.ANIMATIONLOOPMODE_CYCLE:
+ case Animation.ANIMATIONLOOPMODE_CONSTANT:
+ case Animation.ANIMATIONLOOPMODE_YOYO:
+ return color3Value;
+ case Animation.ANIMATIONLOOPMODE_RELATIVE:
+ case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:
+ return color3Value.add((state.offsetValue || _staticOffsetValueColor3).scale(state.repeatCount));
+ }
+ break;
+ }
+ // Color4
+ case Animation.ANIMATIONTYPE_COLOR4: {
+ const color4Value = useTangent
+ ? this.color4InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)
+ : this.color4InterpolateFunction(startValue, endValue, gradient);
+ switch (state.loopMode) {
+ case Animation.ANIMATIONLOOPMODE_CYCLE:
+ case Animation.ANIMATIONLOOPMODE_CONSTANT:
+ case Animation.ANIMATIONLOOPMODE_YOYO:
+ return color4Value;
+ case Animation.ANIMATIONLOOPMODE_RELATIVE:
+ case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:
+ return color4Value.add((state.offsetValue || _staticOffsetValueColor4).scale(state.repeatCount));
+ }
+ break;
+ }
+ // Matrix
+ case Animation.ANIMATIONTYPE_MATRIX: {
+ switch (state.loopMode) {
+ case Animation.ANIMATIONLOOPMODE_CYCLE:
+ case Animation.ANIMATIONLOOPMODE_CONSTANT:
+ case Animation.ANIMATIONLOOPMODE_YOYO: {
+ if (Animation.AllowMatricesInterpolation) {
+ return this.matrixInterpolateFunction(startValue, endValue, gradient, state.workValue);
+ }
+ return startValue;
+ }
+ case Animation.ANIMATIONLOOPMODE_RELATIVE:
+ case Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: {
+ return startValue;
+ }
+ }
+ break;
+ }
+ }
+ return 0;
+ }
+ /**
+ * Defines the function to use to interpolate matrices
+ * @param startValue defines the start matrix
+ * @param endValue defines the end matrix
+ * @param gradient defines the gradient between both matrices
+ * @param result defines an optional target matrix where to store the interpolation
+ * @returns the interpolated matrix
+ */
+ matrixInterpolateFunction(startValue, endValue, gradient, result) {
+ if (Animation.AllowMatrixDecomposeForInterpolation) {
+ if (result) {
+ Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
+ return result;
+ }
+ return Matrix.DecomposeLerp(startValue, endValue, gradient);
+ }
+ if (result) {
+ Matrix.LerpToRef(startValue, endValue, gradient, result);
+ return result;
+ }
+ return Matrix.Lerp(startValue, endValue, gradient);
+ }
+ /**
+ * Makes a copy of the animation
+ * @returns Cloned animation
+ */
+ clone() {
+ const clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
+ clone.enableBlending = this.enableBlending;
+ clone.blendingSpeed = this.blendingSpeed;
+ if (this._keys) {
+ clone.setKeys(this._keys);
+ }
+ if (this._ranges) {
+ clone._ranges = {};
+ for (const name in this._ranges) {
+ const range = this._ranges[name];
+ if (!range) {
+ continue;
+ }
+ clone._ranges[name] = range.clone();
+ }
+ }
+ return clone;
+ }
+ /**
+ * Sets the key frames of the animation
+ * @param values The animation key frames to set
+ * @param dontClone Whether to clone the keys or not (default is false, so the array of keys is cloned)
+ */
+ setKeys(values, dontClone = false) {
+ this._keys = !dontClone ? values.slice(0) : values;
+ }
+ /**
+ * Creates a key for the frame passed as a parameter and adds it to the animation IF a key doesn't already exist for that frame
+ * @param frame Frame number
+ * @returns The key index if the key was added or the index of the pre existing key if the frame passed as parameter already has a corresponding key
+ */
+ createKeyForFrame(frame) {
+ // Find the key corresponding to frame
+ evaluateAnimationState.key = 0;
+ const value = this._interpolate(frame, evaluateAnimationState, true);
+ if (!value) {
+ // A key corresponding to this frame already exists
+ return this._keys[evaluateAnimationState.key].frame === frame ? evaluateAnimationState.key : evaluateAnimationState.key + 1;
+ }
+ // The frame is between two keys, so create a new key
+ const newKey = {
+ frame,
+ value: value.clone ? value.clone() : value,
+ };
+ this._keys.splice(evaluateAnimationState.key + 1, 0, newKey);
+ return evaluateAnimationState.key + 1;
+ }
+ /**
+ * Serializes the animation to an object
+ * @returns Serialized object
+ */
+ serialize() {
+ const serializationObject = {};
+ serializationObject.name = this.name;
+ serializationObject.property = this.targetProperty;
+ serializationObject.framePerSecond = this.framePerSecond;
+ serializationObject.dataType = this.dataType;
+ serializationObject.loopBehavior = this.loopMode;
+ serializationObject.enableBlending = this.enableBlending;
+ serializationObject.blendingSpeed = this.blendingSpeed;
+ const dataType = this.dataType;
+ serializationObject.keys = [];
+ const keys = this.getKeys();
+ for (let index = 0; index < keys.length; index++) {
+ const animationKey = keys[index];
+ const key = {};
+ key.frame = animationKey.frame;
+ switch (dataType) {
+ case Animation.ANIMATIONTYPE_FLOAT:
+ key.values = [animationKey.value];
+ if (animationKey.inTangent !== undefined) {
+ key.values.push(animationKey.inTangent);
+ }
+ if (animationKey.outTangent !== undefined) {
+ if (animationKey.inTangent === undefined) {
+ key.values.push(undefined);
+ }
+ key.values.push(animationKey.outTangent);
+ }
+ if (animationKey.interpolation !== undefined) {
+ if (animationKey.inTangent === undefined) {
+ key.values.push(undefined);
+ }
+ if (animationKey.outTangent === undefined) {
+ key.values.push(undefined);
+ }
+ key.values.push(animationKey.interpolation);
+ }
+ break;
+ case Animation.ANIMATIONTYPE_QUATERNION:
+ case Animation.ANIMATIONTYPE_MATRIX:
+ case Animation.ANIMATIONTYPE_VECTOR3:
+ case Animation.ANIMATIONTYPE_COLOR3:
+ case Animation.ANIMATIONTYPE_COLOR4:
+ key.values = animationKey.value.asArray();
+ if (animationKey.inTangent != undefined) {
+ key.values.push(animationKey.inTangent.asArray());
+ }
+ if (animationKey.outTangent != undefined) {
+ if (animationKey.inTangent === undefined) {
+ key.values.push(undefined);
+ }
+ key.values.push(animationKey.outTangent.asArray());
+ }
+ if (animationKey.interpolation !== undefined) {
+ if (animationKey.inTangent === undefined) {
+ key.values.push(undefined);
+ }
+ if (animationKey.outTangent === undefined) {
+ key.values.push(undefined);
+ }
+ key.values.push(animationKey.interpolation);
+ }
+ break;
+ }
+ serializationObject.keys.push(key);
+ }
+ serializationObject.ranges = [];
+ for (const name in this._ranges) {
+ const source = this._ranges[name];
+ if (!source) {
+ continue;
+ }
+ const range = {};
+ range.name = name;
+ range.from = source.from;
+ range.to = source.to;
+ serializationObject.ranges.push(range);
+ }
+ return serializationObject;
+ }
+ /**
+ * @internal
+ */
+ static _UniversalLerp(left, right, amount) {
+ const constructor = left.constructor;
+ if (constructor.Lerp) {
+ // Lerp supported
+ return constructor.Lerp(left, right, amount);
+ }
+ else if (constructor.Slerp) {
+ // Slerp supported
+ return constructor.Slerp(left, right, amount);
+ }
+ else if (left.toFixed) {
+ // Number
+ return left * (1.0 - amount) + amount * right;
+ }
+ else {
+ // Blending not supported
+ return right;
+ }
+ }
+ /**
+ * Parses an animation object and creates an animation
+ * @param parsedAnimation Parsed animation object
+ * @returns Animation object
+ */
+ static Parse(parsedAnimation) {
+ const animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
+ const dataType = parsedAnimation.dataType;
+ const keys = [];
+ let data;
+ let index;
+ if (parsedAnimation.enableBlending) {
+ animation.enableBlending = parsedAnimation.enableBlending;
+ }
+ if (parsedAnimation.blendingSpeed) {
+ animation.blendingSpeed = parsedAnimation.blendingSpeed;
+ }
+ for (index = 0; index < parsedAnimation.keys.length; index++) {
+ const key = parsedAnimation.keys[index];
+ let inTangent = undefined;
+ let outTangent = undefined;
+ let interpolation = undefined;
+ switch (dataType) {
+ case Animation.ANIMATIONTYPE_FLOAT:
+ data = key.values[0];
+ if (key.values.length >= 2) {
+ inTangent = key.values[1];
+ }
+ if (key.values.length >= 3) {
+ outTangent = key.values[2];
+ }
+ if (key.values.length >= 4) {
+ interpolation = key.values[3];
+ }
+ break;
+ case Animation.ANIMATIONTYPE_QUATERNION:
+ data = Quaternion.FromArray(key.values);
+ if (key.values.length >= 8) {
+ const _inTangent = Quaternion.FromArray(key.values.slice(4, 8));
+ if (!_inTangent.equals(Quaternion.Zero())) {
+ inTangent = _inTangent;
+ }
+ }
+ if (key.values.length >= 12) {
+ const _outTangent = Quaternion.FromArray(key.values.slice(8, 12));
+ if (!_outTangent.equals(Quaternion.Zero())) {
+ outTangent = _outTangent;
+ }
+ }
+ if (key.values.length >= 13) {
+ interpolation = key.values[12];
+ }
+ break;
+ case Animation.ANIMATIONTYPE_MATRIX:
+ data = Matrix.FromArray(key.values);
+ if (key.values.length >= 17) {
+ interpolation = key.values[16];
+ }
+ break;
+ case Animation.ANIMATIONTYPE_COLOR3:
+ data = Color3.FromArray(key.values);
+ if (key.values[3]) {
+ inTangent = Color3.FromArray(key.values[3]);
+ }
+ if (key.values[4]) {
+ outTangent = Color3.FromArray(key.values[4]);
+ }
+ if (key.values[5]) {
+ interpolation = key.values[5];
+ }
+ break;
+ case Animation.ANIMATIONTYPE_COLOR4:
+ data = Color4.FromArray(key.values);
+ if (key.values[4]) {
+ inTangent = Color4.FromArray(key.values[4]);
+ }
+ if (key.values[5]) {
+ outTangent = Color4.FromArray(key.values[5]);
+ }
+ if (key.values[6]) {
+ interpolation = Color4.FromArray(key.values[6]);
+ }
+ break;
+ case Animation.ANIMATIONTYPE_VECTOR3:
+ default:
+ data = Vector3.FromArray(key.values);
+ if (key.values[3]) {
+ inTangent = Vector3.FromArray(key.values[3]);
+ }
+ if (key.values[4]) {
+ outTangent = Vector3.FromArray(key.values[4]);
+ }
+ if (key.values[5]) {
+ interpolation = key.values[5];
+ }
+ break;
+ }
+ const keyData = {};
+ keyData.frame = key.frame;
+ keyData.value = data;
+ if (inTangent != undefined) {
+ keyData.inTangent = inTangent;
+ }
+ if (outTangent != undefined) {
+ keyData.outTangent = outTangent;
+ }
+ if (interpolation != undefined) {
+ keyData.interpolation = interpolation;
+ }
+ keys.push(keyData);
+ }
+ animation.setKeys(keys);
+ if (parsedAnimation.ranges) {
+ for (index = 0; index < parsedAnimation.ranges.length; index++) {
+ data = parsedAnimation.ranges[index];
+ animation.createRange(data.name, data.from, data.to);
+ }
+ }
+ return animation;
+ }
+ /**
+ * Appends the serialized animations from the source animations
+ * @param source Source containing the animations
+ * @param destination Target to store the animations
+ */
+ static AppendSerializedAnimations(source, destination) {
+ SerializationHelper.AppendSerializedAnimations(source, destination);
+ }
+ /**
+ * Creates a new animation or an array of animations from a snippet saved in a remote file
+ * @param name defines the name of the animation to create (can be null or empty to use the one from the json data)
+ * @param url defines the url to load from
+ * @returns a promise that will resolve to the new animation or an array of animations
+ */
+ static ParseFromFileAsync(name, url) {
+ return new Promise((resolve, reject) => {
+ const request = new WebRequest();
+ request.addEventListener("readystatechange", () => {
+ if (request.readyState == 4) {
+ if (request.status == 200) {
+ let serializationObject = JSON.parse(request.responseText);
+ if (serializationObject.animations) {
+ serializationObject = serializationObject.animations;
+ }
+ if (serializationObject.length) {
+ const output = [];
+ for (const serializedAnimation of serializationObject) {
+ output.push(this.Parse(serializedAnimation));
+ }
+ resolve(output);
+ }
+ else {
+ const output = this.Parse(serializationObject);
+ if (name) {
+ output.name = name;
+ }
+ resolve(output);
+ }
+ }
+ else {
+ reject("Unable to load the animation");
+ }
+ }
+ });
+ request.open("GET", url);
+ request.send();
+ });
+ }
+ /**
+ * Creates an animation or an array of animations from a snippet saved by the Inspector
+ * @param snippetId defines the snippet to load
+ * @returns a promise that will resolve to the new animation or a new array of animations
+ */
+ static ParseFromSnippetAsync(snippetId) {
+ return new Promise((resolve, reject) => {
+ const request = new WebRequest();
+ request.addEventListener("readystatechange", () => {
+ if (request.readyState == 4) {
+ if (request.status == 200) {
+ const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);
+ if (snippet.animations) {
+ const serializationObject = JSON.parse(snippet.animations);
+ const outputs = [];
+ for (const serializedAnimation of serializationObject.animations) {
+ const output = this.Parse(serializedAnimation);
+ output.snippetId = snippetId;
+ outputs.push(output);
+ }
+ resolve(outputs);
+ }
+ else {
+ const serializationObject = JSON.parse(snippet.animation);
+ const output = this.Parse(serializationObject);
+ output.snippetId = snippetId;
+ resolve(output);
+ }
+ }
+ else {
+ reject("Unable to load the snippet " + snippetId);
+ }
+ }
+ });
+ request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
+ request.send();
+ });
+ }
+}
+Animation._UniqueIdGenerator = 0;
+/**
+ * Use matrix interpolation instead of using direct key value when animating matrices
+ */
+Animation.AllowMatricesInterpolation = false;
+/**
+ * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
+ */
+Animation.AllowMatrixDecomposeForInterpolation = true;
+/** Define the Url to load snippets */
+Animation.SnippetUrl = `https://snippet.babylonjs.com`;
+// Statics
+/**
+ * Float animation type
+ */
+Animation.ANIMATIONTYPE_FLOAT = 0;
+/**
+ * Vector3 animation type
+ */
+Animation.ANIMATIONTYPE_VECTOR3 = 1;
+/**
+ * Quaternion animation type
+ */
+Animation.ANIMATIONTYPE_QUATERNION = 2;
+/**
+ * Matrix animation type
+ */
+Animation.ANIMATIONTYPE_MATRIX = 3;
+/**
+ * Color3 animation type
+ */
+Animation.ANIMATIONTYPE_COLOR3 = 4;
+/**
+ * Color3 animation type
+ */
+Animation.ANIMATIONTYPE_COLOR4 = 7;
+/**
+ * Vector2 animation type
+ */
+Animation.ANIMATIONTYPE_VECTOR2 = 5;
+/**
+ * Size animation type
+ */
+Animation.ANIMATIONTYPE_SIZE = 6;
+/**
+ * Relative Loop Mode
+ */
+Animation.ANIMATIONLOOPMODE_RELATIVE = 0;
+/**
+ * Cycle Loop Mode
+ */
+Animation.ANIMATIONLOOPMODE_CYCLE = 1;
+/**
+ * Constant Loop Mode
+ */
+Animation.ANIMATIONLOOPMODE_CONSTANT = 2;
+/**
+ * Yoyo Loop Mode
+ */
+Animation.ANIMATIONLOOPMODE_YOYO = 4;
+/**
+ * Relative Loop Mode (add to current value of animated object, unlike ANIMATIONLOOPMODE_RELATIVE)
+ */
+Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT = 5;
+/**
+ * Creates an animation or an array of animations from a snippet saved by the Inspector
+ * @deprecated Please use ParseFromSnippetAsync instead
+ * @param snippetId defines the snippet to load
+ * @returns a promise that will resolve to the new animation or a new array of animations
+ */
+Animation.CreateFromSnippetAsync = Animation.ParseFromSnippetAsync;
+RegisterClass("BABYLON.Animation", Animation);
+Node$2._AnimationRangeFactory = (name, from, to) => new AnimationRange(name, from, to);
+
+/**
+ * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior
+ */
+class BouncingBehavior {
+ constructor() {
+ /**
+ * The duration of the animation, in milliseconds
+ */
+ this.transitionDuration = 450;
+ /**
+ * Length of the distance animated by the transition when lower radius is reached
+ */
+ this.lowerRadiusTransitionRange = 2;
+ /**
+ * Length of the distance animated by the transition when upper radius is reached
+ */
+ this.upperRadiusTransitionRange = -2;
+ this._autoTransitionRange = false;
+ // Animations
+ this._radiusIsAnimating = false;
+ this._radiusBounceTransition = null;
+ this._animatables = new Array();
+ }
+ /**
+ * Gets the name of the behavior.
+ */
+ get name() {
+ return "Bouncing";
+ }
+ /**
+ * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
+ */
+ get autoTransitionRange() {
+ return this._autoTransitionRange;
+ }
+ /**
+ * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
+ * Transition ranges will be set to 5% of the bounding box diagonal in world space
+ */
+ set autoTransitionRange(value) {
+ if (this._autoTransitionRange === value) {
+ return;
+ }
+ this._autoTransitionRange = value;
+ const camera = this._attachedCamera;
+ if (!camera) {
+ return;
+ }
+ if (value) {
+ this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((transformNode) => {
+ if (!transformNode) {
+ return;
+ }
+ transformNode.computeWorldMatrix(true);
+ if (transformNode.getBoundingInfo) {
+ const diagonal = transformNode.getBoundingInfo().diagonalLength;
+ this.lowerRadiusTransitionRange = diagonal * 0.05;
+ this.upperRadiusTransitionRange = diagonal * 0.05;
+ }
+ });
+ }
+ else if (this._onMeshTargetChangedObserver) {
+ camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
+ }
+ }
+ /**
+ * Initializes the behavior.
+ */
+ init() {
+ // Do nothing
+ }
+ /**
+ * Attaches the behavior to its arc rotate camera.
+ * @param camera Defines the camera to attach the behavior to
+ */
+ attach(camera) {
+ this._attachedCamera = camera;
+ this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {
+ if (!this._attachedCamera) {
+ return;
+ }
+ // Add the bounce animation to the lower radius limit
+ if (this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)) {
+ this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange);
+ }
+ // Add the bounce animation to the upper radius limit
+ if (this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)) {
+ this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange);
+ }
+ });
+ }
+ /**
+ * Detaches the behavior from its current arc rotate camera.
+ */
+ detach() {
+ if (!this._attachedCamera) {
+ return;
+ }
+ if (this._onAfterCheckInputsObserver) {
+ this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
+ }
+ if (this._onMeshTargetChangedObserver) {
+ this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
+ }
+ this._attachedCamera = null;
+ }
+ /**
+ * Checks if the camera radius is at the specified limit. Takes into account animation locks.
+ * @param radiusLimit The limit to check against.
+ * @returns Bool to indicate if at limit.
+ */
+ _isRadiusAtLimit(radiusLimit) {
+ if (!this._attachedCamera) {
+ return false;
+ }
+ if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Applies an animation to the radius of the camera, extending by the radiusDelta.
+ * @param radiusDelta The delta by which to animate to. Can be negative.
+ */
+ _applyBoundRadiusAnimation(radiusDelta) {
+ if (!this._attachedCamera) {
+ return;
+ }
+ if (!this._radiusBounceTransition) {
+ BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
+ this._radiusBounceTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
+ }
+ // Prevent zoom until bounce has completed
+ this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
+ this._attachedCamera.wheelPrecision = Infinity;
+ this._attachedCamera.inertialRadiusOffset = 0;
+ // Animate to the radius limit
+ this.stopAllAnimations();
+ this._radiusIsAnimating = true;
+ const animatable = Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, () => this._clearAnimationLocks());
+ if (animatable) {
+ this._animatables.push(animatable);
+ }
+ }
+ /**
+ * Removes all animation locks. Allows new animations to be added to any of the camera properties.
+ */
+ _clearAnimationLocks() {
+ this._radiusIsAnimating = false;
+ if (this._attachedCamera) {
+ this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
+ }
+ }
+ /**
+ * Stops and removes all animations that have been applied to the camera
+ */
+ stopAllAnimations() {
+ if (this._attachedCamera) {
+ this._attachedCamera.animations = [];
+ }
+ while (this._animatables.length) {
+ this._animatables[0].onAnimationEnd = null;
+ this._animatables[0].stop();
+ this._animatables.shift();
+ }
+ }
+}
+/**
+ * The easing function used by animations
+ */
+BouncingBehavior.EasingFunction = new BackEase(0.3);
+/**
+ * The easing mode used by animations
+ */
+BouncingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEOUT;
+
+/**
+ * The framing behavior (FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior
+ */
+class FramingBehavior {
+ constructor() {
+ /**
+ * An event triggered when the animation to zoom on target mesh has ended
+ */
+ this.onTargetFramingAnimationEndObservable = new Observable();
+ this._mode = FramingBehavior.FitFrustumSidesMode;
+ this._radiusScale = 1.0;
+ this._positionScale = 0.5;
+ this._defaultElevation = 0.3;
+ this._elevationReturnTime = 1500;
+ this._elevationReturnWaitTime = 1000;
+ this._zoomStopsAnimation = false;
+ this._framingTime = 1500;
+ /**
+ * Define if the behavior should automatically change the configured
+ * camera limits and sensibilities.
+ */
+ this.autoCorrectCameraLimitsAndSensibility = true;
+ this._isPointerDown = false;
+ this._lastInteractionTime = -Infinity;
+ // Framing control
+ this._animatables = new Array();
+ this._betaIsAnimating = false;
+ }
+ /**
+ * Gets the name of the behavior.
+ */
+ get name() {
+ return "Framing";
+ }
+ /**
+ * Sets the current mode used by the behavior
+ */
+ set mode(mode) {
+ this._mode = mode;
+ }
+ /**
+ * Gets current mode used by the behavior.
+ */
+ get mode() {
+ return this._mode;
+ }
+ /**
+ * Sets the scale applied to the radius (1 by default)
+ */
+ set radiusScale(radius) {
+ this._radiusScale = radius;
+ }
+ /**
+ * Gets the scale applied to the radius
+ */
+ get radiusScale() {
+ return this._radiusScale;
+ }
+ /**
+ * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
+ */
+ set positionScale(scale) {
+ this._positionScale = scale;
+ }
+ /**
+ * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
+ */
+ get positionScale() {
+ return this._positionScale;
+ }
+ /**
+ * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
+ * behaviour is triggered, in radians.
+ */
+ set defaultElevation(elevation) {
+ this._defaultElevation = elevation;
+ }
+ /**
+ * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
+ * behaviour is triggered, in radians.
+ */
+ get defaultElevation() {
+ return this._defaultElevation;
+ }
+ /**
+ * Sets the time (in milliseconds) taken to return to the default beta position.
+ * Negative value indicates camera should not return to default.
+ */
+ set elevationReturnTime(speed) {
+ this._elevationReturnTime = speed;
+ }
+ /**
+ * Gets the time (in milliseconds) taken to return to the default beta position.
+ * Negative value indicates camera should not return to default.
+ */
+ get elevationReturnTime() {
+ return this._elevationReturnTime;
+ }
+ /**
+ * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
+ */
+ set elevationReturnWaitTime(time) {
+ this._elevationReturnWaitTime = time;
+ }
+ /**
+ * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
+ */
+ get elevationReturnWaitTime() {
+ return this._elevationReturnWaitTime;
+ }
+ /**
+ * Sets the flag that indicates if user zooming should stop animation.
+ */
+ set zoomStopsAnimation(flag) {
+ this._zoomStopsAnimation = flag;
+ }
+ /**
+ * Gets the flag that indicates if user zooming should stop animation.
+ */
+ get zoomStopsAnimation() {
+ return this._zoomStopsAnimation;
+ }
+ /**
+ * Sets the transition time when framing the mesh, in milliseconds
+ */
+ set framingTime(time) {
+ this._framingTime = time;
+ }
+ /**
+ * Gets the transition time when framing the mesh, in milliseconds
+ */
+ get framingTime() {
+ return this._framingTime;
+ }
+ /**
+ * Initializes the behavior.
+ */
+ init() {
+ // Do nothing
+ }
+ /**
+ * Attaches the behavior to its arc rotate camera.
+ * @param camera Defines the camera to attach the behavior to
+ */
+ attach(camera) {
+ this._attachedCamera = camera;
+ const scene = this._attachedCamera.getScene();
+ FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
+ this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => {
+ if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) {
+ this._isPointerDown = true;
+ return;
+ }
+ if (pointerInfoPre.type === PointerEventTypes.POINTERUP) {
+ this._isPointerDown = false;
+ }
+ });
+ this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((transformNode) => {
+ if (transformNode && transformNode.getBoundingInfo) {
+ this.zoomOnMesh(transformNode, undefined, () => {
+ this.onTargetFramingAnimationEndObservable.notifyObservers();
+ });
+ }
+ });
+ this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {
+ // Stop the animation if there is user interaction and the animation should stop for this interaction
+ this._applyUserInteraction();
+ // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
+ // back to the default position after a given timeout
+ this._maintainCameraAboveGround();
+ });
+ }
+ /**
+ * Detaches the behavior from its current arc rotate camera.
+ */
+ detach() {
+ if (!this._attachedCamera) {
+ return;
+ }
+ const scene = this._attachedCamera.getScene();
+ if (this._onPrePointerObservableObserver) {
+ scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
+ }
+ if (this._onAfterCheckInputsObserver) {
+ this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
+ }
+ if (this._onMeshTargetChangedObserver) {
+ this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
+ }
+ this._attachedCamera = null;
+ }
+ /**
+ * Targets the given mesh and updates zoom level accordingly.
+ * @param mesh The mesh to target.
+ * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
+ * @param onAnimationEnd Callback triggered at the end of the framing animation
+ */
+ zoomOnMesh(mesh, focusOnOriginXZ = false, onAnimationEnd = null) {
+ mesh.computeWorldMatrix(true);
+ const boundingBox = mesh.getBoundingInfo().boundingBox;
+ this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
+ }
+ /**
+ * Targets the given mesh with its children and updates zoom level accordingly.
+ * @param mesh The mesh to target.
+ * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
+ * @param onAnimationEnd Callback triggered at the end of the framing animation
+ */
+ zoomOnMeshHierarchy(mesh, focusOnOriginXZ = false, onAnimationEnd = null) {
+ mesh.computeWorldMatrix(true);
+ const boundingBox = mesh.getHierarchyBoundingVectors(true);
+ this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
+ }
+ /**
+ * Targets the given meshes with their children and updates zoom level accordingly.
+ * @param meshes The mesh to target.
+ * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
+ * @param onAnimationEnd Callback triggered at the end of the framing animation
+ */
+ zoomOnMeshesHierarchy(meshes, focusOnOriginXZ = false, onAnimationEnd = null) {
+ const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+ for (let i = 0; i < meshes.length; i++) {
+ const boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
+ Vector3.CheckExtends(boundingInfo.min, min, max);
+ Vector3.CheckExtends(boundingInfo.max, min, max);
+ }
+ this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
+ }
+ /**
+ * Targets the bounding box info defined by its extends and updates zoom level accordingly.
+ * @param minimumWorld Determines the smaller position of the bounding box extend
+ * @param maximumWorld Determines the bigger position of the bounding box extend
+ * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
+ * @param onAnimationEnd Callback triggered at the end of the framing animation
+ * @returns true if the zoom was done
+ */
+ zoomOnBoundingInfo(minimumWorld, maximumWorld, focusOnOriginXZ = false, onAnimationEnd = null) {
+ let zoomTarget;
+ if (!this._attachedCamera) {
+ return false;
+ }
+ // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
+ const bottom = minimumWorld.y;
+ const top = maximumWorld.y;
+ const zoomTargetY = bottom + (top - bottom) * this._positionScale;
+ const radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
+ if (!isFinite(zoomTargetY)) {
+ return false; // Abort mission as there is no target
+ }
+ if (focusOnOriginXZ) {
+ zoomTarget = new Vector3(0, zoomTargetY, 0);
+ }
+ else {
+ const centerWorld = minimumWorld.add(radiusWorld);
+ zoomTarget = new Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
+ }
+ if (!this._vectorTransition) {
+ this._vectorTransition = Animation.CreateAnimation("target", Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
+ }
+ this._betaIsAnimating = true;
+ let animatable = Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
+ if (animatable) {
+ this._animatables.push(animatable);
+ }
+ // sets the radius and lower radius bounds
+ // Small delta ensures camera is not always at lower zoom limit.
+ let radius = 0;
+ if (this._mode === FramingBehavior.FitFrustumSidesMode) {
+ const position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
+ if (this.autoCorrectCameraLimitsAndSensibility) {
+ this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
+ }
+ radius = position;
+ }
+ else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
+ radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
+ if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
+ this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
+ }
+ }
+ // Set sensibilities
+ if (this.autoCorrectCameraLimitsAndSensibility) {
+ const extend = maximumWorld.subtract(minimumWorld).length();
+ this._attachedCamera.panningSensibility = 5000 / extend;
+ this._attachedCamera.wheelPrecision = 100 / radius;
+ }
+ // transition to new radius
+ if (!this._radiusTransition) {
+ this._radiusTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
+ }
+ animatable = Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, () => {
+ this.stopAllAnimations();
+ if (onAnimationEnd) {
+ onAnimationEnd();
+ }
+ if (this._attachedCamera && this._attachedCamera.useInputToRestoreState) {
+ this._attachedCamera.storeState();
+ }
+ });
+ if (animatable) {
+ this._animatables.push(animatable);
+ }
+ return true;
+ }
+ /**
+ * Calculates the lowest radius for the camera based on the bounding box of the mesh.
+ * @param minimumWorld
+ * @param maximumWorld
+ * @returns The minimum distance from the primary mesh's center point at which the camera must be kept in order
+ * to fully enclose the mesh in the viewing frustum.
+ */
+ _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld) {
+ const camera = this._attachedCamera;
+ if (!camera) {
+ return 0;
+ }
+ let distance = camera._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld, this._radiusScale);
+ if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
+ // Don't exceed the requested limit
+ distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
+ }
+ // Don't exceed the upper radius limit
+ if (camera.upperRadiusLimit) {
+ distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
+ }
+ return distance;
+ }
+ /**
+ * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
+ * is automatically returned to its default position (expected to be above ground plane).
+ */
+ _maintainCameraAboveGround() {
+ if (this._elevationReturnTime < 0) {
+ return;
+ }
+ const timeSinceInteraction = PrecisionDate.Now - this._lastInteractionTime;
+ const defaultBeta = Math.PI * 0.5 - this._defaultElevation;
+ const limitBeta = Math.PI * 0.5;
+ // Bring the camera back up if below the ground plane
+ if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
+ this._betaIsAnimating = true;
+ //Transition to new position
+ this.stopAllAnimations();
+ if (!this._betaTransition) {
+ this._betaTransition = Animation.CreateAnimation("beta", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
+ }
+ const animatabe = Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, () => {
+ this._clearAnimationLocks();
+ this.stopAllAnimations();
+ });
+ if (animatabe) {
+ this._animatables.push(animatabe);
+ }
+ }
+ }
+ /**
+ * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
+ */
+ _clearAnimationLocks() {
+ this._betaIsAnimating = false;
+ }
+ /**
+ * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
+ */
+ _applyUserInteraction() {
+ if (this.isUserIsMoving) {
+ this._lastInteractionTime = PrecisionDate.Now;
+ this.stopAllAnimations();
+ this._clearAnimationLocks();
+ }
+ }
+ /**
+ * Stops and removes all animations that have been applied to the camera
+ */
+ stopAllAnimations() {
+ if (this._attachedCamera) {
+ this._attachedCamera.animations = [];
+ }
+ while (this._animatables.length) {
+ if (this._animatables[0]) {
+ this._animatables[0].onAnimationEnd = null;
+ this._animatables[0].stop();
+ }
+ this._animatables.shift();
+ }
+ }
+ /**
+ * Gets a value indicating if the user is moving the camera
+ */
+ get isUserIsMoving() {
+ if (!this._attachedCamera) {
+ return false;
+ }
+ return (this._attachedCamera.inertialAlphaOffset !== 0 ||
+ this._attachedCamera.inertialBetaOffset !== 0 ||
+ this._attachedCamera.inertialRadiusOffset !== 0 ||
+ this._attachedCamera.inertialPanningX !== 0 ||
+ this._attachedCamera.inertialPanningY !== 0 ||
+ this._isPointerDown);
+ }
+}
+/**
+ * The easing function used by animations
+ */
+FramingBehavior.EasingFunction = new ExponentialEase();
+/**
+ * The easing mode used by animations
+ */
+FramingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEINOUT;
+// Statics
+/**
+ * The camera can move all the way towards the mesh.
+ */
+FramingBehavior.IgnoreBoundsSizeMode = 0;
+/**
+ * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
+ */
+FramingBehavior.FitFrustumSidesMode = 1;
+
+Node$2.AddNodeConstructor("TargetCamera", (name, scene) => {
+ return () => new TargetCamera(name, Vector3.Zero(), scene);
+});
+/**
+ * A target camera takes a mesh or position as a target and continues to look at it while it moves.
+ * This is the base of the follow, arc rotate cameras and Free camera
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras
+ */
+class TargetCamera extends Camera {
+ /**
+ * Instantiates a target camera that takes a mesh or position as a target and continues to look at it while it moves.
+ * This is the base of the follow, arc rotate cameras and Free camera
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras
+ * @param name Defines the name of the camera in the scene
+ * @param position Defines the start position of the camera in the scene
+ * @param scene Defines the scene the camera belongs to
+ * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined
+ */
+ constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {
+ super(name, position, scene, setActiveOnSceneIfNoneActive);
+ this._tmpUpVector = Vector3.Zero();
+ this._tmpTargetVector = Vector3.Zero();
+ /**
+ * Define the current direction the camera is moving to
+ */
+ this.cameraDirection = new Vector3(0, 0, 0);
+ /**
+ * Define the current rotation the camera is rotating to
+ */
+ this.cameraRotation = new Vector2(0, 0);
+ /** Gets or sets a boolean indicating that the scaling of the parent hierarchy will not be taken in account by the camera */
+ this.ignoreParentScaling = false;
+ /**
+ * When set, the up vector of the camera will be updated by the rotation of the camera
+ */
+ this.updateUpVectorFromRotation = false;
+ this._tmpQuaternion = new Quaternion();
+ /**
+ * Define the current rotation of the camera
+ */
+ this.rotation = new Vector3(0, 0, 0);
+ /**
+ * Define the current speed of the camera
+ */
+ this.speed = 2.0;
+ /**
+ * Add constraint to the camera to prevent it to move freely in all directions and
+ * around all axis.
+ */
+ this.noRotationConstraint = false;
+ /**
+ * Reverses mouselook direction to 'natural' panning as opposed to traditional direct
+ * panning
+ */
+ this.invertRotation = false;
+ /**
+ * Speed multiplier for inverse camera panning
+ */
+ this.inverseRotationSpeed = 0.2;
+ /**
+ * Define the current target of the camera as an object or a position.
+ * Please note that locking a target will disable panning.
+ */
+ this.lockedTarget = null;
+ /** @internal */
+ this._currentTarget = Vector3.Zero();
+ /** @internal */
+ this._initialFocalDistance = 1;
+ /** @internal */
+ this._viewMatrix = Matrix.Zero();
+ /** @internal */
+ this._camMatrix = Matrix.Zero();
+ /** @internal */
+ this._cameraTransformMatrix = Matrix.Zero();
+ /** @internal */
+ this._cameraRotationMatrix = Matrix.Zero();
+ /** @internal */
+ this._referencePoint = new Vector3(0, 0, 1);
+ /** @internal */
+ this._transformedReferencePoint = Vector3.Zero();
+ this._deferredPositionUpdate = new Vector3();
+ this._deferredRotationQuaternionUpdate = new Quaternion();
+ this._deferredRotationUpdate = new Vector3();
+ this._deferredUpdated = false;
+ this._deferOnly = false;
+ this._defaultUp = Vector3.Up();
+ this._cachedRotationZ = 0;
+ this._cachedQuaternionRotationZ = 0;
+ }
+ /**
+ * Gets the position in front of the camera at a given distance.
+ * @param distance The distance from the camera we want the position to be
+ * @returns the position
+ */
+ getFrontPosition(distance) {
+ this.getWorldMatrix();
+ const worldForward = TmpVectors.Vector3[0];
+ const localForward = TmpVectors.Vector3[1];
+ localForward.set(0, 0, this._scene.useRightHandedSystem ? -1 : 1.0);
+ this.getDirectionToRef(localForward, worldForward);
+ worldForward.scaleInPlace(distance);
+ return this.globalPosition.add(worldForward);
+ }
+ /** @internal */
+ _getLockedTargetPosition() {
+ if (!this.lockedTarget) {
+ return null;
+ }
+ if (this.lockedTarget.absolutePosition) {
+ const lockedTarget = this.lockedTarget;
+ const m = lockedTarget.computeWorldMatrix();
+ // in some cases the absolute position resets externally, but doesn't update since the matrix is cached.
+ m.getTranslationToRef(lockedTarget.absolutePosition);
+ }
+ return this.lockedTarget.absolutePosition || this.lockedTarget;
+ }
+ /**
+ * Store current camera state of the camera (fov, position, rotation, etc..)
+ * @returns the camera
+ */
+ storeState() {
+ this._storedPosition = this.position.clone();
+ this._storedRotation = this.rotation.clone();
+ if (this.rotationQuaternion) {
+ this._storedRotationQuaternion = this.rotationQuaternion.clone();
+ }
+ return super.storeState();
+ }
+ /**
+ * Restored camera state. You must call storeState() first
+ * @returns whether it was successful or not
+ * @internal
+ */
+ _restoreStateValues() {
+ if (!super._restoreStateValues()) {
+ return false;
+ }
+ this.position = this._storedPosition.clone();
+ this.rotation = this._storedRotation.clone();
+ if (this.rotationQuaternion) {
+ this.rotationQuaternion = this._storedRotationQuaternion.clone();
+ }
+ this.cameraDirection.copyFromFloats(0, 0, 0);
+ this.cameraRotation.copyFromFloats(0, 0);
+ return true;
+ }
+ /** @internal */
+ _initCache() {
+ super._initCache();
+ this._cache.lockedTarget = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._cache.rotation = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._cache.rotationQuaternion = new Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ }
+ /**
+ * @internal
+ */
+ _updateCache(ignoreParentClass) {
+ if (!ignoreParentClass) {
+ super._updateCache();
+ }
+ const lockedTargetPosition = this._getLockedTargetPosition();
+ if (!lockedTargetPosition) {
+ this._cache.lockedTarget = null;
+ }
+ else {
+ if (!this._cache.lockedTarget) {
+ this._cache.lockedTarget = lockedTargetPosition.clone();
+ }
+ else {
+ this._cache.lockedTarget.copyFrom(lockedTargetPosition);
+ }
+ }
+ this._cache.rotation.copyFrom(this.rotation);
+ if (this.rotationQuaternion) {
+ this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
+ }
+ }
+ // Synchronized
+ /** @internal */
+ _isSynchronizedViewMatrix() {
+ if (!super._isSynchronizedViewMatrix()) {
+ return false;
+ }
+ const lockedTargetPosition = this._getLockedTargetPosition();
+ return ((this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) &&
+ (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation)));
+ }
+ // Methods
+ /** @internal */
+ _computeLocalCameraSpeed() {
+ const engine = this.getEngine();
+ return this.speed * Math.sqrt(engine.getDeltaTime() / (engine.getFps() * 100.0));
+ }
+ // Target
+ /**
+ * Defines the target the camera should look at.
+ * @param target Defines the new target as a Vector
+ */
+ setTarget(target) {
+ this.upVector.normalize();
+ this._initialFocalDistance = target.subtract(this.position).length();
+ if (this.position.z === target.z) {
+ this.position.z += Epsilon;
+ }
+ this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance);
+ Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
+ this._camMatrix.invert();
+ this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
+ const vDir = target.subtract(this.position);
+ if (vDir.x >= 0.0) {
+ this.rotation.y = -Math.atan(vDir.z / vDir.x) + Math.PI / 2.0;
+ }
+ else {
+ this.rotation.y = -Math.atan(vDir.z / vDir.x) - Math.PI / 2.0;
+ }
+ this.rotation.z = 0;
+ if (isNaN(this.rotation.x)) {
+ this.rotation.x = 0;
+ }
+ if (isNaN(this.rotation.y)) {
+ this.rotation.y = 0;
+ }
+ if (isNaN(this.rotation.z)) {
+ this.rotation.z = 0;
+ }
+ if (this.rotationQuaternion) {
+ Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
+ }
+ }
+ /**
+ * Defines the target point of the camera.
+ * The camera looks towards it form the radius distance.
+ */
+ get target() {
+ return this.getTarget();
+ }
+ set target(value) {
+ this.setTarget(value);
+ }
+ /**
+ * Return the current target position of the camera. This value is expressed in local space.
+ * @returns the target position
+ */
+ getTarget() {
+ return this._currentTarget;
+ }
+ /** @internal */
+ _decideIfNeedsToMove() {
+ return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
+ }
+ /** @internal */
+ _updatePosition() {
+ if (this.parent) {
+ this.parent.getWorldMatrix().invertToRef(TmpVectors.Matrix[0]);
+ Vector3.TransformNormalToRef(this.cameraDirection, TmpVectors.Matrix[0], TmpVectors.Vector3[0]);
+ this._deferredPositionUpdate.addInPlace(TmpVectors.Vector3[0]);
+ if (!this._deferOnly) {
+ this.position.copyFrom(this._deferredPositionUpdate);
+ }
+ else {
+ this._deferredUpdated = true;
+ }
+ return;
+ }
+ this._deferredPositionUpdate.addInPlace(this.cameraDirection);
+ if (!this._deferOnly) {
+ this.position.copyFrom(this._deferredPositionUpdate);
+ }
+ else {
+ this._deferredUpdated = true;
+ }
+ }
+ /** @internal */
+ _checkInputs() {
+ const directionMultiplier = this.invertRotation ? -this.inverseRotationSpeed : 1.0;
+ const needToMove = this._decideIfNeedsToMove();
+ const needToRotate = this.cameraRotation.x || this.cameraRotation.y;
+ this._deferredUpdated = false;
+ this._deferredRotationUpdate.copyFrom(this.rotation);
+ this._deferredPositionUpdate.copyFrom(this.position);
+ if (this.rotationQuaternion) {
+ this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion);
+ }
+ // Move
+ if (needToMove) {
+ this._updatePosition();
+ }
+ // Rotate
+ if (needToRotate) {
+ //rotate, if quaternion is set and rotation was used
+ if (this.rotationQuaternion) {
+ this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate);
+ }
+ this._deferredRotationUpdate.x += this.cameraRotation.x * directionMultiplier;
+ this._deferredRotationUpdate.y += this.cameraRotation.y * directionMultiplier;
+ // Apply constraints
+ if (!this.noRotationConstraint) {
+ const limit = 1.570796;
+ if (this._deferredRotationUpdate.x > limit) {
+ this._deferredRotationUpdate.x = limit;
+ }
+ if (this._deferredRotationUpdate.x < -limit) {
+ this._deferredRotationUpdate.x = -limit;
+ }
+ }
+ if (!this._deferOnly) {
+ this.rotation.copyFrom(this._deferredRotationUpdate);
+ }
+ else {
+ this._deferredUpdated = true;
+ }
+ //rotate, if quaternion is set and rotation was used
+ if (this.rotationQuaternion) {
+ const len = this._deferredRotationUpdate.lengthSquared();
+ if (len) {
+ Quaternion.RotationYawPitchRollToRef(this._deferredRotationUpdate.y, this._deferredRotationUpdate.x, this._deferredRotationUpdate.z, this._deferredRotationQuaternionUpdate);
+ if (!this._deferOnly) {
+ this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate);
+ }
+ else {
+ this._deferredUpdated = true;
+ }
+ }
+ }
+ }
+ // Inertia
+ if (needToMove) {
+ if (Math.abs(this.cameraDirection.x) < this.speed * Epsilon) {
+ this.cameraDirection.x = 0;
+ }
+ if (Math.abs(this.cameraDirection.y) < this.speed * Epsilon) {
+ this.cameraDirection.y = 0;
+ }
+ if (Math.abs(this.cameraDirection.z) < this.speed * Epsilon) {
+ this.cameraDirection.z = 0;
+ }
+ this.cameraDirection.scaleInPlace(this.inertia);
+ }
+ if (needToRotate) {
+ if (Math.abs(this.cameraRotation.x) < this.speed * Epsilon) {
+ this.cameraRotation.x = 0;
+ }
+ if (Math.abs(this.cameraRotation.y) < this.speed * Epsilon) {
+ this.cameraRotation.y = 0;
+ }
+ this.cameraRotation.scaleInPlace(this.inertia);
+ }
+ super._checkInputs();
+ }
+ _updateCameraRotationMatrix() {
+ if (this.rotationQuaternion) {
+ this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
+ }
+ else {
+ Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
+ }
+ }
+ /**
+ * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
+ * @returns the current camera
+ */
+ _rotateUpVectorWithCameraRotationMatrix() {
+ Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
+ return this;
+ }
+ /** @internal */
+ _getViewMatrix() {
+ if (this.lockedTarget) {
+ this.setTarget(this._getLockedTargetPosition());
+ }
+ // Compute
+ this._updateCameraRotationMatrix();
+ // Apply the changed rotation to the upVector
+ if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
+ this._rotateUpVectorWithCameraRotationMatrix();
+ this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
+ }
+ else if (this._cachedRotationZ !== this.rotation.z) {
+ this._rotateUpVectorWithCameraRotationMatrix();
+ this._cachedRotationZ = this.rotation.z;
+ }
+ Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
+ // Computing target and final matrix
+ this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
+ if (this.updateUpVectorFromRotation) {
+ if (this.rotationQuaternion) {
+ Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector);
+ }
+ else {
+ Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion);
+ Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
+ }
+ }
+ this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
+ return this._viewMatrix;
+ }
+ _computeViewMatrix(position, target, up) {
+ if (this.ignoreParentScaling) {
+ if (this.parent) {
+ const parentWorldMatrix = this.parent.getWorldMatrix();
+ Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
+ Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._tmpTargetVector);
+ Vector3.TransformNormalToRef(up, parentWorldMatrix, this._tmpUpVector);
+ this._markSyncedWithParent();
+ }
+ else {
+ this._globalPosition.copyFrom(position);
+ this._tmpTargetVector.copyFrom(target);
+ this._tmpUpVector.copyFrom(up);
+ }
+ if (this.getScene().useRightHandedSystem) {
+ Matrix.LookAtRHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);
+ }
+ else {
+ Matrix.LookAtLHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);
+ }
+ return;
+ }
+ if (this.getScene().useRightHandedSystem) {
+ Matrix.LookAtRHToRef(position, target, up, this._viewMatrix);
+ }
+ else {
+ Matrix.LookAtLHToRef(position, target, up, this._viewMatrix);
+ }
+ if (this.parent) {
+ const parentWorldMatrix = this.parent.getWorldMatrix();
+ this._viewMatrix.invert();
+ this._viewMatrix.multiplyToRef(parentWorldMatrix, this._viewMatrix);
+ this._viewMatrix.getTranslationToRef(this._globalPosition);
+ this._viewMatrix.invert();
+ this._markSyncedWithParent();
+ }
+ else {
+ this._globalPosition.copyFrom(position);
+ }
+ }
+ /**
+ * @internal
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ createRigCamera(name, cameraIndex) {
+ if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
+ const rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
+ rigCamera.isRigCamera = true;
+ rigCamera.rigParent = this;
+ if (this.cameraRigMode === Camera.RIG_MODE_VR) {
+ if (!this.rotationQuaternion) {
+ this.rotationQuaternion = new Quaternion();
+ }
+ rigCamera._cameraRigParams = {};
+ rigCamera.rotationQuaternion = new Quaternion();
+ }
+ rigCamera.mode = this.mode;
+ rigCamera.orthoLeft = this.orthoLeft;
+ rigCamera.orthoRight = this.orthoRight;
+ rigCamera.orthoTop = this.orthoTop;
+ rigCamera.orthoBottom = this.orthoBottom;
+ return rigCamera;
+ }
+ return null;
+ }
+ /**
+ * @internal
+ */
+ _updateRigCameras() {
+ const camLeft = this._rigCameras[0];
+ const camRight = this._rigCameras[1];
+ this.computeWorldMatrix();
+ switch (this.cameraRigMode) {
+ case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
+ case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
+ case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
+ case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
+ case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: {
+ //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
+ const leftSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1;
+ const rightSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1;
+ this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft);
+ this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight);
+ break;
+ }
+ case Camera.RIG_MODE_VR:
+ if (camLeft.rotationQuaternion) {
+ camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
+ camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
+ }
+ else {
+ camLeft.rotation.copyFrom(this.rotation);
+ camRight.rotation.copyFrom(this.rotation);
+ }
+ camLeft.position.copyFrom(this.position);
+ camRight.position.copyFrom(this.position);
+ break;
+ }
+ super._updateRigCameras();
+ }
+ _getRigCamPositionAndTarget(halfSpace, rigCamera) {
+ const target = this.getTarget();
+ target.subtractToRef(this.position, TargetCamera._TargetFocalPoint);
+ TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);
+ const newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position);
+ Matrix.TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix);
+ TargetCamera._TargetTransformMatrix.multiplyToRef(Matrix.RotationAxis(rigCamera.upVector, halfSpace), TargetCamera._RigCamTransformMatrix);
+ Matrix.TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix);
+ TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix);
+ Vector3.TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position);
+ rigCamera.setTarget(newFocalTarget);
+ }
+ /**
+ * Gets the current object class name.
+ * @returns the class name
+ */
+ getClassName() {
+ return "TargetCamera";
+ }
+}
+TargetCamera._RigCamTransformMatrix = new Matrix();
+TargetCamera._TargetTransformMatrix = new Matrix();
+TargetCamera._TargetFocalPoint = new Vector3();
+__decorate([
+ serialize()
+], TargetCamera.prototype, "ignoreParentScaling", void 0);
+__decorate([
+ serialize()
+], TargetCamera.prototype, "updateUpVectorFromRotation", void 0);
+__decorate([
+ serializeAsVector3()
+], TargetCamera.prototype, "rotation", void 0);
+__decorate([
+ serialize()
+], TargetCamera.prototype, "speed", void 0);
+__decorate([
+ serializeAsMeshReference("lockedTargetId")
+], TargetCamera.prototype, "lockedTarget", void 0);
+
+/**
+ * @ignore
+ * This is a list of all the different input types that are available in the application.
+ * Fo instance: ArcRotateCameraGamepadInput...
+ */
+// eslint-disable-next-line no-var, @typescript-eslint/naming-convention
+var CameraInputTypes = {};
+/**
+ * This represents the input manager used within a camera.
+ * It helps dealing with all the different kind of input attached to a camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class CameraInputsManager {
+ /**
+ * Instantiate a new Camera Input Manager.
+ * @param camera Defines the camera the input manager belongs to
+ */
+ constructor(camera) {
+ /**
+ * Defines the dom element the camera is collecting inputs from.
+ * This is null if the controls have not been attached.
+ */
+ this.attachedToElement = false;
+ this.attached = {};
+ this.camera = camera;
+ this.checkInputs = () => { };
+ }
+ /**
+ * Add an input method to a camera
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ * @param input Camera input method
+ */
+ add(input) {
+ const type = input.getSimpleName();
+ if (this.attached[type]) {
+ Logger.Warn("camera input of type " + type + " already exists on camera");
+ return;
+ }
+ this.attached[type] = input;
+ input.camera = this.camera;
+ // for checkInputs, we are dynamically creating a function
+ // the goal is to avoid the performance penalty of looping for inputs in the render loop
+ if (input.checkInputs) {
+ this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
+ }
+ if (this.attachedToElement) {
+ input.attachControl(this.noPreventDefault);
+ }
+ }
+ /**
+ * Remove a specific input method from a camera
+ * example: camera.inputs.remove(camera.inputs.attached.mouse);
+ * @param inputToRemove camera input method
+ */
+ remove(inputToRemove) {
+ for (const cam in this.attached) {
+ const input = this.attached[cam];
+ if (input === inputToRemove) {
+ input.detachControl();
+ input.camera = null;
+ delete this.attached[cam];
+ this.rebuildInputCheck();
+ return;
+ }
+ }
+ }
+ /**
+ * Remove a specific input type from a camera
+ * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
+ * @param inputType the type of the input to remove
+ */
+ removeByType(inputType) {
+ for (const cam in this.attached) {
+ const input = this.attached[cam];
+ if (input.getClassName() === inputType) {
+ input.detachControl();
+ input.camera = null;
+ delete this.attached[cam];
+ this.rebuildInputCheck();
+ }
+ }
+ }
+ _addCheckInputs(fn) {
+ const current = this.checkInputs;
+ return () => {
+ current();
+ fn();
+ };
+ }
+ /**
+ * Attach the input controls to the currently attached dom element to listen the events from.
+ * @param input Defines the input to attach
+ */
+ attachInput(input) {
+ if (this.attachedToElement) {
+ input.attachControl(this.noPreventDefault);
+ }
+ }
+ /**
+ * Attach the current manager inputs controls to a specific dom element to listen the events from.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachElement(noPreventDefault = false) {
+ if (this.attachedToElement) {
+ return;
+ }
+ noPreventDefault = Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
+ this.attachedToElement = true;
+ this.noPreventDefault = noPreventDefault;
+ for (const cam in this.attached) {
+ this.attached[cam].attachControl(noPreventDefault);
+ }
+ }
+ /**
+ * Detach the current manager inputs controls from a specific dom element.
+ * @param disconnect Defines whether the input should be removed from the current list of attached inputs
+ */
+ detachElement(disconnect = false) {
+ for (const cam in this.attached) {
+ this.attached[cam].detachControl();
+ if (disconnect) {
+ this.attached[cam].camera = null;
+ }
+ }
+ this.attachedToElement = false;
+ }
+ /**
+ * Rebuild the dynamic inputCheck function from the current list of
+ * defined inputs in the manager.
+ */
+ rebuildInputCheck() {
+ this.checkInputs = () => { };
+ for (const cam in this.attached) {
+ const input = this.attached[cam];
+ if (input.checkInputs) {
+ this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
+ }
+ }
+ }
+ /**
+ * Remove all attached input methods from a camera
+ */
+ clear() {
+ if (this.attachedToElement) {
+ this.detachElement(true);
+ }
+ this.attached = {};
+ this.attachedToElement = false;
+ this.checkInputs = () => { };
+ }
+ /**
+ * Serialize the current input manager attached to a camera.
+ * This ensures than once parsed,
+ * the input associated to the camera will be identical to the current ones
+ * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
+ */
+ serialize(serializedCamera) {
+ const inputs = {};
+ for (const cam in this.attached) {
+ const input = this.attached[cam];
+ const res = SerializationHelper.Serialize(input);
+ inputs[input.getClassName()] = res;
+ }
+ serializedCamera.inputsmgr = inputs;
+ }
+ /**
+ * Parses an input manager serialized JSON to restore the previous list of inputs
+ * and states associated to a camera.
+ * @param parsedCamera Defines the JSON to parse
+ */
+ parse(parsedCamera) {
+ const parsedInputs = parsedCamera.inputsmgr;
+ if (parsedInputs) {
+ this.clear();
+ for (const n in parsedInputs) {
+ const construct = CameraInputTypes[n];
+ if (construct) {
+ const parsedinput = parsedInputs[n];
+ const input = SerializationHelper.Parse(() => {
+ return new construct();
+ }, parsedinput, null);
+ this.add(input);
+ }
+ }
+ }
+ else {
+ //2016-03-08 this part is for managing backward compatibility
+ for (const n in this.attached) {
+ const construct = CameraInputTypes[this.attached[n].getClassName()];
+ if (construct) {
+ const input = SerializationHelper.Parse(() => {
+ return new construct();
+ }, parsedCamera, null);
+ this.remove(this.attached[n]);
+ this.add(input);
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Base class for Camera Pointer Inputs.
+ * See FollowCameraPointersInput in src/Cameras/Inputs/followCameraPointersInput.ts
+ * for example usage.
+ */
+class BaseCameraPointersInput {
+ constructor() {
+ /**
+ * Which pointer ID is currently down (only for mouse events, not used for touch events)
+ */
+ this._currentMousePointerIdDown = -1;
+ /**
+ * Defines the buttons associated with the input to handle camera move.
+ */
+ this.buttons = [0, 1, 2];
+ }
+ /**
+ * Attach the input controls to a specific dom element to get the input from.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(noPreventDefault) {
+ // eslint-disable-next-line prefer-rest-params
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
+ const engine = this.camera.getEngine();
+ const element = engine.getInputElement();
+ let previousPinchSquaredDistance = 0;
+ let previousMultiTouchPanPosition = null;
+ this._pointA = null;
+ this._pointB = null;
+ this._altKey = false;
+ this._ctrlKey = false;
+ this._metaKey = false;
+ this._shiftKey = false;
+ this._buttonsPressed = 0;
+ this._pointerInput = (p) => {
+ const evt = p.event;
+ const isTouch = evt.pointerType === "touch";
+ if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) {
+ return;
+ }
+ const srcElement = evt.target;
+ this._altKey = evt.altKey;
+ this._ctrlKey = evt.ctrlKey;
+ this._metaKey = evt.metaKey;
+ this._shiftKey = evt.shiftKey;
+ this._buttonsPressed = evt.buttons;
+ if (engine.isPointerLock) {
+ const offsetX = evt.movementX;
+ const offsetY = evt.movementY;
+ this.onTouch(null, offsetX, offsetY);
+ this._pointA = null;
+ this._pointB = null;
+ }
+ else if (p.type !== PointerEventTypes.POINTERDOWN &&
+ p.type !== PointerEventTypes.POINTERDOUBLETAP &&
+ isTouch &&
+ this._pointA?.pointerId !== evt.pointerId &&
+ this._pointB?.pointerId !== evt.pointerId) {
+ return; // If we get a non-down event for a touch that we're not tracking, ignore it
+ }
+ else if (p.type === PointerEventTypes.POINTERDOWN && (this._currentMousePointerIdDown === -1 || isTouch)) {
+ try {
+ srcElement?.setPointerCapture(evt.pointerId);
+ }
+ catch (e) {
+ //Nothing to do with the error. Execution will continue.
+ }
+ if (this._pointA === null) {
+ this._pointA = {
+ x: evt.clientX,
+ y: evt.clientY,
+ pointerId: evt.pointerId,
+ type: evt.pointerType,
+ };
+ }
+ else if (this._pointB === null) {
+ this._pointB = {
+ x: evt.clientX,
+ y: evt.clientY,
+ pointerId: evt.pointerId,
+ type: evt.pointerType,
+ };
+ }
+ else {
+ return; // We are already tracking two pointers so ignore this one
+ }
+ if (this._currentMousePointerIdDown === -1 && !isTouch) {
+ this._currentMousePointerIdDown = evt.pointerId;
+ }
+ this.onButtonDown(evt);
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ element && element.focus();
+ }
+ }
+ else if (p.type === PointerEventTypes.POINTERDOUBLETAP) {
+ this.onDoubleTap(evt.pointerType);
+ }
+ else if (p.type === PointerEventTypes.POINTERUP && (this._currentMousePointerIdDown === evt.pointerId || isTouch)) {
+ try {
+ srcElement?.releasePointerCapture(evt.pointerId);
+ }
+ catch (e) {
+ //Nothing to do with the error.
+ }
+ if (!isTouch) {
+ this._pointB = null; // Mouse and pen are mono pointer
+ }
+ //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
+ //but emptying completely pointers collection is required to fix a bug on iPhone :
+ //when changing orientation while pinching camera,
+ //one pointer stay pressed forever if we don't release all pointers
+ //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
+ if (engine._badOS) {
+ this._pointA = this._pointB = null;
+ }
+ else {
+ //only remove the impacted pointer in case of multitouch allowing on most
+ //platforms switching from rotate to zoom and pan seamlessly.
+ if (this._pointB && this._pointA && this._pointA.pointerId == evt.pointerId) {
+ this._pointA = this._pointB;
+ this._pointB = null;
+ }
+ else if (this._pointA && this._pointB && this._pointB.pointerId == evt.pointerId) {
+ this._pointB = null;
+ }
+ else {
+ this._pointA = this._pointB = null;
+ }
+ }
+ if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) {
+ // Previous pinch data is populated but a button has been lifted
+ // so pinch has ended.
+ this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, 0, // pinchSquaredDistance
+ previousMultiTouchPanPosition, null // multiTouchPanPosition
+ );
+ previousPinchSquaredDistance = 0;
+ previousMultiTouchPanPosition = null;
+ }
+ this._currentMousePointerIdDown = -1;
+ this.onButtonUp(evt);
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ }
+ else if (p.type === PointerEventTypes.POINTERMOVE) {
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ // One button down
+ if (this._pointA && this._pointB === null) {
+ const offsetX = evt.clientX - this._pointA.x;
+ const offsetY = evt.clientY - this._pointA.y;
+ this._pointA.x = evt.clientX;
+ this._pointA.y = evt.clientY;
+ this.onTouch(this._pointA, offsetX, offsetY);
+ }
+ // Two buttons down: pinch
+ else if (this._pointA && this._pointB) {
+ const ed = this._pointA.pointerId === evt.pointerId ? this._pointA : this._pointB;
+ ed.x = evt.clientX;
+ ed.y = evt.clientY;
+ const distX = this._pointA.x - this._pointB.x;
+ const distY = this._pointA.y - this._pointB.y;
+ const pinchSquaredDistance = distX * distX + distY * distY;
+ const multiTouchPanPosition = {
+ x: (this._pointA.x + this._pointB.x) / 2,
+ y: (this._pointA.y + this._pointB.y) / 2,
+ pointerId: evt.pointerId,
+ type: p.type,
+ };
+ this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition);
+ previousMultiTouchPanPosition = multiTouchPanPosition;
+ previousPinchSquaredDistance = pinchSquaredDistance;
+ }
+ }
+ };
+ this._observer = this.camera
+ .getScene()
+ ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE | PointerEventTypes.POINTERDOUBLETAP);
+ this._onLostFocus = () => {
+ this._pointA = this._pointB = null;
+ previousPinchSquaredDistance = 0;
+ previousMultiTouchPanPosition = null;
+ this.onLostFocus();
+ };
+ this._contextMenuBind = (evt) => this.onContextMenu(evt);
+ element && element.addEventListener("contextmenu", this._contextMenuBind, false);
+ const hostWindow = this.camera.getScene().getEngine().getHostWindow();
+ if (hostWindow) {
+ Tools.RegisterTopRootEvents(hostWindow, [{ name: "blur", handler: this._onLostFocus }]);
+ }
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ if (this._onLostFocus) {
+ const hostWindow = this.camera.getScene().getEngine().getHostWindow();
+ if (hostWindow) {
+ Tools.UnregisterTopRootEvents(hostWindow, [{ name: "blur", handler: this._onLostFocus }]);
+ }
+ }
+ if (this._observer) {
+ this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
+ this._observer = null;
+ if (this._contextMenuBind) {
+ const inputElement = this.camera.getScene().getEngine().getInputElement();
+ inputElement && inputElement.removeEventListener("contextmenu", this._contextMenuBind);
+ }
+ this._onLostFocus = null;
+ }
+ this._altKey = false;
+ this._ctrlKey = false;
+ this._metaKey = false;
+ this._shiftKey = false;
+ this._buttonsPressed = 0;
+ this._currentMousePointerIdDown = -1;
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "BaseCameraPointersInput";
+ }
+ /**
+ * Get the friendly name associated with the input class.
+ * @returns the input friendly name
+ */
+ getSimpleName() {
+ return "pointers";
+ }
+ /**
+ * Called on pointer POINTERDOUBLETAP event.
+ * Override this method to provide functionality on POINTERDOUBLETAP event.
+ * @param type type of event
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ onDoubleTap(type) { }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ /**
+ * Called on pointer POINTERMOVE event if only a single touch is active.
+ * Override this method to provide functionality.
+ * @param point The current position of the pointer
+ * @param offsetX The offsetX of the pointer when the event occurred
+ * @param offsetY The offsetY of the pointer when the event occurred
+ */
+ onTouch(point, offsetX, offsetY) { }
+ /**
+ * Called on pointer POINTERMOVE event if multiple touches are active.
+ * Override this method to provide functionality.
+ * @param _pointA First point in the pair
+ * @param _pointB Second point in the pair
+ * @param previousPinchSquaredDistance Sqr Distance between the points the last time this event was fired (by this input)
+ * @param pinchSquaredDistance Sqr Distance between the points this time
+ * @param previousMultiTouchPanPosition Previous center point between the points
+ * @param multiTouchPanPosition Current center point between the points
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ onMultiTouch(_pointA, _pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { }
+ /**
+ * Called on JS contextmenu event.
+ * Override this method to provide functionality.
+ * @param evt the event to be handled
+ */
+ onContextMenu(evt) {
+ evt.preventDefault();
+ }
+ /**
+ * Called each time a new POINTERDOWN event occurs. Ie, for each button
+ * press.
+ * Override this method to provide functionality.
+ * @param _evt Defines the event to track
+ */
+ onButtonDown(_evt) { }
+ /**
+ * Called each time a new POINTERUP event occurs. Ie, for each button
+ * release.
+ * Override this method to provide functionality.
+ * @param _evt Defines the event to track
+ */
+ onButtonUp(_evt) { }
+ /**
+ * Called when window becomes inactive.
+ * Override this method to provide functionality.
+ */
+ onLostFocus() { }
+}
+__decorate([
+ serialize()
+], BaseCameraPointersInput.prototype, "buttons", void 0);
+
+/**
+ * Manage the pointers inputs to control an arc rotate camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class ArcRotateCameraPointersInput extends BaseCameraPointersInput {
+ constructor() {
+ super(...arguments);
+ /**
+ * Defines the buttons associated with the input to handle camera move.
+ */
+ this.buttons = [0, 1, 2];
+ /**
+ * Defines the pointer angular sensibility along the X axis or how fast is
+ * the camera rotating.
+ */
+ this.angularSensibilityX = 1000.0;
+ /**
+ * Defines the pointer angular sensibility along the Y axis or how fast is
+ * the camera rotating.
+ */
+ this.angularSensibilityY = 1000.0;
+ /**
+ * Defines the pointer pinch precision or how fast is the camera zooming.
+ */
+ this.pinchPrecision = 12.0;
+ /**
+ * pinchDeltaPercentage will be used instead of pinchPrecision if different
+ * from 0.
+ * It defines the percentage of current camera.radius to use as delta when
+ * pinch zoom is used.
+ */
+ this.pinchDeltaPercentage = 0;
+ /**
+ * When useNaturalPinchZoom is true, multi touch zoom will zoom in such
+ * that any object in the plane at the camera's target point will scale
+ * perfectly with finger motion.
+ * Overrides pinchDeltaPercentage and pinchPrecision.
+ */
+ this.useNaturalPinchZoom = false;
+ /**
+ * Defines whether zoom (2 fingers pinch) is enabled through multitouch
+ */
+ this.pinchZoom = true;
+ /**
+ * Defines the pointer panning sensibility or how fast is the camera moving.
+ */
+ this.panningSensibility = 1000.0;
+ /**
+ * Defines whether panning (2 fingers swipe) is enabled through multitouch.
+ */
+ this.multiTouchPanning = true;
+ /**
+ * Defines whether panning is enabled for both pan (2 fingers swipe) and
+ * zoom (pinch) through multitouch.
+ */
+ this.multiTouchPanAndZoom = true;
+ /**
+ * Revers pinch action direction.
+ */
+ this.pinchInwards = true;
+ this._isPanClick = false;
+ this._twoFingerActivityCount = 0;
+ this._isPinching = false;
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "ArcRotateCameraPointersInput";
+ }
+ /**
+ * Move camera from multi touch panning positions.
+ * @param previousMultiTouchPanPosition
+ * @param multiTouchPanPosition
+ */
+ _computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition) {
+ if (this.panningSensibility !== 0 && previousMultiTouchPanPosition && multiTouchPanPosition) {
+ const moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x;
+ const moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y;
+ this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility;
+ this.camera.inertialPanningY += moveDeltaY / this.panningSensibility;
+ }
+ }
+ /**
+ * Move camera from pinch zoom distances.
+ * @param previousPinchSquaredDistance
+ * @param pinchSquaredDistance
+ */
+ _computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance) {
+ const radius = this.camera.radius || ArcRotateCameraPointersInput.MinimumRadiusForPinch;
+ if (this.useNaturalPinchZoom) {
+ this.camera.radius = (radius * Math.sqrt(previousPinchSquaredDistance)) / Math.sqrt(pinchSquaredDistance);
+ }
+ else if (this.pinchDeltaPercentage) {
+ this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * radius * this.pinchDeltaPercentage;
+ }
+ else {
+ this.camera.inertialRadiusOffset +=
+ (pinchSquaredDistance - previousPinchSquaredDistance) /
+ ((this.pinchPrecision * (this.pinchInwards ? 1 : -1) * (this.angularSensibilityX + this.angularSensibilityY)) / 2);
+ }
+ }
+ /**
+ * Called on pointer POINTERMOVE event if only a single touch is active.
+ * @param point current touch point
+ * @param offsetX offset on X
+ * @param offsetY offset on Y
+ */
+ onTouch(point, offsetX, offsetY) {
+ if (this.panningSensibility !== 0 && ((this._ctrlKey && this.camera._useCtrlForPanning) || this._isPanClick)) {
+ this.camera.inertialPanningX += -offsetX / this.panningSensibility;
+ this.camera.inertialPanningY += offsetY / this.panningSensibility;
+ }
+ else {
+ this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX;
+ this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY;
+ }
+ }
+ /**
+ * Called on pointer POINTERDOUBLETAP event.
+ */
+ onDoubleTap() {
+ if (this.camera.useInputToRestoreState) {
+ this.camera.restoreState();
+ }
+ }
+ /**
+ * Called on pointer POINTERMOVE event if multiple touches are active.
+ * @param pointA point A
+ * @param pointB point B
+ * @param previousPinchSquaredDistance distance between points in previous pinch
+ * @param pinchSquaredDistance distance between points in current pinch
+ * @param previousMultiTouchPanPosition multi-touch position in previous step
+ * @param multiTouchPanPosition multi-touch position in current step
+ */
+ onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) {
+ if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) {
+ // First time this method is called for new pinch.
+ // Next time this is called there will be a
+ // previousPinchSquaredDistance and pinchSquaredDistance to compare.
+ return;
+ }
+ if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) {
+ // Last time this method is called at the end of a pinch.
+ return;
+ }
+ // Zoom and panning enabled together
+ if (this.multiTouchPanAndZoom) {
+ this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);
+ this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);
+ // Zoom and panning enabled but only one at a time
+ }
+ else if (this.multiTouchPanning && this.pinchZoom) {
+ this._twoFingerActivityCount++;
+ if (this._isPinching ||
+ (this._twoFingerActivityCount < 20 && Math.abs(Math.sqrt(pinchSquaredDistance) - Math.sqrt(previousPinchSquaredDistance)) > this.camera.pinchToPanMaxDistance)) {
+ // Since pinch has not been active long, assume we intend to zoom.
+ this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);
+ // Since we are pinching, remain pinching on next iteration.
+ this._isPinching = true;
+ }
+ else {
+ // Pause between pinch starting and moving implies not a zoom event. Pan instead.
+ this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);
+ }
+ // Panning enabled, zoom disabled
+ }
+ else if (this.multiTouchPanning) {
+ this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);
+ // Zoom enabled, panning disabled
+ }
+ else if (this.pinchZoom) {
+ this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);
+ }
+ }
+ /**
+ * Called each time a new POINTERDOWN event occurs. Ie, for each button
+ * press.
+ * @param evt Defines the event to track
+ */
+ onButtonDown(evt) {
+ this._isPanClick = evt.button === this.camera._panningMouseButton;
+ }
+ /**
+ * Called each time a new POINTERUP event occurs. Ie, for each button
+ * release.
+ * @param _evt Defines the event to track
+ */
+ onButtonUp(_evt) {
+ this._twoFingerActivityCount = 0;
+ this._isPinching = false;
+ }
+ /**
+ * Called when window becomes inactive.
+ */
+ onLostFocus() {
+ this._isPanClick = false;
+ this._twoFingerActivityCount = 0;
+ this._isPinching = false;
+ }
+}
+/**
+ * The minimum radius used for pinch, to avoid radius lock at 0
+ */
+ArcRotateCameraPointersInput.MinimumRadiusForPinch = 0.001;
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "useNaturalPinchZoom", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "pinchZoom", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
+CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
+
+/**
+ * Manage the keyboard inputs to control the movement of an arc rotate camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class ArcRotateCameraKeyboardMoveInput {
+ constructor() {
+ /**
+ * Defines the list of key codes associated with the up action (increase alpha)
+ */
+ this.keysUp = [38];
+ /**
+ * Defines the list of key codes associated with the down action (decrease alpha)
+ */
+ this.keysDown = [40];
+ /**
+ * Defines the list of key codes associated with the left action (increase beta)
+ */
+ this.keysLeft = [37];
+ /**
+ * Defines the list of key codes associated with the right action (decrease beta)
+ */
+ this.keysRight = [39];
+ /**
+ * Defines the list of key codes associated with the reset action.
+ * Those keys reset the camera to its last stored state (with the method camera.storeState())
+ */
+ this.keysReset = [220];
+ /**
+ * Defines the panning sensibility of the inputs.
+ * (How fast is the camera panning)
+ */
+ this.panningSensibility = 50.0;
+ /**
+ * Defines the zooming sensibility of the inputs.
+ * (How fast is the camera zooming)
+ */
+ this.zoomingSensibility = 25.0;
+ /**
+ * Defines whether maintaining the alt key down switch the movement mode from
+ * orientation to zoom.
+ */
+ this.useAltToZoom = true;
+ /**
+ * Rotation speed of the camera
+ */
+ this.angularSpeed = 0.01;
+ this._keys = new Array();
+ }
+ /**
+ * Attach the input controls to a specific dom element to get the input from.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(noPreventDefault) {
+ // was there a second variable defined?
+ // eslint-disable-next-line prefer-rest-params
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
+ if (this._onCanvasBlurObserver) {
+ return;
+ }
+ this._scene = this.camera.getScene();
+ this._engine = this._scene.getEngine();
+ this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {
+ this._keys.length = 0;
+ });
+ this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {
+ const evt = info.event;
+ if (!evt.metaKey) {
+ if (info.type === KeyboardEventTypes.KEYDOWN) {
+ this._ctrlPressed = evt.ctrlKey;
+ this._altPressed = evt.altKey;
+ if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
+ this.keysDown.indexOf(evt.keyCode) !== -1 ||
+ this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+ this.keysRight.indexOf(evt.keyCode) !== -1 ||
+ this.keysReset.indexOf(evt.keyCode) !== -1) {
+ const index = this._keys.indexOf(evt.keyCode);
+ if (index === -1) {
+ this._keys.push(evt.keyCode);
+ }
+ if (evt.preventDefault) {
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ }
+ }
+ }
+ else {
+ if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
+ this.keysDown.indexOf(evt.keyCode) !== -1 ||
+ this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+ this.keysRight.indexOf(evt.keyCode) !== -1 ||
+ this.keysReset.indexOf(evt.keyCode) !== -1) {
+ const index = this._keys.indexOf(evt.keyCode);
+ if (index >= 0) {
+ this._keys.splice(index, 1);
+ }
+ if (evt.preventDefault) {
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ }
+ }
+ }
+ }
+ });
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ if (this._scene) {
+ if (this._onKeyboardObserver) {
+ this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
+ }
+ if (this._onCanvasBlurObserver) {
+ this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
+ }
+ this._onKeyboardObserver = null;
+ this._onCanvasBlurObserver = null;
+ }
+ this._keys.length = 0;
+ }
+ /**
+ * Update the current camera state depending on the inputs that have been used this frame.
+ * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
+ */
+ checkInputs() {
+ if (this._onKeyboardObserver) {
+ const camera = this.camera;
+ for (let index = 0; index < this._keys.length; index++) {
+ const keyCode = this._keys[index];
+ if (this.keysLeft.indexOf(keyCode) !== -1) {
+ if (this._ctrlPressed && this.camera._useCtrlForPanning) {
+ camera.inertialPanningX -= 1 / this.panningSensibility;
+ }
+ else {
+ camera.inertialAlphaOffset -= this.angularSpeed;
+ }
+ }
+ else if (this.keysUp.indexOf(keyCode) !== -1) {
+ if (this._ctrlPressed && this.camera._useCtrlForPanning) {
+ camera.inertialPanningY += 1 / this.panningSensibility;
+ }
+ else if (this._altPressed && this.useAltToZoom) {
+ camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
+ }
+ else {
+ camera.inertialBetaOffset -= this.angularSpeed;
+ }
+ }
+ else if (this.keysRight.indexOf(keyCode) !== -1) {
+ if (this._ctrlPressed && this.camera._useCtrlForPanning) {
+ camera.inertialPanningX += 1 / this.panningSensibility;
+ }
+ else {
+ camera.inertialAlphaOffset += this.angularSpeed;
+ }
+ }
+ else if (this.keysDown.indexOf(keyCode) !== -1) {
+ if (this._ctrlPressed && this.camera._useCtrlForPanning) {
+ camera.inertialPanningY -= 1 / this.panningSensibility;
+ }
+ else if (this._altPressed && this.useAltToZoom) {
+ camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
+ }
+ else {
+ camera.inertialBetaOffset += this.angularSpeed;
+ }
+ }
+ else if (this.keysReset.indexOf(keyCode) !== -1) {
+ if (camera.useInputToRestoreState) {
+ camera.restoreState();
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "ArcRotateCameraKeyboardMoveInput";
+ }
+ /**
+ * Get the friendly name associated with the input class.
+ * @returns the input friendly name
+ */
+ getSimpleName() {
+ return "keyboard";
+ }
+}
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
+CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
+
+/**
+ * Firefox uses a different scheme to report scroll distances to other
+ * browsers. Rather than use complicated methods to calculate the exact
+ * multiple we need to apply, let's just cheat and use a constant.
+ * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode
+ * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line
+ */
+const ffMultiplier = 40;
+/**
+ * Manage the mouse wheel inputs to control an arc rotate camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class ArcRotateCameraMouseWheelInput {
+ constructor() {
+ /**
+ * Gets or Set the mouse wheel precision or how fast is the camera zooming.
+ */
+ this.wheelPrecision = 3.0;
+ /**
+ * Gets or Set the boolean value that controls whether or not the mouse wheel
+ * zooms to the location of the mouse pointer or not. The default is false.
+ */
+ this.zoomToMouseLocation = false;
+ /**
+ * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
+ * It defines the percentage of current camera.radius to use as delta when wheel is used.
+ */
+ this.wheelDeltaPercentage = 0;
+ /**
+ * If set, this function will be used to set the radius delta that will be added to the current camera radius
+ */
+ this.customComputeDeltaFromMouseWheel = null;
+ this._viewOffset = new Vector3(0, 0, 0);
+ this._globalOffset = new Vector3(0, 0, 0);
+ this._inertialPanning = Vector3.Zero();
+ }
+ _computeDeltaFromMouseWheelLegacyEvent(mouseWheelDelta, radius) {
+ let delta = 0;
+ const wheelDelta = mouseWheelDelta * 0.01 * this.wheelDeltaPercentage * radius;
+ if (mouseWheelDelta > 0) {
+ delta = wheelDelta / (1.0 + this.wheelDeltaPercentage);
+ }
+ else {
+ delta = wheelDelta * (1.0 + this.wheelDeltaPercentage);
+ }
+ return delta;
+ }
+ /**
+ * Attach the input controls to a specific dom element to get the input from.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(noPreventDefault) {
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
+ this._wheel = (p) => {
+ //sanity check - this should be a PointerWheel event.
+ if (p.type !== PointerEventTypes.POINTERWHEEL) {
+ return;
+ }
+ const event = p.event;
+ let delta = 0;
+ const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly
+ const wheelDelta = -(event.deltaY * platformScale);
+ if (this.customComputeDeltaFromMouseWheel) {
+ delta = this.customComputeDeltaFromMouseWheel(wheelDelta, this, event);
+ }
+ else {
+ if (this.wheelDeltaPercentage) {
+ delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, this.camera.radius);
+ // If zooming in, estimate the target radius and use that to compute the delta for inertia
+ // this will stop multiple scroll events zooming in from adding too much inertia
+ if (delta > 0) {
+ let estimatedTargetRadius = this.camera.radius;
+ let targetInertia = this.camera.inertialRadiusOffset + delta;
+ for (let i = 0; i < 20 && Math.abs(targetInertia) > 0.001; i++) {
+ estimatedTargetRadius -= targetInertia;
+ targetInertia *= this.camera.inertia;
+ }
+ estimatedTargetRadius = Clamp(estimatedTargetRadius, 0, Number.MAX_VALUE);
+ delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, estimatedTargetRadius);
+ }
+ }
+ else {
+ delta = wheelDelta / (this.wheelPrecision * 40);
+ }
+ }
+ if (delta) {
+ if (this.zoomToMouseLocation) {
+ // If we are zooming to the mouse location, then we need to get the hit plane at the start of the zoom gesture if it doesn't exist
+ // The hit plane is normally calculated after the first motion and each time there's motion so if we don't do this first,
+ // the first zoom will be to the center of the screen
+ if (!this._hitPlane) {
+ this._updateHitPlane();
+ }
+ this._zoomToMouse(delta);
+ }
+ else {
+ this.camera.inertialRadiusOffset += delta;
+ }
+ }
+ if (event.preventDefault) {
+ if (!noPreventDefault) {
+ event.preventDefault();
+ }
+ }
+ };
+ this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);
+ if (this.zoomToMouseLocation) {
+ this._inertialPanning.setAll(0);
+ }
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ if (this._observer) {
+ this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
+ this._observer = null;
+ this._wheel = null;
+ }
+ }
+ /**
+ * Update the current camera state depending on the inputs that have been used this frame.
+ * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
+ */
+ checkInputs() {
+ if (!this.zoomToMouseLocation) {
+ return;
+ }
+ const camera = this.camera;
+ const motion = 0.0 + camera.inertialAlphaOffset + camera.inertialBetaOffset + camera.inertialRadiusOffset;
+ if (motion) {
+ // if zooming is still happening as a result of inertia, then we also need to update
+ // the hit plane.
+ this._updateHitPlane();
+ // Note we cannot use arcRotateCamera.inertialPlanning here because arcRotateCamera panning
+ // uses a different panningInertia which could cause this panning to get out of sync with
+ // the zooming, and for this to work they must be exactly in sync.
+ camera.target.addInPlace(this._inertialPanning);
+ this._inertialPanning.scaleInPlace(camera.inertia);
+ this._zeroIfClose(this._inertialPanning);
+ }
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "ArcRotateCameraMouseWheelInput";
+ }
+ /**
+ * Get the friendly name associated with the input class.
+ * @returns the input friendly name
+ */
+ getSimpleName() {
+ return "mousewheel";
+ }
+ _updateHitPlane() {
+ const camera = this.camera;
+ const direction = camera.target.subtract(camera.position);
+ this._hitPlane = Plane.FromPositionAndNormal(camera.target, direction);
+ }
+ // Get position on the hit plane
+ _getPosition() {
+ const camera = this.camera;
+ const scene = camera.getScene();
+ // since the _hitPlane is always updated to be orthogonal to the camera position vector
+ // we don't have to worry about this ray shooting off to infinity. This ray creates
+ // a vector defining where we want to zoom to.
+ const ray = scene.createPickingRay(scene.pointerX, scene.pointerY, Matrix.Identity(), camera, false);
+ // Since the camera is the origin of the picking ray, we need to offset it by the camera's offset manually
+ // Because the offset is in view space, we need to convert it to world space first
+ if (camera.targetScreenOffset.x !== 0 || camera.targetScreenOffset.y !== 0) {
+ this._viewOffset.set(camera.targetScreenOffset.x, camera.targetScreenOffset.y, 0);
+ camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
+ this._globalOffset = Vector3.TransformNormal(this._viewOffset, camera._cameraTransformMatrix);
+ ray.origin.addInPlace(this._globalOffset);
+ }
+ let distance = 0;
+ if (this._hitPlane) {
+ distance = ray.intersectsPlane(this._hitPlane) ?? 0;
+ }
+ // not using this ray again, so modifying its vectors here is fine
+ return ray.origin.addInPlace(ray.direction.scaleInPlace(distance));
+ }
+ _zoomToMouse(delta) {
+ const camera = this.camera;
+ const inertiaComp = 1 - camera.inertia;
+ if (camera.lowerRadiusLimit) {
+ const lowerLimit = camera.lowerRadiusLimit ?? 0;
+ if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp < lowerLimit) {
+ delta = (camera.radius - lowerLimit) * inertiaComp - camera.inertialRadiusOffset;
+ }
+ }
+ if (camera.upperRadiusLimit) {
+ const upperLimit = camera.upperRadiusLimit ?? 0;
+ if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp > upperLimit) {
+ delta = (camera.radius - upperLimit) * inertiaComp - camera.inertialRadiusOffset;
+ }
+ }
+ const zoomDistance = delta / inertiaComp;
+ const ratio = zoomDistance / camera.radius;
+ const vec = this._getPosition();
+ // Now this vector tells us how much we also need to pan the camera
+ // so the targeted mouse location becomes the center of zooming.
+ const directionToZoomLocation = TmpVectors.Vector3[6];
+ vec.subtractToRef(camera.target, directionToZoomLocation);
+ directionToZoomLocation.scaleInPlace(ratio);
+ directionToZoomLocation.scaleInPlace(inertiaComp);
+ this._inertialPanning.addInPlace(directionToZoomLocation);
+ camera.inertialRadiusOffset += delta;
+ }
+ // Sets x y or z of passed in vector to zero if less than Epsilon.
+ _zeroIfClose(vec) {
+ if (Math.abs(vec.x) < Epsilon) {
+ vec.x = 0;
+ }
+ if (Math.abs(vec.y) < Epsilon) {
+ vec.y = 0;
+ }
+ if (Math.abs(vec.z) < Epsilon) {
+ vec.z = 0;
+ }
+ }
+}
+__decorate([
+ serialize()
+], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraMouseWheelInput.prototype, "zoomToMouseLocation", void 0);
+__decorate([
+ serialize()
+], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
+CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
+
+/**
+ * Default Inputs manager for the ArcRotateCamera.
+ * It groups all the default supported inputs for ease of use.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class ArcRotateCameraInputsManager extends CameraInputsManager {
+ /**
+ * Instantiates a new ArcRotateCameraInputsManager.
+ * @param camera Defines the camera the inputs belong to
+ */
+ constructor(camera) {
+ super(camera);
+ }
+ /**
+ * Add mouse wheel input support to the input manager.
+ * @returns the current input manager
+ */
+ addMouseWheel() {
+ this.add(new ArcRotateCameraMouseWheelInput());
+ return this;
+ }
+ /**
+ * Add pointers input support to the input manager.
+ * @returns the current input manager
+ */
+ addPointers() {
+ this.add(new ArcRotateCameraPointersInput());
+ return this;
+ }
+ /**
+ * Add keyboard input support to the input manager.
+ * @returns the current input manager
+ */
+ addKeyboard() {
+ this.add(new ArcRotateCameraKeyboardMoveInput());
+ return this;
+ }
+}
+
+Node$2.AddNodeConstructor("ArcRotateCamera", (name, scene) => {
+ return () => new ArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), scene);
+});
+/**
+ * Computes the alpha angle based on the source position and the target position.
+ * @param offset The directional offset between the source position and the target position
+ * @returns The alpha angle in radians
+ */
+function ComputeAlpha(offset) {
+ // Default alpha to π/2 to handle the edge case where x and z are both zero (when looking along up axis)
+ let alpha = Math.PI / 2;
+ if (!(offset.x === 0 && offset.z === 0)) {
+ alpha = Math.acos(offset.x / Math.sqrt(Math.pow(offset.x, 2) + Math.pow(offset.z, 2)));
+ }
+ if (offset.z < 0) {
+ alpha = 2 * Math.PI - alpha;
+ }
+ return alpha;
+}
+/**
+ * Computes the beta angle based on the source position and the target position.
+ * @param verticalOffset The y value of the directional offset between the source position and the target position
+ * @param radius The distance between the source position and the target position
+ * @returns The beta angle in radians
+ */
+function ComputeBeta(verticalOffset, radius) {
+ return Math.acos(verticalOffset / radius);
+}
+/**
+ * This represents an orbital type of camera.
+ *
+ * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
+ * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#arc-rotate-camera
+ */
+class ArcRotateCamera extends TargetCamera {
+ /**
+ * Defines the target point of the camera.
+ * The camera looks towards it from the radius distance.
+ */
+ get target() {
+ return this._target;
+ }
+ set target(value) {
+ this.setTarget(value);
+ }
+ /**
+ * Defines the target transform node of the camera.
+ * The camera looks towards it from the radius distance.
+ * Please note that setting a target host will disable panning.
+ */
+ get targetHost() {
+ return this._targetHost;
+ }
+ set targetHost(value) {
+ if (value) {
+ this.setTarget(value);
+ }
+ }
+ /**
+ * Return the current target position of the camera. This value is expressed in local space.
+ * @returns the target position
+ */
+ getTarget() {
+ return this.target;
+ }
+ /**
+ * Define the current local position of the camera in the scene
+ */
+ get position() {
+ return this._position;
+ }
+ set position(newPosition) {
+ this.setPosition(newPosition);
+ }
+ /**
+ * The vector the camera should consider as up. (default is Vector3(0, 1, 0) as returned by Vector3.Up())
+ * Setting this will copy the given vector to the camera's upVector, and set rotation matrices to and from Y up.
+ * DO NOT set the up vector using copyFrom or copyFromFloats, as this bypasses setting the above matrices.
+ */
+ set upVector(vec) {
+ if (!this._upToYMatrix) {
+ this._yToUpMatrix = new Matrix();
+ this._upToYMatrix = new Matrix();
+ this._upVector = Vector3.Zero();
+ }
+ vec.normalize();
+ this._upVector.copyFrom(vec);
+ this.setMatUp();
+ }
+ get upVector() {
+ return this._upVector;
+ }
+ /**
+ * Sets the Y-up to camera up-vector rotation matrix, and the up-vector to Y-up rotation matrix.
+ */
+ setMatUp() {
+ // from y-up to custom-up (used in _getViewMatrix)
+ Matrix.RotationAlignToRef(Vector3.UpReadOnly, this._upVector, this._yToUpMatrix);
+ // from custom-up to y-up (used in rebuildAnglesAndRadius)
+ Matrix.RotationAlignToRef(this._upVector, Vector3.UpReadOnly, this._upToYMatrix);
+ }
+ //-- begin properties for backward compatibility for inputs
+ /**
+ * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
+ */
+ get angularSensibilityX() {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ return pointers.angularSensibilityX;
+ }
+ return 0;
+ }
+ set angularSensibilityX(value) {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ pointers.angularSensibilityX = value;
+ }
+ }
+ /**
+ * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
+ */
+ get angularSensibilityY() {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ return pointers.angularSensibilityY;
+ }
+ return 0;
+ }
+ set angularSensibilityY(value) {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ pointers.angularSensibilityY = value;
+ }
+ }
+ /**
+ * Gets or Set the pointer pinch precision or how fast is the camera zooming.
+ */
+ get pinchPrecision() {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ return pointers.pinchPrecision;
+ }
+ return 0;
+ }
+ set pinchPrecision(value) {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ pointers.pinchPrecision = value;
+ }
+ }
+ /**
+ * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
+ * It will be used instead of pinchPrecision if different from 0.
+ * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
+ */
+ get pinchDeltaPercentage() {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ return pointers.pinchDeltaPercentage;
+ }
+ return 0;
+ }
+ set pinchDeltaPercentage(value) {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ pointers.pinchDeltaPercentage = value;
+ }
+ }
+ /**
+ * Gets or Set the pointer use natural pinch zoom to override the pinch precision
+ * and pinch delta percentage.
+ * When useNaturalPinchZoom is true, multi touch zoom will zoom in such
+ * that any object in the plane at the camera's target point will scale
+ * perfectly with finger motion.
+ */
+ get useNaturalPinchZoom() {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ return pointers.useNaturalPinchZoom;
+ }
+ return false;
+ }
+ set useNaturalPinchZoom(value) {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ pointers.useNaturalPinchZoom = value;
+ }
+ }
+ /**
+ * Gets or Set the pointer panning sensibility or how fast is the camera moving.
+ */
+ get panningSensibility() {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ return pointers.panningSensibility;
+ }
+ return 0;
+ }
+ set panningSensibility(value) {
+ const pointers = this.inputs.attached["pointers"];
+ if (pointers) {
+ pointers.panningSensibility = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
+ */
+ get keysUp() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysUp;
+ }
+ return [];
+ }
+ set keysUp(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysUp = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
+ */
+ get keysDown() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysDown;
+ }
+ return [];
+ }
+ set keysDown(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysDown = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
+ */
+ get keysLeft() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysLeft;
+ }
+ return [];
+ }
+ set keysLeft(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysLeft = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
+ */
+ get keysRight() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysRight;
+ }
+ return [];
+ }
+ set keysRight(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysRight = value;
+ }
+ }
+ /**
+ * Gets or Set the mouse wheel precision or how fast is the camera zooming.
+ */
+ get wheelPrecision() {
+ const mousewheel = this.inputs.attached["mousewheel"];
+ if (mousewheel) {
+ return mousewheel.wheelPrecision;
+ }
+ return 0;
+ }
+ set wheelPrecision(value) {
+ const mousewheel = this.inputs.attached["mousewheel"];
+ if (mousewheel) {
+ mousewheel.wheelPrecision = value;
+ }
+ }
+ /**
+ * Gets or Set the boolean value that controls whether or not the mouse wheel
+ * zooms to the location of the mouse pointer or not. The default is false.
+ */
+ get zoomToMouseLocation() {
+ const mousewheel = this.inputs.attached["mousewheel"];
+ if (mousewheel) {
+ return mousewheel.zoomToMouseLocation;
+ }
+ return false;
+ }
+ set zoomToMouseLocation(value) {
+ const mousewheel = this.inputs.attached["mousewheel"];
+ if (mousewheel) {
+ mousewheel.zoomToMouseLocation = value;
+ }
+ }
+ /**
+ * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
+ * It will be used instead of wheelPrecision if different from 0.
+ * It defines the percentage of current camera.radius to use as delta when wheel zoom is used.
+ */
+ get wheelDeltaPercentage() {
+ const mousewheel = this.inputs.attached["mousewheel"];
+ if (mousewheel) {
+ return mousewheel.wheelDeltaPercentage;
+ }
+ return 0;
+ }
+ set wheelDeltaPercentage(value) {
+ const mousewheel = this.inputs.attached["mousewheel"];
+ if (mousewheel) {
+ mousewheel.wheelDeltaPercentage = value;
+ }
+ }
+ /**
+ * Gets the bouncing behavior of the camera if it has been enabled.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior
+ */
+ get bouncingBehavior() {
+ return this._bouncingBehavior;
+ }
+ /**
+ * Defines if the bouncing behavior of the camera is enabled on the camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior
+ */
+ get useBouncingBehavior() {
+ return this._bouncingBehavior != null;
+ }
+ set useBouncingBehavior(value) {
+ if (value === this.useBouncingBehavior) {
+ return;
+ }
+ if (value) {
+ this._bouncingBehavior = new BouncingBehavior();
+ this.addBehavior(this._bouncingBehavior);
+ }
+ else if (this._bouncingBehavior) {
+ this.removeBehavior(this._bouncingBehavior);
+ this._bouncingBehavior = null;
+ }
+ }
+ /**
+ * Gets the framing behavior of the camera if it has been enabled.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior
+ */
+ get framingBehavior() {
+ return this._framingBehavior;
+ }
+ /**
+ * Defines if the framing behavior of the camera is enabled on the camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior
+ */
+ get useFramingBehavior() {
+ return this._framingBehavior != null;
+ }
+ set useFramingBehavior(value) {
+ if (value === this.useFramingBehavior) {
+ return;
+ }
+ if (value) {
+ this._framingBehavior = new FramingBehavior();
+ this.addBehavior(this._framingBehavior);
+ }
+ else if (this._framingBehavior) {
+ this.removeBehavior(this._framingBehavior);
+ this._framingBehavior = null;
+ }
+ }
+ /**
+ * Gets the auto rotation behavior of the camera if it has been enabled.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior
+ */
+ get autoRotationBehavior() {
+ return this._autoRotationBehavior;
+ }
+ /**
+ * Defines if the auto rotation behavior of the camera is enabled on the camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior
+ */
+ get useAutoRotationBehavior() {
+ return this._autoRotationBehavior != null;
+ }
+ set useAutoRotationBehavior(value) {
+ if (value === this.useAutoRotationBehavior) {
+ return;
+ }
+ if (value) {
+ this._autoRotationBehavior = new AutoRotationBehavior();
+ this.addBehavior(this._autoRotationBehavior);
+ }
+ else if (this._autoRotationBehavior) {
+ this.removeBehavior(this._autoRotationBehavior);
+ this._autoRotationBehavior = null;
+ }
+ }
+ /**
+ * Instantiates a new ArcRotateCamera in a given scene
+ * @param name Defines the name of the camera
+ * @param alpha Defines the camera rotation along the longitudinal axis
+ * @param beta Defines the camera rotation along the latitudinal axis
+ * @param radius Defines the camera distance from its target
+ * @param target Defines the camera target
+ * @param scene Defines the scene the camera belongs to
+ * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined
+ */
+ constructor(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive = true) {
+ super(name, Vector3.Zero(), scene, setActiveOnSceneIfNoneActive);
+ /**
+ * Current inertia value on the longitudinal axis.
+ * The bigger this number the longer it will take for the camera to stop.
+ */
+ this.inertialAlphaOffset = 0;
+ /**
+ * Current inertia value on the latitudinal axis.
+ * The bigger this number the longer it will take for the camera to stop.
+ */
+ this.inertialBetaOffset = 0;
+ /**
+ * Current inertia value on the radius axis.
+ * The bigger this number the longer it will take for the camera to stop.
+ */
+ this.inertialRadiusOffset = 0;
+ /**
+ * Minimum allowed angle on the longitudinal axis.
+ * This can help limiting how the Camera is able to move in the scene.
+ */
+ this.lowerAlphaLimit = null;
+ /**
+ * Maximum allowed angle on the longitudinal axis.
+ * This can help limiting how the Camera is able to move in the scene.
+ */
+ this.upperAlphaLimit = null;
+ /**
+ * Minimum allowed angle on the latitudinal axis.
+ * This can help limiting how the Camera is able to move in the scene.
+ */
+ this.lowerBetaLimit = 0.01;
+ /**
+ * Maximum allowed angle on the latitudinal axis.
+ * This can help limiting how the Camera is able to move in the scene.
+ */
+ this.upperBetaLimit = Math.PI - 0.01;
+ /**
+ * Minimum allowed distance of the camera to the target (The camera can not get closer).
+ * This can help limiting how the Camera is able to move in the scene.
+ */
+ this.lowerRadiusLimit = null;
+ /**
+ * Maximum allowed distance of the camera to the target (The camera can not get further).
+ * This can help limiting how the Camera is able to move in the scene.
+ */
+ this.upperRadiusLimit = null;
+ /**
+ * Minimum allowed vertical target position of the camera.
+ * Use this setting in combination with `upperRadiusLimit` to set a global limit for the Cameras vertical position.
+ */
+ this.lowerTargetYLimit = -Infinity;
+ /**
+ * Defines the current inertia value used during panning of the camera along the X axis.
+ */
+ this.inertialPanningX = 0;
+ /**
+ * Defines the current inertia value used during panning of the camera along the Y axis.
+ */
+ this.inertialPanningY = 0;
+ /**
+ * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
+ * Basically if your fingers moves away from more than this distance you will be considered
+ * in pinch mode.
+ */
+ this.pinchToPanMaxDistance = 20;
+ /**
+ * Defines the maximum distance the camera can pan.
+ * This could help keeping the camera always in your scene.
+ */
+ this.panningDistanceLimit = null;
+ /**
+ * Defines the target of the camera before panning.
+ */
+ this.panningOriginTarget = Vector3.Zero();
+ /**
+ * Defines the value of the inertia used during panning.
+ * 0 would mean stop inertia and one would mean no deceleration at all.
+ */
+ this.panningInertia = 0.9;
+ //-- end properties for backward compatibility for inputs
+ /**
+ * Defines how much the radius should be scaled while zooming on a particular mesh (through the zoomOn function)
+ */
+ this.zoomOnFactor = 1;
+ /**
+ * Defines a screen offset for the camera position.
+ */
+ this.targetScreenOffset = Vector2.Zero();
+ /**
+ * Allows the camera to be completely reversed.
+ * If false the camera can not arrive upside down.
+ */
+ this.allowUpsideDown = true;
+ /**
+ * Define if double tap/click is used to restore the previously saved state of the camera.
+ */
+ this.useInputToRestoreState = true;
+ /**
+ * Factor for restoring information interpolation. default is 0 = off. Any value \< 0 or \> 1 will disable interpolation.
+ */
+ this.restoreStateInterpolationFactor = 0;
+ this._currentInterpolationFactor = 0;
+ /** @internal */
+ this._viewMatrix = new Matrix();
+ /**
+ * Defines the allowed panning axis.
+ */
+ this.panningAxis = new Vector3(1, 1, 0);
+ this._transformedDirection = new Vector3();
+ /**
+ * Defines if camera will eliminate transform on y axis.
+ */
+ this.mapPanning = false;
+ // restoring state progressively
+ this._progressiveRestore = false;
+ /**
+ * Observable triggered when the transform node target has been changed on the camera.
+ */
+ this.onMeshTargetChangedObservable = new Observable();
+ /**
+ * Defines whether the camera should check collision with the objects oh the scene.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#how-can-i-do-this-
+ */
+ this.checkCollisions = false;
+ /**
+ * Defines the collision radius of the camera.
+ * This simulates a sphere around the camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera
+ */
+ this.collisionRadius = new Vector3(0.5, 0.5, 0.5);
+ this._previousPosition = Vector3.Zero();
+ this._collisionVelocity = Vector3.Zero();
+ this._newPosition = Vector3.Zero();
+ this._computationVector = Vector3.Zero();
+ this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {
+ if (!collidedMesh) {
+ this._previousPosition.copyFrom(this._position);
+ }
+ else {
+ this.setPosition(newPosition);
+ if (this.onCollide) {
+ this.onCollide(collidedMesh);
+ }
+ }
+ // Recompute because of constraints
+ const cosa = Math.cos(this.alpha);
+ const sina = Math.sin(this.alpha);
+ const cosb = Math.cos(this.beta);
+ let sinb = Math.sin(this.beta);
+ if (sinb === 0) {
+ sinb = 0.0001;
+ }
+ const target = this._getTargetPosition();
+ this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
+ target.addToRef(this._computationVector, this._newPosition);
+ this._position.copyFrom(this._newPosition);
+ let up = this.upVector;
+ if (this.allowUpsideDown && this.beta < 0) {
+ up = up.clone();
+ up = up.negate();
+ }
+ this._computeViewMatrix(this._position, target, up);
+ this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
+ this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
+ this._collisionTriggered = false;
+ };
+ this._target = Vector3.Zero();
+ if (target) {
+ this.setTarget(target);
+ }
+ this.alpha = alpha;
+ this.beta = beta;
+ this.radius = radius;
+ this.getViewMatrix();
+ this.inputs = new ArcRotateCameraInputsManager(this);
+ this.inputs.addKeyboard().addMouseWheel().addPointers();
+ }
+ // Cache
+ /** @internal */
+ _initCache() {
+ super._initCache();
+ this._cache._target = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._cache.alpha = undefined;
+ this._cache.beta = undefined;
+ this._cache.radius = undefined;
+ this._cache.targetScreenOffset = Vector2.Zero();
+ }
+ /**
+ * @internal
+ */
+ _updateCache(ignoreParentClass) {
+ if (!ignoreParentClass) {
+ super._updateCache();
+ }
+ this._cache._target.copyFrom(this._getTargetPosition());
+ this._cache.alpha = this.alpha;
+ this._cache.beta = this.beta;
+ this._cache.radius = this.radius;
+ this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
+ }
+ _getTargetPosition() {
+ if (this._targetHost && this._targetHost.getAbsolutePosition) {
+ const pos = this._targetHost.getAbsolutePosition();
+ if (this._targetBoundingCenter) {
+ pos.addToRef(this._targetBoundingCenter, this._target);
+ }
+ else {
+ this._target.copyFrom(pos);
+ }
+ }
+ const lockedTargetPosition = this._getLockedTargetPosition();
+ if (lockedTargetPosition) {
+ return lockedTargetPosition;
+ }
+ return this._target;
+ }
+ /**
+ * Stores the current state of the camera (alpha, beta, radius and target)
+ * @returns the camera itself
+ */
+ storeState() {
+ this._storedAlpha = this._goalAlpha = this.alpha;
+ this._storedBeta = this._goalBeta = this.beta;
+ this._storedRadius = this._goalRadius = this.radius;
+ this._storedTarget = this._goalTarget = this._getTargetPosition().clone();
+ this._storedTargetScreenOffset = this._goalTargetScreenOffset = this.targetScreenOffset.clone();
+ return super.storeState();
+ }
+ /**
+ * @internal
+ * Restored camera state. You must call storeState() first
+ */
+ _restoreStateValues() {
+ if (this.hasStateStored() && this.restoreStateInterpolationFactor > Epsilon && this.restoreStateInterpolationFactor < 1) {
+ this.interpolateTo(this._storedAlpha, this._storedBeta, this._storedRadius, this._storedTarget, this._storedTargetScreenOffset, this.restoreStateInterpolationFactor);
+ return true;
+ }
+ if (!super._restoreStateValues()) {
+ return false;
+ }
+ this.setTarget(this._storedTarget.clone());
+ this.alpha = this._storedAlpha;
+ this.beta = this._storedBeta;
+ this.radius = this._storedRadius;
+ this.targetScreenOffset = this._storedTargetScreenOffset.clone();
+ this.inertialAlphaOffset = 0;
+ this.inertialBetaOffset = 0;
+ this.inertialRadiusOffset = 0;
+ this.inertialPanningX = 0;
+ this.inertialPanningY = 0;
+ return true;
+ }
+ /**
+ * Interpolates the camera to a goal state.
+ * @param alpha Defines the goal alpha.
+ * @param beta Defines the goal beta.
+ * @param radius Defines the goal radius.
+ * @param target Defines the goal target.
+ * @param targetScreenOffset Defines the goal target screen offset.
+ * @param interpolationFactor A value between 0 and 1 that determines the speed of the interpolation.
+ */
+ interpolateTo(alpha = this.alpha, beta = this.beta, radius = this.radius, target = this.target, targetScreenOffset = this.targetScreenOffset, interpolationFactor) {
+ this._progressiveRestore = true;
+ this.inertialAlphaOffset = 0;
+ this.inertialBetaOffset = 0;
+ this.inertialRadiusOffset = 0;
+ this.inertialPanningX = 0;
+ this.inertialPanningY = 0;
+ if (interpolationFactor != null) {
+ this._currentInterpolationFactor = interpolationFactor;
+ }
+ else if (this.restoreStateInterpolationFactor !== 0) {
+ this._currentInterpolationFactor = this.restoreStateInterpolationFactor;
+ }
+ else {
+ this._currentInterpolationFactor = 0.1;
+ }
+ alpha = Clamp(alpha, this.lowerAlphaLimit ?? -Infinity, this.upperAlphaLimit ?? Infinity);
+ beta = Clamp(beta, this.lowerBetaLimit ?? -Infinity, this.upperBetaLimit ?? Infinity);
+ radius = Clamp(radius, this.lowerRadiusLimit ?? -Infinity, this.upperRadiusLimit ?? Infinity);
+ target.y = Clamp(target.y, this.lowerTargetYLimit ?? -Infinity, Infinity);
+ this._goalAlpha = alpha;
+ this._goalBeta = beta;
+ this._goalRadius = radius;
+ this._goalTarget = target;
+ this._goalTargetScreenOffset = targetScreenOffset;
+ }
+ // Synchronized
+ /** @internal */
+ _isSynchronizedViewMatrix() {
+ if (!super._isSynchronizedViewMatrix()) {
+ return false;
+ }
+ return (this._cache._target.equals(this._getTargetPosition()) &&
+ this._cache.alpha === this.alpha &&
+ this._cache.beta === this.beta &&
+ this._cache.radius === this.radius &&
+ this._cache.targetScreenOffset.equals(this.targetScreenOffset));
+ }
+ /**
+ * Attached controls to the current camera.
+ * @param ignored defines an ignored parameter kept for backward compatibility.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ * @param useCtrlForPanning Defines whether ctrl is used for panning within the controls
+ * @param panningMouseButton Defines whether panning is allowed through mouse click button
+ */
+ attachControl(ignored, noPreventDefault, useCtrlForPanning = true, panningMouseButton = 2) {
+ // eslint-disable-next-line prefer-rest-params
+ const args = arguments;
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(args);
+ this._useCtrlForPanning = useCtrlForPanning;
+ this._panningMouseButton = panningMouseButton;
+ // backwards compatibility
+ if (typeof args[0] === "boolean") {
+ if (args.length > 1) {
+ this._useCtrlForPanning = args[1];
+ }
+ if (args.length > 2) {
+ this._panningMouseButton = args[2];
+ }
+ }
+ this.inputs.attachElement(noPreventDefault);
+ this._reset = () => {
+ this.inertialAlphaOffset = 0;
+ this.inertialBetaOffset = 0;
+ this.inertialRadiusOffset = 0;
+ this.inertialPanningX = 0;
+ this.inertialPanningY = 0;
+ };
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ this.inputs.detachElement();
+ if (this._reset) {
+ this._reset();
+ }
+ }
+ /** @internal */
+ _checkInputs() {
+ //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
+ if (this._collisionTriggered) {
+ return;
+ }
+ this.inputs.checkInputs();
+ // progressive restore
+ if (this._progressiveRestore) {
+ const dt = this._scene.getEngine().getDeltaTime() / 1000;
+ const t = 1 - Math.pow(2, -dt / this._currentInterpolationFactor);
+ // can't use tmp vector here because of assignment
+ this.setTarget(Vector3.Lerp(this.getTarget(), this._goalTarget, t));
+ // Using quaternion for smoother interpolation (and no Euler angles modulo)
+ Quaternion.RotationAlphaBetaGammaToRef(this._goalAlpha, this._goalBeta, 0, TmpVectors.Quaternion[0]);
+ Quaternion.RotationAlphaBetaGammaToRef(this.alpha, this.beta, 0, TmpVectors.Quaternion[1]);
+ Quaternion.SlerpToRef(TmpVectors.Quaternion[1], TmpVectors.Quaternion[0], t, TmpVectors.Quaternion[2]);
+ TmpVectors.Quaternion[2].normalize();
+ TmpVectors.Quaternion[2].toAlphaBetaGammaToRef(TmpVectors.Vector3[0]);
+ this.alpha = TmpVectors.Vector3[0].x;
+ this.beta = TmpVectors.Vector3[0].y;
+ this.radius += (this._goalRadius - this.radius) * t;
+ Vector2.LerpToRef(this.targetScreenOffset, this._goalTargetScreenOffset, t, this.targetScreenOffset);
+ // stop restoring when within close range or when user starts interacting
+ if ((Vector3.DistanceSquared(this.getTarget(), this._goalTarget) < Epsilon &&
+ TmpVectors.Quaternion[2].isApprox(TmpVectors.Quaternion[0]) &&
+ Math.pow(this._goalRadius - this.radius, 2) < Epsilon &&
+ Vector2.Distance(this.targetScreenOffset, this._goalTargetScreenOffset) < Epsilon) ||
+ this.inertialAlphaOffset !== 0 ||
+ this.inertialBetaOffset !== 0 ||
+ this.inertialRadiusOffset !== 0 ||
+ this.inertialPanningX !== 0 ||
+ this.inertialPanningY !== 0) {
+ this._progressiveRestore = false;
+ }
+ }
+ // Inertia
+ if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
+ const directionModifier = this.invertRotation ? -1 : 1;
+ const handednessMultiplier = this._calculateHandednessMultiplier();
+ let inertialAlphaOffset = this.inertialAlphaOffset * handednessMultiplier;
+ if (this.beta < 0) {
+ inertialAlphaOffset *= -1;
+ }
+ this.alpha += inertialAlphaOffset * directionModifier;
+ this.beta += this.inertialBetaOffset * directionModifier;
+ this.radius -= this.inertialRadiusOffset;
+ this.inertialAlphaOffset *= this.inertia;
+ this.inertialBetaOffset *= this.inertia;
+ this.inertialRadiusOffset *= this.inertia;
+ if (Math.abs(this.inertialAlphaOffset) < Epsilon) {
+ this.inertialAlphaOffset = 0;
+ }
+ if (Math.abs(this.inertialBetaOffset) < Epsilon) {
+ this.inertialBetaOffset = 0;
+ }
+ if (Math.abs(this.inertialRadiusOffset) < this.speed * Epsilon) {
+ this.inertialRadiusOffset = 0;
+ }
+ }
+ // Panning inertia
+ if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
+ const localDirection = new Vector3(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
+ this._viewMatrix.invertToRef(this._cameraTransformMatrix);
+ localDirection.multiplyInPlace(this.panningAxis);
+ Vector3.TransformNormalToRef(localDirection, this._cameraTransformMatrix, this._transformedDirection);
+ // If mapPanning is enabled, we need to take the upVector into account and
+ // make sure we're not panning in the y direction
+ if (this.mapPanning) {
+ const up = this.upVector;
+ const right = Vector3.CrossToRef(this._transformedDirection, up, this._transformedDirection);
+ Vector3.CrossToRef(up, right, this._transformedDirection);
+ }
+ else if (!this.panningAxis.y) {
+ this._transformedDirection.y = 0;
+ }
+ if (!this._targetHost) {
+ if (this.panningDistanceLimit) {
+ this._transformedDirection.addInPlace(this._target);
+ const distanceSquared = Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
+ if (distanceSquared <= this.panningDistanceLimit * this.panningDistanceLimit) {
+ this._target.copyFrom(this._transformedDirection);
+ }
+ }
+ else {
+ if (this.parent) {
+ const m = TmpVectors.Matrix[0];
+ this.parent.getWorldMatrix().getRotationMatrixToRef(m);
+ m.transposeToRef(m);
+ Vector3.TransformCoordinatesToRef(this._transformedDirection, m, this._transformedDirection);
+ }
+ this._target.addInPlace(this._transformedDirection);
+ }
+ }
+ this.inertialPanningX *= this.panningInertia;
+ this.inertialPanningY *= this.panningInertia;
+ if (Math.abs(this.inertialPanningX) < this.speed * Epsilon) {
+ this.inertialPanningX = 0;
+ }
+ if (Math.abs(this.inertialPanningY) < this.speed * Epsilon) {
+ this.inertialPanningY = 0;
+ }
+ }
+ // Limits
+ this._checkLimits();
+ super._checkInputs();
+ }
+ _checkLimits() {
+ if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
+ if (this.allowUpsideDown && this.beta > Math.PI) {
+ this.beta = this.beta - 2 * Math.PI;
+ }
+ }
+ else {
+ if (this.beta < this.lowerBetaLimit) {
+ this.beta = this.lowerBetaLimit;
+ }
+ }
+ if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
+ if (this.allowUpsideDown && this.beta < -Math.PI) {
+ this.beta = this.beta + 2 * Math.PI;
+ }
+ }
+ else {
+ if (this.beta > this.upperBetaLimit) {
+ this.beta = this.upperBetaLimit;
+ }
+ }
+ if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
+ this.alpha = this.lowerAlphaLimit;
+ }
+ if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
+ this.alpha = this.upperAlphaLimit;
+ }
+ if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
+ this.radius = this.lowerRadiusLimit;
+ this.inertialRadiusOffset = 0;
+ }
+ if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
+ this.radius = this.upperRadiusLimit;
+ this.inertialRadiusOffset = 0;
+ }
+ this.target.y = Math.max(this.target.y, this.lowerTargetYLimit);
+ }
+ /**
+ * Rebuilds angles (alpha, beta) and radius from the give position and target
+ */
+ rebuildAnglesAndRadius() {
+ this._position.subtractToRef(this._getTargetPosition(), this._computationVector);
+ // need to rotate to Y up equivalent if up vector not Axis.Y
+ if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) {
+ Vector3.TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector);
+ }
+ this.radius = this._computationVector.length();
+ if (this.radius === 0) {
+ this.radius = 0.0001; // Just to avoid division by zero
+ }
+ // Alpha and Beta
+ const previousAlpha = this.alpha;
+ this.alpha = ComputeAlpha(this._computationVector);
+ this.beta = ComputeBeta(this._computationVector.y, this.radius);
+ // Calculate the number of revolutions between the new and old alpha values.
+ const alphaCorrectionTurns = Math.round((previousAlpha - this.alpha) / (2.0 * Math.PI));
+ // Adjust alpha so that its numerical representation is the closest one to the old value.
+ this.alpha += alphaCorrectionTurns * 2.0 * Math.PI;
+ this._checkLimits();
+ }
+ /**
+ * Use a position to define the current camera related information like alpha, beta and radius
+ * @param position Defines the position to set the camera at
+ */
+ setPosition(position) {
+ if (this._position.equals(position)) {
+ return;
+ }
+ this._position.copyFrom(position);
+ this.rebuildAnglesAndRadius();
+ }
+ /**
+ * Defines the target the camera should look at.
+ * This will automatically adapt alpha beta and radius to fit within the new target.
+ * Please note that setting a target as a mesh will disable panning.
+ * @param target Defines the new target as a Vector or a transform node
+ * @param toBoundingCenter In case of a mesh target, defines whether to target the mesh position or its bounding information center
+ * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
+ * @param cloneAlphaBetaRadius If true, replicate the current setup (alpha, beta, radius) on the new target
+ */
+ setTarget(target, toBoundingCenter = false, allowSamePosition = false, cloneAlphaBetaRadius = false) {
+ cloneAlphaBetaRadius = this.overrideCloneAlphaBetaRadius ?? cloneAlphaBetaRadius;
+ if (target.computeWorldMatrix) {
+ if (toBoundingCenter && target.getBoundingInfo) {
+ this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
+ }
+ else {
+ this._targetBoundingCenter = null;
+ }
+ target.computeWorldMatrix();
+ this._targetHost = target;
+ this._target = this._getTargetPosition();
+ this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
+ }
+ else {
+ const newTarget = target;
+ const currentTarget = this._getTargetPosition();
+ if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
+ return;
+ }
+ this._targetHost = null;
+ this._target = newTarget;
+ this._targetBoundingCenter = null;
+ this.onMeshTargetChangedObservable.notifyObservers(null);
+ }
+ if (!cloneAlphaBetaRadius) {
+ this.rebuildAnglesAndRadius();
+ }
+ }
+ /** @internal */
+ _getViewMatrix() {
+ // Compute
+ const cosa = Math.cos(this.alpha);
+ const sina = Math.sin(this.alpha);
+ const cosb = Math.cos(this.beta);
+ let sinb = Math.sin(this.beta);
+ if (sinb === 0) {
+ sinb = 0.0001;
+ }
+ if (this.radius === 0) {
+ this.radius = 0.0001; // Just to avoid division by zero
+ }
+ const target = this._getTargetPosition();
+ this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
+ // Rotate according to up vector
+ if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) {
+ Vector3.TransformCoordinatesToRef(this._computationVector, this._yToUpMatrix, this._computationVector);
+ }
+ target.addToRef(this._computationVector, this._newPosition);
+ if (this.getScene().collisionsEnabled && this.checkCollisions) {
+ const coordinator = this.getScene().collisionCoordinator;
+ if (!this._collider) {
+ this._collider = coordinator.createCollider();
+ }
+ this._collider._radius = this.collisionRadius;
+ this._newPosition.subtractToRef(this._position, this._collisionVelocity);
+ this._collisionTriggered = true;
+ coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
+ }
+ else {
+ this._position.copyFrom(this._newPosition);
+ let up = this.upVector;
+ if (this.allowUpsideDown && sinb < 0) {
+ up = up.negate();
+ }
+ this._computeViewMatrix(this._position, target, up);
+ this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
+ this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
+ }
+ this._currentTarget = target;
+ return this._viewMatrix;
+ }
+ /**
+ * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
+ * @param meshes Defines the mesh to zoom on
+ * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
+ */
+ zoomOn(meshes, doNotUpdateMaxZ = false) {
+ meshes = meshes || this.getScene().meshes;
+ const minMaxVector = Mesh.MinMax(meshes);
+ let distance = this._calculateLowerRadiusFromModelBoundingSphere(minMaxVector.min, minMaxVector.max);
+ // If there are defined limits, we need to take them into account
+ distance = Math.max(Math.min(distance, this.upperRadiusLimit || Number.MAX_VALUE), this.lowerRadiusLimit || 0);
+ this.radius = distance * this.zoomOnFactor;
+ this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
+ }
+ /**
+ * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
+ * The target will be changed but the radius
+ * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
+ * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
+ */
+ focusOn(meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ = false) {
+ let meshesOrMinMaxVector;
+ let distance;
+ if (meshesOrMinMaxVectorAndDistance.min === undefined) {
+ // meshes
+ const meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
+ meshesOrMinMaxVector = Mesh.MinMax(meshes);
+ distance = Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
+ }
+ else {
+ //minMaxVector and distance
+ const minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
+ meshesOrMinMaxVector = minMaxVectorAndDistance;
+ distance = minMaxVectorAndDistance.distance;
+ }
+ this._target = Mesh.Center(meshesOrMinMaxVector);
+ if (!doNotUpdateMaxZ) {
+ this.maxZ = distance * 2;
+ }
+ }
+ /**
+ * @override
+ * Override Camera.createRigCamera
+ * @param name the name of the camera
+ * @param cameraIndex the index of the camera in the rig cameras array
+ */
+ createRigCamera(name, cameraIndex) {
+ let alphaShift = 0;
+ switch (this.cameraRigMode) {
+ case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
+ case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
+ case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
+ case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:
+ case Camera.RIG_MODE_VR:
+ alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
+ break;
+ case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
+ alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
+ break;
+ }
+ const rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
+ rigCam._cameraRigParams = {};
+ rigCam.isRigCamera = true;
+ rigCam.rigParent = this;
+ rigCam.upVector = this.upVector;
+ rigCam.mode = this.mode;
+ rigCam.orthoLeft = this.orthoLeft;
+ rigCam.orthoRight = this.orthoRight;
+ rigCam.orthoBottom = this.orthoBottom;
+ rigCam.orthoTop = this.orthoTop;
+ return rigCam;
+ }
+ /**
+ * @internal
+ * @override
+ * Override Camera._updateRigCameras
+ */
+ _updateRigCameras() {
+ const camLeft = this._rigCameras[0];
+ const camRight = this._rigCameras[1];
+ camLeft.beta = camRight.beta = this.beta;
+ switch (this.cameraRigMode) {
+ case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
+ case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
+ case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
+ case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:
+ case Camera.RIG_MODE_VR:
+ camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
+ camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
+ break;
+ case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
+ camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
+ camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
+ break;
+ }
+ super._updateRigCameras();
+ }
+ /**
+ * @internal
+ */
+ _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld, radiusScale = 1) {
+ const boxVectorGlobalDiagonal = Vector3.Distance(minimumWorld, maximumWorld);
+ // Get aspect ratio in order to calculate frustum slope
+ const engine = this.getScene().getEngine();
+ const aspectRatio = engine.getAspectRatio(this);
+ const frustumSlopeY = Math.tan(this.fov / 2);
+ const frustumSlopeX = frustumSlopeY * aspectRatio;
+ // Formula for setting distance
+ // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
+ const radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
+ // Horizon distance
+ const radius = radiusWithoutFraming * radiusScale;
+ const distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlopeX * frustumSlopeX));
+ const distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlopeY * frustumSlopeY));
+ return Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
+ }
+ /**
+ * Destroy the camera and release the current resources hold by it.
+ */
+ dispose() {
+ this.inputs.clear();
+ super.dispose();
+ }
+ /**
+ * Gets the current object class name.
+ * @returns the class name
+ */
+ getClassName() {
+ return "ArcRotateCamera";
+ }
+}
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "alpha", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "beta", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "radius", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "overrideCloneAlphaBetaRadius", void 0);
+__decorate([
+ serializeAsVector3("target")
+], ArcRotateCamera.prototype, "_target", void 0);
+__decorate([
+ serializeAsMeshReference("targetHost")
+], ArcRotateCamera.prototype, "_targetHost", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "lowerTargetYLimit", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "inertialPanningX", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "inertialPanningY", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
+__decorate([
+ serializeAsVector3()
+], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "panningInertia", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "zoomToMouseLocation", null);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
+__decorate([
+ serializeAsVector2()
+], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
+__decorate([
+ serialize()
+], ArcRotateCamera.prototype, "restoreStateInterpolationFactor", void 0);
+// Register Class Name
+RegisterClass("BABYLON.ArcRotateCamera", ArcRotateCamera);
+
+class AppCamera extends Monobehiver {
+ object;
+ constructor(mainApp) {
+ super(mainApp);
+ this.object = null;
+ }
+ /** 初始化相机 */
+ Awake() {
+ const scene = this.mainApp.appScene.object;
+ const canvas = AppConfig.container;
+ if (!scene || !canvas) return;
+ this.object = new ArcRotateCamera("Camera", Tools.ToRadians(70), Tools.ToRadians(85), 5, new Vector3(0, 2, 0), scene);
+ this.object.attachControl(canvas, true);
+ this.object.minZ = 0.01;
+ this.object.panningSensibility = 0;
+ this.object.position = new Vector3(-0, 100, 0);
+ this.setTarget(0, 2, 0);
+ }
+ /** 设置相机目标点 */
+ setTarget(x, y, z) {
+ if (this.object) {
+ this.object.target = new Vector3(x, y, z);
+ }
+ }
+ /** 重置相机到默认位置 */
+ reset() {
+ if (!this.object) return;
+ this.object.radius = 5;
+ this.object.alpha = Tools.ToRadians(60);
+ this.object.beta = Tools.ToRadians(60);
+ this.setTarget(0, 2, 0);
+ this.object.position = new Vector3(-0, 100, 0);
+ }
+ update() {
+ }
+}
+
+/**
+ * Base class of all the lights in Babylon. It groups all the generic information about lights.
+ * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
+ * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
+ */
+class Light extends Node$2 {
+ /**
+ * Defines how far from the source the light is impacting in scene units.
+ * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
+ */
+ get range() {
+ return this._range;
+ }
+ /**
+ * Defines how far from the source the light is impacting in scene units.
+ * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
+ */
+ set range(value) {
+ this._range = value;
+ this._inverseSquaredRange = 1.0 / (this.range * this.range);
+ }
+ /**
+ * Gets the photometric scale used to interpret the intensity.
+ * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
+ */
+ get intensityMode() {
+ return this._intensityMode;
+ }
+ /**
+ * Sets the photometric scale used to interpret the intensity.
+ * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
+ */
+ set intensityMode(value) {
+ this._intensityMode = value;
+ this._computePhotometricScale();
+ }
+ /**
+ * Gets the light radius used by PBR Materials to simulate soft area lights.
+ */
+ get radius() {
+ return this._radius;
+ }
+ /**
+ * sets the light radius used by PBR Materials to simulate soft area lights.
+ */
+ set radius(value) {
+ this._radius = value;
+ this._computePhotometricScale();
+ }
+ /**
+ * Gets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
+ * the current shadow generator.
+ */
+ get shadowEnabled() {
+ return this._shadowEnabled;
+ }
+ /**
+ * Sets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
+ * the current shadow generator.
+ */
+ set shadowEnabled(value) {
+ if (this._shadowEnabled === value) {
+ return;
+ }
+ this._shadowEnabled = value;
+ this._markMeshesAsLightDirty();
+ }
+ /**
+ * Gets the only meshes impacted by this light.
+ */
+ get includedOnlyMeshes() {
+ return this._includedOnlyMeshes;
+ }
+ /**
+ * Sets the only meshes impacted by this light.
+ */
+ set includedOnlyMeshes(value) {
+ this._includedOnlyMeshes = value;
+ this._hookArrayForIncludedOnly(value);
+ }
+ /**
+ * Gets the meshes not impacted by this light.
+ */
+ get excludedMeshes() {
+ return this._excludedMeshes;
+ }
+ /**
+ * Sets the meshes not impacted by this light.
+ */
+ set excludedMeshes(value) {
+ this._excludedMeshes = value;
+ this._hookArrayForExcluded(value);
+ }
+ /**
+ * Gets the layer id use to find what meshes are not impacted by the light.
+ * Inactive if 0
+ */
+ get excludeWithLayerMask() {
+ return this._excludeWithLayerMask;
+ }
+ /**
+ * Sets the layer id use to find what meshes are not impacted by the light.
+ * Inactive if 0
+ */
+ set excludeWithLayerMask(value) {
+ this._excludeWithLayerMask = value;
+ this._resyncMeshes();
+ }
+ /**
+ * Gets the layer id use to find what meshes are impacted by the light.
+ * Inactive if 0
+ */
+ get includeOnlyWithLayerMask() {
+ return this._includeOnlyWithLayerMask;
+ }
+ /**
+ * Sets the layer id use to find what meshes are impacted by the light.
+ * Inactive if 0
+ */
+ set includeOnlyWithLayerMask(value) {
+ this._includeOnlyWithLayerMask = value;
+ this._resyncMeshes();
+ }
+ /**
+ * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
+ */
+ get lightmapMode() {
+ return this._lightmapMode;
+ }
+ /**
+ * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
+ */
+ set lightmapMode(value) {
+ if (this._lightmapMode === value) {
+ return;
+ }
+ this._lightmapMode = value;
+ this._markMeshesAsLightDirty();
+ }
+ /**
+ * Returns the view matrix.
+ * @param _faceIndex The index of the face for which we want to extract the view matrix. Only used for point light types.
+ * @returns The view matrix. Can be null, if a view matrix cannot be defined for the type of light considered (as for a hemispherical light, for example).
+ */
+ getViewMatrix(_faceIndex) {
+ return null;
+ }
+ /**
+ * Returns the projection matrix.
+ * Note that viewMatrix and renderList are optional and are only used by lights that calculate the projection matrix from a list of meshes (e.g. directional lights with automatic extents calculation).
+ * @param _viewMatrix The view transform matrix of the light (optional).
+ * @param _renderList The list of meshes to take into account when calculating the projection matrix (optional).
+ * @returns The projection matrix. Can be null, if a projection matrix cannot be defined for the type of light considered (as for a hemispherical light, for example).
+ */
+ getProjectionMatrix(_viewMatrix, _renderList) {
+ return null;
+ }
+ /**
+ * Creates a Light object in the scene.
+ * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ * @param name The friendly name of the light
+ * @param scene The scene the light belongs too
+ */
+ constructor(name, scene) {
+ super(name, scene, false);
+ /**
+ * Diffuse gives the basic color to an object.
+ */
+ this.diffuse = new Color3(1.0, 1.0, 1.0);
+ /**
+ * Specular produces a highlight color on an object.
+ * Note: This is not affecting PBR materials.
+ */
+ this.specular = new Color3(1.0, 1.0, 1.0);
+ /**
+ * Defines the falloff type for this light. This lets overriding how punctual light are
+ * falling off base on range or angle.
+ * This can be set to any values in Light.FALLOFF_x.
+ *
+ * Note: This is only useful for PBR Materials at the moment. This could be extended if required to
+ * other types of materials.
+ */
+ this.falloffType = Light.FALLOFF_DEFAULT;
+ /**
+ * Strength of the light.
+ * Note: By default it is define in the framework own unit.
+ * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
+ */
+ this.intensity = 1.0;
+ this._range = Number.MAX_VALUE;
+ this._inverseSquaredRange = 0;
+ /**
+ * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
+ * of light.
+ */
+ this._photometricScale = 1.0;
+ this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
+ this._radius = 0.00001;
+ /**
+ * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
+ * exceeding the number allowed of the materials.
+ */
+ this.renderPriority = 0;
+ this._shadowEnabled = true;
+ this._excludeWithLayerMask = 0;
+ this._includeOnlyWithLayerMask = 0;
+ this._lightmapMode = 0;
+ /**
+ * Shadow generators associated to the light.
+ * @internal Internal use only.
+ */
+ this._shadowGenerators = null;
+ /**
+ * @internal Internal use only.
+ */
+ this._excludedMeshesIds = new Array();
+ /**
+ * @internal Internal use only.
+ */
+ this._includedOnlyMeshesIds = new Array();
+ /** @internal */
+ this._isLight = true;
+ this.getScene().addLight(this);
+ this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name);
+ this._buildUniformLayout();
+ this.includedOnlyMeshes = [];
+ this.excludedMeshes = [];
+ this._resyncMeshes();
+ }
+ /**
+ * Sets the passed Effect "effect" with the Light textures.
+ * @param effect The effect to update
+ * @param lightIndex The index of the light in the effect to update
+ * @returns The light
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ transferTexturesToEffect(effect, lightIndex) {
+ // Do nothing by default.
+ return this;
+ }
+ /**
+ * Binds the lights information from the scene to the effect for the given mesh.
+ * @param lightIndex Light index
+ * @param scene The scene where the light belongs to
+ * @param effect The effect we are binding the data to
+ * @param useSpecular Defines if specular is supported
+ * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows
+ */
+ _bindLight(lightIndex, scene, effect, useSpecular, receiveShadows = true) {
+ const iAsString = lightIndex.toString();
+ let needUpdate = false;
+ this._uniformBuffer.bindToEffect(effect, "Light" + iAsString);
+ if (this._renderId !== scene.getRenderId() || this._lastUseSpecular !== useSpecular || !this._uniformBuffer.useUbo) {
+ this._renderId = scene.getRenderId();
+ this._lastUseSpecular = useSpecular;
+ const scaledIntensity = this.getScaledIntensity();
+ this.transferToEffect(effect, iAsString);
+ this.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]);
+ this._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], this.range, iAsString);
+ if (useSpecular) {
+ this.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]);
+ this._uniformBuffer.updateColor4("vLightSpecular", TmpColors.Color3[1], this.radius, iAsString);
+ }
+ needUpdate = true;
+ }
+ // Textures might still need to be rebound.
+ this.transferTexturesToEffect(effect, iAsString);
+ // Shadows
+ if (scene.shadowsEnabled && this.shadowEnabled && receiveShadows) {
+ const shadowGenerator = this.getShadowGenerator(scene.activeCamera) ?? this.getShadowGenerator();
+ if (shadowGenerator) {
+ shadowGenerator.bindShadowLight(iAsString, effect);
+ needUpdate = true;
+ }
+ }
+ if (needUpdate) {
+ this._uniformBuffer.update();
+ }
+ else {
+ this._uniformBuffer.bindUniformBuffer();
+ }
+ }
+ /**
+ * Returns the string "Light".
+ * @returns the class name
+ */
+ getClassName() {
+ return "Light";
+ }
+ /**
+ * Converts the light information to a readable string for debug purpose.
+ * @param fullDetails Supports for multiple levels of logging within scene loading
+ * @returns the human readable light info
+ */
+ toString(fullDetails) {
+ let ret = "Name: " + this.name;
+ ret += ", type: " + ["Point", "Directional", "Spot", "Hemispheric"][this.getTypeID()];
+ if (this.animations) {
+ for (let i = 0; i < this.animations.length; i++) {
+ ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
+ }
+ }
+ return ret;
+ }
+ /** @internal */
+ _syncParentEnabledState() {
+ super._syncParentEnabledState();
+ if (!this.isDisposed()) {
+ this._resyncMeshes();
+ }
+ }
+ /**
+ * Set the enabled state of this node.
+ * @param value - the new enabled state
+ */
+ setEnabled(value) {
+ super.setEnabled(value);
+ this._resyncMeshes();
+ }
+ /**
+ * Returns the Light associated shadow generator if any.
+ * @param camera Camera for which the shadow generator should be retrieved (default: null). If null, retrieves the default shadow generator
+ * @returns the associated shadow generator.
+ */
+ getShadowGenerator(camera = null) {
+ if (this._shadowGenerators === null) {
+ return null;
+ }
+ return this._shadowGenerators.get(camera) ?? null;
+ }
+ /**
+ * Returns all the shadow generators associated to this light
+ * @returns
+ */
+ getShadowGenerators() {
+ return this._shadowGenerators;
+ }
+ /**
+ * Returns a Vector3, the absolute light position in the World.
+ * @returns the world space position of the light
+ */
+ getAbsolutePosition() {
+ return Vector3.Zero();
+ }
+ /**
+ * Specifies if the light will affect the passed mesh.
+ * @param mesh The mesh to test against the light
+ * @returns true the mesh is affected otherwise, false.
+ */
+ canAffectMesh(mesh) {
+ if (!mesh) {
+ return true;
+ }
+ if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
+ return false;
+ }
+ if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
+ return false;
+ }
+ if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
+ return false;
+ }
+ if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Releases resources associated with this node.
+ * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
+ * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
+ */
+ dispose(doNotRecurse, disposeMaterialAndTextures = false) {
+ if (this._shadowGenerators) {
+ const iterator = this._shadowGenerators.values();
+ for (let key = iterator.next(); key.done !== true; key = iterator.next()) {
+ const shadowGenerator = key.value;
+ shadowGenerator.dispose();
+ }
+ this._shadowGenerators = null;
+ }
+ // Animations
+ this.getScene().stopAnimation(this);
+ if (this._parentContainer) {
+ const index = this._parentContainer.lights.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.lights.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ // Remove from meshes
+ for (const mesh of this.getScene().meshes) {
+ mesh._removeLightSource(this, true);
+ }
+ this._uniformBuffer.dispose();
+ // Remove from scene
+ this.getScene().removeLight(this);
+ super.dispose(doNotRecurse, disposeMaterialAndTextures);
+ }
+ /**
+ * Returns the light type ID (integer).
+ * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
+ */
+ getTypeID() {
+ return 0;
+ }
+ /**
+ * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
+ * @returns the scaled intensity in intensity mode unit
+ */
+ getScaledIntensity() {
+ return this._photometricScale * this.intensity;
+ }
+ /**
+ * Returns a new Light object, named "name", from the current one.
+ * @param name The name of the cloned light
+ * @param newParent The parent of this light, if it has one
+ * @returns the new created light
+ */
+ clone(name, newParent = null) {
+ const constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
+ if (!constructor) {
+ return null;
+ }
+ const clonedLight = SerializationHelper.Clone(constructor, this);
+ if (name) {
+ clonedLight.name = name;
+ }
+ if (newParent) {
+ clonedLight.parent = newParent;
+ }
+ clonedLight.setEnabled(this.isEnabled());
+ this.onClonedObservable.notifyObservers(clonedLight);
+ return clonedLight;
+ }
+ /**
+ * Serializes the current light into a Serialization object.
+ * @returns the serialized object.
+ */
+ serialize() {
+ const serializationObject = SerializationHelper.Serialize(this);
+ serializationObject.uniqueId = this.uniqueId;
+ // Type
+ serializationObject.type = this.getTypeID();
+ // Parent
+ if (this.parent) {
+ this.parent._serializeAsParent(serializationObject);
+ }
+ // Inclusion / exclusions
+ if (this.excludedMeshes.length > 0) {
+ serializationObject.excludedMeshesIds = [];
+ this.excludedMeshes.forEach((mesh) => {
+ serializationObject.excludedMeshesIds.push(mesh.id);
+ });
+ }
+ if (this.includedOnlyMeshes.length > 0) {
+ serializationObject.includedOnlyMeshesIds = [];
+ this.includedOnlyMeshes.forEach((mesh) => {
+ serializationObject.includedOnlyMeshesIds.push(mesh.id);
+ });
+ }
+ // Animations
+ SerializationHelper.AppendSerializedAnimations(this, serializationObject);
+ serializationObject.ranges = this.serializeAnimationRanges();
+ serializationObject.isEnabled = this.isEnabled();
+ return serializationObject;
+ }
+ /**
+ * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
+ * This new light is named "name" and added to the passed scene.
+ * @param type Type according to the types available in Light.LIGHTTYPEID_x
+ * @param name The friendly name of the light
+ * @param scene The scene the new light will belong to
+ * @returns the constructor function
+ */
+ static GetConstructorFromName(type, name, scene) {
+ const constructorFunc = Node$2.Construct("Light_Type_" + type, name, scene);
+ if (constructorFunc) {
+ return constructorFunc;
+ }
+ // Default to no light for none present once.
+ return null;
+ }
+ /**
+ * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
+ * @param parsedLight The JSON representation of the light
+ * @param scene The scene to create the parsed light in
+ * @returns the created light after parsing
+ */
+ static Parse(parsedLight, scene) {
+ const constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
+ if (!constructor) {
+ return null;
+ }
+ const light = SerializationHelper.Parse(constructor, parsedLight, scene);
+ // Inclusion / exclusions
+ if (parsedLight.excludedMeshesIds) {
+ light._excludedMeshesIds = parsedLight.excludedMeshesIds;
+ }
+ if (parsedLight.includedOnlyMeshesIds) {
+ light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
+ }
+ // Parent
+ if (parsedLight.parentId !== undefined) {
+ light._waitingParentId = parsedLight.parentId;
+ }
+ if (parsedLight.parentInstanceIndex !== undefined) {
+ light._waitingParentInstanceIndex = parsedLight.parentInstanceIndex;
+ }
+ // Falloff
+ if (parsedLight.falloffType !== undefined) {
+ light.falloffType = parsedLight.falloffType;
+ }
+ // Lightmaps
+ if (parsedLight.lightmapMode !== undefined) {
+ light.lightmapMode = parsedLight.lightmapMode;
+ }
+ // Animations
+ if (parsedLight.animations) {
+ for (let animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
+ const parsedAnimation = parsedLight.animations[animationIndex];
+ const internalClass = GetClass("BABYLON.Animation");
+ if (internalClass) {
+ light.animations.push(internalClass.Parse(parsedAnimation));
+ }
+ }
+ Node$2.ParseAnimationRanges(light, parsedLight, scene);
+ }
+ if (parsedLight.autoAnimate) {
+ scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
+ }
+ // Check if isEnabled is defined to be back compatible with prior serialized versions.
+ if (parsedLight.isEnabled !== undefined) {
+ light.setEnabled(parsedLight.isEnabled);
+ }
+ return light;
+ }
+ _hookArrayForExcluded(array) {
+ const oldPush = array.push;
+ array.push = (...items) => {
+ const result = oldPush.apply(array, items);
+ for (const item of items) {
+ item._resyncLightSource(this);
+ }
+ return result;
+ };
+ const oldSplice = array.splice;
+ array.splice = (index, deleteCount) => {
+ const deleted = oldSplice.apply(array, [index, deleteCount]);
+ for (const item of deleted) {
+ item._resyncLightSource(this);
+ }
+ return deleted;
+ };
+ for (const item of array) {
+ item._resyncLightSource(this);
+ }
+ }
+ _hookArrayForIncludedOnly(array) {
+ const oldPush = array.push;
+ array.push = (...items) => {
+ const result = oldPush.apply(array, items);
+ this._resyncMeshes();
+ return result;
+ };
+ const oldSplice = array.splice;
+ array.splice = (index, deleteCount) => {
+ const deleted = oldSplice.apply(array, [index, deleteCount]);
+ this._resyncMeshes();
+ return deleted;
+ };
+ this._resyncMeshes();
+ }
+ _resyncMeshes() {
+ for (const mesh of this.getScene().meshes) {
+ mesh._resyncLightSource(this);
+ }
+ }
+ /**
+ * Forces the meshes to update their light related information in their rendering used effects
+ * @internal Internal Use Only
+ */
+ _markMeshesAsLightDirty() {
+ for (const mesh of this.getScene().meshes) {
+ if (mesh.lightSources.indexOf(this) !== -1) {
+ mesh._markSubMeshesAsLightDirty();
+ }
+ }
+ }
+ /**
+ * Recomputes the cached photometric scale if needed.
+ */
+ _computePhotometricScale() {
+ this._photometricScale = this._getPhotometricScale();
+ this.getScene().resetCachedMaterial();
+ }
+ /**
+ * @returns the Photometric Scale according to the light type and intensity mode.
+ */
+ _getPhotometricScale() {
+ let photometricScale = 0.0;
+ const lightTypeID = this.getTypeID();
+ //get photometric mode
+ let photometricMode = this.intensityMode;
+ if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
+ if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
+ photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
+ }
+ else {
+ photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
+ }
+ }
+ //compute photometric scale
+ switch (lightTypeID) {
+ case Light.LIGHTTYPEID_POINTLIGHT:
+ case Light.LIGHTTYPEID_SPOTLIGHT:
+ switch (photometricMode) {
+ case Light.INTENSITYMODE_LUMINOUSPOWER:
+ photometricScale = 1.0 / (4.0 * Math.PI);
+ break;
+ case Light.INTENSITYMODE_LUMINOUSINTENSITY:
+ photometricScale = 1.0;
+ break;
+ case Light.INTENSITYMODE_LUMINANCE:
+ photometricScale = this.radius * this.radius;
+ break;
+ }
+ break;
+ case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
+ switch (photometricMode) {
+ case Light.INTENSITYMODE_ILLUMINANCE:
+ photometricScale = 1.0;
+ break;
+ case Light.INTENSITYMODE_LUMINANCE: {
+ // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
+ // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
+ let apexAngleRadians = this.radius;
+ // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
+ apexAngleRadians = Math.max(apexAngleRadians, 0.001);
+ const solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
+ photometricScale = solidAngle;
+ break;
+ }
+ }
+ break;
+ case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
+ // No fall off in hemispheric light.
+ photometricScale = 1.0;
+ break;
+ }
+ return photometricScale;
+ }
+ /**
+ * Reorder the light in the scene according to their defined priority.
+ * @internal Internal Use Only
+ */
+ _reorderLightsInScene() {
+ const scene = this.getScene();
+ if (this._renderPriority != 0) {
+ scene.requireLightSorting = true;
+ }
+ this.getScene().sortLightsByPriority();
+ }
+ /**
+ * @internal
+ */
+ _isReady() {
+ return true;
+ }
+}
+/**
+ * Falloff Default: light is falling off following the material specification:
+ * standard material is using standard falloff whereas pbr material can request special falloff per materials.
+ */
+Light.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT;
+/**
+ * Falloff Physical: light is falling off following the inverse squared distance law.
+ */
+Light.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL;
+/**
+ * Falloff gltf: light is falling off as described in the gltf moving to PBR document
+ * to enhance interoperability with other engines.
+ */
+Light.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF;
+/**
+ * Falloff Standard: light is falling off like in the standard material
+ * to enhance interoperability with other materials.
+ */
+Light.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD;
+//lightmapMode Consts
+/**
+ * If every light affecting the material is in this lightmapMode,
+ * material.lightmapTexture adds or multiplies
+ * (depends on material.useLightmapAsShadowmap)
+ * after every other light calculations.
+ */
+Light.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT;
+/**
+ * material.lightmapTexture as only diffuse lighting from this light
+ * adds only specular lighting from this light
+ * adds dynamic shadows
+ */
+Light.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR;
+/**
+ * material.lightmapTexture as only lighting
+ * no light calculation from this light
+ * only adds dynamic shadows from this light
+ */
+Light.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY;
+// Intensity Mode Consts
+/**
+ * Each light type uses the default quantity according to its type:
+ * point/spot lights use luminous intensity
+ * directional lights use illuminance
+ */
+Light.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC;
+/**
+ * lumen (lm)
+ */
+Light.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER;
+/**
+ * candela (lm/sr)
+ */
+Light.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY;
+/**
+ * lux (lm/m^2)
+ */
+Light.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE;
+/**
+ * nit (cd/m^2)
+ */
+Light.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE;
+// Light types ids const.
+/**
+ * Light type const id of the point light.
+ */
+Light.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT;
+/**
+ * Light type const id of the directional light.
+ */
+Light.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT;
+/**
+ * Light type const id of the spot light.
+ */
+Light.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT;
+/**
+ * Light type const id of the hemispheric light.
+ */
+Light.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT;
+/**
+ * Light type const id of the area light.
+ */
+Light.LIGHTTYPEID_RECT_AREALIGHT = LightConstants.LIGHTTYPEID_RECT_AREALIGHT;
+__decorate([
+ serializeAsColor3()
+], Light.prototype, "diffuse", void 0);
+__decorate([
+ serializeAsColor3()
+], Light.prototype, "specular", void 0);
+__decorate([
+ serialize()
+], Light.prototype, "falloffType", void 0);
+__decorate([
+ serialize()
+], Light.prototype, "intensity", void 0);
+__decorate([
+ serialize()
+], Light.prototype, "range", null);
+__decorate([
+ serialize()
+], Light.prototype, "intensityMode", null);
+__decorate([
+ serialize()
+], Light.prototype, "radius", null);
+__decorate([
+ serialize()
+], Light.prototype, "_renderPriority", void 0);
+__decorate([
+ expandToProperty("_reorderLightsInScene")
+], Light.prototype, "renderPriority", void 0);
+__decorate([
+ serialize("shadowEnabled")
+], Light.prototype, "_shadowEnabled", void 0);
+__decorate([
+ serialize("excludeWithLayerMask")
+], Light.prototype, "_excludeWithLayerMask", void 0);
+__decorate([
+ serialize("includeOnlyWithLayerMask")
+], Light.prototype, "_includeOnlyWithLayerMask", void 0);
+__decorate([
+ serialize("lightmapMode")
+], Light.prototype, "_lightmapMode", void 0);
+
+/**
+ * Base implementation IShadowLight
+ * It groups all the common behaviour in order to reduce duplication and better follow the DRY pattern.
+ */
+class ShadowLight extends Light {
+ constructor() {
+ super(...arguments);
+ this._needProjectionMatrixCompute = true;
+ this._viewMatrix = Matrix.Identity();
+ this._projectionMatrix = Matrix.Identity();
+ }
+ _setPosition(value) {
+ this._position = value;
+ }
+ /**
+ * Sets the position the shadow will be casted from. Also use as the light position for both
+ * point and spot lights.
+ */
+ get position() {
+ return this._position;
+ }
+ /**
+ * Sets the position the shadow will be casted from. Also use as the light position for both
+ * point and spot lights.
+ */
+ set position(value) {
+ this._setPosition(value);
+ }
+ _setDirection(value) {
+ this._direction = value;
+ }
+ /**
+ * In 2d mode (needCube being false), gets the direction used to cast the shadow.
+ * Also use as the light direction on spot and directional lights.
+ */
+ get direction() {
+ return this._direction;
+ }
+ /**
+ * In 2d mode (needCube being false), sets the direction used to cast the shadow.
+ * Also use as the light direction on spot and directional lights.
+ */
+ set direction(value) {
+ this._setDirection(value);
+ }
+ /**
+ * Gets the shadow projection clipping minimum z value.
+ */
+ get shadowMinZ() {
+ return this._shadowMinZ;
+ }
+ /**
+ * Sets the shadow projection clipping minimum z value.
+ */
+ set shadowMinZ(value) {
+ this._shadowMinZ = value;
+ this.forceProjectionMatrixCompute();
+ }
+ /**
+ * Sets the shadow projection clipping maximum z value.
+ */
+ get shadowMaxZ() {
+ return this._shadowMaxZ;
+ }
+ /**
+ * Gets the shadow projection clipping maximum z value.
+ */
+ set shadowMaxZ(value) {
+ this._shadowMaxZ = value;
+ this.forceProjectionMatrixCompute();
+ }
+ /**
+ * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
+ * @returns true if the information has been computed, false if it does not need to (no parenting)
+ */
+ computeTransformedInformation() {
+ if (this.parent && this.parent.getWorldMatrix) {
+ if (!this.transformedPosition) {
+ this.transformedPosition = Vector3.Zero();
+ }
+ Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
+ // In case the direction is present.
+ if (this.direction) {
+ if (!this.transformedDirection) {
+ this.transformedDirection = Vector3.Zero();
+ }
+ Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
+ }
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Return the depth scale used for the shadow map.
+ * @returns the depth scale.
+ */
+ getDepthScale() {
+ return 50.0;
+ }
+ /**
+ * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
+ * @param faceIndex The index of the face we are computed the direction to generate shadow
+ * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getShadowDirection(faceIndex) {
+ return this.transformedDirection ? this.transformedDirection : this.direction;
+ }
+ /**
+ * If computeTransformedInformation has been called, returns the ShadowLight absolute position in the world. Otherwise, returns the local position.
+ * @returns the position vector in world space
+ */
+ getAbsolutePosition() {
+ return this.transformedPosition ? this.transformedPosition : this.position;
+ }
+ /**
+ * Sets the ShadowLight direction toward the passed target.
+ * @param target The point to target in local space
+ * @returns the updated ShadowLight direction
+ */
+ setDirectionToTarget(target) {
+ this.direction = Vector3.Normalize(target.subtract(this.position));
+ return this.direction;
+ }
+ /**
+ * Returns the light rotation in euler definition.
+ * @returns the x y z rotation in local space.
+ */
+ getRotation() {
+ this.direction.normalize();
+ const xaxis = Vector3.Cross(this.direction, Axis.Y);
+ const yaxis = Vector3.Cross(xaxis, this.direction);
+ return Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
+ }
+ /**
+ * Returns whether or not the shadow generation require a cube texture or a 2d texture.
+ * @returns true if a cube texture needs to be use
+ */
+ needCube() {
+ return false;
+ }
+ /**
+ * Detects if the projection matrix requires to be recomputed this frame.
+ * @returns true if it requires to be recomputed otherwise, false.
+ */
+ needProjectionMatrixCompute() {
+ return this._needProjectionMatrixCompute;
+ }
+ /**
+ * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
+ */
+ forceProjectionMatrixCompute() {
+ this._needProjectionMatrixCompute = true;
+ }
+ /** @internal */
+ _initCache() {
+ super._initCache();
+ this._cache.position = Vector3.Zero();
+ }
+ /** @internal */
+ _isSynchronized() {
+ if (!this._cache.position.equals(this.position)) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Computes the world matrix of the node
+ * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
+ * @returns the world matrix
+ */
+ computeWorldMatrix(force) {
+ if (!force && this.isSynchronized()) {
+ this._currentRenderId = this.getScene().getRenderId();
+ return this._worldMatrix;
+ }
+ this._updateCache();
+ this._cache.position.copyFrom(this.position);
+ if (!this._worldMatrix) {
+ this._worldMatrix = Matrix.Identity();
+ }
+ Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
+ if (this.parent && this.parent.getWorldMatrix) {
+ this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
+ this._markSyncedWithParent();
+ }
+ // Cache the determinant
+ this._worldMatrixDeterminantIsDirty = true;
+ return this._worldMatrix;
+ }
+ /**
+ * Gets the minZ used for shadow according to both the scene and the light.
+ * @param activeCamera The camera we are returning the min for
+ * @returns the depth min z
+ */
+ getDepthMinZ(activeCamera) {
+ return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera?.minZ || 0;
+ }
+ /**
+ * Gets the maxZ used for shadow according to both the scene and the light.
+ * @param activeCamera The camera we are returning the max for
+ * @returns the depth max z
+ */
+ getDepthMaxZ(activeCamera) {
+ return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera?.maxZ || 10000;
+ }
+ /**
+ * Sets the shadow projection matrix in parameter to the generated projection matrix.
+ * @param matrix The matrix to updated with the projection information
+ * @param viewMatrix The transform matrix of the light
+ * @param renderList The list of mesh to render in the map
+ * @returns The current light
+ */
+ setShadowProjectionMatrix(matrix, viewMatrix, renderList) {
+ if (this.customProjectionMatrixBuilder) {
+ this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
+ }
+ else {
+ this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
+ }
+ return this;
+ }
+ /** @internal */
+ _syncParentEnabledState() {
+ super._syncParentEnabledState();
+ if (!this.parent || !this.parent.getWorldMatrix) {
+ this.transformedPosition = null;
+ this.transformedDirection = null;
+ }
+ }
+ /**
+ * Returns the view matrix.
+ * @param faceIndex The index of the face for which we want to extract the view matrix. Only used for point light types.
+ * @returns The view matrix. Can be null, if a view matrix cannot be defined for the type of light considered (as for a hemispherical light, for example).
+ */
+ getViewMatrix(faceIndex) {
+ const lightDirection = TmpVectors.Vector3[0];
+ let lightPosition = this.position;
+ if (this.computeTransformedInformation()) {
+ lightPosition = this.transformedPosition;
+ }
+ Vector3.NormalizeToRef(this.getShadowDirection(faceIndex), lightDirection);
+ if (Math.abs(Vector3.Dot(lightDirection, Vector3.Up())) === 1.0) {
+ lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
+ }
+ const lightTarget = TmpVectors.Vector3[1];
+ lightPosition.addToRef(lightDirection, lightTarget);
+ Matrix.LookAtLHToRef(lightPosition, lightTarget, Vector3.Up(), this._viewMatrix);
+ return this._viewMatrix;
+ }
+ /**
+ * Returns the projection matrix.
+ * Note that viewMatrix and renderList are optional and are only used by lights that calculate the projection matrix from a list of meshes (e.g. directional lights with automatic extents calculation).
+ * @param viewMatrix The view transform matrix of the light (optional).
+ * @param renderList The list of meshes to take into account when calculating the projection matrix (optional).
+ * @returns The projection matrix. Can be null, if a projection matrix cannot be defined for the type of light considered (as for a hemispherical light, for example).
+ */
+ getProjectionMatrix(viewMatrix, renderList) {
+ this.setShadowProjectionMatrix(this._projectionMatrix, viewMatrix ?? this._viewMatrix, renderList ?? []);
+ return this._projectionMatrix;
+ }
+}
+__decorate([
+ serializeAsVector3()
+], ShadowLight.prototype, "position", null);
+__decorate([
+ serializeAsVector3()
+], ShadowLight.prototype, "direction", null);
+__decorate([
+ serialize()
+], ShadowLight.prototype, "shadowMinZ", null);
+__decorate([
+ serialize()
+], ShadowLight.prototype, "shadowMaxZ", null);
+
+Node$2.AddNodeConstructor("Light_Type_1", (name, scene) => {
+ return () => new DirectionalLight(name, Vector3.Zero(), scene);
+});
+/**
+ * A directional light is defined by a direction (what a surprise!).
+ * The light is emitted from everywhere in the specified direction, and has an infinite range.
+ * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
+ * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ */
+class DirectionalLight extends ShadowLight {
+ /**
+ * Fix frustum size for the shadow generation. This is disabled if the value is 0.
+ */
+ get shadowFrustumSize() {
+ return this._shadowFrustumSize;
+ }
+ /**
+ * Specifies a fix frustum size for the shadow generation.
+ */
+ set shadowFrustumSize(value) {
+ this._shadowFrustumSize = value;
+ this.forceProjectionMatrixCompute();
+ }
+ /**
+ * Gets the shadow projection scale against the optimal computed one.
+ * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
+ * This does not impact in fixed frustum size (shadowFrustumSize being set)
+ */
+ get shadowOrthoScale() {
+ return this._shadowOrthoScale;
+ }
+ /**
+ * Sets the shadow projection scale against the optimal computed one.
+ * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
+ * This does not impact in fixed frustum size (shadowFrustumSize being set)
+ */
+ set shadowOrthoScale(value) {
+ this._shadowOrthoScale = value;
+ this.forceProjectionMatrixCompute();
+ }
+ /**
+ * Gets or sets the orthoLeft property used to build the light frustum
+ */
+ get orthoLeft() {
+ return this._orthoLeft;
+ }
+ set orthoLeft(left) {
+ this._orthoLeft = left;
+ }
+ /**
+ * Gets or sets the orthoRight property used to build the light frustum
+ */
+ get orthoRight() {
+ return this._orthoRight;
+ }
+ set orthoRight(right) {
+ this._orthoRight = right;
+ }
+ /**
+ * Gets or sets the orthoTop property used to build the light frustum
+ */
+ get orthoTop() {
+ return this._orthoTop;
+ }
+ set orthoTop(top) {
+ this._orthoTop = top;
+ }
+ /**
+ * Gets or sets the orthoBottom property used to build the light frustum
+ */
+ get orthoBottom() {
+ return this._orthoBottom;
+ }
+ set orthoBottom(bottom) {
+ this._orthoBottom = bottom;
+ }
+ /**
+ * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
+ * The directional light is emitted from everywhere in the given direction.
+ * It can cast shadows.
+ * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ * @param name The friendly name of the light
+ * @param direction The direction of the light
+ * @param scene The scene the light belongs to
+ */
+ constructor(name, direction, scene) {
+ super(name, scene);
+ this._shadowFrustumSize = 0;
+ this._shadowOrthoScale = 0.1;
+ /**
+ * Automatically compute the projection matrix to best fit (including all the casters)
+ * on each frame.
+ */
+ this.autoUpdateExtends = true;
+ /**
+ * Automatically compute the shadowMinZ and shadowMaxZ for the projection matrix to best fit (including all the casters)
+ * on each frame. autoUpdateExtends must be set to true for this to work
+ */
+ this.autoCalcShadowZBounds = false;
+ // Cache
+ this._orthoLeft = Number.MAX_VALUE;
+ this._orthoRight = Number.MIN_VALUE;
+ this._orthoTop = Number.MIN_VALUE;
+ this._orthoBottom = Number.MAX_VALUE;
+ this.position = direction.scale(-1);
+ this.direction = direction;
+ }
+ /**
+ * Returns the string "DirectionalLight".
+ * @returns The class name
+ */
+ getClassName() {
+ return "DirectionalLight";
+ }
+ /**
+ * Returns the integer 1.
+ * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
+ */
+ getTypeID() {
+ return Light.LIGHTTYPEID_DIRECTIONALLIGHT;
+ }
+ /**
+ * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
+ * Returns the DirectionalLight Shadow projection matrix.
+ * @param matrix
+ * @param viewMatrix
+ * @param renderList
+ */
+ _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {
+ if (this.shadowFrustumSize > 0) {
+ this._setDefaultFixedFrustumShadowProjectionMatrix(matrix);
+ }
+ else {
+ this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
+ }
+ }
+ /**
+ * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
+ * Returns the DirectionalLight Shadow projection matrix.
+ * @param matrix
+ */
+ _setDefaultFixedFrustumShadowProjectionMatrix(matrix) {
+ const activeCamera = this.getScene().activeCamera;
+ if (!activeCamera) {
+ return;
+ }
+ Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange);
+ }
+ /**
+ * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
+ * Returns the DirectionalLight Shadow projection matrix.
+ * @param matrix
+ * @param viewMatrix
+ * @param renderList
+ */
+ _setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList) {
+ const activeCamera = this.getScene().activeCamera;
+ // Check extends
+ if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
+ const tempVector3 = Vector3.Zero();
+ this._orthoLeft = Number.MAX_VALUE;
+ this._orthoRight = -Number.MAX_VALUE;
+ this._orthoTop = -Number.MAX_VALUE;
+ this._orthoBottom = Number.MAX_VALUE;
+ let shadowMinZ = Number.MAX_VALUE;
+ let shadowMaxZ = -Number.MAX_VALUE;
+ for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
+ const mesh = renderList[meshIndex];
+ if (!mesh) {
+ continue;
+ }
+ const boundingInfo = mesh.getBoundingInfo();
+ const boundingBox = boundingInfo.boundingBox;
+ for (let index = 0; index < boundingBox.vectorsWorld.length; index++) {
+ Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
+ if (tempVector3.x < this._orthoLeft) {
+ this._orthoLeft = tempVector3.x;
+ }
+ if (tempVector3.y < this._orthoBottom) {
+ this._orthoBottom = tempVector3.y;
+ }
+ if (tempVector3.x > this._orthoRight) {
+ this._orthoRight = tempVector3.x;
+ }
+ if (tempVector3.y > this._orthoTop) {
+ this._orthoTop = tempVector3.y;
+ }
+ if (this.autoCalcShadowZBounds) {
+ if (tempVector3.z < shadowMinZ) {
+ shadowMinZ = tempVector3.z;
+ }
+ if (tempVector3.z > shadowMaxZ) {
+ shadowMaxZ = tempVector3.z;
+ }
+ }
+ }
+ }
+ if (this.autoCalcShadowZBounds) {
+ this._shadowMinZ = shadowMinZ;
+ this._shadowMaxZ = shadowMaxZ;
+ }
+ }
+ const xOffset = this._orthoRight - this._orthoLeft;
+ const yOffset = this._orthoTop - this._orthoBottom;
+ const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera?.minZ || 0;
+ const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera?.maxZ || 10000;
+ const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;
+ Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange);
+ }
+ _buildUniformLayout() {
+ this._uniformBuffer.addUniform("vLightData", 4);
+ this._uniformBuffer.addUniform("vLightDiffuse", 4);
+ this._uniformBuffer.addUniform("vLightSpecular", 4);
+ this._uniformBuffer.addUniform("shadowsInfo", 3);
+ this._uniformBuffer.addUniform("depthValues", 2);
+ this._uniformBuffer.create();
+ }
+ /**
+ * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
+ * @param effect The effect to update
+ * @param lightIndex The index of the light in the effect to update
+ * @returns The directional light
+ */
+ transferToEffect(effect, lightIndex) {
+ if (this.computeTransformedInformation()) {
+ this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
+ return this;
+ }
+ this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
+ return this;
+ }
+ transferToNodeMaterialEffect(effect, lightDataUniformName) {
+ if (this.computeTransformedInformation()) {
+ effect.setFloat3(lightDataUniformName, this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z);
+ return this;
+ }
+ effect.setFloat3(lightDataUniformName, this.direction.x, this.direction.y, this.direction.z);
+ return this;
+ }
+ /**
+ * Gets the minZ used for shadow according to both the scene and the light.
+ *
+ * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
+ * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
+ * (when not using reverse depth buffer / NDC half Z range)
+ * @param _activeCamera The camera we are returning the min for (not used)
+ * @returns the depth min z
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getDepthMinZ(_activeCamera) {
+ const engine = this._scene.getEngine();
+ return !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1;
+ }
+ /**
+ * Gets the maxZ used for shadow according to both the scene and the light.
+ *
+ * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
+ * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
+ * (when not using reverse depth buffer / NDC half Z range)
+ * @param _activeCamera The camera we are returning the max for
+ * @returns the depth max z
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getDepthMaxZ(_activeCamera) {
+ const engine = this._scene.getEngine();
+ return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1;
+ }
+ /**
+ * Prepares the list of defines specific to the light type.
+ * @param defines the list of defines
+ * @param lightIndex defines the index of the light for the effect
+ */
+ prepareLightSpecificDefines(defines, lightIndex) {
+ defines["DIRLIGHT" + lightIndex] = true;
+ }
+}
+__decorate([
+ serialize()
+], DirectionalLight.prototype, "shadowFrustumSize", null);
+__decorate([
+ serialize()
+], DirectionalLight.prototype, "shadowOrthoScale", null);
+__decorate([
+ serialize()
+], DirectionalLight.prototype, "autoUpdateExtends", void 0);
+__decorate([
+ serialize()
+], DirectionalLight.prototype, "autoCalcShadowZBounds", void 0);
+__decorate([
+ serialize("orthoLeft")
+], DirectionalLight.prototype, "_orthoLeft", void 0);
+__decorate([
+ serialize("orthoRight")
+], DirectionalLight.prototype, "_orthoRight", void 0);
+__decorate([
+ serialize("orthoTop")
+], DirectionalLight.prototype, "_orthoTop", void 0);
+__decorate([
+ serialize("orthoBottom")
+], DirectionalLight.prototype, "_orthoBottom", void 0);
+// Register Class Name
+RegisterClass("BABYLON.DirectionalLight", DirectionalLight);
+
+/**
+ * Transform some pixel data to a base64 string
+ * @param pixels defines the pixel data to transform to base64
+ * @param size defines the width and height of the (texture) data
+ * @param invertY true if the data must be inverted for the Y coordinate during the conversion
+ * @returns The base64 encoded string or null
+ */
+function GenerateBase64StringFromPixelData(pixels, size, invertY = false) {
+ const width = size.width;
+ const height = size.height;
+ if (pixels instanceof Float32Array) {
+ let len = pixels.byteLength / pixels.BYTES_PER_ELEMENT;
+ const npixels = new Uint8Array(len);
+ while (--len >= 0) {
+ let val = pixels[len];
+ if (val < 0) {
+ val = 0;
+ }
+ else if (val > 1) {
+ val = 1;
+ }
+ npixels[len] = val * 255;
+ }
+ pixels = npixels;
+ }
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) {
+ return null;
+ }
+ const imageData = ctx.createImageData(width, height);
+ const castData = imageData.data;
+ castData.set(pixels);
+ ctx.putImageData(imageData, 0, 0);
+ if (invertY) {
+ const canvas2 = document.createElement("canvas");
+ canvas2.width = width;
+ canvas2.height = height;
+ const ctx2 = canvas2.getContext("2d");
+ if (!ctx2) {
+ return null;
+ }
+ ctx2.translate(0, height);
+ ctx2.scale(1, -1);
+ ctx2.drawImage(canvas, 0, 0);
+ return canvas2.toDataURL("image/png");
+ }
+ return canvas.toDataURL("image/png");
+}
+/**
+ * Reads the pixels stored in the webgl texture and returns them as a base64 string
+ * @param texture defines the texture to read pixels from
+ * @param faceIndex defines the face of the texture to read (in case of cube texture)
+ * @param level defines the LOD level of the texture to read (in case of Mip Maps)
+ * @returns The base64 encoded string or null
+ */
+function GenerateBase64StringFromTexture(texture, faceIndex = 0, level = 0) {
+ const internalTexture = texture.getInternalTexture();
+ if (!internalTexture) {
+ return null;
+ }
+ const pixels = texture._readPixelsSync(faceIndex, level);
+ if (!pixels) {
+ return null;
+ }
+ return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY);
+}
+/**
+ * Reads the pixels stored in the webgl texture and returns them as a base64 string
+ * @param texture defines the texture to read pixels from
+ * @param faceIndex defines the face of the texture to read (in case of cube texture)
+ * @param level defines the LOD level of the texture to read (in case of Mip Maps)
+ * @returns The base64 encoded string or null wrapped in a promise
+ */
+async function GenerateBase64StringFromTextureAsync(texture, faceIndex = 0, level = 0) {
+ const internalTexture = texture.getInternalTexture();
+ if (!internalTexture) {
+ return null;
+ }
+ const pixels = await texture.readPixels(faceIndex, level);
+ if (!pixels) {
+ return null;
+ }
+ return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY);
+}
+
+/**
+ * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture
+ */
+class Texture extends BaseTexture {
+ /**
+ * @internal
+ */
+ static _CreateVideoTexture(name, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) {
+ throw _WarnImport("VideoTexture");
+ }
+ /**
+ * Are mip maps generated for this texture or not.
+ */
+ get noMipmap() {
+ return this._noMipmap;
+ }
+ /** Returns the texture mime type if it was defined by a loader (undefined else) */
+ get mimeType() {
+ return this._mimeType;
+ }
+ /**
+ * Is the texture preventing material to render while loading.
+ * If false, a default texture will be used instead of the loading one during the preparation step.
+ */
+ set isBlocking(value) {
+ this._isBlocking = value;
+ }
+ get isBlocking() {
+ return this._isBlocking;
+ }
+ /**
+ * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading
+ */
+ get invertY() {
+ return this._invertY;
+ }
+ /**
+ * Instantiates a new texture.
+ * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture
+ * @param url defines the url of the picture to load as a texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture
+ * @param invertY defines if the texture needs to be inverted on the y axis during loading
+ * @param samplingMode defines the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)
+ * @param onLoad defines a callback triggered when the texture has been loaded
+ * @param onError defines a callback triggered when an error occurred during the loading session
+ * @param buffer defines the buffer to load the texture from in case the texture is loaded from a buffer representation
+ * @param deleteBuffer defines if the buffer we are loading the texture from should be deleted after load
+ * @param format defines the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
+ * @param mimeType defines an optional mime type information
+ * @param loaderOptions options to be passed to the loader
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @param forcedExtension defines the extension to use to pick the right loader
+ */
+ constructor(url, sceneOrEngine, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, buffer = null, deleteBuffer = false, format, mimeType, loaderOptions, creationFlags, forcedExtension) {
+ super(sceneOrEngine);
+ /**
+ * Define the url of the texture.
+ */
+ this.url = null;
+ /**
+ * Define an offset on the texture to offset the u coordinates of the UVs
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting
+ */
+ this.uOffset = 0;
+ /**
+ * Define an offset on the texture to offset the v coordinates of the UVs
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting
+ */
+ this.vOffset = 0;
+ /**
+ * Define an offset on the texture to scale the u coordinates of the UVs
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling
+ */
+ this.uScale = 1.0;
+ /**
+ * Define an offset on the texture to scale the v coordinates of the UVs
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling
+ */
+ this.vScale = 1.0;
+ /**
+ * Define an offset on the texture to rotate around the u coordinates of the UVs
+ * The angle is defined in radians.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials
+ */
+ this.uAng = 0;
+ /**
+ * Define an offset on the texture to rotate around the v coordinates of the UVs
+ * The angle is defined in radians.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials
+ */
+ this.vAng = 0;
+ /**
+ * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
+ * The angle is defined in radians.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials
+ */
+ this.wAng = 0;
+ /**
+ * Defines the center of rotation (U)
+ */
+ this.uRotationCenter = 0.5;
+ /**
+ * Defines the center of rotation (V)
+ */
+ this.vRotationCenter = 0.5;
+ /**
+ * Defines the center of rotation (W)
+ */
+ this.wRotationCenter = 0.5;
+ /**
+ * Sets this property to true to avoid deformations when rotating the texture with non-uniform scaling
+ */
+ this.homogeneousRotationInUVTransform = false;
+ /**
+ * List of inspectable custom properties (used by the Inspector)
+ * @see https://doc.babylonjs.com/toolsAndResources/inspector#extensibility
+ */
+ this.inspectableCustomProperties = null;
+ /** @internal */
+ this._noMipmap = false;
+ /** @internal */
+ this._invertY = false;
+ this._rowGenerationMatrix = null;
+ this._cachedTextureMatrix = null;
+ this._projectionModeMatrix = null;
+ this._t0 = null;
+ this._t1 = null;
+ this._t2 = null;
+ this._cachedUOffset = -1;
+ this._cachedVOffset = -1;
+ this._cachedUScale = 0;
+ this._cachedVScale = 0;
+ this._cachedUAng = -1;
+ this._cachedVAng = -1;
+ this._cachedWAng = -1;
+ this._cachedReflectionProjectionMatrixId = -1;
+ this._cachedURotationCenter = -1;
+ this._cachedVRotationCenter = -1;
+ this._cachedWRotationCenter = -1;
+ this._cachedHomogeneousRotationInUVTransform = false;
+ this._cachedIdentity3x2 = true;
+ this._cachedReflectionTextureMatrix = null;
+ this._cachedReflectionUOffset = -1;
+ this._cachedReflectionVOffset = -1;
+ this._cachedReflectionUScale = 0;
+ this._cachedReflectionVScale = 0;
+ this._cachedReflectionCoordinatesMode = -1;
+ /** @internal */
+ this._buffer = null;
+ this._deleteBuffer = false;
+ this._format = null;
+ this._delayedOnLoad = null;
+ this._delayedOnError = null;
+ /**
+ * Observable triggered once the texture has been loaded.
+ */
+ this.onLoadObservable = new Observable();
+ this._isBlocking = true;
+ this.name = url || "";
+ this.url = url;
+ let noMipmap;
+ let useSRGBBuffer = false;
+ let internalTexture = null;
+ let gammaSpace = true;
+ if (typeof noMipmapOrOptions === "object" && noMipmapOrOptions !== null) {
+ noMipmap = noMipmapOrOptions.noMipmap ?? false;
+ invertY = noMipmapOrOptions.invertY ?? true;
+ samplingMode = noMipmapOrOptions.samplingMode ?? Texture.TRILINEAR_SAMPLINGMODE;
+ onLoad = noMipmapOrOptions.onLoad ?? null;
+ onError = noMipmapOrOptions.onError ?? null;
+ buffer = noMipmapOrOptions.buffer ?? null;
+ deleteBuffer = noMipmapOrOptions.deleteBuffer ?? false;
+ format = noMipmapOrOptions.format;
+ mimeType = noMipmapOrOptions.mimeType;
+ loaderOptions = noMipmapOrOptions.loaderOptions;
+ creationFlags = noMipmapOrOptions.creationFlags;
+ useSRGBBuffer = noMipmapOrOptions.useSRGBBuffer ?? false;
+ internalTexture = noMipmapOrOptions.internalTexture ?? null;
+ gammaSpace = noMipmapOrOptions.gammaSpace ?? gammaSpace;
+ forcedExtension = noMipmapOrOptions.forcedExtension ?? forcedExtension;
+ }
+ else {
+ noMipmap = !!noMipmapOrOptions;
+ }
+ this._gammaSpace = gammaSpace;
+ this._noMipmap = noMipmap;
+ this._invertY = invertY === undefined ? true : invertY;
+ this._initialSamplingMode = samplingMode;
+ this._buffer = buffer;
+ this._deleteBuffer = deleteBuffer;
+ this._mimeType = mimeType;
+ this._loaderOptions = loaderOptions;
+ this._creationFlags = creationFlags;
+ this._useSRGBBuffer = useSRGBBuffer;
+ this._forcedExtension = forcedExtension;
+ if (format) {
+ this._format = format;
+ }
+ const scene = this.getScene();
+ const engine = this._getEngine();
+ if (!engine) {
+ return;
+ }
+ engine.onBeforeTextureInitObservable.notifyObservers(this);
+ const load = () => {
+ if (this._texture) {
+ if (this._texture._invertVScale) {
+ this.vScale *= -1;
+ this.vOffset += 1;
+ }
+ // Update texture to match internal texture's wrapping
+ if (this._texture._cachedWrapU !== null) {
+ this.wrapU = this._texture._cachedWrapU;
+ this._texture._cachedWrapU = null;
+ }
+ if (this._texture._cachedWrapV !== null) {
+ this.wrapV = this._texture._cachedWrapV;
+ this._texture._cachedWrapV = null;
+ }
+ if (this._texture._cachedWrapR !== null) {
+ this.wrapR = this._texture._cachedWrapR;
+ this._texture._cachedWrapR = null;
+ }
+ }
+ if (this.onLoadObservable.hasObservers()) {
+ this.onLoadObservable.notifyObservers(this);
+ }
+ if (onLoad) {
+ onLoad();
+ }
+ if (!this.isBlocking && scene) {
+ scene.resetCachedMaterial();
+ }
+ };
+ const errorHandler = (message, exception) => {
+ this._loadingError = true;
+ this._errorObject = { message, exception };
+ if (onError) {
+ onError(message, exception);
+ }
+ Texture.OnTextureLoadErrorObservable.notifyObservers(this);
+ };
+ if (!this.url && !internalTexture) {
+ this._delayedOnLoad = load;
+ this._delayedOnError = errorHandler;
+ return;
+ }
+ this._texture = internalTexture ?? this._getFromCache(this.url, noMipmap, samplingMode, this._invertY, useSRGBBuffer, this.isCube);
+ if (!this._texture) {
+ if (!scene || !scene.useDelayedTextureLoading) {
+ try {
+ this._texture = engine.createTexture(this.url, noMipmap, this._invertY, scene, samplingMode, load, errorHandler, this._buffer, undefined, this._format, this._forcedExtension, mimeType, loaderOptions, creationFlags, useSRGBBuffer);
+ }
+ catch (e) {
+ errorHandler("error loading", e);
+ throw e;
+ }
+ if (deleteBuffer) {
+ this._buffer = null;
+ }
+ }
+ else {
+ this.delayLoadState = 4;
+ this._delayedOnLoad = load;
+ this._delayedOnError = errorHandler;
+ }
+ }
+ else {
+ if (this._texture.isReady) {
+ TimingTools.SetImmediate(() => load());
+ }
+ else {
+ const loadObserver = this._texture.onLoadedObservable.add(load);
+ this._texture.onErrorObservable.add((e) => {
+ errorHandler(e.message, e.exception);
+ this._texture?.onLoadedObservable.remove(loadObserver);
+ });
+ }
+ }
+ }
+ /**
+ * Update the url (and optional buffer) of this texture if url was null during construction.
+ * @param url the url of the texture
+ * @param buffer the buffer of the texture (defaults to null)
+ * @param onLoad callback called when the texture is loaded (defaults to null)
+ * @param forcedExtension defines the extension to use to pick the right loader
+ */
+ updateURL(url, buffer = null, onLoad, forcedExtension) {
+ if (this.url) {
+ this.releaseInternalTexture();
+ this.getScene().markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ if (!this.name || this.name.startsWith("data:")) {
+ this.name = url;
+ }
+ this.url = url;
+ this._buffer = buffer;
+ this._forcedExtension = forcedExtension;
+ this.delayLoadState = 4;
+ if (onLoad) {
+ this._delayedOnLoad = onLoad;
+ }
+ this.delayLoad();
+ }
+ /**
+ * Finish the loading sequence of a texture flagged as delayed load.
+ * @internal
+ */
+ delayLoad() {
+ if (this.delayLoadState !== 4) {
+ return;
+ }
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ this.delayLoadState = 1;
+ this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode, this._invertY, this._useSRGBBuffer, this.isCube);
+ if (!this._texture) {
+ this._texture = scene
+ .getEngine()
+ .createTexture(this.url, this._noMipmap, this._invertY, scene, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format, this._forcedExtension, this._mimeType, this._loaderOptions, this._creationFlags, this._useSRGBBuffer);
+ if (this._deleteBuffer) {
+ this._buffer = null;
+ }
+ }
+ else {
+ if (this._delayedOnLoad) {
+ if (this._texture.isReady) {
+ TimingTools.SetImmediate(this._delayedOnLoad);
+ }
+ else {
+ this._texture.onLoadedObservable.add(this._delayedOnLoad);
+ }
+ }
+ }
+ this._delayedOnLoad = null;
+ this._delayedOnError = null;
+ }
+ _prepareRowForTextureGeneration(x, y, z, t) {
+ x *= this._cachedUScale;
+ y *= this._cachedVScale;
+ x -= this.uRotationCenter * this._cachedUScale;
+ y -= this.vRotationCenter * this._cachedVScale;
+ z -= this.wRotationCenter;
+ Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
+ t.x += this.uRotationCenter * this._cachedUScale + this._cachedUOffset;
+ t.y += this.vRotationCenter * this._cachedVScale + this._cachedVOffset;
+ t.z += this.wRotationCenter;
+ }
+ /**
+ * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
+ * @param uBase The horizontal base offset multiplier (1 by default)
+ * @returns the transform matrix of the texture.
+ */
+ getTextureMatrix(uBase = 1) {
+ if (this.uOffset === this._cachedUOffset &&
+ this.vOffset === this._cachedVOffset &&
+ this.uScale * uBase === this._cachedUScale &&
+ this.vScale === this._cachedVScale &&
+ this.uAng === this._cachedUAng &&
+ this.vAng === this._cachedVAng &&
+ this.wAng === this._cachedWAng &&
+ this.uRotationCenter === this._cachedURotationCenter &&
+ this.vRotationCenter === this._cachedVRotationCenter &&
+ this.wRotationCenter === this._cachedWRotationCenter &&
+ this.homogeneousRotationInUVTransform === this._cachedHomogeneousRotationInUVTransform) {
+ return this._cachedTextureMatrix;
+ }
+ this._cachedUOffset = this.uOffset;
+ this._cachedVOffset = this.vOffset;
+ this._cachedUScale = this.uScale * uBase;
+ this._cachedVScale = this.vScale;
+ this._cachedUAng = this.uAng;
+ this._cachedVAng = this.vAng;
+ this._cachedWAng = this.wAng;
+ this._cachedURotationCenter = this.uRotationCenter;
+ this._cachedVRotationCenter = this.vRotationCenter;
+ this._cachedWRotationCenter = this.wRotationCenter;
+ this._cachedHomogeneousRotationInUVTransform = this.homogeneousRotationInUVTransform;
+ if (!this._cachedTextureMatrix || !this._rowGenerationMatrix) {
+ this._cachedTextureMatrix = Matrix.Zero();
+ this._rowGenerationMatrix = new Matrix();
+ this._t0 = Vector3.Zero();
+ this._t1 = Vector3.Zero();
+ this._t2 = Vector3.Zero();
+ }
+ Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
+ if (this.homogeneousRotationInUVTransform) {
+ Matrix.TranslationToRef(-this._cachedURotationCenter, -this._cachedVRotationCenter, -this._cachedWRotationCenter, TmpVectors.Matrix[0]);
+ Matrix.TranslationToRef(this._cachedURotationCenter, this._cachedVRotationCenter, this._cachedWRotationCenter, TmpVectors.Matrix[1]);
+ Matrix.ScalingToRef(this._cachedUScale, this._cachedVScale, 0, TmpVectors.Matrix[2]);
+ Matrix.TranslationToRef(this._cachedUOffset, this._cachedVOffset, 0, TmpVectors.Matrix[3]);
+ TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix, this._cachedTextureMatrix);
+ this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[1], this._cachedTextureMatrix);
+ this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[2], this._cachedTextureMatrix);
+ this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[3], this._cachedTextureMatrix);
+ // copy the translation row to the 3rd row of the matrix so that we don't need to update the shaders (which expects the translation to be on the 3rd row)
+ this._cachedTextureMatrix.setRowFromFloats(2, this._cachedTextureMatrix.m[12], this._cachedTextureMatrix.m[13], this._cachedTextureMatrix.m[14], 1);
+ }
+ else {
+ this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
+ this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
+ this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
+ this._t1.subtractInPlace(this._t0);
+ this._t2.subtractInPlace(this._t0);
+ Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix);
+ }
+ const scene = this.getScene();
+ if (!scene) {
+ return this._cachedTextureMatrix;
+ }
+ const previousIdentity3x2 = this._cachedIdentity3x2;
+ this._cachedIdentity3x2 = this._cachedTextureMatrix.isIdentityAs3x2();
+ if (this.optimizeUVAllocation && previousIdentity3x2 !== this._cachedIdentity3x2) {
+ // We flag the materials that are using this texture as "texture dirty" because depending on the fact that the matrix is the identity or not, some defines
+ // will get different values (see PrepareDefinesForMergedUV), meaning we should regenerate the effect accordingly
+ scene.markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ return this._cachedTextureMatrix;
+ }
+ /**
+ * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
+ * @returns The reflection texture transform
+ */
+ getReflectionTextureMatrix() {
+ const scene = this.getScene();
+ if (!scene) {
+ return this._cachedReflectionTextureMatrix;
+ }
+ if (this.uOffset === this._cachedReflectionUOffset &&
+ this.vOffset === this._cachedReflectionVOffset &&
+ this.uScale === this._cachedReflectionUScale &&
+ this.vScale === this._cachedReflectionVScale &&
+ this.coordinatesMode === this._cachedReflectionCoordinatesMode) {
+ if (this.coordinatesMode === Texture.PROJECTION_MODE) {
+ if (this._cachedReflectionProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
+ return this._cachedReflectionTextureMatrix;
+ }
+ }
+ else {
+ return this._cachedReflectionTextureMatrix;
+ }
+ }
+ if (!this._cachedReflectionTextureMatrix) {
+ this._cachedReflectionTextureMatrix = Matrix.Zero();
+ }
+ if (!this._projectionModeMatrix) {
+ this._projectionModeMatrix = Matrix.Zero();
+ }
+ const flagMaterialsAsTextureDirty = this._cachedReflectionCoordinatesMode !== this.coordinatesMode;
+ this._cachedReflectionUOffset = this.uOffset;
+ this._cachedReflectionVOffset = this.vOffset;
+ this._cachedReflectionUScale = this.uScale;
+ this._cachedReflectionVScale = this.vScale;
+ this._cachedReflectionCoordinatesMode = this.coordinatesMode;
+ switch (this.coordinatesMode) {
+ case Texture.PLANAR_MODE: {
+ Matrix.IdentityToRef(this._cachedReflectionTextureMatrix);
+ this._cachedReflectionTextureMatrix[0] = this.uScale;
+ this._cachedReflectionTextureMatrix[5] = this.vScale;
+ this._cachedReflectionTextureMatrix[12] = this.uOffset;
+ this._cachedReflectionTextureMatrix[13] = this.vOffset;
+ break;
+ }
+ case Texture.PROJECTION_MODE: {
+ Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix);
+ const projectionMatrix = scene.getProjectionMatrix();
+ this._cachedReflectionProjectionMatrixId = projectionMatrix.updateFlag;
+ projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedReflectionTextureMatrix);
+ break;
+ }
+ default:
+ Matrix.IdentityToRef(this._cachedReflectionTextureMatrix);
+ break;
+ }
+ if (flagMaterialsAsTextureDirty) {
+ // We flag the materials that are using this texture as "texture dirty" if the coordinatesMode has changed.
+ // Indeed, this property is used to set the value of some defines used to generate the effect (in material.isReadyForSubMesh), so we must make sure this code will be re-executed and the effect recreated if necessary
+ scene.markAllMaterialsAsDirty(1, (mat) => {
+ return mat.hasTexture(this);
+ });
+ }
+ return this._cachedReflectionTextureMatrix;
+ }
+ /**
+ * Clones the texture.
+ * @returns the cloned texture
+ */
+ clone() {
+ const options = {
+ noMipmap: this._noMipmap,
+ invertY: this._invertY,
+ samplingMode: this.samplingMode,
+ onLoad: undefined,
+ onError: undefined,
+ buffer: this._texture ? this._texture._buffer : undefined,
+ deleteBuffer: this._deleteBuffer,
+ format: this.textureFormat,
+ mimeType: this.mimeType,
+ loaderOptions: this._loaderOptions,
+ creationFlags: this._creationFlags,
+ useSRGBBuffer: this._useSRGBBuffer,
+ };
+ return SerializationHelper.Clone(() => {
+ return new Texture(this._texture ? this._texture.url : null, this.getScene(), options);
+ }, this);
+ }
+ /**
+ * Serialize the texture to a JSON representation we can easily use in the respective Parse function.
+ * @returns The JSON representation of the texture
+ */
+ serialize() {
+ const savedName = this.name;
+ if (!Texture.SerializeBuffers) {
+ if (this.name.startsWith("data:")) {
+ this.name = "";
+ }
+ }
+ if (this.name.startsWith("data:") && this.url === this.name) {
+ this.url = "";
+ }
+ const serializationObject = super.serialize(Texture._SerializeInternalTextureUniqueId);
+ if (!serializationObject) {
+ return null;
+ }
+ if (Texture.SerializeBuffers || Texture.ForceSerializeBuffers) {
+ if (typeof this._buffer === "string" && this._buffer.substring(0, 5) === "data:") {
+ serializationObject.base64String = this._buffer;
+ serializationObject.name = serializationObject.name.replace("data:", "");
+ }
+ else if (this.url && this.url.startsWith("data:") && this._buffer instanceof Uint8Array) {
+ serializationObject.base64String = "data:image/png;base64," + EncodeArrayBufferToBase64(this._buffer);
+ }
+ else if (Texture.ForceSerializeBuffers || (this.url && this.url.startsWith("blob:")) || this._forceSerialize) {
+ serializationObject.base64String =
+ !this._engine || this._engine._features.supportSyncTextureRead ? GenerateBase64StringFromTexture(this) : GenerateBase64StringFromTextureAsync(this);
+ }
+ }
+ serializationObject.invertY = this._invertY;
+ serializationObject.samplingMode = this.samplingMode;
+ serializationObject._creationFlags = this._creationFlags;
+ serializationObject._useSRGBBuffer = this._useSRGBBuffer;
+ if (Texture._SerializeInternalTextureUniqueId) {
+ serializationObject.internalTextureUniqueId = this._texture?.uniqueId;
+ }
+ serializationObject.internalTextureLabel = this._texture?.label;
+ serializationObject.noMipmap = this._noMipmap;
+ this.name = savedName;
+ return serializationObject;
+ }
+ /**
+ * Get the current class name of the texture useful for serialization or dynamic coding.
+ * @returns "Texture"
+ */
+ getClassName() {
+ return "Texture";
+ }
+ /**
+ * Dispose the texture and release its associated resources.
+ */
+ dispose() {
+ super.dispose();
+ this.onLoadObservable.clear();
+ this._delayedOnLoad = null;
+ this._delayedOnError = null;
+ this._buffer = null;
+ }
+ /**
+ * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
+ * @param parsedTexture Define the JSON representation of the texture
+ * @param scene Define the scene the parsed texture should be instantiated in
+ * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
+ * @returns The parsed texture if successful
+ */
+ static Parse(parsedTexture, scene, rootUrl) {
+ if (parsedTexture.customType) {
+ const customTexture = InstantiationTools.Instantiate(parsedTexture.customType);
+ // Update Sampling Mode
+ const parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
+ if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
+ if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
+ parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
+ }
+ }
+ return parsedCustomTexture;
+ }
+ if (parsedTexture.isCube && !parsedTexture.isRenderTarget) {
+ return Texture._CubeTextureParser(parsedTexture, scene, rootUrl);
+ }
+ const hasInternalTextureUniqueId = parsedTexture.internalTextureUniqueId !== undefined;
+ if (!parsedTexture.name && !parsedTexture.isRenderTarget && !hasInternalTextureUniqueId) {
+ return null;
+ }
+ let internalTexture;
+ if (hasInternalTextureUniqueId) {
+ const cache = scene.getEngine().getLoadedTexturesCache();
+ for (const texture of cache) {
+ if (texture.uniqueId === parsedTexture.internalTextureUniqueId) {
+ internalTexture = texture;
+ break;
+ }
+ }
+ }
+ const onLoaded = (texture) => {
+ // Clear cache
+ if (texture && texture._texture) {
+ texture._texture._cachedWrapU = null;
+ texture._texture._cachedWrapV = null;
+ texture._texture._cachedWrapR = null;
+ }
+ // Update Sampling Mode
+ if (parsedTexture.samplingMode) {
+ const sampling = parsedTexture.samplingMode;
+ if (texture && texture.samplingMode !== sampling) {
+ texture.updateSamplingMode(sampling);
+ }
+ }
+ // Animations
+ if (texture && parsedTexture.animations) {
+ for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
+ const parsedAnimation = parsedTexture.animations[animationIndex];
+ const internalClass = GetClass("BABYLON.Animation");
+ if (internalClass) {
+ texture.animations.push(internalClass.Parse(parsedAnimation));
+ }
+ }
+ }
+ if (texture && texture._texture) {
+ if (hasInternalTextureUniqueId && !internalTexture) {
+ texture._texture._setUniqueId(parsedTexture.internalTextureUniqueId);
+ }
+ texture._texture.label = parsedTexture.internalTextureLabel;
+ }
+ };
+ const texture = SerializationHelper.Parse(() => {
+ let generateMipMaps = true;
+ if (parsedTexture.noMipmap) {
+ generateMipMaps = false;
+ }
+ if (parsedTexture.mirrorPlane) {
+ const mirrorTexture = Texture._CreateMirror(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
+ mirrorTexture._waitingRenderList = parsedTexture.renderList;
+ mirrorTexture.mirrorPlane = Plane.FromArray(parsedTexture.mirrorPlane);
+ onLoaded(mirrorTexture);
+ return mirrorTexture;
+ }
+ else if (parsedTexture.isRenderTarget) {
+ let renderTargetTexture = null;
+ if (parsedTexture.isCube) {
+ // Search for an existing reflection probe (which contains a cube render target texture)
+ if (scene.reflectionProbes) {
+ for (let index = 0; index < scene.reflectionProbes.length; index++) {
+ const probe = scene.reflectionProbes[index];
+ if (probe.name === parsedTexture.name) {
+ return probe.cubeTexture;
+ }
+ }
+ }
+ }
+ else {
+ renderTargetTexture = Texture._CreateRenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps, parsedTexture._creationFlags ?? 0);
+ renderTargetTexture._waitingRenderList = parsedTexture.renderList;
+ }
+ onLoaded(renderTargetTexture);
+ return renderTargetTexture;
+ }
+ else if (parsedTexture.isVideo) {
+ const texture = Texture._CreateVideoTexture(rootUrl + (parsedTexture.url || parsedTexture.name), rootUrl + (parsedTexture.src || parsedTexture.url), scene, generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, parsedTexture.settings || {});
+ onLoaded(texture);
+ return texture;
+ }
+ else {
+ let texture;
+ if (parsedTexture.base64String && !internalTexture) {
+ // name and url are the same to ensure caching happens from the actual base64 string
+ texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.base64String, scene, !generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, () => {
+ onLoaded(texture);
+ }, parsedTexture._creationFlags ?? 0, parsedTexture._useSRGBBuffer ?? false);
+ // prettier name to fit with the loaded data
+ texture.name = parsedTexture.name;
+ }
+ else {
+ let url;
+ if (parsedTexture.name && (parsedTexture.name.indexOf("://") > 0 || parsedTexture.name.startsWith("data:"))) {
+ url = parsedTexture.name;
+ }
+ else {
+ url = rootUrl + parsedTexture.name;
+ }
+ if (parsedTexture.url && (parsedTexture.url.startsWith("data:") || Texture.UseSerializedUrlIfAny)) {
+ url = parsedTexture.url;
+ }
+ const options = {
+ noMipmap: !generateMipMaps,
+ invertY: parsedTexture.invertY,
+ samplingMode: parsedTexture.samplingMode,
+ onLoad: () => {
+ onLoaded(texture);
+ },
+ internalTexture,
+ };
+ texture = new Texture(url, scene, options);
+ }
+ return texture;
+ }
+ }, parsedTexture, scene);
+ return texture;
+ }
+ /**
+ * Creates a texture from its base 64 representation.
+ * @param data Define the base64 payload without the data: prefix
+ * @param name Define the name of the texture in the scene useful fo caching purpose for instance
+ * @param scene Define the scene the texture should belong to
+ * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture
+ * @param invertY define if the texture needs to be inverted on the y axis during loading
+ * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)
+ * @param onLoad define a callback triggered when the texture has been loaded
+ * @param onError define a callback triggered when an error occurred during the loading session
+ * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @param forcedExtension defines the extension to use to pick the right loader
+ * @returns the created texture
+ */
+ static CreateFromBase64String(data, name, scene, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) {
+ return new Texture("data:" + name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, data, false, format, undefined, undefined, creationFlags, forcedExtension);
+ }
+ /**
+ * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
+ * @param name Define the name of the texture in the scene useful fo caching purpose for instance
+ * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
+ * @param scene Define the scene the texture should belong to
+ * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
+ * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture
+ * @param invertY define if the texture needs to be inverted on the y axis during loading
+ * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)
+ * @param onLoad define a callback triggered when the texture has been loaded
+ * @param onError define a callback triggered when an error occurred during the loading session
+ * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @param forcedExtension defines the extension to use to pick the right loader
+ * @returns the created texture
+ */
+ static LoadFromDataString(name, buffer, scene, deleteBuffer = false, noMipmapOrOptions, invertY = true, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) {
+ if (name.substring(0, 5) !== "data:") {
+ name = "data:" + name;
+ }
+ return new Texture(name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format, undefined, undefined, creationFlags, forcedExtension);
+ }
+}
+/**
+ * Gets or sets a general boolean used to indicate that textures containing direct data (buffers) must be saved as part of the serialization process
+ */
+Texture.SerializeBuffers = true;
+/**
+ * Gets or sets a general boolean used to indicate that texture buffers must be saved as part of the serialization process.
+ * If no buffer exists, one will be created as base64 string from the internal webgl data.
+ */
+Texture.ForceSerializeBuffers = false;
+/**
+ * This observable will notify when any texture had a loading error
+ */
+Texture.OnTextureLoadErrorObservable = new Observable();
+/** @internal */
+Texture._SerializeInternalTextureUniqueId = false;
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Texture._CubeTextureParser = (jsonTexture, scene, rootUrl) => {
+ throw _WarnImport("CubeTexture");
+};
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Texture._CreateMirror = (name, renderTargetSize, scene, generateMipMaps) => {
+ throw _WarnImport("MirrorTexture");
+};
+/**
+ * @internal
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Texture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => {
+ throw _WarnImport("RenderTargetTexture");
+};
+/** nearest is mag = nearest and min = nearest and no mip */
+Texture.NEAREST_SAMPLINGMODE = 1;
+/** nearest is mag = nearest and min = nearest and mip = linear */
+Texture.NEAREST_NEAREST_MIPLINEAR = 8; // nearest is mag = nearest and min = nearest and mip = linear
+/** Bilinear is mag = linear and min = linear and no mip */
+Texture.BILINEAR_SAMPLINGMODE = 2;
+/** Bilinear is mag = linear and min = linear and mip = nearest */
+Texture.LINEAR_LINEAR_MIPNEAREST = 11; // Bilinear is mag = linear and min = linear and mip = nearest
+/** Trilinear is mag = linear and min = linear and mip = linear */
+Texture.TRILINEAR_SAMPLINGMODE = 3;
+/** Trilinear is mag = linear and min = linear and mip = linear */
+Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
+/** mag = nearest and min = nearest and mip = nearest */
+Texture.NEAREST_NEAREST_MIPNEAREST = 4;
+/** mag = nearest and min = linear and mip = nearest */
+Texture.NEAREST_LINEAR_MIPNEAREST = 5;
+/** mag = nearest and min = linear and mip = linear */
+Texture.NEAREST_LINEAR_MIPLINEAR = 6;
+/** mag = nearest and min = linear and mip = none */
+Texture.NEAREST_LINEAR = 7;
+/** mag = nearest and min = nearest and mip = none */
+Texture.NEAREST_NEAREST = 1;
+/** mag = linear and min = nearest and mip = nearest */
+Texture.LINEAR_NEAREST_MIPNEAREST = 9;
+/** mag = linear and min = nearest and mip = linear */
+Texture.LINEAR_NEAREST_MIPLINEAR = 10;
+/** mag = linear and min = linear and mip = none */
+Texture.LINEAR_LINEAR = 2;
+/** mag = linear and min = nearest and mip = none */
+Texture.LINEAR_NEAREST = 12;
+/** Explicit coordinates mode */
+Texture.EXPLICIT_MODE = 0;
+/** Spherical coordinates mode */
+Texture.SPHERICAL_MODE = 1;
+/** Planar coordinates mode */
+Texture.PLANAR_MODE = 2;
+/** Cubic coordinates mode */
+Texture.CUBIC_MODE = 3;
+/** Projection coordinates mode */
+Texture.PROJECTION_MODE = 4;
+/** Inverse Cubic coordinates mode */
+Texture.SKYBOX_MODE = 5;
+/** Inverse Cubic coordinates mode */
+Texture.INVCUBIC_MODE = 6;
+/** Equirectangular coordinates mode */
+Texture.EQUIRECTANGULAR_MODE = 7;
+/** Equirectangular Fixed coordinates mode */
+Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
+/** Equirectangular Fixed Mirrored coordinates mode */
+Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
+/** Texture is not repeating outside of 0..1 UVs */
+Texture.CLAMP_ADDRESSMODE = 0;
+/** Texture is repeating outside of 0..1 UVs */
+Texture.WRAP_ADDRESSMODE = 1;
+/** Texture is repeating and mirrored */
+Texture.MIRROR_ADDRESSMODE = 2;
+/**
+ * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
+ */
+Texture.UseSerializedUrlIfAny = false;
+__decorate([
+ serialize()
+], Texture.prototype, "url", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "uOffset", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "vOffset", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "uScale", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "vScale", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "uAng", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "vAng", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "wAng", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "uRotationCenter", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "vRotationCenter", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "wRotationCenter", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "homogeneousRotationInUVTransform", void 0);
+__decorate([
+ serialize()
+], Texture.prototype, "isBlocking", null);
+// References the dependencies.
+RegisterClass("BABYLON.Texture", Texture);
+SerializationHelper._TextureParser = Texture.Parse;
+
+/**
+ * A class that renders objects to the currently bound render target.
+ * This class only renders objects, and is not concerned with the output texture or post-processing.
+ */
+class ObjectRenderer {
+ /**
+ * Use this list to define the list of mesh you want to render.
+ */
+ get renderList() {
+ return this._renderList;
+ }
+ set renderList(value) {
+ if (this._renderList === value) {
+ return;
+ }
+ if (this._unObserveRenderList) {
+ this._unObserveRenderList();
+ this._unObserveRenderList = null;
+ }
+ if (value) {
+ this._unObserveRenderList = _ObserveArray(value, this._renderListHasChanged);
+ }
+ this._renderList = value;
+ }
+ /**
+ * If true, the object renderer will render all objects in linear space (default: false)
+ */
+ get renderInLinearSpace() {
+ return this._renderInLinearSpace;
+ }
+ set renderInLinearSpace(value) {
+ if (value === this._renderInLinearSpace) {
+ return;
+ }
+ this._renderInLinearSpace = value;
+ this._scene.markAllMaterialsAsDirty(64);
+ }
+ /**
+ * Friendly name of the object renderer
+ */
+ get name() {
+ return this._name;
+ }
+ set name(value) {
+ if (this._name === value) {
+ return;
+ }
+ this._name = value;
+ if (!this._scene) {
+ return;
+ }
+ const engine = this._scene.getEngine();
+ for (let i = 0; i < this._renderPassIds.length; ++i) {
+ const renderPassId = this._renderPassIds[i];
+ engine._renderPassNames[renderPassId] = `${this._name}#${i}`;
+ }
+ }
+ /**
+ * Gets the render pass ids used by the object renderer.
+ */
+ get renderPassIds() {
+ return this._renderPassIds;
+ }
+ /**
+ * Gets the current value of the refreshId counter
+ */
+ get currentRefreshId() {
+ return this._currentRefreshId;
+ }
+ /**
+ * Sets a specific material to be used to render a mesh/a list of meshes with this object renderer
+ * @param mesh mesh or array of meshes
+ * @param material material or array of materials to use for this render pass. If undefined is passed, no specific material will be used but the regular material instead (mesh.material). It's possible to provide an array of materials to use a different material for each rendering pass.
+ */
+ setMaterialForRendering(mesh, material) {
+ let meshes;
+ if (!Array.isArray(mesh)) {
+ meshes = [mesh];
+ }
+ else {
+ meshes = mesh;
+ }
+ for (let j = 0; j < meshes.length; ++j) {
+ for (let i = 0; i < this.options.numPasses; ++i) {
+ meshes[j].setMaterialForRenderPass(this._renderPassIds[i], material !== undefined ? (Array.isArray(material) ? material[i] : material) : undefined);
+ }
+ }
+ }
+ /**
+ * Instantiates an object renderer.
+ * @param name The friendly name of the object renderer
+ * @param scene The scene the renderer belongs to
+ * @param options The options used to create the renderer (optional)
+ */
+ constructor(name, scene, options) {
+ this._unObserveRenderList = null;
+ this._renderListHasChanged = (_functionName, previousLength) => {
+ const newLength = this._renderList ? this._renderList.length : 0;
+ if ((previousLength === 0 && newLength > 0) || newLength === 0) {
+ this._scene.meshes.forEach((mesh) => {
+ mesh._markSubMeshesAsLightDirty();
+ });
+ }
+ };
+ /**
+ * Define the list of particle systems to render. If not provided, will render all the particle systems of the scene.
+ * Note that the particle systems are rendered only if renderParticles is set to true.
+ */
+ this.particleSystemList = null;
+ /**
+ * Use this function to overload the renderList array at rendering time.
+ * Return null to render with the current renderList, else return the list of meshes to use for rendering.
+ * For 2DArray, layerOrFace is the index of the layer that is going to be rendered, else it is the faceIndex of
+ * the cube (if the RTT is a cube, else layerOrFace=0).
+ * The renderList passed to the function is the current render list (the one that will be used if the function returns null).
+ * The length of this list is passed through renderListLength: don't use renderList.length directly because the array can
+ * hold dummy elements!
+ */
+ this.getCustomRenderList = null;
+ /**
+ * Define if particles should be rendered.
+ */
+ this.renderParticles = true;
+ /**
+ * Define if sprites should be rendered.
+ */
+ this.renderSprites = false;
+ /**
+ * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined)
+ */
+ this.forceLayerMaskCheck = false;
+ this._renderInLinearSpace = false;
+ /**
+ * An event triggered before rendering the objects
+ */
+ this.onBeforeRenderObservable = new Observable();
+ /**
+ * An event triggered after rendering the objects
+ */
+ this.onAfterRenderObservable = new Observable();
+ /**
+ * An event triggered before the rendering group is processed
+ */
+ this.onBeforeRenderingManagerRenderObservable = new Observable();
+ /**
+ * An event triggered after the rendering group is processed
+ */
+ this.onAfterRenderingManagerRenderObservable = new Observable();
+ /**
+ * An event triggered when fast path rendering is used
+ */
+ this.onFastPathRenderObservable = new Observable();
+ this._currentRefreshId = -1;
+ this._refreshRate = 1;
+ this._currentApplyByPostProcessSetting = false;
+ this._currentSceneCamera = null;
+ this.name = name;
+ this._scene = scene;
+ this.renderList = [];
+ this._renderPassIds = [];
+ this.options = {
+ numPasses: 1,
+ doNotChangeAspectRatio: true,
+ ...options,
+ };
+ this._createRenderPassId();
+ this.renderPassId = this._renderPassIds[0];
+ // Rendering groups
+ this._renderingManager = new RenderingManager(scene);
+ this._renderingManager._useSceneAutoClearSetup = true;
+ }
+ _releaseRenderPassId() {
+ const engine = this._scene.getEngine();
+ for (let i = 0; i < this.options.numPasses; ++i) {
+ engine.releaseRenderPassId(this._renderPassIds[i]);
+ }
+ this._renderPassIds.length = 0;
+ }
+ _createRenderPassId() {
+ this._releaseRenderPassId();
+ const engine = this._scene.getEngine();
+ for (let i = 0; i < this.options.numPasses; ++i) {
+ this._renderPassIds[i] = engine.createRenderPassId(`${this.name}#${i}`);
+ }
+ }
+ /**
+ * Resets the refresh counter of the renderer and start back from scratch.
+ * Could be useful to re-render if it is setup to render only once.
+ */
+ resetRefreshCounter() {
+ this._currentRefreshId = -1;
+ }
+ /**
+ * Defines the refresh rate of the rendering or the rendering frequency.
+ * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
+ */
+ get refreshRate() {
+ return this._refreshRate;
+ }
+ set refreshRate(value) {
+ this._refreshRate = value;
+ this.resetRefreshCounter();
+ }
+ /**
+ * Indicates if the renderer should render the current frame.
+ * The output is based on the specified refresh rate.
+ * @returns true if the renderer should render the current frame
+ */
+ shouldRender() {
+ if (this._currentRefreshId === -1) {
+ // At least render once
+ this._currentRefreshId = 1;
+ return true;
+ }
+ if (this.refreshRate === this._currentRefreshId) {
+ this._currentRefreshId = 1;
+ return true;
+ }
+ this._currentRefreshId++;
+ return false;
+ }
+ /**
+ * This function will check if the renderer is ready to render (textures are loaded, shaders are compiled)
+ * @param viewportWidth defines the width of the viewport
+ * @param viewportHeight defines the height of the viewport
+ * @returns true if all required resources are ready
+ */
+ isReadyForRendering(viewportWidth, viewportHeight) {
+ this.prepareRenderList();
+ this.initRender(viewportWidth, viewportHeight);
+ const isReady = this._checkReadiness();
+ this.finishRender();
+ return isReady;
+ }
+ /**
+ * Makes sure the list of meshes is ready to be rendered
+ * You should call this function before "initRender", but if you know the render list is ok, you may call "initRender" directly
+ */
+ prepareRenderList() {
+ const scene = this._scene;
+ if (this._waitingRenderList) {
+ if (!this.renderListPredicate) {
+ this.renderList = [];
+ for (let index = 0; index < this._waitingRenderList.length; index++) {
+ const id = this._waitingRenderList[index];
+ const mesh = scene.getMeshById(id);
+ if (mesh) {
+ this.renderList.push(mesh);
+ }
+ }
+ }
+ this._waitingRenderList = undefined;
+ }
+ // Is predicate defined?
+ if (this.renderListPredicate) {
+ if (this.renderList) {
+ this.renderList.length = 0; // Clear previous renderList
+ }
+ else {
+ this.renderList = [];
+ }
+ const sceneMeshes = this._scene.meshes;
+ for (let index = 0; index < sceneMeshes.length; index++) {
+ const mesh = sceneMeshes[index];
+ if (this.renderListPredicate(mesh)) {
+ this.renderList.push(mesh);
+ }
+ }
+ }
+ this._currentApplyByPostProcessSetting = this._scene.imageProcessingConfiguration.applyByPostProcess;
+ // we do not use the applyByPostProcess setter to avoid flagging all the materials as "image processing dirty"!
+ this._scene.imageProcessingConfiguration._applyByPostProcess = !!this._renderInLinearSpace;
+ }
+ /**
+ * This method makes sure everything is setup before "render" can be called
+ * @param viewportWidth Width of the viewport to render to
+ * @param viewportHeight Height of the viewport to render to
+ */
+ initRender(viewportWidth, viewportHeight) {
+ const engine = this._scene.getEngine();
+ const camera = this.activeCamera ?? this._scene.activeCamera;
+ this._currentSceneCamera = this._scene.activeCamera;
+ if (camera) {
+ if (camera !== this._scene.activeCamera) {
+ this._scene.setTransformMatrix(camera.getViewMatrix(), camera.getProjectionMatrix(true));
+ this._scene.activeCamera = camera;
+ }
+ engine.setViewport(camera.rigParent ? camera.rigParent.viewport : camera.viewport, viewportWidth, viewportHeight);
+ }
+ this._defaultRenderListPrepared = false;
+ }
+ /**
+ * This method must be called after the "render" call(s), to complete the rendering process.
+ */
+ finishRender() {
+ const scene = this._scene;
+ scene.imageProcessingConfiguration._applyByPostProcess = this._currentApplyByPostProcessSetting;
+ scene.activeCamera = this._currentSceneCamera;
+ if (this._currentSceneCamera) {
+ if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
+ scene.setTransformMatrix(this._currentSceneCamera.getViewMatrix(), this._currentSceneCamera.getProjectionMatrix(true));
+ }
+ scene.getEngine().setViewport(this._currentSceneCamera.viewport);
+ }
+ scene.resetCachedMaterial();
+ }
+ /**
+ * Renders all the objects (meshes, particles systems, sprites) to the currently bound render target texture.
+ * @param passIndex defines the pass index to use (default: 0)
+ * @param skipOnAfterRenderObservable defines a flag to skip raising the onAfterRenderObservable
+ */
+ render(passIndex = 0, skipOnAfterRenderObservable = false) {
+ const scene = this._scene;
+ const engine = scene.getEngine();
+ const currentRenderPassId = engine.currentRenderPassId;
+ engine.currentRenderPassId = this._renderPassIds[passIndex];
+ this.onBeforeRenderObservable.notifyObservers(passIndex);
+ const fastPath = engine.snapshotRendering && engine.snapshotRenderingMode === 1;
+ if (!fastPath) {
+ // Get the list of meshes to render
+ let currentRenderList = null;
+ const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
+ const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
+ if (this.getCustomRenderList) {
+ currentRenderList = this.getCustomRenderList(passIndex, defaultRenderList, defaultRenderListLength);
+ }
+ if (!currentRenderList) {
+ // No custom render list provided, we prepare the rendering for the default list, but check
+ // first if we did not already performed the preparation before so as to avoid re-doing it several times
+ if (!this._defaultRenderListPrepared) {
+ this._prepareRenderingManager(defaultRenderList, defaultRenderListLength, !this.renderList || this.forceLayerMaskCheck);
+ this._defaultRenderListPrepared = true;
+ }
+ currentRenderList = defaultRenderList;
+ }
+ else {
+ // Prepare the rendering for the custom render list provided
+ this._prepareRenderingManager(currentRenderList, currentRenderList.length, this.forceLayerMaskCheck);
+ }
+ this.onBeforeRenderingManagerRenderObservable.notifyObservers(passIndex);
+ this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
+ this.onAfterRenderingManagerRenderObservable.notifyObservers(passIndex);
+ }
+ else {
+ this.onFastPathRenderObservable.notifyObservers(passIndex);
+ }
+ if (!skipOnAfterRenderObservable) {
+ this.onAfterRenderObservable.notifyObservers(passIndex);
+ }
+ engine.currentRenderPassId = currentRenderPassId;
+ }
+ /** @internal */
+ _checkReadiness() {
+ const scene = this._scene;
+ const engine = scene.getEngine();
+ const currentRenderPassId = engine.currentRenderPassId;
+ let returnValue = true;
+ if (!scene.getViewMatrix()) {
+ // We probably didn't execute scene.render() yet, so make sure we have a view/projection matrix setup for the scene
+ scene.updateTransformMatrix();
+ }
+ const numPasses = this.options.numPasses;
+ for (let passIndex = 0; passIndex < numPasses && returnValue; passIndex++) {
+ let currentRenderList = null;
+ const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
+ const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
+ engine.currentRenderPassId = this._renderPassIds[passIndex];
+ this.onBeforeRenderObservable.notifyObservers(passIndex);
+ if (this.getCustomRenderList) {
+ currentRenderList = this.getCustomRenderList(passIndex, defaultRenderList, defaultRenderListLength);
+ }
+ if (!currentRenderList) {
+ currentRenderList = defaultRenderList;
+ }
+ if (!this.options.doNotChangeAspectRatio) {
+ scene.updateTransformMatrix(true);
+ }
+ for (let i = 0; i < currentRenderList.length && returnValue; ++i) {
+ const mesh = currentRenderList[i];
+ if (!mesh.isEnabled() || mesh.isBlocked || !mesh.isVisible || !mesh.subMeshes) {
+ continue;
+ }
+ if (this.customIsReadyFunction) {
+ if (!this.customIsReadyFunction(mesh, this.refreshRate, true)) {
+ returnValue = false;
+ continue;
+ }
+ }
+ else if (!mesh.isReady(true)) {
+ returnValue = false;
+ continue;
+ }
+ }
+ this.onAfterRenderObservable.notifyObservers(passIndex);
+ if (numPasses > 1) {
+ scene.incrementRenderId();
+ scene.resetCachedMaterial();
+ }
+ }
+ const particleSystems = this.particleSystemList || scene.particleSystems;
+ for (const particleSystem of particleSystems) {
+ if (!particleSystem.isReady()) {
+ returnValue = false;
+ }
+ }
+ engine.currentRenderPassId = currentRenderPassId;
+ return returnValue;
+ }
+ _prepareRenderingManager(currentRenderList, currentRenderListLength, checkLayerMask) {
+ const scene = this._scene;
+ const camera = scene.activeCamera; // note that at this point, scene.activeCamera == this.activeCamera if defined, because initRender() has been called before
+ const cameraForLOD = this.cameraForLOD ?? camera;
+ this._renderingManager.reset();
+ const sceneRenderId = scene.getRenderId();
+ const currentFrameId = scene.getFrameId();
+ for (let meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
+ const mesh = currentRenderList[meshIndex];
+ if (mesh && !mesh.isBlocked) {
+ if (this.customIsReadyFunction) {
+ if (!this.customIsReadyFunction(mesh, this.refreshRate, false)) {
+ this.resetRefreshCounter();
+ continue;
+ }
+ }
+ else if (!mesh.isReady(this.refreshRate === 0)) {
+ this.resetRefreshCounter();
+ continue;
+ }
+ let meshToRender = null;
+ if (cameraForLOD) {
+ const meshToRenderAndFrameId = mesh._internalAbstractMeshDataInfo._currentLOD.get(cameraForLOD);
+ if (!meshToRenderAndFrameId || meshToRenderAndFrameId[1] !== currentFrameId) {
+ meshToRender = scene.customLODSelector ? scene.customLODSelector(mesh, cameraForLOD) : mesh.getLOD(cameraForLOD);
+ if (!meshToRenderAndFrameId) {
+ mesh._internalAbstractMeshDataInfo._currentLOD.set(cameraForLOD, [meshToRender, currentFrameId]);
+ }
+ else {
+ meshToRenderAndFrameId[0] = meshToRender;
+ meshToRenderAndFrameId[1] = currentFrameId;
+ }
+ }
+ else {
+ meshToRender = meshToRenderAndFrameId[0];
+ }
+ }
+ else {
+ meshToRender = mesh;
+ }
+ if (!meshToRender) {
+ continue;
+ }
+ if (meshToRender !== mesh && meshToRender.billboardMode !== 0) {
+ meshToRender.computeWorldMatrix(); // Compute world matrix if LOD is billboard
+ }
+ meshToRender._preActivateForIntermediateRendering(sceneRenderId);
+ let isMasked;
+ if (checkLayerMask && camera) {
+ isMasked = (mesh.layerMask & camera.layerMask) === 0;
+ }
+ else {
+ isMasked = false;
+ }
+ if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
+ if (meshToRender !== mesh) {
+ meshToRender._activate(sceneRenderId, true);
+ }
+ if (mesh._activate(sceneRenderId, true) && mesh.subMeshes.length) {
+ if (!mesh.isAnInstance) {
+ meshToRender._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false;
+ }
+ else {
+ if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) {
+ meshToRender = mesh;
+ }
+ }
+ meshToRender._internalAbstractMeshDataInfo._isActiveIntermediate = true;
+ scene._prepareSkeleton(meshToRender);
+ for (let subIndex = 0; subIndex < meshToRender.subMeshes.length; subIndex++) {
+ const subMesh = meshToRender.subMeshes[subIndex];
+ this._renderingManager.dispatch(subMesh, meshToRender);
+ }
+ }
+ mesh._postActivate();
+ }
+ }
+ }
+ const particleSystems = this.particleSystemList || scene.particleSystems;
+ for (let particleIndex = 0; particleIndex < particleSystems.length; particleIndex++) {
+ const particleSystem = particleSystems[particleIndex];
+ const emitter = particleSystem.emitter;
+ if (!particleSystem.isStarted() || !emitter || (emitter.position && !emitter.isEnabled())) {
+ continue;
+ }
+ this._renderingManager.dispatchParticles(particleSystem);
+ }
+ }
+ /**
+ * Overrides the default sort function applied in the rendering group to prepare the meshes.
+ * This allowed control for front to back rendering or reversely depending of the special needs.
+ *
+ * @param renderingGroupId The rendering group id corresponding to its index
+ * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
+ * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
+ * @param transparentSortCompareFn The transparent queue comparison function use to sort.
+ */
+ setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {
+ this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
+ }
+ /**
+ * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
+ *
+ * @param renderingGroupId The rendering group id corresponding to its index
+ * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
+ * @param depth Automatically clears depth between groups if true and autoClear is true.
+ * @param stencil Automatically clears stencil between groups if true and autoClear is true.
+ */
+ setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) {
+ this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
+ this._renderingManager._useSceneAutoClearSetup = false;
+ }
+ /**
+ * Clones the renderer.
+ * @returns the cloned renderer
+ */
+ clone() {
+ const newRenderer = new ObjectRenderer(this.name, this._scene, this.options);
+ if (this.renderList) {
+ newRenderer.renderList = this.renderList.slice(0);
+ }
+ return newRenderer;
+ }
+ /**
+ * Dispose the renderer and release its associated resources.
+ */
+ dispose() {
+ const renderList = this.renderList ? this.renderList : this._scene.getActiveMeshes().data;
+ const renderListLength = this.renderList ? this.renderList.length : this._scene.getActiveMeshes().length;
+ for (let i = 0; i < renderListLength; i++) {
+ const mesh = renderList[i];
+ if (mesh.getMaterialForRenderPass(this.renderPassId) !== undefined) {
+ mesh.setMaterialForRenderPass(this.renderPassId, undefined);
+ }
+ }
+ this.onBeforeRenderObservable.clear();
+ this.onAfterRenderObservable.clear();
+ this.onBeforeRenderingManagerRenderObservable.clear();
+ this.onAfterRenderingManagerRenderObservable.clear();
+ this.onFastPathRenderObservable.clear();
+ this._releaseRenderPassId();
+ this.renderList = null;
+ }
+ /** @internal */
+ _rebuild() {
+ if (this.refreshRate === ObjectRenderer.REFRESHRATE_RENDER_ONCE) {
+ this.refreshRate = ObjectRenderer.REFRESHRATE_RENDER_ONCE;
+ }
+ }
+ /**
+ * Clear the info related to rendering groups preventing retention point in material dispose.
+ */
+ freeRenderingGroups() {
+ if (this._renderingManager) {
+ this._renderingManager.freeRenderingGroups();
+ }
+ }
+}
+/**
+ * Objects will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
+ */
+ObjectRenderer.REFRESHRATE_RENDER_ONCE = 0;
+/**
+ * Objects will be rendered every frame and is recommended for dynamic contents.
+ */
+ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
+/**
+ * Objects will be rendered every 2 frames which could be enough if your dynamic objects are not
+ * the central point of your effect and can save a lot of performances.
+ */
+ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
+
+/**
+ * Sets a depth stencil texture from a render target on the engine to be used in the shader.
+ * @param channel Name of the sampler variable.
+ * @param texture Texture to set.
+ */
+Effect.prototype.setDepthStencilTexture = function (channel, texture) {
+ this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture, channel);
+};
+/**
+ * This Helps creating a texture that will be created from a camera in your scene.
+ * It is basically a dynamic texture that could be used to create special effects for instance.
+ * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
+ */
+class RenderTargetTexture extends Texture {
+ /**
+ * Use this predicate to dynamically define the list of mesh you want to render.
+ * If set, the renderList property will be overwritten.
+ */
+ get renderListPredicate() {
+ return this._objectRenderer.renderListPredicate;
+ }
+ set renderListPredicate(value) {
+ this._objectRenderer.renderListPredicate = value;
+ }
+ /**
+ * Use this list to define the list of mesh you want to render.
+ */
+ get renderList() {
+ return this._objectRenderer.renderList;
+ }
+ set renderList(value) {
+ this._objectRenderer.renderList = value;
+ }
+ /**
+ * Define the list of particle systems to render in the texture. If not provided, will render all the particle systems of the scene.
+ * Note that the particle systems are rendered only if renderParticles is set to true.
+ */
+ get particleSystemList() {
+ return this._objectRenderer.particleSystemList;
+ }
+ set particleSystemList(value) {
+ this._objectRenderer.particleSystemList = value;
+ }
+ /**
+ * Use this function to overload the renderList array at rendering time.
+ * Return null to render with the current renderList, else return the list of meshes to use for rendering.
+ * For 2DArray RTT, layerOrFace is the index of the layer that is going to be rendered, else it is the faceIndex of
+ * the cube (if the RTT is a cube, else layerOrFace=0).
+ * The renderList passed to the function is the current render list (the one that will be used if the function returns null).
+ * The length of this list is passed through renderListLength: don't use renderList.length directly because the array can
+ * hold dummy elements!
+ */
+ get getCustomRenderList() {
+ return this._objectRenderer.getCustomRenderList;
+ }
+ set getCustomRenderList(value) {
+ this._objectRenderer.getCustomRenderList = value;
+ }
+ /**
+ * Define if particles should be rendered in your texture (default: true).
+ */
+ get renderParticles() {
+ return this._objectRenderer.renderParticles;
+ }
+ set renderParticles(value) {
+ this._objectRenderer.renderParticles = value;
+ }
+ /**
+ * Define if sprites should be rendered in your texture (default: false).
+ */
+ get renderSprites() {
+ return this._objectRenderer.renderSprites;
+ }
+ set renderSprites(value) {
+ this._objectRenderer.renderSprites = value;
+ }
+ /**
+ * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined) (default: false).
+ */
+ get forceLayerMaskCheck() {
+ return this._objectRenderer.forceLayerMaskCheck;
+ }
+ set forceLayerMaskCheck(value) {
+ this._objectRenderer.forceLayerMaskCheck = value;
+ }
+ /**
+ * Define the camera used to render the texture.
+ */
+ get activeCamera() {
+ return this._objectRenderer.activeCamera;
+ }
+ set activeCamera(value) {
+ this._objectRenderer.activeCamera = value;
+ }
+ /**
+ * Define the camera used to calculate the LOD of the objects.
+ * If not defined, activeCamera will be used. If not defined nor activeCamera, scene's active camera will be used.
+ */
+ get cameraForLOD() {
+ return this._objectRenderer.cameraForLOD;
+ }
+ set cameraForLOD(value) {
+ this._objectRenderer.cameraForLOD = value;
+ }
+ /**
+ * If true, all objects will be rendered in linear space (default: false)
+ */
+ get renderInLinearSpace() {
+ return this._objectRenderer.renderInLinearSpace;
+ }
+ set renderInLinearSpace(value) {
+ this._objectRenderer.renderInLinearSpace = value;
+ }
+ /**
+ * Override the mesh isReady function with your own one.
+ */
+ get customIsReadyFunction() {
+ return this._objectRenderer.customIsReadyFunction;
+ }
+ set customIsReadyFunction(value) {
+ this._objectRenderer.customIsReadyFunction = value;
+ }
+ /**
+ * Override the render function of the texture with your own one.
+ */
+ get customRenderFunction() {
+ return this._objectRenderer.customRenderFunction;
+ }
+ set customRenderFunction(value) {
+ this._objectRenderer.customRenderFunction = value;
+ }
+ /**
+ * Post-processes for this render target
+ */
+ get postProcesses() {
+ return this._postProcesses;
+ }
+ get _prePassEnabled() {
+ return !!this._prePassRenderTarget && this._prePassRenderTarget.enabled;
+ }
+ /**
+ * Set a after unbind callback in the texture.
+ * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
+ */
+ set onAfterUnbind(callback) {
+ if (this._onAfterUnbindObserver) {
+ this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
+ }
+ this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
+ }
+ /**
+ * An event triggered before rendering the texture
+ */
+ get onBeforeRenderObservable() {
+ return this._objectRenderer.onBeforeRenderObservable;
+ }
+ /**
+ * Set a before render callback in the texture.
+ * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
+ */
+ set onBeforeRender(callback) {
+ if (this._onBeforeRenderObserver) {
+ this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
+ }
+ this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
+ }
+ /**
+ * An event triggered after rendering the texture
+ */
+ get onAfterRenderObservable() {
+ return this._objectRenderer.onAfterRenderObservable;
+ }
+ /**
+ * Set a after render callback in the texture.
+ * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
+ */
+ set onAfterRender(callback) {
+ if (this._onAfterRenderObserver) {
+ this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
+ }
+ this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
+ }
+ /**
+ * Set a clear callback in the texture.
+ * This has been kept for backward compatibility and use of onClearObservable is recommended.
+ */
+ set onClear(callback) {
+ if (this._onClearObserver) {
+ this.onClearObservable.remove(this._onClearObserver);
+ }
+ this._onClearObserver = this.onClearObservable.add(callback);
+ }
+ /** @internal */
+ get _waitingRenderList() {
+ return this._objectRenderer._waitingRenderList;
+ }
+ /** @internal */
+ set _waitingRenderList(value) {
+ this._objectRenderer._waitingRenderList = value;
+ }
+ /**
+ * Current render pass id of the render target texture. Note it can change over the rendering as there's a separate id for each face of a cube / each layer of an array layer!
+ */
+ get renderPassId() {
+ return this._objectRenderer.renderPassId;
+ }
+ /**
+ * Gets the render pass ids used by the render target texture. For a single render target the array length will be 1, for a cube texture it will be 6 and for
+ * a 2D texture array it will return an array of ids the size of the 2D texture array
+ */
+ get renderPassIds() {
+ return this._objectRenderer.renderPassIds;
+ }
+ /**
+ * Gets the current value of the refreshId counter
+ */
+ get currentRefreshId() {
+ return this._objectRenderer.currentRefreshId;
+ }
+ /**
+ * Sets a specific material to be used to render a mesh/a list of meshes in this render target texture
+ * @param mesh mesh or array of meshes
+ * @param material material or array of materials to use for this render pass. If undefined is passed, no specific material will be used but the regular material instead (mesh.material). It's possible to provide an array of materials to use a different material for each rendering in the case of a cube texture (6 rendering) and a 2D texture array (as many rendering as the length of the array)
+ */
+ setMaterialForRendering(mesh, material) {
+ this._objectRenderer.setMaterialForRendering(mesh, material);
+ }
+ /**
+ * Define if the texture has multiple draw buffers or if false a single draw buffer.
+ */
+ get isMulti() {
+ return this._renderTarget?.isMulti ?? false;
+ }
+ /**
+ * Gets render target creation options that were used.
+ */
+ get renderTargetOptions() {
+ return this._renderTargetOptions;
+ }
+ /**
+ * Gets the render target wrapper associated with this render target
+ */
+ get renderTarget() {
+ return this._renderTarget;
+ }
+ _onRatioRescale() {
+ if (this._sizeRatio) {
+ this.resize(this._initialSizeParameter);
+ }
+ }
+ /**
+ * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
+ * When defined, the cubemap will switch to local mode
+ * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
+ * @example https://www.babylonjs-playground.com/#RNASML
+ */
+ set boundingBoxSize(value) {
+ if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
+ return;
+ }
+ this._boundingBoxSize = value;
+ const scene = this.getScene();
+ if (scene) {
+ scene.markAllMaterialsAsDirty(1);
+ }
+ }
+ get boundingBoxSize() {
+ return this._boundingBoxSize;
+ }
+ /**
+ * In case the RTT has been created with a depth texture, get the associated
+ * depth texture.
+ * Otherwise, return null.
+ */
+ get depthStencilTexture() {
+ return this._renderTarget?._depthStencilTexture ?? null;
+ }
+ /** @internal */
+ constructor(name, size, scene, generateMipMaps = false, doNotChangeAspectRatio = true, type = 0, isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = 5, delayAllocation = false, samples, creationFlags, noColorAttachment = false, useSRGBBuffer = false) {
+ let colorAttachment = undefined;
+ let gammaSpace = true;
+ let existingObjectRenderer = undefined;
+ if (typeof generateMipMaps === "object") {
+ const options = generateMipMaps;
+ generateMipMaps = !!options.generateMipMaps;
+ doNotChangeAspectRatio = options.doNotChangeAspectRatio ?? true;
+ type = options.type ?? 0;
+ isCube = !!options.isCube;
+ samplingMode = options.samplingMode ?? Texture.TRILINEAR_SAMPLINGMODE;
+ generateDepthBuffer = options.generateDepthBuffer ?? true;
+ generateStencilBuffer = !!options.generateStencilBuffer;
+ isMulti = !!options.isMulti;
+ format = options.format ?? 5;
+ delayAllocation = !!options.delayAllocation;
+ samples = options.samples;
+ creationFlags = options.creationFlags;
+ noColorAttachment = !!options.noColorAttachment;
+ useSRGBBuffer = !!options.useSRGBBuffer;
+ colorAttachment = options.colorAttachment;
+ gammaSpace = options.gammaSpace ?? gammaSpace;
+ existingObjectRenderer = options.existingObjectRenderer;
+ }
+ super(null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format);
+ /**
+ * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
+ */
+ this.ignoreCameraViewport = false;
+ /**
+ * An event triggered when the texture is unbind.
+ */
+ this.onBeforeBindObservable = new Observable();
+ /**
+ * An event triggered when the texture is unbind.
+ */
+ this.onAfterUnbindObservable = new Observable();
+ /**
+ * An event triggered after the texture clear
+ */
+ this.onClearObservable = new Observable();
+ /**
+ * An event triggered when the texture is resized.
+ */
+ this.onResizeObservable = new Observable();
+ /** @internal */
+ this._cleared = false;
+ /**
+ * Skip the initial clear of the rtt at the beginning of the frame render loop
+ */
+ this.skipInitialClear = false;
+ this._samples = 1;
+ this._canRescale = true;
+ this._renderTarget = null;
+ this._dontDisposeObjectRenderer = false;
+ /**
+ * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
+ * It must define where the camera used to render the texture is set
+ */
+ this.boundingBoxPosition = Vector3.Zero();
+ /** @internal */
+ this._disableEngineStages = false; // TODO: remove this when the shadow generator task (frame graph) is reworked (see https://github.com/BabylonJS/Babylon.js/pull/15962#discussion_r1874417607)
+ this._dumpToolsLoading = false;
+ scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ const engine = this.getScene().getEngine();
+ this._gammaSpace = gammaSpace;
+ this._coordinatesMode = Texture.PROJECTION_MODE;
+ this.name = name;
+ this.isRenderTarget = true;
+ this._initialSizeParameter = size;
+ this._dontDisposeObjectRenderer = !!existingObjectRenderer;
+ this._processSizeParameter(size);
+ this._objectRenderer =
+ existingObjectRenderer ??
+ new ObjectRenderer(name, scene, {
+ numPasses: isCube ? 6 : this.getRenderLayers() || 1,
+ doNotChangeAspectRatio,
+ });
+ this._onBeforeRenderingManagerRenderObserver = this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(() => {
+ // Before clear
+ if (!this._disableEngineStages) {
+ for (const step of this._scene._beforeRenderTargetClearStage) {
+ step.action(this, this._currentFaceIndex, this._currentLayer);
+ }
+ }
+ // Clear
+ if (this.onClearObservable.hasObservers()) {
+ this.onClearObservable.notifyObservers(engine);
+ }
+ else if (!this.skipInitialClear) {
+ engine.clear(this.clearColor || this._scene.clearColor, true, true, true);
+ }
+ if (!this._doNotChangeAspectRatio) {
+ this._scene.updateTransformMatrix(true);
+ }
+ // Before Camera Draw
+ if (!this._disableEngineStages) {
+ for (const step of this._scene._beforeRenderTargetDrawStage) {
+ step.action(this, this._currentFaceIndex, this._currentLayer);
+ }
+ }
+ });
+ this._onAfterRenderingManagerRenderObserver = this._objectRenderer.onAfterRenderingManagerRenderObservable.add(() => {
+ // After Camera Draw
+ if (!this._disableEngineStages) {
+ for (const step of this._scene._afterRenderTargetDrawStage) {
+ step.action(this, this._currentFaceIndex, this._currentLayer);
+ }
+ }
+ const saveGenerateMipMaps = this._texture?.generateMipMaps ?? false;
+ if (this._texture) {
+ this._texture.generateMipMaps = false; // if left true, the mipmaps will be generated (if this._texture.generateMipMaps = true) when the first post process binds its own RTT: by doing so it will unbind the current RTT,
+ // which will trigger a mipmap generation. We don't want this because it's a wasted work, we will do an unbind of the current RTT at the end of the process (see unbindFrameBuffer) which will
+ // trigger the generation of the final mipmaps
+ }
+ if (this._postProcessManager) {
+ this._postProcessManager._finalizeFrame(false, this._renderTarget ?? undefined, this._currentFaceIndex, this._postProcesses, this.ignoreCameraViewport);
+ }
+ else if (this._currentUseCameraPostProcess) {
+ this._scene.postProcessManager._finalizeFrame(false, this._renderTarget ?? undefined, this._currentFaceIndex);
+ }
+ if (!this._disableEngineStages) {
+ for (const step of this._scene._afterRenderTargetPostProcessStage) {
+ step.action(this, this._currentFaceIndex, this._currentLayer);
+ }
+ }
+ if (this._texture) {
+ this._texture.generateMipMaps = saveGenerateMipMaps;
+ }
+ if (!this._doNotChangeAspectRatio) {
+ this._scene.updateTransformMatrix(true);
+ }
+ // Dump ?
+ if (this._currentDumpForDebug) {
+ if (!this._dumpTools) {
+ Logger.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project");
+ }
+ else {
+ this._dumpTools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
+ }
+ }
+ });
+ this._onFastPathRenderObserver = this._objectRenderer.onFastPathRenderObservable.add(() => {
+ if (this.onClearObservable.hasObservers()) {
+ this.onClearObservable.notifyObservers(engine);
+ }
+ else {
+ if (!this.skipInitialClear) {
+ engine.clear(this.clearColor || this._scene.clearColor, true, true, true);
+ }
+ }
+ });
+ this._resizeObserver = engine.onResizeObservable.add(() => { });
+ this._generateMipMaps = generateMipMaps ? true : false;
+ this._doNotChangeAspectRatio = doNotChangeAspectRatio;
+ if (isMulti) {
+ return;
+ }
+ this._renderTargetOptions = {
+ generateMipMaps: generateMipMaps,
+ type: type,
+ format: this._format ?? undefined,
+ samplingMode: this.samplingMode,
+ generateDepthBuffer: generateDepthBuffer,
+ generateStencilBuffer: generateStencilBuffer,
+ samples,
+ creationFlags,
+ noColorAttachment: noColorAttachment,
+ useSRGBBuffer,
+ colorAttachment: colorAttachment,
+ label: this.name,
+ };
+ if (this.samplingMode === Texture.NEAREST_SAMPLINGMODE) {
+ this.wrapU = Texture.CLAMP_ADDRESSMODE;
+ this.wrapV = Texture.CLAMP_ADDRESSMODE;
+ }
+ if (!delayAllocation) {
+ if (isCube) {
+ this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
+ this.coordinatesMode = Texture.INVCUBIC_MODE;
+ this._textureMatrix = Matrix.Identity();
+ }
+ else {
+ this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
+ }
+ this._texture = this._renderTarget.texture;
+ if (samples !== undefined) {
+ this.samples = samples;
+ }
+ }
+ }
+ /**
+ * Creates a depth stencil texture.
+ * This is only available in WebGL 2 or with the depth texture extension available.
+ * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode (default: 0)
+ * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture (default: true)
+ * @param generateStencil Specifies whether or not a stencil should be allocated in the texture (default: false)
+ * @param samples sample count of the depth/stencil texture (default: 1)
+ * @param format format of the depth texture (default: 14)
+ * @param label defines the label of the texture (for debugging purpose)
+ */
+ createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) {
+ this._renderTarget?.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format, label);
+ }
+ _processSizeParameter(size) {
+ if (size.ratio) {
+ this._sizeRatio = size.ratio;
+ const engine = this._getEngine();
+ this._size = {
+ width: this._bestReflectionRenderTargetDimension(engine.getRenderWidth(), this._sizeRatio),
+ height: this._bestReflectionRenderTargetDimension(engine.getRenderHeight(), this._sizeRatio),
+ };
+ }
+ else {
+ this._size = size;
+ }
+ }
+ /**
+ * Define the number of samples to use in case of MSAA.
+ * It defaults to one meaning no MSAA has been enabled.
+ */
+ get samples() {
+ return this._renderTarget?.samples ?? this._samples;
+ }
+ set samples(value) {
+ if (this._renderTarget) {
+ this._samples = this._renderTarget.setSamples(value);
+ }
+ }
+ /**
+ * Adds a post process to the render target rendering passes.
+ * @param postProcess define the post process to add
+ */
+ addPostProcess(postProcess) {
+ if (!this._postProcessManager) {
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ this._postProcessManager = new PostProcessManager(scene);
+ this._postProcesses = new Array();
+ }
+ this._postProcesses.push(postProcess);
+ this._postProcesses[0].autoClear = false;
+ }
+ /**
+ * Clear all the post processes attached to the render target
+ * @param dispose define if the cleared post processes should also be disposed (false by default)
+ */
+ clearPostProcesses(dispose = false) {
+ if (!this._postProcesses) {
+ return;
+ }
+ if (dispose) {
+ for (const postProcess of this._postProcesses) {
+ postProcess.dispose();
+ }
+ }
+ this._postProcesses = [];
+ }
+ /**
+ * Remove one of the post process from the list of attached post processes to the texture
+ * @param postProcess define the post process to remove from the list
+ */
+ removePostProcess(postProcess) {
+ if (!this._postProcesses) {
+ return;
+ }
+ const index = this._postProcesses.indexOf(postProcess);
+ if (index === -1) {
+ return;
+ }
+ this._postProcesses.splice(index, 1);
+ if (this._postProcesses.length > 0) {
+ this._postProcesses[0].autoClear = false;
+ }
+ }
+ /**
+ * Resets the refresh counter of the texture and start bak from scratch.
+ * Could be useful to regenerate the texture if it is setup to render only once.
+ */
+ resetRefreshCounter() {
+ this._objectRenderer.resetRefreshCounter();
+ }
+ /**
+ * Define the refresh rate of the texture or the rendering frequency.
+ * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
+ */
+ get refreshRate() {
+ return this._objectRenderer.refreshRate;
+ }
+ set refreshRate(value) {
+ this._objectRenderer.refreshRate = value;
+ }
+ /** @internal */
+ _shouldRender() {
+ return this._objectRenderer.shouldRender();
+ }
+ /**
+ * Gets the actual render size of the texture.
+ * @returns the width of the render size
+ */
+ getRenderSize() {
+ return this.getRenderWidth();
+ }
+ /**
+ * Gets the actual render width of the texture.
+ * @returns the width of the render size
+ */
+ getRenderWidth() {
+ if (this._size.width) {
+ return this._size.width;
+ }
+ return this._size;
+ }
+ /**
+ * Gets the actual render height of the texture.
+ * @returns the height of the render size
+ */
+ getRenderHeight() {
+ if (this._size.width) {
+ return this._size.height;
+ }
+ return this._size;
+ }
+ /**
+ * Gets the actual number of layers of the texture or, in the case of a 3D texture, return the depth.
+ * @returns the number of layers
+ */
+ getRenderLayers() {
+ const layers = this._size.layers;
+ if (layers) {
+ return layers;
+ }
+ const depth = this._size.depth;
+ if (depth) {
+ return depth;
+ }
+ return 0;
+ }
+ /**
+ * Don't allow this render target texture to rescale. Mainly used to prevent rescaling by the scene optimizer.
+ */
+ disableRescaling() {
+ this._canRescale = false;
+ }
+ /**
+ * Get if the texture can be rescaled or not.
+ */
+ get canRescale() {
+ return this._canRescale;
+ }
+ /**
+ * Resize the texture using a ratio.
+ * @param ratio the ratio to apply to the texture size in order to compute the new target size
+ */
+ scale(ratio) {
+ const newSize = Math.max(1, this.getRenderSize() * ratio);
+ this.resize(newSize);
+ }
+ /**
+ * Get the texture reflection matrix used to rotate/transform the reflection.
+ * @returns the reflection matrix
+ */
+ getReflectionTextureMatrix() {
+ if (this.isCube) {
+ return this._textureMatrix;
+ }
+ return super.getReflectionTextureMatrix();
+ }
+ /**
+ * Resize the texture to a new desired size.
+ * Be careful as it will recreate all the data in the new texture.
+ * @param size Define the new size. It can be:
+ * - a number for squared texture,
+ * - an object containing { width: number, height: number }
+ * - or an object containing a ratio { ratio: number }
+ */
+ resize(size) {
+ const wasCube = this.isCube;
+ this._renderTarget?.dispose();
+ this._renderTarget = null;
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ this._processSizeParameter(size);
+ if (wasCube) {
+ this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
+ }
+ else {
+ this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
+ }
+ this._texture = this._renderTarget.texture;
+ if (this._renderTargetOptions.samples !== undefined) {
+ this.samples = this._renderTargetOptions.samples;
+ }
+ if (this.onResizeObservable.hasObservers()) {
+ this.onResizeObservable.notifyObservers(this);
+ }
+ }
+ /**
+ * Renders all the objects from the render list into the texture.
+ * @param useCameraPostProcess Define if camera post processes should be used during the rendering
+ * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
+ */
+ render(useCameraPostProcess = false, dumpForDebug = false) {
+ this._render(useCameraPostProcess, dumpForDebug);
+ }
+ /**
+ * This function will check if the render target texture can be rendered (textures are loaded, shaders are compiled)
+ * @returns true if all required resources are ready
+ */
+ isReadyForRendering() {
+ if (!this._dumpToolsLoading) {
+ this._dumpToolsLoading = true;
+ // avoid a static import to allow ignoring the import in some cases
+ Promise.resolve().then(() => dumpTools).then((module) => (this._dumpTools = module));
+ }
+ this._objectRenderer.prepareRenderList();
+ this.onBeforeBindObservable.notifyObservers(this);
+ this._objectRenderer.initRender(this.getRenderWidth(), this.getRenderHeight());
+ const isReady = this._objectRenderer._checkReadiness();
+ this.onAfterUnbindObservable.notifyObservers(this);
+ this._objectRenderer.finishRender();
+ return isReady;
+ }
+ _render(useCameraPostProcess = false, dumpForDebug = false) {
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ if (this.useCameraPostProcesses !== undefined) {
+ useCameraPostProcess = this.useCameraPostProcesses;
+ }
+ this._objectRenderer.prepareRenderList();
+ this.onBeforeBindObservable.notifyObservers(this);
+ this._objectRenderer.initRender(this.getRenderWidth(), this.getRenderHeight());
+ if ((this.is2DArray || this.is3D) && !this.isMulti) {
+ for (let layer = 0; layer < this.getRenderLayers(); layer++) {
+ this._renderToTarget(0, useCameraPostProcess, dumpForDebug, layer);
+ scene.incrementRenderId();
+ scene.resetCachedMaterial();
+ }
+ }
+ else if (this.isCube && !this.isMulti) {
+ for (let face = 0; face < 6; face++) {
+ this._renderToTarget(face, useCameraPostProcess, dumpForDebug);
+ scene.incrementRenderId();
+ scene.resetCachedMaterial();
+ }
+ }
+ else {
+ this._renderToTarget(0, useCameraPostProcess, dumpForDebug);
+ }
+ this.onAfterUnbindObservable.notifyObservers(this);
+ this._objectRenderer.finishRender();
+ }
+ _bestReflectionRenderTargetDimension(renderDimension, scale) {
+ const minimum = 128;
+ const x = renderDimension * scale;
+ const curved = NearestPOT(x + (minimum * minimum) / (minimum + x));
+ // Ensure we don't exceed the render dimension (while staying POT)
+ return Math.min(FloorPOT(renderDimension), curved);
+ }
+ /**
+ * @internal
+ * @param faceIndex face index to bind to if this is a cubetexture
+ * @param layer defines the index of the texture to bind in the array
+ */
+ _bindFrameBuffer(faceIndex = 0, layer = 0) {
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ const engine = scene.getEngine();
+ if (this._renderTarget) {
+ engine.bindFramebuffer(this._renderTarget, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, 0, layer);
+ }
+ }
+ _unbindFrameBuffer(engine, faceIndex) {
+ if (!this._renderTarget) {
+ return;
+ }
+ engine.unBindFramebuffer(this._renderTarget, this.isCube, () => {
+ this.onAfterRenderObservable.notifyObservers(faceIndex);
+ });
+ }
+ /**
+ * @internal
+ */
+ _prepareFrame(scene, faceIndex, layer, useCameraPostProcess) {
+ if (this._postProcessManager) {
+ if (!this._prePassEnabled) {
+ this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
+ }
+ }
+ else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
+ this._bindFrameBuffer(faceIndex, layer);
+ }
+ }
+ _renderToTarget(faceIndex, useCameraPostProcess, dumpForDebug, layer = 0) {
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ const engine = scene.getEngine();
+ this._currentFaceIndex = faceIndex;
+ this._currentLayer = layer;
+ this._currentUseCameraPostProcess = useCameraPostProcess;
+ this._currentDumpForDebug = dumpForDebug;
+ this._prepareFrame(scene, faceIndex, layer, useCameraPostProcess);
+ engine._debugPushGroup?.(`render to face #${faceIndex} layer #${layer}`, 2);
+ this._objectRenderer.render(faceIndex + layer, true); // only faceIndex or layer (if any) will be different from 0 (we don't support array of cubes), so it's safe to add them to get the pass index
+ engine._debugPopGroup?.(2);
+ this._unbindFrameBuffer(engine, faceIndex);
+ if (this._texture && this.isCube && faceIndex === 5) {
+ engine.generateMipMapsForCubemap(this._texture, true);
+ }
+ }
+ /**
+ * Overrides the default sort function applied in the rendering group to prepare the meshes.
+ * This allowed control for front to back rendering or reversely depending of the special needs.
+ *
+ * @param renderingGroupId The rendering group id corresponding to its index
+ * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
+ * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
+ * @param transparentSortCompareFn The transparent queue comparison function use to sort.
+ */
+ setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {
+ this._objectRenderer.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
+ }
+ /**
+ * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
+ *
+ * @param renderingGroupId The rendering group id corresponding to its index
+ * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
+ */
+ setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) {
+ this._objectRenderer.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
+ }
+ /**
+ * Clones the texture.
+ * @returns the cloned texture
+ */
+ clone() {
+ const textureSize = this.getSize();
+ const newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer, undefined, this._renderTargetOptions.format, undefined, this._renderTargetOptions.samples);
+ // Base texture
+ newTexture.hasAlpha = this.hasAlpha;
+ newTexture.level = this.level;
+ // RenderTarget Texture
+ newTexture.coordinatesMode = this.coordinatesMode;
+ if (this.renderList) {
+ newTexture.renderList = this.renderList.slice(0);
+ }
+ return newTexture;
+ }
+ /**
+ * Serialize the texture to a JSON representation we can easily use in the respective Parse function.
+ * @returns The JSON representation of the texture
+ */
+ serialize() {
+ if (!this.name) {
+ return null;
+ }
+ const serializationObject = super.serialize();
+ serializationObject.renderTargetSize = this.getRenderSize();
+ serializationObject.renderList = [];
+ if (this.renderList) {
+ for (let index = 0; index < this.renderList.length; index++) {
+ serializationObject.renderList.push(this.renderList[index].id);
+ }
+ }
+ return serializationObject;
+ }
+ /**
+ * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
+ */
+ disposeFramebufferObjects() {
+ this._renderTarget?.dispose(true);
+ }
+ /**
+ * Release and destroy the underlying lower level texture aka internalTexture.
+ */
+ releaseInternalTexture() {
+ this._renderTarget?.releaseTextures();
+ this._texture = null;
+ }
+ /**
+ * Dispose the texture and release its associated resources.
+ */
+ dispose() {
+ this.onResizeObservable.clear();
+ this.onClearObservable.clear();
+ this.onAfterUnbindObservable.clear();
+ this.onBeforeBindObservable.clear();
+ if (this._postProcessManager) {
+ this._postProcessManager.dispose();
+ this._postProcessManager = null;
+ }
+ if (this._prePassRenderTarget) {
+ this._prePassRenderTarget.dispose();
+ }
+ this._objectRenderer.onBeforeRenderingManagerRenderObservable.remove(this._onBeforeRenderingManagerRenderObserver);
+ this._objectRenderer.onAfterRenderingManagerRenderObservable.remove(this._onAfterRenderingManagerRenderObserver);
+ this._objectRenderer.onFastPathRenderObservable.remove(this._onFastPathRenderObserver);
+ if (!this._dontDisposeObjectRenderer) {
+ this._objectRenderer.dispose();
+ }
+ this.clearPostProcesses(true);
+ if (this._resizeObserver) {
+ this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
+ this._resizeObserver = null;
+ }
+ // Remove from custom render targets
+ const scene = this.getScene();
+ if (!scene) {
+ return;
+ }
+ let index = scene.customRenderTargets.indexOf(this);
+ if (index >= 0) {
+ scene.customRenderTargets.splice(index, 1);
+ }
+ for (const camera of scene.cameras) {
+ index = camera.customRenderTargets.indexOf(this);
+ if (index >= 0) {
+ camera.customRenderTargets.splice(index, 1);
+ }
+ }
+ this._renderTarget?.dispose();
+ this._renderTarget = null;
+ this._texture = null;
+ super.dispose();
+ }
+ /** @internal */
+ _rebuild() {
+ this._objectRenderer._rebuild();
+ if (this._postProcessManager) {
+ this._postProcessManager._rebuild();
+ }
+ }
+ /**
+ * Clear the info related to rendering groups preventing retention point in material dispose.
+ */
+ freeRenderingGroups() {
+ this._objectRenderer.freeRenderingGroups();
+ }
+ /**
+ * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)
+ * @returns the view count
+ */
+ getViewCount() {
+ return 1;
+ }
+}
+/**
+ * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
+ */
+RenderTargetTexture.REFRESHRATE_RENDER_ONCE = ObjectRenderer.REFRESHRATE_RENDER_ONCE;
+/**
+ * The texture will be rendered every frame and is recommended for dynamic contents.
+ */
+RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME;
+/**
+ * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
+ * the central point of your effect and can save a lot of performances.
+ */
+RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+Texture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => {
+ return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps);
+};
+
+// Do not edit.
+const name$8h = "postprocessVertexShader";
+const shader$8g = `attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
+#define CUSTOM_VERTEX_DEFINITIONS
+void main(void) {
+#define CUSTOM_VERTEX_MAIN_BEGIN
+vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);
+#define CUSTOM_VERTEX_MAIN_END
+}`;
+// Sideeffect
+if (!ShaderStore.ShadersStore[name$8h]) {
+ ShaderStore.ShadersStore[name$8h] = shader$8g;
+}
+/** @internal */
+const postprocessVertexShader = { name: name$8h, shader: shader$8g };
+
+const postprocess_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ postprocessVertexShader
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Fullscreen quad buffers by default.
+const defaultOptions = {
+ positions: [1, 1, -1, 1, -1, -1, 1, -1],
+ indices: [0, 1, 2, 0, 2, 3],
+};
+/**
+ * Helper class to render one or more effects.
+ * You can access the previous rendering in your shader by declaring a sampler named textureSampler
+ */
+class EffectRenderer {
+ /**
+ * Creates an effect renderer
+ * @param engine the engine to use for rendering
+ * @param options defines the options of the effect renderer
+ */
+ constructor(engine, options = defaultOptions) {
+ this._fullscreenViewport = new Viewport(0, 0, 1, 1);
+ const positions = options.positions ?? defaultOptions.positions;
+ const indices = options.indices ?? defaultOptions.indices;
+ this.engine = engine;
+ this._vertexBuffers = {
+ [VertexBuffer.PositionKind]: new VertexBuffer(engine, positions, VertexBuffer.PositionKind, false, false, 2),
+ };
+ this._indexBuffer = engine.createIndexBuffer(indices);
+ this._onContextRestoredObserver = engine.onContextRestoredObservable.add(() => {
+ this._indexBuffer = engine.createIndexBuffer(indices);
+ for (const key in this._vertexBuffers) {
+ const vertexBuffer = this._vertexBuffers[key];
+ vertexBuffer._rebuild();
+ }
+ });
+ }
+ /**
+ * Sets the current viewport in normalized coordinates 0-1
+ * @param viewport Defines the viewport to set (defaults to 0 0 1 1)
+ */
+ setViewport(viewport = this._fullscreenViewport) {
+ this.engine.setViewport(viewport);
+ }
+ /**
+ * Binds the embedded attributes buffer to the effect.
+ * @param effect Defines the effect to bind the attributes for
+ */
+ bindBuffers(effect) {
+ this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
+ }
+ /**
+ * Sets the current effect wrapper to use during draw.
+ * The effect needs to be ready before calling this api.
+ * This also sets the default full screen position attribute.
+ * @param effectWrapper Defines the effect to draw with
+ */
+ applyEffectWrapper(effectWrapper) {
+ this.engine.setState(true);
+ this.engine.depthCullingState.depthTest = false;
+ this.engine.stencilState.stencilTest = false;
+ this.engine.enableEffect(effectWrapper.drawWrapper);
+ this.bindBuffers(effectWrapper.effect);
+ effectWrapper.onApplyObservable.notifyObservers({});
+ }
+ /**
+ * Saves engine states
+ */
+ saveStates() {
+ this._savedStateDepthTest = this.engine.depthCullingState.depthTest;
+ this._savedStateStencilTest = this.engine.stencilState.stencilTest;
+ }
+ /**
+ * Restores engine states
+ */
+ restoreStates() {
+ this.engine.depthCullingState.depthTest = this._savedStateDepthTest;
+ this.engine.stencilState.stencilTest = this._savedStateStencilTest;
+ }
+ /**
+ * Draws a full screen quad.
+ */
+ draw() {
+ this.engine.drawElementsType(0, 0, 6);
+ }
+ _isRenderTargetTexture(texture) {
+ return texture.renderTarget !== undefined;
+ }
+ /**
+ * renders one or more effects to a specified texture
+ * @param effectWrapper the effect to renderer
+ * @param outputTexture texture to draw to, if null it will render to the currently bound frame buffer
+ */
+ render(effectWrapper, outputTexture = null) {
+ // Ensure effect is ready
+ if (!effectWrapper.effect.isReady()) {
+ return;
+ }
+ this.saveStates();
+ // Reset state
+ this.setViewport();
+ const out = outputTexture === null ? null : this._isRenderTargetTexture(outputTexture) ? outputTexture.renderTarget : outputTexture;
+ if (out) {
+ this.engine.bindFramebuffer(out);
+ }
+ this.applyEffectWrapper(effectWrapper);
+ this.draw();
+ if (out) {
+ this.engine.unBindFramebuffer(out);
+ }
+ this.restoreStates();
+ }
+ /**
+ * Disposes of the effect renderer
+ */
+ dispose() {
+ const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
+ if (vertexBuffer) {
+ vertexBuffer.dispose();
+ delete this._vertexBuffers[VertexBuffer.PositionKind];
+ }
+ if (this._indexBuffer) {
+ this.engine._releaseBuffer(this._indexBuffer);
+ }
+ if (this._onContextRestoredObserver) {
+ this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver);
+ this._onContextRestoredObserver = null;
+ }
+ }
+}
+/**
+ * Wraps an effect to be used for rendering
+ */
+class EffectWrapper {
+ /**
+ * Registers a shader code processing with an effect wrapper name.
+ * @param effectWrapperName name of the effect wrapper. Use null for the fallback shader code processing. This is the shader code processing that will be used in case no specific shader code processing has been associated to an effect wrapper name
+ * @param customShaderCodeProcessing shader code processing to associate to the effect wrapper name
+ */
+ static RegisterShaderCodeProcessing(effectWrapperName, customShaderCodeProcessing) {
+ if (!customShaderCodeProcessing) {
+ delete EffectWrapper._CustomShaderCodeProcessing[effectWrapperName ?? ""];
+ return;
+ }
+ EffectWrapper._CustomShaderCodeProcessing[effectWrapperName ?? ""] = customShaderCodeProcessing;
+ }
+ static _GetShaderCodeProcessing(effectWrapperName) {
+ return EffectWrapper._CustomShaderCodeProcessing[effectWrapperName] ?? EffectWrapper._CustomShaderCodeProcessing[""];
+ }
+ /**
+ * Gets or sets the name of the effect wrapper
+ */
+ get name() {
+ return this.options.name;
+ }
+ set name(value) {
+ this.options.name = value;
+ }
+ /**
+ * Get a value indicating if the effect is ready to be used
+ * @returns true if the post-process is ready (shader is compiled)
+ */
+ isReady() {
+ return this._drawWrapper.effect?.isReady() ?? false;
+ }
+ /**
+ * Get the draw wrapper associated with the effect wrapper
+ * @returns the draw wrapper associated with the effect wrapper
+ */
+ get drawWrapper() {
+ return this._drawWrapper;
+ }
+ /**
+ * The underlying effect
+ */
+ get effect() {
+ return this._drawWrapper.effect;
+ }
+ set effect(effect) {
+ this._drawWrapper.effect = effect;
+ }
+ /**
+ * Creates an effect to be rendered
+ * @param creationOptions options to create the effect
+ */
+ constructor(creationOptions) {
+ /**
+ * Type of alpha mode to use when applying the effect (default: Engine.ALPHA_DISABLE). Used only if useAsPostProcess is true.
+ */
+ this.alphaMode = 0;
+ /**
+ * Executed when the effect is created
+ * @returns effect that was created for this effect wrapper
+ */
+ this.onEffectCreatedObservable = new Observable(undefined, true);
+ /**
+ * Event that is fired (only when the EffectWrapper is used with an EffectRenderer) right before the effect is drawn (should be used to update uniforms)
+ */
+ this.onApplyObservable = new Observable();
+ this._shadersLoaded = false;
+ /** @internal */
+ this._webGPUReady = false;
+ this._importPromises = [];
+ this.options = {
+ ...creationOptions,
+ name: creationOptions.name || "effectWrapper",
+ engine: creationOptions.engine,
+ uniforms: creationOptions.uniforms || creationOptions.uniformNames || [],
+ uniformNames: undefined,
+ samplers: creationOptions.samplers || creationOptions.samplerNames || [],
+ samplerNames: undefined,
+ attributeNames: creationOptions.attributeNames || ["position"],
+ uniformBuffers: creationOptions.uniformBuffers || [],
+ defines: creationOptions.defines || "",
+ useShaderStore: creationOptions.useShaderStore || false,
+ vertexUrl: creationOptions.vertexUrl || creationOptions.vertexShader || "postprocess",
+ vertexShader: undefined,
+ fragmentShader: creationOptions.fragmentShader || "pass",
+ indexParameters: creationOptions.indexParameters,
+ blockCompilation: creationOptions.blockCompilation || false,
+ shaderLanguage: creationOptions.shaderLanguage || 0 /* ShaderLanguage.GLSL */,
+ onCompiled: creationOptions.onCompiled || undefined,
+ extraInitializations: creationOptions.extraInitializations || undefined,
+ extraInitializationsAsync: creationOptions.extraInitializationsAsync || undefined,
+ useAsPostProcess: creationOptions.useAsPostProcess ?? false,
+ };
+ this.options.uniformNames = this.options.uniforms;
+ this.options.samplerNames = this.options.samplers;
+ this.options.vertexShader = this.options.vertexUrl;
+ if (this.options.useAsPostProcess) {
+ if (this.options.samplers.indexOf("textureSampler") === -1) {
+ this.options.samplers.push("textureSampler");
+ }
+ if (this.options.uniforms.indexOf("scale") === -1) {
+ this.options.uniforms.push("scale");
+ }
+ }
+ if (creationOptions.vertexUrl || creationOptions.vertexShader) {
+ this._shaderPath = {
+ vertexSource: this.options.vertexShader,
+ };
+ }
+ else {
+ if (!this.options.useAsPostProcess) {
+ this.options.uniforms.push("scale");
+ this.onApplyObservable.add(() => {
+ this.effect.setFloat2("scale", 1, 1);
+ });
+ }
+ this._shaderPath = {
+ vertex: this.options.vertexShader,
+ };
+ }
+ this._shaderPath.fragmentSource = this.options.fragmentShader;
+ this._shaderPath.spectorName = this.options.name;
+ if (this.options.useShaderStore) {
+ this._shaderPath.fragment = this._shaderPath.fragmentSource;
+ if (!this._shaderPath.vertex) {
+ this._shaderPath.vertex = this._shaderPath.vertexSource;
+ }
+ delete this._shaderPath.fragmentSource;
+ delete this._shaderPath.vertexSource;
+ }
+ this.onApplyObservable.add(() => {
+ this.bind();
+ });
+ if (!this.options.useShaderStore) {
+ this._onContextRestoredObserver = this.options.engine.onContextRestoredObservable.add(() => {
+ this.effect._pipelineContext = null; // because _prepareEffect will try to dispose this pipeline before recreating it and that would lead to webgl errors
+ this.effect._prepareEffect();
+ });
+ }
+ this._drawWrapper = new DrawWrapper(this.options.engine);
+ this._webGPUReady = this.options.shaderLanguage === 1 /* ShaderLanguage.WGSL */;
+ const defines = Array.isArray(this.options.defines) ? this.options.defines.join("\n") : this.options.defines;
+ this._postConstructor(this.options.blockCompilation, defines, this.options.extraInitializations);
+ }
+ _gatherImports(useWebGPU = false, list) {
+ if (!this.options.useAsPostProcess) {
+ return;
+ }
+ // this._webGPUReady is used to detect when an effect wrapper is intended to be used with WebGPU
+ if (useWebGPU && this._webGPUReady) {
+ list.push(Promise.all([Promise.resolve().then(() => postprocess_vertex)]));
+ }
+ else {
+ list.push(Promise.all([Promise.resolve().then(() => postprocess_vertex$1)]));
+ }
+ }
+ /** @internal */
+ _postConstructor(blockCompilation, defines = null, extraInitializations, importPromises) {
+ this._importPromises.length = 0;
+ if (importPromises) {
+ this._importPromises.push(...importPromises);
+ }
+ const useWebGPU = this.options.engine.isWebGPU && !EffectWrapper.ForceGLSL;
+ this._gatherImports(useWebGPU, this._importPromises);
+ if (extraInitializations !== undefined) {
+ extraInitializations(useWebGPU, this._importPromises);
+ }
+ if (useWebGPU && this._webGPUReady) {
+ this.options.shaderLanguage = 1 /* ShaderLanguage.WGSL */;
+ }
+ if (!blockCompilation) {
+ this.updateEffect(defines);
+ }
+ }
+ /**
+ * Updates the effect with the current effect wrapper compile time values and recompiles the shader.
+ * @param defines Define statements that should be added at the beginning of the shader. (default: null)
+ * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
+ * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
+ * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
+ * @param onCompiled Called when the shader has been compiled.
+ * @param onError Called if there is an error when compiling a shader.
+ * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time)
+ * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time)
+ */
+ updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) {
+ const customShaderCodeProcessing = EffectWrapper._GetShaderCodeProcessing(this.name);
+ if (customShaderCodeProcessing?.defineCustomBindings) {
+ const newUniforms = uniforms?.slice() ?? [];
+ newUniforms.push(...this.options.uniforms);
+ const newSamplers = samplers?.slice() ?? [];
+ newSamplers.push(...this.options.samplers);
+ defines = customShaderCodeProcessing.defineCustomBindings(this.name, defines, newUniforms, newSamplers);
+ uniforms = newUniforms;
+ samplers = newSamplers;
+ }
+ this.options.defines = defines || "";
+ const waitImportsLoaded = this._shadersLoaded || this._importPromises.length === 0
+ ? undefined
+ : async () => {
+ await Promise.all(this._importPromises);
+ this._shadersLoaded = true;
+ };
+ let extraInitializationsAsync;
+ if (this.options.extraInitializationsAsync) {
+ extraInitializationsAsync = async () => {
+ waitImportsLoaded?.();
+ await this.options.extraInitializationsAsync();
+ };
+ }
+ else {
+ extraInitializationsAsync = waitImportsLoaded;
+ }
+ if (this.options.useShaderStore) {
+ this._drawWrapper.effect = this.options.engine.createEffect({ vertex: vertexUrl ?? this._shaderPath.vertex, fragment: fragmentUrl ?? this._shaderPath.fragment }, {
+ attributes: this.options.attributeNames,
+ uniformsNames: uniforms || this.options.uniforms,
+ uniformBuffersNames: this.options.uniformBuffers,
+ samplers: samplers || this.options.samplers,
+ defines: defines !== null ? defines : "",
+ fallbacks: null,
+ onCompiled: onCompiled ?? this.options.onCompiled,
+ onError: onError ?? null,
+ indexParameters: indexParameters || this.options.indexParameters,
+ processCodeAfterIncludes: customShaderCodeProcessing?.processCodeAfterIncludes
+ ? (shaderType, code) => customShaderCodeProcessing.processCodeAfterIncludes(this.name, shaderType, code)
+ : null,
+ processFinalCode: customShaderCodeProcessing?.processFinalCode
+ ? (shaderType, code) => customShaderCodeProcessing.processFinalCode(this.name, shaderType, code)
+ : null,
+ shaderLanguage: this.options.shaderLanguage,
+ extraInitializationsAsync,
+ }, this.options.engine);
+ }
+ else {
+ this._drawWrapper.effect = new Effect(this._shaderPath, this.options.attributeNames, uniforms || this.options.uniforms, samplers || this.options.samplerNames, this.options.engine, defines, undefined, onCompiled || this.options.onCompiled, undefined, undefined, undefined, this.options.shaderLanguage, extraInitializationsAsync);
+ }
+ this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect);
+ }
+ /**
+ * Binds the data to the effect.
+ */
+ bind() {
+ if (this.options.useAsPostProcess) {
+ this.options.engine.setAlphaMode(this.alphaMode);
+ this.drawWrapper.effect.setFloat2("scale", 1, 1);
+ }
+ EffectWrapper._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name, this._drawWrapper.effect);
+ }
+ /**
+ * Disposes of the effect wrapper
+ * @param _ignored kept for backward compatibility
+ */
+ dispose(_ignored = false) {
+ if (this._onContextRestoredObserver) {
+ this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
+ this._onContextRestoredObserver = null;
+ }
+ this.onEffectCreatedObservable.clear();
+ this._drawWrapper.dispose(true);
+ }
+}
+/**
+ * Force code to compile to glsl even on WebGPU engines.
+ * False by default. This is mostly meant for backward compatibility.
+ */
+EffectWrapper.ForceGLSL = false;
+EffectWrapper._CustomShaderCodeProcessing = {};
+
+AbstractEngine.prototype.setTextureFromPostProcess = function (channel, postProcess, name) {
+ let postProcessInput = null;
+ if (postProcess) {
+ if (postProcess._forcedOutputTexture) {
+ postProcessInput = postProcess._forcedOutputTexture;
+ }
+ else if (postProcess._textures.data[postProcess._currentRenderTextureInd]) {
+ postProcessInput = postProcess._textures.data[postProcess._currentRenderTextureInd];
+ }
+ }
+ this._bindTexture(channel, postProcessInput?.texture ?? null, name);
+};
+AbstractEngine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess, name) {
+ this._bindTexture(channel, postProcess?._outputTexture?.texture ?? null, name);
+};
+/**
+ * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
+ * @param channel Name of the sampler variable.
+ * @param postProcess Post process to get the input texture from.
+ */
+Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
+ this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess, channel);
+};
+/**
+ * (Warning! setTextureFromPostProcessOutput may be desired instead)
+ * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
+ * @param channel Name of the sampler variable.
+ * @param postProcess Post process to get the output texture from.
+ */
+Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
+ this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess, channel);
+};
+/**
+ * PostProcess can be used to apply a shader to a texture after it has been rendered
+ * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses
+ */
+class PostProcess {
+ /**
+ * Force all the postprocesses to compile to glsl even on WebGPU engines.
+ * False by default. This is mostly meant for backward compatibility.
+ */
+ static get ForceGLSL() {
+ return EffectWrapper.ForceGLSL;
+ }
+ static set ForceGLSL(force) {
+ EffectWrapper.ForceGLSL = force;
+ }
+ /**
+ * Registers a shader code processing with a post process name.
+ * @param postProcessName name of the post process. Use null for the fallback shader code processing. This is the shader code processing that will be used in case no specific shader code processing has been associated to a post process name
+ * @param customShaderCodeProcessing shader code processing to associate to the post process name
+ */
+ static RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing) {
+ EffectWrapper.RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing);
+ }
+ /** Name of the PostProcess. */
+ get name() {
+ return this._effectWrapper.name;
+ }
+ set name(value) {
+ this._effectWrapper.name = value;
+ }
+ /**
+ * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
+ */
+ get alphaMode() {
+ return this._effectWrapper.alphaMode;
+ }
+ set alphaMode(value) {
+ this._effectWrapper.alphaMode = value;
+ }
+ /**
+ * Number of sample textures (default: 1)
+ */
+ get samples() {
+ return this._samples;
+ }
+ set samples(n) {
+ this._samples = Math.min(n, this._engine.getCaps().maxMSAASamples);
+ this._textures.forEach((texture) => {
+ texture.setSamples(this._samples);
+ });
+ }
+ /**
+ * Gets the shader language type used to generate vertex and fragment source code.
+ */
+ get shaderLanguage() {
+ return this._shaderLanguage;
+ }
+ /**
+ * Returns the fragment url or shader name used in the post process.
+ * @returns the fragment url or name in the shader store.
+ */
+ getEffectName() {
+ return this._fragmentUrl;
+ }
+ /**
+ * A function that is added to the onActivateObservable
+ */
+ set onActivate(callback) {
+ if (this._onActivateObserver) {
+ this.onActivateObservable.remove(this._onActivateObserver);
+ }
+ if (callback) {
+ this._onActivateObserver = this.onActivateObservable.add(callback);
+ }
+ }
+ /**
+ * A function that is added to the onSizeChangedObservable
+ */
+ set onSizeChanged(callback) {
+ if (this._onSizeChangedObserver) {
+ this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
+ }
+ this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
+ }
+ /**
+ * A function that is added to the onApplyObservable
+ */
+ set onApply(callback) {
+ if (this._onApplyObserver) {
+ this.onApplyObservable.remove(this._onApplyObserver);
+ }
+ this._onApplyObserver = this.onApplyObservable.add(callback);
+ }
+ /**
+ * A function that is added to the onBeforeRenderObservable
+ */
+ set onBeforeRender(callback) {
+ if (this._onBeforeRenderObserver) {
+ this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
+ }
+ this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
+ }
+ /**
+ * A function that is added to the onAfterRenderObservable
+ */
+ set onAfterRender(callback) {
+ if (this._onAfterRenderObserver) {
+ this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
+ }
+ this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
+ }
+ /**
+ * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
+ * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
+ */
+ get inputTexture() {
+ return this._textures.data[this._currentRenderTextureInd];
+ }
+ set inputTexture(value) {
+ this._forcedOutputTexture = value;
+ }
+ /**
+ * Since inputTexture should always be defined, if we previously manually set `inputTexture`,
+ * the only way to unset it is to use this function to restore its internal state
+ */
+ restoreDefaultInputTexture() {
+ if (this._forcedOutputTexture) {
+ this._forcedOutputTexture = null;
+ this.markTextureDirty();
+ }
+ }
+ /**
+ * Gets the camera which post process is applied to.
+ * @returns The camera the post process is applied to.
+ */
+ getCamera() {
+ return this._camera;
+ }
+ /**
+ * Gets the texel size of the postprocess.
+ * See https://en.wikipedia.org/wiki/Texel_(graphics)
+ */
+ get texelSize() {
+ if (this._shareOutputWithPostProcess) {
+ return this._shareOutputWithPostProcess.texelSize;
+ }
+ if (this._forcedOutputTexture) {
+ this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
+ }
+ return this._texelSize;
+ }
+ /** @internal */
+ constructor(name, fragmentUrl, parameters, samplers, _size, camera, samplingMode = 1, engine, reusable, defines = null, textureType = 0, vertexUrl = "postprocess", indexParameters, blockCompilation = false, textureFormat = 5, shaderLanguage, extraInitializations) {
+ /** @internal */
+ this._parentContainer = null;
+ /**
+ * Width of the texture to apply the post process on
+ */
+ this.width = -1;
+ /**
+ * Height of the texture to apply the post process on
+ */
+ this.height = -1;
+ /**
+ * Gets the node material used to create this postprocess (null if the postprocess was manually created)
+ */
+ this.nodeMaterialSource = null;
+ /**
+ * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
+ * @internal
+ */
+ this._outputTexture = null;
+ /**
+ * If the buffer needs to be cleared before applying the post process. (default: true)
+ * Should be set to false if shader will overwrite all previous pixels.
+ */
+ this.autoClear = true;
+ /**
+ * If clearing the buffer should be forced in autoClear mode, even when alpha mode is enabled (default: false).
+ * By default, the buffer will only be cleared if alpha mode is disabled (and autoClear is true).
+ */
+ this.forceAutoClearInAlphaMode = false;
+ /**
+ * Animations to be used for the post processing
+ */
+ this.animations = [];
+ /**
+ * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
+ * Can only be used on a single postprocess or on the last one of a chain. (default: false)
+ */
+ this.enablePixelPerfectMode = false;
+ /**
+ * Force the postprocess to be applied without taking in account viewport
+ */
+ this.forceFullscreenViewport = true;
+ /**
+ * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
+ *
+ * | Value | Type | Description |
+ * | ----- | ----------------------------------- | ----------- |
+ * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
+ * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
+ * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
+ *
+ */
+ this.scaleMode = 1;
+ /**
+ * Force textures to be a power of two (default: false)
+ */
+ this.alwaysForcePOT = false;
+ this._samples = 1;
+ /**
+ * Modify the scale of the post process to be the same as the viewport (default: false)
+ */
+ this.adaptScaleToCurrentViewport = false;
+ this._webGPUReady = false;
+ this._reusable = false;
+ this._renderId = 0;
+ /**
+ * if externalTextureSamplerBinding is true, the "apply" method won't bind the textureSampler texture, it is expected to be done by the "outside" (by the onApplyObservable observer most probably).
+ * counter-productive in some cases because if the texture bound by "apply" is different from the currently texture bound, (the one set by the onApplyObservable observer, for eg) some
+ * internal structures (materialContext) will be dirtified, which may impact performances
+ */
+ this.externalTextureSamplerBinding = false;
+ /**
+ * Smart array of input and output textures for the post process.
+ * @internal
+ */
+ this._textures = new SmartArray(2);
+ /**
+ * Smart array of input and output textures for the post process.
+ * @internal
+ */
+ this._textureCache = [];
+ /**
+ * The index in _textures that corresponds to the output texture.
+ * @internal
+ */
+ this._currentRenderTextureInd = 0;
+ this._scaleRatio = new Vector2(1, 1);
+ this._texelSize = Vector2.Zero();
+ // Events
+ /**
+ * An event triggered when the postprocess is activated.
+ */
+ this.onActivateObservable = new Observable();
+ /**
+ * An event triggered when the postprocess changes its size.
+ */
+ this.onSizeChangedObservable = new Observable();
+ /**
+ * An event triggered when the postprocess applies its effect.
+ */
+ this.onApplyObservable = new Observable();
+ /**
+ * An event triggered before rendering the postprocess
+ */
+ this.onBeforeRenderObservable = new Observable();
+ /**
+ * An event triggered after rendering the postprocess
+ */
+ this.onAfterRenderObservable = new Observable();
+ /**
+ * An event triggered when the post-process is disposed
+ */
+ this.onDisposeObservable = new Observable();
+ let size = 1;
+ let uniformBuffers = null;
+ let effectWrapper;
+ if (parameters && !Array.isArray(parameters)) {
+ const options = parameters;
+ parameters = options.uniforms ?? null;
+ samplers = options.samplers ?? null;
+ size = options.size ?? 1;
+ camera = options.camera ?? null;
+ samplingMode = options.samplingMode ?? 1;
+ engine = options.engine;
+ reusable = options.reusable;
+ defines = Array.isArray(options.defines) ? options.defines.join("\n") : (options.defines ?? null);
+ textureType = options.textureType ?? 0;
+ vertexUrl = options.vertexUrl ?? "postprocess";
+ indexParameters = options.indexParameters;
+ blockCompilation = options.blockCompilation ?? false;
+ textureFormat = options.textureFormat ?? 5;
+ shaderLanguage = options.shaderLanguage ?? 0 /* ShaderLanguage.GLSL */;
+ uniformBuffers = options.uniformBuffers ?? null;
+ extraInitializations = options.extraInitializations;
+ effectWrapper = options.effectWrapper;
+ }
+ else if (_size) {
+ if (typeof _size === "number") {
+ size = _size;
+ }
+ else {
+ size = { width: _size.width, height: _size.height };
+ }
+ }
+ this._useExistingThinPostProcess = !!effectWrapper;
+ this._effectWrapper =
+ effectWrapper ??
+ new EffectWrapper({
+ name,
+ useShaderStore: true,
+ useAsPostProcess: true,
+ fragmentShader: fragmentUrl,
+ engine: engine || camera?.getScene().getEngine(),
+ uniforms: parameters,
+ samplers,
+ uniformBuffers,
+ defines,
+ vertexUrl,
+ indexParameters,
+ blockCompilation: true,
+ shaderLanguage,
+ extraInitializations: undefined,
+ });
+ this.name = name;
+ this.onEffectCreatedObservable = this._effectWrapper.onEffectCreatedObservable;
+ if (camera != null) {
+ this._camera = camera;
+ this._scene = camera.getScene();
+ camera.attachPostProcess(this);
+ this._engine = this._scene.getEngine();
+ this._scene.postProcesses.push(this);
+ this.uniqueId = this._scene.getUniqueId();
+ }
+ else if (engine) {
+ this._engine = engine;
+ this._engine.postProcesses.push(this);
+ }
+ this._options = size;
+ this.renderTargetSamplingMode = samplingMode ? samplingMode : 1;
+ this._reusable = reusable || false;
+ this._textureType = textureType;
+ this._textureFormat = textureFormat;
+ this._shaderLanguage = shaderLanguage || 0 /* ShaderLanguage.GLSL */;
+ this._samplers = samplers || [];
+ if (this._samplers.indexOf("textureSampler") === -1) {
+ this._samplers.push("textureSampler");
+ }
+ this._fragmentUrl = fragmentUrl;
+ this._vertexUrl = vertexUrl;
+ this._parameters = parameters || [];
+ if (this._parameters.indexOf("scale") === -1) {
+ this._parameters.push("scale");
+ }
+ this._uniformBuffers = uniformBuffers || [];
+ this._indexParameters = indexParameters;
+ if (!this._useExistingThinPostProcess) {
+ this._webGPUReady = this._shaderLanguage === 1 /* ShaderLanguage.WGSL */;
+ const importPromises = [];
+ this._gatherImports(this._engine.isWebGPU && !PostProcess.ForceGLSL, importPromises);
+ this._effectWrapper._webGPUReady = this._webGPUReady;
+ this._effectWrapper._postConstructor(blockCompilation, defines, extraInitializations, importPromises);
+ }
+ }
+ _gatherImports(useWebGPU = false, list) {
+ // this._webGPUReady is used to detect when a postprocess is intended to be used with WebGPU
+ if (useWebGPU && this._webGPUReady) {
+ list.push(Promise.all([Promise.resolve().then(() => postprocess_vertex)]));
+ }
+ else {
+ list.push(Promise.all([Promise.resolve().then(() => postprocess_vertex$1)]));
+ }
+ }
+ /**
+ * Gets a string identifying the name of the class
+ * @returns "PostProcess" string
+ */
+ getClassName() {
+ return "PostProcess";
+ }
+ /**
+ * Gets the engine which this post process belongs to.
+ * @returns The engine the post process was enabled with.
+ */
+ getEngine() {
+ return this._engine;
+ }
+ /**
+ * The effect that is created when initializing the post process.
+ * @returns The created effect corresponding to the postprocess.
+ */
+ getEffect() {
+ return this._effectWrapper.drawWrapper.effect;
+ }
+ /**
+ * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
+ * @param postProcess The post process to share the output with.
+ * @returns This post process.
+ */
+ shareOutputWith(postProcess) {
+ this._disposeTextures();
+ this._shareOutputWithPostProcess = postProcess;
+ return this;
+ }
+ /**
+ * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
+ * This should be called if the post process that shares output with this post process is disabled/disposed.
+ */
+ useOwnOutput() {
+ if (this._textures.length == 0) {
+ this._textures = new SmartArray(2);
+ }
+ this._shareOutputWithPostProcess = null;
+ }
+ /**
+ * Updates the effect with the current post process compile time values and recompiles the shader.
+ * @param defines Define statements that should be added at the beginning of the shader. (default: null)
+ * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
+ * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
+ * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
+ * @param onCompiled Called when the shader has been compiled.
+ * @param onError Called if there is an error when compiling a shader.
+ * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time)
+ * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time)
+ */
+ updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) {
+ this._effectWrapper.updateEffect(defines, uniforms, samplers, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl);
+ this._postProcessDefines = Array.isArray(this._effectWrapper.options.defines) ? this._effectWrapper.options.defines.join("\n") : this._effectWrapper.options.defines;
+ }
+ /**
+ * The post process is reusable if it can be used multiple times within one frame.
+ * @returns If the post process is reusable
+ */
+ isReusable() {
+ return this._reusable;
+ }
+ /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
+ markTextureDirty() {
+ this.width = -1;
+ }
+ _createRenderTargetTexture(textureSize, textureOptions, channel = 0) {
+ for (let i = 0; i < this._textureCache.length; i++) {
+ if (this._textureCache[i].texture.width === textureSize.width &&
+ this._textureCache[i].texture.height === textureSize.height &&
+ this._textureCache[i].postProcessChannel === channel &&
+ this._textureCache[i].texture._generateDepthBuffer === textureOptions.generateDepthBuffer &&
+ this._textureCache[i].texture.samples === textureOptions.samples) {
+ return this._textureCache[i].texture;
+ }
+ }
+ const tex = this._engine.createRenderTargetTexture(textureSize, textureOptions);
+ this._textureCache.push({ texture: tex, postProcessChannel: channel, lastUsedRenderId: -1 });
+ return tex;
+ }
+ _flushTextureCache() {
+ const currentRenderId = this._renderId;
+ for (let i = this._textureCache.length - 1; i >= 0; i--) {
+ if (currentRenderId - this._textureCache[i].lastUsedRenderId > 100) {
+ let currentlyUsed = false;
+ for (let j = 0; j < this._textures.length; j++) {
+ if (this._textures.data[j] === this._textureCache[i].texture) {
+ currentlyUsed = true;
+ break;
+ }
+ }
+ if (!currentlyUsed) {
+ this._textureCache[i].texture.dispose();
+ this._textureCache.splice(i, 1);
+ }
+ }
+ }
+ }
+ /**
+ * Resizes the post-process texture
+ * @param width Width of the texture
+ * @param height Height of the texture
+ * @param camera The camera this post-process is applied to. Pass null if the post-process is used outside the context of a camera post-process chain (default: null)
+ * @param needMipMaps True if mip maps need to be generated after render (default: false)
+ * @param forceDepthStencil True to force post-process texture creation with stencil depth and buffer (default: false)
+ */
+ resize(width, height, camera = null, needMipMaps = false, forceDepthStencil = false) {
+ if (this._textures.length > 0) {
+ this._textures.reset();
+ }
+ this.width = width;
+ this.height = height;
+ let firstPP = null;
+ if (camera) {
+ for (let i = 0; i < camera._postProcesses.length; i++) {
+ if (camera._postProcesses[i] !== null) {
+ firstPP = camera._postProcesses[i];
+ break;
+ }
+ }
+ }
+ const textureSize = { width: this.width, height: this.height };
+ const textureOptions = {
+ generateMipMaps: needMipMaps,
+ generateDepthBuffer: forceDepthStencil || firstPP === this,
+ generateStencilBuffer: (forceDepthStencil || firstPP === this) && this._engine.isStencilEnable,
+ samplingMode: this.renderTargetSamplingMode,
+ type: this._textureType,
+ format: this._textureFormat,
+ samples: this._samples,
+ label: "PostProcessRTT-" + this.name,
+ };
+ this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 0));
+ if (this._reusable) {
+ this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 1));
+ }
+ this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
+ this.onSizeChangedObservable.notifyObservers(this);
+ }
+ _getTarget() {
+ let target;
+ if (this._shareOutputWithPostProcess) {
+ target = this._shareOutputWithPostProcess.inputTexture;
+ }
+ else if (this._forcedOutputTexture) {
+ target = this._forcedOutputTexture;
+ this.width = this._forcedOutputTexture.width;
+ this.height = this._forcedOutputTexture.height;
+ }
+ else {
+ target = this.inputTexture;
+ let cache;
+ for (let i = 0; i < this._textureCache.length; i++) {
+ if (this._textureCache[i].texture === target) {
+ cache = this._textureCache[i];
+ break;
+ }
+ }
+ if (cache) {
+ cache.lastUsedRenderId = this._renderId;
+ }
+ }
+ return target;
+ }
+ /**
+ * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
+ * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
+ * @param cameraOrScene The camera that will be used in the post process. This camera will be used when calling onActivateObservable. You can also pass the scene if no camera is available.
+ * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
+ * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
+ * @returns The render target wrapper that was bound to be written to.
+ */
+ activate(cameraOrScene, sourceTexture = null, forceDepthStencil) {
+ const camera = cameraOrScene === null || cameraOrScene.cameraRigMode !== undefined ? cameraOrScene || this._camera : null;
+ const scene = camera?.getScene() ?? cameraOrScene;
+ const engine = scene.getEngine();
+ const maxSize = engine.getCaps().maxTextureSize;
+ const requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
+ const requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
+ let desiredWidth = this._options.width || requiredWidth;
+ let desiredHeight = this._options.height || requiredHeight;
+ const needMipMaps = this.renderTargetSamplingMode !== 7 &&
+ this.renderTargetSamplingMode !== 1 &&
+ this.renderTargetSamplingMode !== 2;
+ let target = null;
+ if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
+ if (this.adaptScaleToCurrentViewport) {
+ const currentViewport = engine.currentViewport;
+ if (currentViewport) {
+ desiredWidth *= currentViewport.width;
+ desiredHeight *= currentViewport.height;
+ }
+ }
+ if (needMipMaps || this.alwaysForcePOT) {
+ if (!this._options.width) {
+ desiredWidth = engine.needPOTTextures ? GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
+ }
+ if (!this._options.height) {
+ desiredHeight = engine.needPOTTextures ? GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
+ }
+ }
+ if (this.width !== desiredWidth || this.height !== desiredHeight || !(target = this._getTarget())) {
+ this.resize(desiredWidth, desiredHeight, camera, needMipMaps, forceDepthStencil);
+ }
+ this._textures.forEach((texture) => {
+ if (texture.samples !== this.samples) {
+ this._engine.updateRenderTargetTextureSampleCount(texture, this.samples);
+ }
+ });
+ this._flushTextureCache();
+ this._renderId++;
+ }
+ if (!target) {
+ target = this._getTarget();
+ }
+ // Bind the input of this post process to be used as the output of the previous post process.
+ if (this.enablePixelPerfectMode) {
+ this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
+ this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
+ }
+ else {
+ this._scaleRatio.copyFromFloats(1, 1);
+ this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
+ }
+ this._engine._debugInsertMarker?.(`post process ${this.name} input`);
+ this.onActivateObservable.notifyObservers(camera);
+ // Clear
+ if (this.autoClear && (this.alphaMode === 0 || this.forceAutoClearInAlphaMode)) {
+ this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
+ }
+ if (this._reusable) {
+ this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
+ }
+ return target;
+ }
+ /**
+ * If the post process is supported.
+ */
+ get isSupported() {
+ return this._effectWrapper.drawWrapper.effect.isSupported;
+ }
+ /**
+ * The aspect ratio of the output texture.
+ */
+ get aspectRatio() {
+ if (this._shareOutputWithPostProcess) {
+ return this._shareOutputWithPostProcess.aspectRatio;
+ }
+ if (this._forcedOutputTexture) {
+ return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
+ }
+ return this.width / this.height;
+ }
+ /**
+ * Get a value indicating if the post-process is ready to be used
+ * @returns true if the post-process is ready (shader is compiled)
+ */
+ isReady() {
+ return this._effectWrapper.isReady();
+ }
+ /**
+ * Binds all textures and uniforms to the shader, this will be run on every pass.
+ * @returns the effect corresponding to this post process. Null if not compiled or not ready.
+ */
+ apply() {
+ // Check
+ if (!this._effectWrapper.isReady()) {
+ return null;
+ }
+ // States
+ this._engine.enableEffect(this._effectWrapper.drawWrapper);
+ this._engine.setState(false);
+ this._engine.setDepthBuffer(false);
+ this._engine.setDepthWrite(false);
+ // Alpha
+ if (this.alphaConstants) {
+ this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
+ }
+ // Bind the output texture of the preivous post process as the input to this post process.
+ let source;
+ if (this._shareOutputWithPostProcess) {
+ source = this._shareOutputWithPostProcess.inputTexture;
+ }
+ else if (this._forcedOutputTexture) {
+ source = this._forcedOutputTexture;
+ }
+ else {
+ source = this.inputTexture;
+ }
+ if (!this.externalTextureSamplerBinding) {
+ this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler", source?.texture);
+ }
+ // Parameters
+ this._effectWrapper.drawWrapper.effect.setVector2("scale", this._scaleRatio);
+ this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect);
+ this._effectWrapper.bind();
+ return this._effectWrapper.drawWrapper.effect;
+ }
+ _disposeTextures() {
+ if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
+ this._disposeTextureCache();
+ return;
+ }
+ this._disposeTextureCache();
+ this._textures.dispose();
+ }
+ _disposeTextureCache() {
+ for (let i = this._textureCache.length - 1; i >= 0; i--) {
+ this._textureCache[i].texture.dispose();
+ }
+ this._textureCache.length = 0;
+ }
+ /**
+ * Sets the required values to the prepass renderer.
+ * @param prePassRenderer defines the prepass renderer to setup.
+ * @returns true if the pre pass is needed.
+ */
+ setPrePassRenderer(prePassRenderer) {
+ if (this._prePassEffectConfiguration) {
+ this._prePassEffectConfiguration = prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration);
+ this._prePassEffectConfiguration.enabled = true;
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Disposes the post process.
+ * @param camera The camera to dispose the post process on.
+ */
+ dispose(camera) {
+ camera = camera || this._camera;
+ if (!this._useExistingThinPostProcess) {
+ this._effectWrapper.dispose();
+ }
+ this._disposeTextures();
+ let index;
+ if (this._scene) {
+ index = this._scene.postProcesses.indexOf(this);
+ if (index !== -1) {
+ this._scene.postProcesses.splice(index, 1);
+ }
+ }
+ if (this._parentContainer) {
+ const index = this._parentContainer.postProcesses.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.postProcesses.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ index = this._engine.postProcesses.indexOf(this);
+ if (index !== -1) {
+ this._engine.postProcesses.splice(index, 1);
+ }
+ this.onDisposeObservable.notifyObservers();
+ if (!camera) {
+ return;
+ }
+ camera.detachPostProcess(this);
+ index = camera._postProcesses.indexOf(this);
+ if (index === 0 && camera._postProcesses.length > 0) {
+ const firstPostProcess = this._camera._getFirstPostProcess();
+ if (firstPostProcess) {
+ firstPostProcess.markTextureDirty();
+ }
+ }
+ this.onActivateObservable.clear();
+ this.onAfterRenderObservable.clear();
+ this.onApplyObservable.clear();
+ this.onBeforeRenderObservable.clear();
+ this.onSizeChangedObservable.clear();
+ this.onEffectCreatedObservable.clear();
+ }
+ /**
+ * Serializes the post process to a JSON object
+ * @returns the JSON object
+ */
+ serialize() {
+ const serializationObject = SerializationHelper.Serialize(this);
+ const camera = this.getCamera() || (this._scene && this._scene.activeCamera);
+ serializationObject.customType = "BABYLON." + this.getClassName();
+ serializationObject.cameraId = camera ? camera.id : null;
+ serializationObject.reusable = this._reusable;
+ serializationObject.textureType = this._textureType;
+ serializationObject.fragmentUrl = this._fragmentUrl;
+ serializationObject.parameters = this._parameters;
+ serializationObject.samplers = this._samplers;
+ serializationObject.uniformBuffers = this._uniformBuffers;
+ serializationObject.options = this._options;
+ serializationObject.defines = this._postProcessDefines;
+ serializationObject.textureFormat = this._textureFormat;
+ serializationObject.vertexUrl = this._vertexUrl;
+ serializationObject.indexParameters = this._indexParameters;
+ return serializationObject;
+ }
+ /**
+ * Clones this post process
+ * @returns a new post process similar to this one
+ */
+ clone() {
+ const serializationObject = this.serialize();
+ serializationObject._engine = this._engine;
+ serializationObject.cameraId = null;
+ const result = PostProcess.Parse(serializationObject, this._scene, "");
+ if (!result) {
+ return null;
+ }
+ result.onActivateObservable = this.onActivateObservable.clone();
+ result.onSizeChangedObservable = this.onSizeChangedObservable.clone();
+ result.onApplyObservable = this.onApplyObservable.clone();
+ result.onBeforeRenderObservable = this.onBeforeRenderObservable.clone();
+ result.onAfterRenderObservable = this.onAfterRenderObservable.clone();
+ result._prePassEffectConfiguration = this._prePassEffectConfiguration;
+ return result;
+ }
+ /**
+ * Creates a material from parsed material data
+ * @param parsedPostProcess defines parsed post process data
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root URL to use to load textures
+ * @returns a new post process
+ */
+ static Parse(parsedPostProcess, scene, rootUrl) {
+ const postProcessType = GetClass(parsedPostProcess.customType);
+ if (!postProcessType || !postProcessType._Parse) {
+ return null;
+ }
+ const camera = scene ? scene.getCameraById(parsedPostProcess.cameraId) : null;
+ return postProcessType._Parse(parsedPostProcess, camera, scene, rootUrl);
+ }
+ /**
+ * @internal
+ */
+ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {
+ return SerializationHelper.Parse(() => {
+ return new PostProcess(parsedPostProcess.name, parsedPostProcess.fragmentUrl, parsedPostProcess.parameters, parsedPostProcess.samplers, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable, parsedPostProcess.defines, parsedPostProcess.textureType, parsedPostProcess.vertexUrl, parsedPostProcess.indexParameters, false, parsedPostProcess.textureFormat);
+ }, parsedPostProcess, scene, rootUrl);
+ }
+}
+__decorate([
+ serialize()
+], PostProcess.prototype, "uniqueId", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "name", null);
+__decorate([
+ serialize()
+], PostProcess.prototype, "width", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "height", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "renderTargetSamplingMode", void 0);
+__decorate([
+ serializeAsColor4()
+], PostProcess.prototype, "clearColor", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "autoClear", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "forceAutoClearInAlphaMode", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "alphaMode", null);
+__decorate([
+ serialize()
+], PostProcess.prototype, "alphaConstants", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "enablePixelPerfectMode", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "forceFullscreenViewport", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "scaleMode", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "alwaysForcePOT", void 0);
+__decorate([
+ serialize("samples")
+], PostProcess.prototype, "_samples", void 0);
+__decorate([
+ serialize()
+], PostProcess.prototype, "adaptScaleToCurrentViewport", void 0);
+RegisterClass("BABYLON.PostProcess", PostProcess);
+
+/**
+ * Post process used to apply a blur effect
+ */
+class ThinBlurPostProcess extends EffectWrapper {
+ _gatherImports(useWebGPU, list) {
+ if (useWebGPU) {
+ this._webGPUReady = true;
+ list.push(Promise.all([Promise.resolve().then(() => kernelBlur_fragment), Promise.resolve().then(() => kernelBlur_vertex)]));
+ }
+ else {
+ list.push(Promise.all([Promise.resolve().then(() => kernelBlur_fragment$1), Promise.resolve().then(() => kernelBlur_vertex$1)]));
+ }
+ }
+ /**
+ * Constructs a new blur post process
+ * @param name Name of the effect
+ * @param engine Engine to use to render the effect. If not provided, the last created engine will be used
+ * @param direction Direction in which to apply the blur
+ * @param kernel Kernel size of the blur
+ * @param options Options to configure the effect
+ */
+ constructor(name, engine = null, direction, kernel, options) {
+ const blockCompilationFinal = !!options?.blockCompilation;
+ super({
+ ...options,
+ name,
+ engine: engine || Engine.LastCreatedEngine,
+ useShaderStore: true,
+ useAsPostProcess: true,
+ fragmentShader: ThinBlurPostProcess.FragmentUrl,
+ uniforms: ThinBlurPostProcess.Uniforms,
+ samplers: ThinBlurPostProcess.Samplers,
+ vertexUrl: ThinBlurPostProcess.VertexUrl,
+ blockCompilation: true,
+ });
+ this._packedFloat = false;
+ this._staticDefines = "";
+ /**
+ * Width of the texture to apply the blur on
+ */
+ this.textureWidth = 0;
+ /**
+ * Height of the texture to apply the blur on
+ */
+ this.textureHeight = 0;
+ this.options.blockCompilation = blockCompilationFinal;
+ if (direction !== undefined) {
+ this.direction = direction;
+ }
+ if (kernel !== undefined) {
+ this.kernel = kernel;
+ }
+ }
+ /**
+ * Sets the length in pixels of the blur sample region
+ */
+ set kernel(v) {
+ if (this._idealKernel === v) {
+ return;
+ }
+ v = Math.max(v, 1);
+ this._idealKernel = v;
+ this._kernel = this._nearestBestKernel(v);
+ if (!this.options.blockCompilation) {
+ this._updateParameters();
+ }
+ }
+ /**
+ * Gets the length in pixels of the blur sample region
+ */
+ get kernel() {
+ return this._idealKernel;
+ }
+ /**
+ * Sets whether or not the blur needs to unpack/repack floats
+ */
+ set packedFloat(v) {
+ if (this._packedFloat === v) {
+ return;
+ }
+ this._packedFloat = v;
+ if (!this.options.blockCompilation) {
+ this._updateParameters();
+ }
+ }
+ /**
+ * Gets whether or not the blur is unpacking/repacking floats
+ */
+ get packedFloat() {
+ return this._packedFloat;
+ }
+ bind() {
+ super.bind();
+ this._drawWrapper.effect.setFloat2("delta", (1 / this.textureWidth) * this.direction.x, (1 / this.textureHeight) * this.direction.y);
+ }
+ /** @internal */
+ _updateParameters(onCompiled, onError) {
+ // Generate sampling offsets and weights
+ const N = this._kernel;
+ const centerIndex = (N - 1) / 2;
+ // Generate Gaussian sampling weights over kernel
+ let offsets = [];
+ let weights = [];
+ let totalWeight = 0;
+ for (let i = 0; i < N; i++) {
+ const u = i / (N - 1);
+ const w = this._gaussianWeight(u * 2.0 - 1);
+ offsets[i] = i - centerIndex;
+ weights[i] = w;
+ totalWeight += w;
+ }
+ // Normalize weights
+ for (let i = 0; i < weights.length; i++) {
+ weights[i] /= totalWeight;
+ }
+ // Optimize: combine samples to take advantage of hardware linear sampling
+ // Walk from left to center, combining pairs (symmetrically)
+ const linearSamplingWeights = [];
+ const linearSamplingOffsets = [];
+ const linearSamplingMap = [];
+ for (let i = 0; i <= centerIndex; i += 2) {
+ const j = Math.min(i + 1, Math.floor(centerIndex));
+ const singleCenterSample = i === j;
+ if (singleCenterSample) {
+ linearSamplingMap.push({ o: offsets[i], w: weights[i] });
+ }
+ else {
+ const sharedCell = j === centerIndex;
+ const weightLinear = weights[i] + weights[j] * (sharedCell ? 0.5 : 1);
+ const offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
+ if (offsetLinear === 0) {
+ linearSamplingMap.push({ o: offsets[i], w: weights[i] });
+ linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
+ }
+ else {
+ linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
+ linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
+ }
+ }
+ }
+ for (let i = 0; i < linearSamplingMap.length; i++) {
+ linearSamplingOffsets[i] = linearSamplingMap[i].o;
+ linearSamplingWeights[i] = linearSamplingMap[i].w;
+ }
+ // Replace with optimized
+ offsets = linearSamplingOffsets;
+ weights = linearSamplingWeights;
+ // Generate shaders
+ const maxVaryingRows = this.options.engine.getCaps().maxVaryingVectors - (this.options.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? 1 : 0); // Because of the additional builtins
+ const freeVaryingVec2 = Math.max(maxVaryingRows, 0) - 1; // Because of sampleCenter
+ let varyingCount = Math.min(offsets.length, freeVaryingVec2);
+ let defines = "";
+ defines += this._staticDefines;
+ // The DOF fragment should ignore the center pixel when looping as it is handled manually in the fragment shader.
+ if (this._staticDefines.indexOf("DOF") != -1) {
+ defines += `#define CENTER_WEIGHT ${this._glslFloat(weights[varyingCount - 1])}\n`;
+ varyingCount--;
+ }
+ for (let i = 0; i < varyingCount; i++) {
+ defines += `#define KERNEL_OFFSET${i} ${this._glslFloat(offsets[i])}\n`;
+ defines += `#define KERNEL_WEIGHT${i} ${this._glslFloat(weights[i])}\n`;
+ }
+ let depCount = 0;
+ for (let i = freeVaryingVec2; i < offsets.length; i++) {
+ defines += `#define KERNEL_DEP_OFFSET${depCount} ${this._glslFloat(offsets[i])}\n`;
+ defines += `#define KERNEL_DEP_WEIGHT${depCount} ${this._glslFloat(weights[i])}\n`;
+ depCount++;
+ }
+ if (this.packedFloat) {
+ defines += `#define PACKEDFLOAT 1`;
+ }
+ this.options.blockCompilation = false;
+ this.updateEffect(defines, null, null, {
+ varyingCount: varyingCount,
+ depCount: depCount,
+ }, onCompiled, onError);
+ }
+ /**
+ * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
+ * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
+ * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
+ * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
+ * The gaps between physical kernels are compensated for in the weighting of the samples
+ * @param idealKernel Ideal blur kernel.
+ * @returns Nearest best kernel.
+ */
+ _nearestBestKernel(idealKernel) {
+ const v = Math.round(idealKernel);
+ for (const k of [v, v - 1, v + 1, v - 2, v + 2]) {
+ if (k % 2 !== 0 && Math.floor(k / 2) % 2 === 0 && k > 0) {
+ return Math.max(k, 3);
+ }
+ }
+ return Math.max(v, 3);
+ }
+ /**
+ * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
+ * @param x The point on the Gaussian distribution to sample.
+ * @returns the value of the Gaussian function at x.
+ */
+ _gaussianWeight(x) {
+ //reference: Engines/ImageProcessingBlur.cpp #dcc760
+ // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
+ // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
+ // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
+ // truncated at around 1.3% of peak strength.
+ //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
+ const sigma = 1 / 3;
+ const denominator = Math.sqrt(2.0 * Math.PI) * sigma;
+ const exponent = -((x * x) / (2.0 * sigma * sigma));
+ const weight = (1.0 / denominator) * Math.exp(exponent);
+ return weight;
+ }
+ /**
+ * Generates a string that can be used as a floating point number in GLSL.
+ * @param x Value to print.
+ * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
+ * @returns GLSL float string.
+ */
+ _glslFloat(x, decimalFigures = 8) {
+ return x.toFixed(decimalFigures).replace(/0+$/, "");
+ }
+}
+/**
+ * The vertex shader url
+ */
+ThinBlurPostProcess.VertexUrl = "kernelBlur";
+/**
+ * The fragment shader url
+ */
+ThinBlurPostProcess.FragmentUrl = "kernelBlur";
+/**
+ * The list of uniforms used by the effect
+ */
+ThinBlurPostProcess.Uniforms = ["delta", "direction"];
+/**
+ * The list of samplers used by the effect
+ */
+ThinBlurPostProcess.Samplers = ["circleOfConfusionSampler"];
+
+/**
+ * The Blur Post Process which blurs an image based on a kernel and direction.
+ * Can be used twice in x and y directions to perform a gaussian blur in two passes.
+ */
+class BlurPostProcess extends PostProcess {
+ /** The direction in which to blur the image. */
+ get direction() {
+ return this._effectWrapper.direction;
+ }
+ set direction(value) {
+ this._effectWrapper.direction = value;
+ }
+ /**
+ * Sets the length in pixels of the blur sample region
+ */
+ set kernel(v) {
+ this._effectWrapper.kernel = v;
+ }
+ /**
+ * Gets the length in pixels of the blur sample region
+ */
+ get kernel() {
+ return this._effectWrapper.kernel;
+ }
+ /**
+ * Sets whether or not the blur needs to unpack/repack floats
+ */
+ set packedFloat(v) {
+ this._effectWrapper.packedFloat = v;
+ }
+ /**
+ * Gets whether or not the blur is unpacking/repacking floats
+ */
+ get packedFloat() {
+ return this._effectWrapper.packedFloat;
+ }
+ /**
+ * Gets a string identifying the name of the class
+ * @returns "BlurPostProcess" string
+ */
+ getClassName() {
+ return "BlurPostProcess";
+ }
+ /**
+ * Creates a new instance BlurPostProcess
+ * @param name The name of the effect.
+ * @param direction The direction in which to blur the image.
+ * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
+ * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
+ * @param camera The camera to apply the render pass to.
+ * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
+ * @param engine The engine which the post process will be applied. (default: current engine)
+ * @param reusable If the post process can be reused on the same frame. (default: false)
+ * @param textureType Type of textures used when performing the post process. (default: 0)
+ * @param defines
+ * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
+ * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA)
+ */
+ constructor(name, direction, kernel, options, camera = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = 0, defines = "", blockCompilation = false, textureFormat = 5) {
+ const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation;
+ const localOptions = {
+ uniforms: ThinBlurPostProcess.Uniforms,
+ samplers: ThinBlurPostProcess.Samplers,
+ size: typeof options === "number" ? options : undefined,
+ camera,
+ samplingMode,
+ engine,
+ reusable,
+ textureType,
+ vertexUrl: ThinBlurPostProcess.VertexUrl,
+ indexParameters: { varyingCount: 0, depCount: 0 },
+ textureFormat,
+ defines,
+ ...options,
+ blockCompilation: true,
+ };
+ super(name, ThinBlurPostProcess.FragmentUrl, {
+ effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBlurPostProcess(name, engine, undefined, undefined, localOptions) : undefined,
+ ...localOptions,
+ });
+ this._effectWrapper.options.blockCompilation = blockCompilationFinal;
+ this.direction = direction;
+ this.onApplyObservable.add(() => {
+ this._effectWrapper.textureWidth = this._outputTexture ? this._outputTexture.width : this.width;
+ this._effectWrapper.textureHeight = this._outputTexture ? this._outputTexture.height : this.height;
+ });
+ this.kernel = kernel;
+ }
+ updateEffect(_defines = null, _uniforms = null, _samplers = null, _indexParameters, onCompiled, onError) {
+ this._effectWrapper._updateParameters(onCompiled, onError);
+ }
+ /**
+ * @internal
+ */
+ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {
+ return SerializationHelper.Parse(() => {
+ return new BlurPostProcess(parsedPostProcess.name, parsedPostProcess.direction, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, undefined, false);
+ }, parsedPostProcess, scene, rootUrl);
+ }
+}
+__decorate([
+ serializeAsVector2()
+], BlurPostProcess.prototype, "direction", null);
+__decorate([
+ serialize()
+], BlurPostProcess.prototype, "kernel", null);
+__decorate([
+ serialize()
+], BlurPostProcess.prototype, "packedFloat", null);
+RegisterClass("BABYLON.BlurPostProcess", BlurPostProcess);
+
+/**
+ * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
+ * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
+ */
+class EffectFallbacks {
+ constructor() {
+ this._defines = {};
+ this._currentRank = 32;
+ this._maxRank = -1;
+ this._mesh = null;
+ }
+ /**
+ * Removes the fallback from the bound mesh.
+ */
+ unBindMesh() {
+ this._mesh = null;
+ }
+ /**
+ * Adds a fallback on the specified property.
+ * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
+ * @param define The name of the define in the shader
+ */
+ addFallback(rank, define) {
+ if (!this._defines[rank]) {
+ if (rank < this._currentRank) {
+ this._currentRank = rank;
+ }
+ if (rank > this._maxRank) {
+ this._maxRank = rank;
+ }
+ this._defines[rank] = new Array();
+ }
+ this._defines[rank].push(define);
+ }
+ /**
+ * Sets the mesh to use CPU skinning when needing to fallback.
+ * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
+ * @param mesh The mesh to use the fallbacks.
+ */
+ addCPUSkinningFallback(rank, mesh) {
+ this._mesh = mesh;
+ if (rank < this._currentRank) {
+ this._currentRank = rank;
+ }
+ if (rank > this._maxRank) {
+ this._maxRank = rank;
+ }
+ }
+ /**
+ * Checks to see if more fallbacks are still available.
+ */
+ get hasMoreFallbacks() {
+ return this._currentRank <= this._maxRank;
+ }
+ /**
+ * Removes the defines that should be removed when falling back.
+ * @param currentDefines defines the current define statements for the shader.
+ * @param effect defines the current effect we try to compile
+ * @returns The resulting defines with defines of the current rank removed.
+ */
+ reduce(currentDefines, effect) {
+ // First we try to switch to CPU skinning
+ if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
+ this._mesh.computeBonesUsingShaders = false;
+ currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
+ effect._bonesComputationForcedToCPU = true;
+ const scene = this._mesh.getScene();
+ for (let index = 0; index < scene.meshes.length; index++) {
+ const otherMesh = scene.meshes[index];
+ if (!otherMesh.material) {
+ if (!this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
+ otherMesh.computeBonesUsingShaders = false;
+ }
+ continue;
+ }
+ if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
+ continue;
+ }
+ if (otherMesh.material.getEffect() === effect) {
+ otherMesh.computeBonesUsingShaders = false;
+ }
+ else if (otherMesh.subMeshes) {
+ for (const subMesh of otherMesh.subMeshes) {
+ const subMeshEffect = subMesh.effect;
+ if (subMeshEffect === effect) {
+ otherMesh.computeBonesUsingShaders = false;
+ break;
+ }
+ }
+ }
+ }
+ }
+ else {
+ const currentFallbacks = this._defines[this._currentRank];
+ if (currentFallbacks) {
+ for (let index = 0; index < currentFallbacks.length; index++) {
+ currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
+ }
+ }
+ this._currentRank++;
+ }
+ return currentDefines;
+ }
+}
+
+/**
+ * Default implementation IShadowGenerator.
+ * This is the main object responsible of generating shadows in the framework.
+ * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows
+ * @see [WebGL](https://playground.babylonjs.com/#IFYDRS#0)
+ * @see [WebGPU](https://playground.babylonjs.com/#IFYDRS#835)
+ */
+class ShadowGenerator {
+ /**
+ * Gets the bias: offset applied on the depth preventing acnea (in light direction).
+ */
+ get bias() {
+ return this._bias;
+ }
+ /**
+ * Sets the bias: offset applied on the depth preventing acnea (in light direction).
+ */
+ set bias(bias) {
+ this._bias = bias;
+ }
+ /**
+ * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle).
+ */
+ get normalBias() {
+ return this._normalBias;
+ }
+ /**
+ * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle).
+ */
+ set normalBias(normalBias) {
+ this._normalBias = normalBias;
+ }
+ /**
+ * Gets the blur box offset: offset applied during the blur pass.
+ * Only useful if useKernelBlur = false
+ */
+ get blurBoxOffset() {
+ return this._blurBoxOffset;
+ }
+ /**
+ * Sets the blur box offset: offset applied during the blur pass.
+ * Only useful if useKernelBlur = false
+ */
+ set blurBoxOffset(value) {
+ if (this._blurBoxOffset === value) {
+ return;
+ }
+ this._blurBoxOffset = value;
+ this._disposeBlurPostProcesses();
+ }
+ /**
+ * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
+ * 2 means half of the size.
+ */
+ get blurScale() {
+ return this._blurScale;
+ }
+ /**
+ * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
+ * 2 means half of the size.
+ */
+ set blurScale(value) {
+ if (this._blurScale === value) {
+ return;
+ }
+ this._blurScale = value;
+ this._disposeBlurPostProcesses();
+ }
+ /**
+ * Gets the blur kernel: kernel size of the blur pass.
+ * Only useful if useKernelBlur = true
+ */
+ get blurKernel() {
+ return this._blurKernel;
+ }
+ /**
+ * Sets the blur kernel: kernel size of the blur pass.
+ * Only useful if useKernelBlur = true
+ */
+ set blurKernel(value) {
+ if (this._blurKernel === value) {
+ return;
+ }
+ this._blurKernel = value;
+ this._disposeBlurPostProcesses();
+ }
+ /**
+ * Gets whether the blur pass is a kernel blur (if true) or box blur.
+ * Only useful in filtered mode (useBlurExponentialShadowMap...)
+ */
+ get useKernelBlur() {
+ return this._useKernelBlur;
+ }
+ /**
+ * Sets whether the blur pass is a kernel blur (if true) or box blur.
+ * Only useful in filtered mode (useBlurExponentialShadowMap...)
+ */
+ set useKernelBlur(value) {
+ if (this._useKernelBlur === value) {
+ return;
+ }
+ this._useKernelBlur = value;
+ this._disposeBlurPostProcesses();
+ }
+ /**
+ * Gets the depth scale used in ESM mode.
+ */
+ get depthScale() {
+ return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
+ }
+ /**
+ * Sets the depth scale used in ESM mode.
+ * This can override the scale stored on the light.
+ */
+ set depthScale(value) {
+ this._depthScale = value;
+ }
+ _validateFilter(filter) {
+ return filter;
+ }
+ /**
+ * Gets the current mode of the shadow generator (normal, PCF, ESM...).
+ * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
+ */
+ get filter() {
+ return this._filter;
+ }
+ /**
+ * Sets the current mode of the shadow generator (normal, PCF, ESM...).
+ * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
+ */
+ set filter(value) {
+ value = this._validateFilter(value);
+ // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
+ if (this._light.needCube()) {
+ if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
+ this.useExponentialShadowMap = true;
+ return;
+ }
+ else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
+ this.useCloseExponentialShadowMap = true;
+ return;
+ }
+ // PCF on cubemap would also be expensive
+ else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
+ this.usePoissonSampling = true;
+ return;
+ }
+ }
+ // Weblg1 fallback for PCF.
+ if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
+ if (!this._scene.getEngine()._features.supportShadowSamplers) {
+ this.usePoissonSampling = true;
+ return;
+ }
+ }
+ if (this._filter === value) {
+ return;
+ }
+ this._filter = value;
+ this._disposeBlurPostProcesses();
+ this._applyFilterValues();
+ this._light._markMeshesAsLightDirty();
+ }
+ /**
+ * Gets if the current filter is set to Poisson Sampling.
+ */
+ get usePoissonSampling() {
+ return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
+ }
+ /**
+ * Sets the current filter to Poisson Sampling.
+ */
+ set usePoissonSampling(value) {
+ const filter = this._validateFilter(ShadowGenerator.FILTER_POISSONSAMPLING);
+ if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
+ return;
+ }
+ this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
+ }
+ /**
+ * Gets if the current filter is set to ESM.
+ */
+ get useExponentialShadowMap() {
+ return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
+ }
+ /**
+ * Sets the current filter is to ESM.
+ */
+ set useExponentialShadowMap(value) {
+ const filter = this._validateFilter(ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);
+ if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
+ return;
+ }
+ this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
+ }
+ /**
+ * Gets if the current filter is set to filtered ESM.
+ */
+ get useBlurExponentialShadowMap() {
+ return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
+ }
+ /**
+ * Gets if the current filter is set to filtered ESM.
+ */
+ set useBlurExponentialShadowMap(value) {
+ const filter = this._validateFilter(ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);
+ if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
+ return;
+ }
+ this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
+ }
+ /**
+ * Gets if the current filter is set to "close ESM" (using the inverse of the
+ * exponential to prevent steep falloff artifacts).
+ */
+ get useCloseExponentialShadowMap() {
+ return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
+ }
+ /**
+ * Sets the current filter to "close ESM" (using the inverse of the
+ * exponential to prevent steep falloff artifacts).
+ */
+ set useCloseExponentialShadowMap(value) {
+ const filter = this._validateFilter(ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);
+ if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
+ return;
+ }
+ this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
+ }
+ /**
+ * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
+ * exponential to prevent steep falloff artifacts).
+ */
+ get useBlurCloseExponentialShadowMap() {
+ return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
+ }
+ /**
+ * Sets the current filter to filtered "close ESM" (using the inverse of the
+ * exponential to prevent steep falloff artifacts).
+ */
+ set useBlurCloseExponentialShadowMap(value) {
+ const filter = this._validateFilter(ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);
+ if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
+ return;
+ }
+ this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
+ }
+ /**
+ * Gets if the current filter is set to "PCF" (percentage closer filtering).
+ */
+ get usePercentageCloserFiltering() {
+ return this.filter === ShadowGenerator.FILTER_PCF;
+ }
+ /**
+ * Sets the current filter to "PCF" (percentage closer filtering).
+ */
+ set usePercentageCloserFiltering(value) {
+ const filter = this._validateFilter(ShadowGenerator.FILTER_PCF);
+ if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
+ return;
+ }
+ this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
+ }
+ /**
+ * Gets the PCF or PCSS Quality.
+ * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
+ */
+ get filteringQuality() {
+ return this._filteringQuality;
+ }
+ /**
+ * Sets the PCF or PCSS Quality.
+ * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
+ */
+ set filteringQuality(filteringQuality) {
+ if (this._filteringQuality === filteringQuality) {
+ return;
+ }
+ this._filteringQuality = filteringQuality;
+ this._disposeBlurPostProcesses();
+ this._applyFilterValues();
+ this._light._markMeshesAsLightDirty();
+ }
+ /**
+ * Gets if the current filter is set to "PCSS" (contact hardening).
+ */
+ get useContactHardeningShadow() {
+ return this.filter === ShadowGenerator.FILTER_PCSS;
+ }
+ /**
+ * Sets the current filter to "PCSS" (contact hardening).
+ */
+ set useContactHardeningShadow(value) {
+ const filter = this._validateFilter(ShadowGenerator.FILTER_PCSS);
+ if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
+ return;
+ }
+ this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
+ }
+ /**
+ * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
+ * Using a ratio helps keeping shape stability independently of the map size.
+ *
+ * It does not account for the light projection as it was having too much
+ * instability during the light setup or during light position changes.
+ *
+ * Only valid if useContactHardeningShadow is true.
+ */
+ get contactHardeningLightSizeUVRatio() {
+ return this._contactHardeningLightSizeUVRatio;
+ }
+ /**
+ * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
+ * Using a ratio helps keeping shape stability independently of the map size.
+ *
+ * It does not account for the light projection as it was having too much
+ * instability during the light setup or during light position changes.
+ *
+ * Only valid if useContactHardeningShadow is true.
+ */
+ set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio) {
+ this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
+ }
+ /** Gets or sets the actual darkness of a shadow */
+ get darkness() {
+ return this._darkness;
+ }
+ set darkness(value) {
+ this.setDarkness(value);
+ }
+ /**
+ * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
+ * 0 means strongest and 1 would means no shadow.
+ * @returns the darkness.
+ */
+ getDarkness() {
+ return this._darkness;
+ }
+ /**
+ * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
+ * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
+ * @returns the shadow generator allowing fluent coding.
+ */
+ setDarkness(darkness) {
+ if (darkness >= 1.0) {
+ this._darkness = 1.0;
+ }
+ else if (darkness <= 0.0) {
+ this._darkness = 0.0;
+ }
+ else {
+ this._darkness = darkness;
+ }
+ return this;
+ }
+ /** Gets or sets the ability to have transparent shadow */
+ get transparencyShadow() {
+ return this._transparencyShadow;
+ }
+ set transparencyShadow(value) {
+ this.setTransparencyShadow(value);
+ }
+ /**
+ * Sets the ability to have transparent shadow (boolean).
+ * @param transparent True if transparent else False
+ * @returns the shadow generator allowing fluent coding
+ */
+ setTransparencyShadow(transparent) {
+ this._transparencyShadow = transparent;
+ return this;
+ }
+ /**
+ * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
+ * @returns The render target texture if present otherwise, null
+ */
+ getShadowMap() {
+ return this._shadowMap;
+ }
+ /**
+ * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
+ * @returns The render target texture if the shadow map is present otherwise, null
+ */
+ getShadowMapForRendering() {
+ if (this._shadowMap2) {
+ return this._shadowMap2;
+ }
+ return this._shadowMap;
+ }
+ /**
+ * Gets the class name of that object
+ * @returns "ShadowGenerator"
+ */
+ getClassName() {
+ return ShadowGenerator.CLASSNAME;
+ }
+ /**
+ * Helper function to add a mesh and its descendants to the list of shadow casters.
+ * @param mesh Mesh to add
+ * @param includeDescendants boolean indicating if the descendants should be added. Default to true
+ * @returns the Shadow Generator itself
+ */
+ addShadowCaster(mesh, includeDescendants = true) {
+ if (!this._shadowMap) {
+ return this;
+ }
+ if (!this._shadowMap.renderList) {
+ this._shadowMap.renderList = [];
+ }
+ if (this._shadowMap.renderList.indexOf(mesh) === -1) {
+ this._shadowMap.renderList.push(mesh);
+ }
+ if (includeDescendants) {
+ for (const childMesh of mesh.getChildMeshes()) {
+ if (this._shadowMap.renderList.indexOf(childMesh) === -1) {
+ this._shadowMap.renderList.push(childMesh);
+ }
+ }
+ }
+ return this;
+ }
+ /**
+ * Helper function to remove a mesh and its descendants from the list of shadow casters
+ * @param mesh Mesh to remove
+ * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
+ * @returns the Shadow Generator itself
+ */
+ removeShadowCaster(mesh, includeDescendants = true) {
+ if (!this._shadowMap || !this._shadowMap.renderList) {
+ return this;
+ }
+ const index = this._shadowMap.renderList.indexOf(mesh);
+ if (index !== -1) {
+ this._shadowMap.renderList.splice(index, 1);
+ }
+ if (includeDescendants) {
+ for (const child of mesh.getChildren()) {
+ this.removeShadowCaster(child);
+ }
+ }
+ return this;
+ }
+ /**
+ * Returns the associated light object.
+ * @returns the light generating the shadow
+ */
+ getLight() {
+ return this._light;
+ }
+ /**
+ * Gets the shader language used in this generator.
+ */
+ get shaderLanguage() {
+ return this._shaderLanguage;
+ }
+ _getCamera() {
+ return this._camera ?? this._scene.activeCamera;
+ }
+ /**
+ * Gets or sets the size of the texture what stores the shadows
+ */
+ get mapSize() {
+ return this._mapSize;
+ }
+ set mapSize(size) {
+ this._mapSize = size;
+ this._light._markMeshesAsLightDirty();
+ this.recreateShadowMap();
+ }
+ /**
+ * Creates a ShadowGenerator object.
+ * A ShadowGenerator is the required tool to use the shadows.
+ * Each light casting shadows needs to use its own ShadowGenerator.
+ * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows
+ * @param mapSize The size of the texture what stores the shadows. Example : 1024.
+ * @param light The light object generating the shadows.
+ * @param usefullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
+ * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it
+ * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: false)
+ * @param forceGLSL defines a boolean indicating if the shader must be compiled in GLSL even if we are using WebGPU
+ */
+ constructor(mapSize, light, usefullFloatFirst, camera, useRedTextureType, forceGLSL = false) {
+ /**
+ * Observable triggered before the shadow is rendered. Can be used to update internal effect state
+ */
+ this.onBeforeShadowMapRenderObservable = new Observable();
+ /**
+ * Observable triggered after the shadow is rendered. Can be used to restore internal effect state
+ */
+ this.onAfterShadowMapRenderObservable = new Observable();
+ /**
+ * Observable triggered before a mesh is rendered in the shadow map.
+ * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable)
+ */
+ this.onBeforeShadowMapRenderMeshObservable = new Observable();
+ /**
+ * Observable triggered after a mesh is rendered in the shadow map.
+ * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable)
+ */
+ this.onAfterShadowMapRenderMeshObservable = new Observable();
+ /**
+ * Specifies if the `ShadowGenerator` should be serialized, `true` to skip serialization.
+ * Note a `ShadowGenerator` will not be serialized if its light has `doNotSerialize=true`
+ */
+ this.doNotSerialize = false;
+ this._bias = 0.00005;
+ this._normalBias = 0;
+ this._blurBoxOffset = 1;
+ this._blurScale = 2;
+ this._blurKernel = 1;
+ this._useKernelBlur = false;
+ this._filter = ShadowGenerator.FILTER_NONE;
+ this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
+ this._contactHardeningLightSizeUVRatio = 0.1;
+ this._darkness = 0;
+ this._transparencyShadow = false;
+ /**
+ * Enables or disables shadows with varying strength based on the transparency
+ * When it is enabled, the strength of the shadow is taken equal to mesh.visibility
+ * If you enabled an alpha texture on your material, the alpha value red from the texture is also combined to compute the strength:
+ * mesh.visibility * alphaTexture.a
+ * The texture used is the diffuse by default, but it can be set to the opacity by setting useOpacityTextureForTransparentShadow
+ * Note that by definition transparencyShadow must be set to true for enableSoftTransparentShadow to work!
+ */
+ this.enableSoftTransparentShadow = false;
+ /**
+ * If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one
+ */
+ this.useOpacityTextureForTransparentShadow = false;
+ /**
+ * Controls the extent to which the shadows fade out at the edge of the frustum
+ */
+ this.frustumEdgeFalloff = 0;
+ /** Shader language used by the generator */
+ this._shaderLanguage = 0 /* ShaderLanguage.GLSL */;
+ /**
+ * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
+ * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
+ * It might on the other hand introduce peter panning.
+ */
+ this.forceBackFacesOnly = false;
+ this._lightDirection = Vector3.Zero();
+ this._viewMatrix = Matrix.Zero();
+ this._projectionMatrix = Matrix.Zero();
+ this._transformMatrix = Matrix.Zero();
+ this._cachedPosition = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._cachedDirection = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._currentFaceIndex = 0;
+ this._currentFaceIndexCache = 0;
+ this._defaultTextureMatrix = Matrix.Identity();
+ this._shadersLoaded = false;
+ this._mapSize = mapSize;
+ this._light = light;
+ this._scene = light.getScene();
+ this._camera = camera ?? null;
+ this._useRedTextureType = !!useRedTextureType;
+ this._initShaderSourceAsync(forceGLSL);
+ let shadowGenerators = light._shadowGenerators;
+ if (!shadowGenerators) {
+ shadowGenerators = light._shadowGenerators = new Map();
+ }
+ shadowGenerators.set(this._camera, this);
+ this.id = light.id;
+ this._useUBO = this._scene.getEngine().supportsUniformBuffers;
+ if (this._useUBO) {
+ this._sceneUBOs = [];
+ this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`));
+ }
+ ShadowGenerator._SceneComponentInitialization(this._scene);
+ // Texture type fallback from float to int if not supported.
+ const caps = this._scene.getEngine().getCaps();
+ if (!usefullFloatFirst) {
+ if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
+ this._textureType = 2;
+ }
+ else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
+ this._textureType = 1;
+ }
+ else {
+ this._textureType = 0;
+ }
+ }
+ else {
+ if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
+ this._textureType = 1;
+ }
+ else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
+ this._textureType = 2;
+ }
+ else {
+ this._textureType = 0;
+ }
+ }
+ this._initializeGenerator();
+ this._applyFilterValues();
+ }
+ _initializeGenerator() {
+ this._light._markMeshesAsLightDirty();
+ this._initializeShadowMap();
+ }
+ _createTargetRenderTexture() {
+ const engine = this._scene.getEngine();
+ if (engine._features.supportDepthStencilTexture) {
+ this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false, undefined, this._useRedTextureType ? 6 : 5);
+ this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true, undefined, undefined, undefined, `DepthStencilForShadowGenerator-${this._light.name}`);
+ }
+ else {
+ this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
+ }
+ this._shadowMap.noPrePassRenderer = true;
+ }
+ _initializeShadowMap() {
+ this._createTargetRenderTexture();
+ if (this._shadowMap === null) {
+ return;
+ }
+ this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
+ this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
+ this._shadowMap.anisotropicFilteringLevel = 1;
+ this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
+ this._shadowMap.renderParticles = false;
+ this._shadowMap.ignoreCameraViewport = true;
+ if (this._storedUniqueId) {
+ this._shadowMap.uniqueId = this._storedUniqueId;
+ }
+ // Custom render function.
+ this._shadowMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => this._renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes);
+ // When preWarm is false, forces the mesh is ready function to true as we are double checking it
+ // in the custom render function. Also it prevents side effects and useless
+ // shader variations in DEPTHPREPASS mode.
+ this._shadowMap.customIsReadyFunction = (mesh, _refreshRate, preWarm) => {
+ if (!preWarm || !mesh.subMeshes) {
+ return true;
+ }
+ let isReady = true;
+ for (const subMesh of mesh.subMeshes) {
+ const renderingMesh = subMesh.getRenderingMesh();
+ const scene = this._scene;
+ const engine = scene.getEngine();
+ const material = subMesh.getMaterial();
+ if (!material || subMesh.verticesCount === 0 || (this.customAllowRendering && !this.customAllowRendering(subMesh))) {
+ continue;
+ }
+ const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
+ if (batch.mustReturn) {
+ continue;
+ }
+ const hardwareInstancedRendering = engine.getCaps().instancedArrays &&
+ ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);
+ const isTransparent = material.needAlphaBlendingForMesh(renderingMesh);
+ isReady = this.isReady(subMesh, hardwareInstancedRendering, isTransparent) && isReady;
+ }
+ return isReady;
+ };
+ const engine = this._scene.getEngine();
+ this._shadowMap.onBeforeBindObservable.add(() => {
+ this._currentSceneUBO = this._scene.getSceneUniformBuffer();
+ engine._debugPushGroup?.(`shadow map generation for pass id ${engine.currentRenderPassId}`, 1);
+ });
+ // Record Face Index before render.
+ this._shadowMap.onBeforeRenderObservable.add((faceIndex) => {
+ if (this._sceneUBOs) {
+ this._scene.setSceneUniformBuffer(this._sceneUBOs[0]);
+ }
+ this._currentFaceIndex = faceIndex;
+ if (this._filter === ShadowGenerator.FILTER_PCF) {
+ engine.setColorWrite(false);
+ }
+ this.getTransformMatrix(); // generate the view/projection matrix
+ this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix);
+ if (this._useUBO) {
+ this._scene.getSceneUniformBuffer().unbindEffect();
+ this._scene.finalizeSceneUbo();
+ }
+ });
+ // Blur if required after render.
+ this._shadowMap.onAfterUnbindObservable.add(() => {
+ if (this._sceneUBOs) {
+ this._scene.setSceneUniformBuffer(this._currentSceneUBO);
+ }
+ this._scene.updateTransformMatrix(); // restore the view/projection matrices of the active camera
+ if (this._filter === ShadowGenerator.FILTER_PCF) {
+ engine.setColorWrite(true);
+ }
+ if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) {
+ engine._debugPopGroup?.(1);
+ return;
+ }
+ const shadowMap = this.getShadowMapForRendering();
+ if (shadowMap) {
+ this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.renderTarget, true);
+ engine.unBindFramebuffer(shadowMap.renderTarget, true);
+ }
+ engine._debugPopGroup?.(1);
+ });
+ // Clear according to the chosen filter.
+ const clearZero = new Color4(0, 0, 0, 0);
+ const clearOne = new Color4(1.0, 1.0, 1.0, 1.0);
+ this._shadowMap.onClearObservable.add((engine) => {
+ if (this._filter === ShadowGenerator.FILTER_PCF) {
+ engine.clear(clearOne, false, true, false);
+ }
+ else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
+ engine.clear(clearZero, true, true, false);
+ }
+ else {
+ engine.clear(clearOne, true, true, false);
+ }
+ });
+ // Recreate on resize.
+ this._shadowMap.onResizeObservable.add((rtt) => {
+ this._storedUniqueId = this._shadowMap.uniqueId;
+ this._mapSize = rtt.getRenderSize();
+ this._light._markMeshesAsLightDirty();
+ this.recreateShadowMap();
+ });
+ // Ensures rendering groupids do not erase the depth buffer
+ // or we would lose the shadows information.
+ for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
+ this._shadowMap.setRenderingAutoClearDepthStencil(i, false);
+ }
+ }
+ async _initShaderSourceAsync(forceGLSL = false) {
+ const engine = this._scene.getEngine();
+ if (engine.isWebGPU && !forceGLSL && !ShadowGenerator.ForceGLSL) {
+ this._shaderLanguage = 1 /* ShaderLanguage.WGSL */;
+ await Promise.all([
+ Promise.resolve().then(() => shadowMap_fragment$1),
+ Promise.resolve().then(() => shadowMap_vertex$1),
+ Promise.resolve().then(() => depthBoxBlur_fragment$1),
+ Promise.resolve().then(() => shadowMapFragmentSoftTransparentShadow$2),
+ ]);
+ }
+ else {
+ await Promise.all([
+ Promise.resolve().then(() => shadowMap_fragment),
+ Promise.resolve().then(() => shadowMap_vertex),
+ Promise.resolve().then(() => depthBoxBlur_fragment),
+ Promise.resolve().then(() => shadowMapFragmentSoftTransparentShadow$1),
+ ]);
+ }
+ this._shadersLoaded = true;
+ }
+ _initializeBlurRTTAndPostProcesses() {
+ const engine = this._scene.getEngine();
+ const targetSize = this._mapSize / this.blurScale;
+ if (!this.useKernelBlur || this.blurScale !== 1.0) {
+ this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType, undefined, undefined, false);
+ this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
+ this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
+ this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
+ }
+ if (this.useKernelBlur) {
+ this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX", new Vector2(1, 0), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
+ this._kernelBlurXPostprocess.width = targetSize;
+ this._kernelBlurXPostprocess.height = targetSize;
+ this._kernelBlurXPostprocess.externalTextureSamplerBinding = true;
+ this._kernelBlurXPostprocess.onApplyObservable.add((effect) => {
+ effect.setTexture("textureSampler", this._shadowMap);
+ });
+ this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY", new Vector2(0, 1), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
+ this._kernelBlurXPostprocess.autoClear = false;
+ this._kernelBlurYPostprocess.autoClear = false;
+ if (this._textureType === 0) {
+ this._kernelBlurXPostprocess.packedFloat = true;
+ this._kernelBlurYPostprocess.packedFloat = true;
+ }
+ this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
+ }
+ else {
+ this._boxBlurPostprocess = new PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType, undefined, undefined, undefined, undefined, this._shaderLanguage);
+ this._boxBlurPostprocess.externalTextureSamplerBinding = true;
+ this._boxBlurPostprocess.onApplyObservable.add((effect) => {
+ effect.setFloat2("screenSize", targetSize, targetSize);
+ effect.setTexture("textureSampler", this._shadowMap);
+ });
+ this._boxBlurPostprocess.autoClear = false;
+ this._blurPostProcesses = [this._boxBlurPostprocess];
+ }
+ }
+ _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
+ let index;
+ if (depthOnlySubMeshes.length) {
+ for (index = 0; index < depthOnlySubMeshes.length; index++) {
+ this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
+ }
+ }
+ for (index = 0; index < opaqueSubMeshes.length; index++) {
+ this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
+ }
+ for (index = 0; index < alphaTestSubMeshes.length; index++) {
+ this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
+ }
+ if (this._transparencyShadow) {
+ for (index = 0; index < transparentSubMeshes.length; index++) {
+ this._renderSubMeshForShadowMap(transparentSubMeshes.data[index], true);
+ }
+ }
+ else {
+ for (index = 0; index < transparentSubMeshes.length; index++) {
+ transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;
+ }
+ }
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, mesh) {
+ effect.setMatrix("viewProjection", this.getTransformMatrix());
+ }
+ _renderSubMeshForShadowMap(subMesh, isTransparent = false) {
+ const renderingMesh = subMesh.getRenderingMesh();
+ const effectiveMesh = subMesh.getEffectiveMesh();
+ const scene = this._scene;
+ const engine = scene.getEngine();
+ const material = subMesh.getMaterial();
+ effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
+ if (!material || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) {
+ return;
+ }
+ // Culling
+ // Note:
+ // In rhs mode, we assume that meshes will be rendered in right-handed space (i.e. with an RHS camera), so the default value of material.sideOrientation is updated accordingly (see material constructor).
+ // However, when generating a shadow map, we render from the point of view of the light, whose view/projection matrices are always in lhs mode.
+ // We therefore need to "undo" the sideOrientation inversion that was previously performed when constructing the material.
+ const useRHS = scene.useRightHandedSystem;
+ const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;
+ let sideOrientation = material._getEffectiveOrientation(renderingMesh);
+ if ((detNeg && !useRHS) || (!detNeg && useRHS)) {
+ sideOrientation =
+ sideOrientation === 0 ? 1 : 0;
+ }
+ const reverseSideOrientation = sideOrientation === 0;
+ engine.setState(material.backFaceCulling, undefined, undefined, reverseSideOrientation, material.cullBackFaces);
+ // Managing instances
+ const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
+ if (batch.mustReturn) {
+ return;
+ }
+ const hardwareInstancedRendering = engine.getCaps().instancedArrays &&
+ ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);
+ if (this.customAllowRendering && !this.customAllowRendering(subMesh)) {
+ return;
+ }
+ if (this.isReady(subMesh, hardwareInstancedRendering, isTransparent)) {
+ subMesh._renderId = scene.getRenderId();
+ const shadowDepthWrapper = material.shadowDepthWrapper;
+ const drawWrapper = shadowDepthWrapper?.getEffect(subMesh, this, engine.currentRenderPassId) ?? subMesh._getDrawWrapper();
+ const effect = DrawWrapper.GetEffect(drawWrapper);
+ engine.enableEffect(drawWrapper);
+ if (!hardwareInstancedRendering) {
+ renderingMesh._bind(subMesh, effect, material.fillMode);
+ }
+ this.getTransformMatrix(); // make sure _cachedDirection et _cachedPosition are up to date
+ effect.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale);
+ if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
+ effect.setVector3("lightDataSM", this._cachedDirection);
+ }
+ else {
+ effect.setVector3("lightDataSM", this._cachedPosition);
+ }
+ const camera = this._getCamera();
+ effect.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera));
+ if (isTransparent && this.enableSoftTransparentShadow) {
+ effect.setFloat2("softTransparentShadowSM", effectiveMesh.visibility * material.alpha, this._opacityTexture?.getAlphaFromRGB ? 1 : 0);
+ }
+ if (shadowDepthWrapper) {
+ subMesh._setMainDrawWrapperOverride(drawWrapper);
+ if (shadowDepthWrapper.standalone) {
+ shadowDepthWrapper.baseMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);
+ }
+ else {
+ material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);
+ }
+ subMesh._setMainDrawWrapperOverride(null);
+ }
+ else {
+ // Alpha test
+ if (this._opacityTexture) {
+ effect.setTexture("diffuseSampler", this._opacityTexture);
+ effect.setMatrix("diffuseMatrix", this._opacityTexture.getTextureMatrix() || this._defaultTextureMatrix);
+ }
+ // Bones
+ if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
+ const skeleton = renderingMesh.skeleton;
+ if (skeleton.isUsingTextureForMatrices) {
+ const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);
+ if (!boneTexture) {
+ return;
+ }
+ effect.setTexture("boneSampler", boneTexture);
+ effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
+ }
+ else {
+ effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh));
+ }
+ }
+ // Morph targets
+ BindMorphTargetParameters(renderingMesh, effect);
+ if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
+ renderingMesh.morphTargetManager._bind(effect);
+ }
+ // Baked vertex animations
+ const bvaManager = subMesh.getMesh().bakedVertexAnimationManager;
+ if (bvaManager && bvaManager.isEnabled) {
+ bvaManager.bind(effect, hardwareInstancedRendering);
+ }
+ // Clip planes
+ bindClipPlane(effect, material, scene);
+ }
+ if (!this._useUBO && !shadowDepthWrapper) {
+ this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, effectiveMesh);
+ }
+ BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer());
+ this._scene.getSceneUniformBuffer().bindUniformBuffer();
+ const world = effectiveMesh.getWorldMatrix();
+ // In the non hardware instanced mode, the Mesh ubo update is done by the callback passed to renderingMesh._processRendering (see below)
+ if (hardwareInstancedRendering) {
+ effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
+ effectiveMesh.transferToEffect(world);
+ }
+ if (this.forceBackFacesOnly) {
+ engine.setState(true, 0, false, true, material.cullBackFaces);
+ }
+ // Observables
+ this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
+ this.onBeforeShadowMapRenderObservable.notifyObservers(effect);
+ // Draw
+ renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, worldOverride) => {
+ if (effectiveMesh !== renderingMesh && !isInstance) {
+ renderingMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
+ renderingMesh.transferToEffect(worldOverride);
+ }
+ else {
+ effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
+ effectiveMesh.transferToEffect(isInstance ? worldOverride : world);
+ }
+ });
+ if (this.forceBackFacesOnly) {
+ engine.setState(true, 0, false, false, material.cullBackFaces);
+ }
+ // Observables
+ this.onAfterShadowMapRenderObservable.notifyObservers(effect);
+ this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
+ }
+ else {
+ // Need to reset refresh rate of the shadowMap
+ if (this._shadowMap) {
+ this._shadowMap.resetRefreshCounter();
+ }
+ }
+ }
+ _applyFilterValues() {
+ if (!this._shadowMap) {
+ return;
+ }
+ if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
+ this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
+ }
+ else {
+ this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
+ }
+ }
+ /**
+ * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects.
+ * @param onCompiled Callback triggered at the and of the effects compilation
+ * @param options Sets of optional options forcing the compilation with different modes
+ */
+ forceCompilation(onCompiled, options) {
+ const localOptions = {
+ useInstances: false,
+ ...options,
+ };
+ const shadowMap = this.getShadowMap();
+ if (!shadowMap) {
+ if (onCompiled) {
+ onCompiled(this);
+ }
+ return;
+ }
+ const renderList = shadowMap.renderList;
+ if (!renderList) {
+ if (onCompiled) {
+ onCompiled(this);
+ }
+ return;
+ }
+ const subMeshes = [];
+ for (const mesh of renderList) {
+ subMeshes.push(...mesh.subMeshes);
+ }
+ if (subMeshes.length === 0) {
+ if (onCompiled) {
+ onCompiled(this);
+ }
+ return;
+ }
+ let currentIndex = 0;
+ const checkReady = () => {
+ if (!this._scene || !this._scene.getEngine()) {
+ return;
+ }
+ while (this.isReady(subMeshes[currentIndex], localOptions.useInstances, subMeshes[currentIndex].getMaterial()?.needAlphaBlendingForMesh(subMeshes[currentIndex].getMesh()) ?? false)) {
+ currentIndex++;
+ if (currentIndex >= subMeshes.length) {
+ if (onCompiled) {
+ onCompiled(this);
+ }
+ return;
+ }
+ }
+ setTimeout(checkReady, 16);
+ };
+ checkReady();
+ }
+ /**
+ * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects.
+ * @param options Sets of optional options forcing the compilation with different modes
+ * @returns A promise that resolves when the compilation completes
+ */
+ forceCompilationAsync(options) {
+ return new Promise((resolve) => {
+ this.forceCompilation(() => {
+ resolve();
+ }, options);
+ });
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _isReadyCustomDefines(defines, subMesh, useInstances) { }
+ _prepareShadowDefines(subMesh, useInstances, defines, isTransparent) {
+ defines.push("#define SM_LIGHTTYPE_" + this._light.getClassName().toUpperCase());
+ defines.push("#define SM_FLOAT " + (this._textureType !== 0 ? "1" : "0"));
+ defines.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0"));
+ defines.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0"));
+ const mesh = subMesh.getMesh();
+ // Normal bias.
+ defines.push("#define SM_NORMALBIAS " + (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind) ? "1" : "0"));
+ defines.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0"));
+ // Point light
+ defines.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0"));
+ // Soft transparent shadows
+ defines.push("#define SM_SOFTTRANSPARENTSHADOW " + (this.enableSoftTransparentShadow && isTransparent ? "1" : "0"));
+ this._isReadyCustomDefines(defines, subMesh, useInstances);
+ return defines;
+ }
+ /**
+ * Determine whether the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
+ * @param subMesh The submesh we want to render in the shadow map
+ * @param useInstances Defines whether will draw in the map using instances
+ * @param isTransparent Indicates that isReady is called for a transparent subMesh
+ * @returns true if ready otherwise, false
+ */
+ isReady(subMesh, useInstances, isTransparent) {
+ if (!this._shadersLoaded) {
+ return false;
+ }
+ const material = subMesh.getMaterial(), shadowDepthWrapper = material?.shadowDepthWrapper;
+ this._opacityTexture = null;
+ if (!material) {
+ return false;
+ }
+ const defines = [];
+ this._prepareShadowDefines(subMesh, useInstances, defines, isTransparent);
+ if (shadowDepthWrapper) {
+ if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances, this._scene.getEngine().currentRenderPassId)) {
+ return false;
+ }
+ }
+ else {
+ const subMeshEffect = subMesh._getDrawWrapper(undefined, true);
+ let effect = subMeshEffect.effect;
+ let cachedDefines = subMeshEffect.defines;
+ const attribs = [VertexBuffer.PositionKind];
+ const mesh = subMesh.getMesh();
+ let useNormal = false;
+ let uv1 = false;
+ let uv2 = false;
+ const color = false;
+ // Normal bias.
+ if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+ attribs.push(VertexBuffer.NormalKind);
+ defines.push("#define NORMAL");
+ useNormal = true;
+ if (mesh.nonUniformScaling) {
+ defines.push("#define NONUNIFORMSCALING");
+ }
+ }
+ // Alpha test
+ const needAlphaTesting = material.needAlphaTestingForMesh(mesh);
+ if (needAlphaTesting || material.needAlphaBlendingForMesh(mesh)) {
+ if (this.useOpacityTextureForTransparentShadow) {
+ this._opacityTexture = material.opacityTexture;
+ }
+ else {
+ this._opacityTexture = material.getAlphaTestTexture();
+ }
+ if (this._opacityTexture) {
+ if (!this._opacityTexture.isReady()) {
+ return false;
+ }
+ const alphaCutOff = material.alphaCutOff ?? ShadowGenerator.DEFAULT_ALPHA_CUTOFF;
+ defines.push("#define ALPHATEXTURE");
+ if (needAlphaTesting) {
+ defines.push(`#define ALPHATESTVALUE ${alphaCutOff}${alphaCutOff % 1 === 0 ? "." : ""}`);
+ }
+ if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
+ attribs.push(VertexBuffer.UVKind);
+ defines.push("#define UV1");
+ uv1 = true;
+ }
+ if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
+ if (this._opacityTexture.coordinatesIndex === 1) {
+ attribs.push(VertexBuffer.UV2Kind);
+ defines.push("#define UV2");
+ uv2 = true;
+ }
+ }
+ }
+ }
+ // Bones
+ const fallbacks = new EffectFallbacks();
+ if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
+ attribs.push(VertexBuffer.MatricesIndicesKind);
+ attribs.push(VertexBuffer.MatricesWeightsKind);
+ if (mesh.numBoneInfluencers > 4) {
+ attribs.push(VertexBuffer.MatricesIndicesExtraKind);
+ attribs.push(VertexBuffer.MatricesWeightsExtraKind);
+ }
+ const skeleton = mesh.skeleton;
+ defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
+ if (mesh.numBoneInfluencers > 0) {
+ fallbacks.addCPUSkinningFallback(0, mesh);
+ }
+ if (skeleton.isUsingTextureForMatrices) {
+ defines.push("#define BONETEXTURE");
+ }
+ else {
+ defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
+ }
+ }
+ else {
+ defines.push("#define NUM_BONE_INFLUENCERS 0");
+ }
+ // Morph targets
+ const numMorphInfluencers = mesh.morphTargetManager
+ ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph
+ useNormal, // useNormalMorph
+ false, // useTangentMorph
+ uv1, // useUVMorph
+ uv2, // useUV2Morph
+ color // useColorMorph
+ )
+ : 0;
+ // ClipPlanes
+ prepareStringDefinesForClipPlanes(material, this._scene, defines);
+ // Instances
+ if (useInstances) {
+ defines.push("#define INSTANCES");
+ PushAttributesForInstances(attribs);
+ if (subMesh.getRenderingMesh().hasThinInstances) {
+ defines.push("#define THIN_INSTANCES");
+ }
+ }
+ if (this.customShaderOptions) {
+ if (this.customShaderOptions.defines) {
+ for (const define of this.customShaderOptions.defines) {
+ if (defines.indexOf(define) === -1) {
+ defines.push(define);
+ }
+ }
+ }
+ }
+ // Baked vertex animations
+ const bvaManager = mesh.bakedVertexAnimationManager;
+ if (bvaManager && bvaManager.isEnabled) {
+ defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
+ if (useInstances) {
+ attribs.push("bakedVertexAnimationSettingsInstanced");
+ }
+ }
+ // Get correct effect
+ const join = defines.join("\n");
+ if (cachedDefines !== join) {
+ cachedDefines = join;
+ let shaderName = "shadowMap";
+ const uniforms = [
+ "world",
+ "mBones",
+ "viewProjection",
+ "diffuseMatrix",
+ "lightDataSM",
+ "depthValuesSM",
+ "biasAndScaleSM",
+ "morphTargetInfluences",
+ "morphTargetCount",
+ "boneTextureWidth",
+ "softTransparentShadowSM",
+ "morphTargetTextureInfo",
+ "morphTargetTextureIndices",
+ "bakedVertexAnimationSettings",
+ "bakedVertexAnimationTextureSizeInverted",
+ "bakedVertexAnimationTime",
+ "bakedVertexAnimationTexture",
+ ];
+ const samplers = ["diffuseSampler", "boneSampler", "morphTargets", "bakedVertexAnimationTexture"];
+ const uniformBuffers = ["Scene", "Mesh"];
+ addClipPlaneUniforms(uniforms);
+ // Custom shader?
+ if (this.customShaderOptions) {
+ shaderName = this.customShaderOptions.shaderName;
+ if (this.customShaderOptions.attributes) {
+ for (const attrib of this.customShaderOptions.attributes) {
+ if (attribs.indexOf(attrib) === -1) {
+ attribs.push(attrib);
+ }
+ }
+ }
+ if (this.customShaderOptions.uniforms) {
+ for (const uniform of this.customShaderOptions.uniforms) {
+ if (uniforms.indexOf(uniform) === -1) {
+ uniforms.push(uniform);
+ }
+ }
+ }
+ if (this.customShaderOptions.samplers) {
+ for (const sampler of this.customShaderOptions.samplers) {
+ if (samplers.indexOf(sampler) === -1) {
+ samplers.push(sampler);
+ }
+ }
+ }
+ }
+ const engine = this._scene.getEngine();
+ effect = engine.createEffect(shaderName, {
+ attributes: attribs,
+ uniformsNames: uniforms,
+ uniformBuffersNames: uniformBuffers,
+ samplers: samplers,
+ defines: join,
+ fallbacks: fallbacks,
+ onCompiled: null,
+ onError: null,
+ indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers },
+ shaderLanguage: this._shaderLanguage,
+ }, engine);
+ subMeshEffect.setEffect(effect, cachedDefines);
+ }
+ if (!effect.isReady()) {
+ return false;
+ }
+ }
+ if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
+ if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
+ this._initializeBlurRTTAndPostProcesses();
+ }
+ }
+ if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
+ return false;
+ }
+ if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
+ return false;
+ }
+ if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Prepare all the defines in a material relying on a shadow map at the specified light index.
+ * @param defines Defines of the material we want to update
+ * @param lightIndex Index of the light in the enabled light list of the material
+ */
+ prepareDefines(defines, lightIndex) {
+ const scene = this._scene;
+ const light = this._light;
+ if (!scene.shadowsEnabled || !light.shadowEnabled) {
+ return;
+ }
+ defines["SHADOW" + lightIndex] = true;
+ if (this.useContactHardeningShadow) {
+ defines["SHADOWPCSS" + lightIndex] = true;
+ if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
+ defines["SHADOWLOWQUALITY" + lightIndex] = true;
+ }
+ else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
+ defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
+ }
+ // else default to high.
+ }
+ else if (this.usePercentageCloserFiltering) {
+ defines["SHADOWPCF" + lightIndex] = true;
+ if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
+ defines["SHADOWLOWQUALITY" + lightIndex] = true;
+ }
+ else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
+ defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
+ }
+ // else default to high.
+ }
+ else if (this.usePoissonSampling) {
+ defines["SHADOWPOISSON" + lightIndex] = true;
+ }
+ else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
+ defines["SHADOWESM" + lightIndex] = true;
+ }
+ else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
+ defines["SHADOWCLOSEESM" + lightIndex] = true;
+ }
+ if (light.needCube()) {
+ defines["SHADOWCUBE" + lightIndex] = true;
+ }
+ }
+ /**
+ * Binds the shadow related information inside of an effect (information like near, far, darkness...
+ * defined in the generator but impacting the effect).
+ * @param lightIndex Index of the light in the enabled light list of the material owning the effect
+ * @param effect The effect we are binding the information for
+ */
+ bindShadowLight(lightIndex, effect) {
+ const light = this._light;
+ const scene = this._scene;
+ if (!scene.shadowsEnabled || !light.shadowEnabled) {
+ return;
+ }
+ const camera = this._getCamera();
+ const shadowMap = this.getShadowMap();
+ if (!shadowMap) {
+ return;
+ }
+ if (!light.needCube()) {
+ effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
+ }
+ // Only PCF uses depth stencil texture.
+ const shadowMapForRendering = this.getShadowMapForRendering();
+ if (this._filter === ShadowGenerator.FILTER_PCF) {
+ effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMapForRendering);
+ light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
+ }
+ else if (this._filter === ShadowGenerator.FILTER_PCSS) {
+ effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMapForRendering);
+ effect.setTexture("depthTexture" + lightIndex, shadowMapForRendering);
+ light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
+ }
+ else {
+ effect.setTexture("shadowTexture" + lightIndex, shadowMapForRendering);
+ light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
+ }
+ light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
+ }
+ /**
+ * Gets the view matrix used to render the shadow map.
+ */
+ get viewMatrix() {
+ return this._viewMatrix;
+ }
+ /**
+ * Gets the projection matrix used to render the shadow map.
+ */
+ get projectionMatrix() {
+ return this._projectionMatrix;
+ }
+ /**
+ * Gets the transformation matrix used to project the meshes into the map from the light point of view.
+ * (eq to shadow projection matrix * light transform matrix)
+ * @returns The transform matrix used to create the shadow map
+ */
+ getTransformMatrix() {
+ const scene = this._scene;
+ if (this._currentRenderId === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
+ return this._transformMatrix;
+ }
+ this._currentRenderId = scene.getRenderId();
+ this._currentFaceIndexCache = this._currentFaceIndex;
+ let lightPosition = this._light.position;
+ if (this._light.computeTransformedInformation()) {
+ lightPosition = this._light.transformedPosition;
+ }
+ Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
+ if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
+ this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
+ }
+ if (this._light.needProjectionMatrixCompute() ||
+ !this._cachedPosition ||
+ !this._cachedDirection ||
+ !lightPosition.equals(this._cachedPosition) ||
+ !this._lightDirection.equals(this._cachedDirection)) {
+ this._cachedPosition.copyFrom(lightPosition);
+ this._cachedDirection.copyFrom(this._lightDirection);
+ Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
+ const shadowMap = this.getShadowMap();
+ if (shadowMap) {
+ const renderList = shadowMap.renderList;
+ if (renderList) {
+ this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
+ }
+ }
+ this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
+ }
+ return this._transformMatrix;
+ }
+ /**
+ * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
+ * Cube and 2D textures for instance.
+ */
+ recreateShadowMap() {
+ const shadowMap = this._shadowMap;
+ if (!shadowMap) {
+ return;
+ }
+ // Track render list.
+ const renderList = shadowMap.renderList;
+ // Clean up existing data.
+ this._disposeRTTandPostProcesses();
+ // Reinitializes.
+ this._initializeGenerator();
+ // Reaffect the filter to ensure a correct fallback if necessary.
+ this.filter = this._filter;
+ // Reaffect the filter.
+ this._applyFilterValues();
+ // Reaffect Render List.
+ if (renderList) {
+ // Note: don't do this._shadowMap!.renderList = renderList;
+ // The renderList hooked array is accessing the old RenderTargetTexture (see RenderTargetTexture._hookArray), which is disposed at this point (by the call to _disposeRTTandPostProcesses)
+ if (!this._shadowMap.renderList) {
+ this._shadowMap.renderList = [];
+ }
+ for (const mesh of renderList) {
+ this._shadowMap.renderList.push(mesh);
+ }
+ }
+ else {
+ this._shadowMap.renderList = null;
+ }
+ }
+ _disposeBlurPostProcesses() {
+ if (this._shadowMap2) {
+ this._shadowMap2.dispose();
+ this._shadowMap2 = null;
+ }
+ if (this._boxBlurPostprocess) {
+ this._boxBlurPostprocess.dispose();
+ this._boxBlurPostprocess = null;
+ }
+ if (this._kernelBlurXPostprocess) {
+ this._kernelBlurXPostprocess.dispose();
+ this._kernelBlurXPostprocess = null;
+ }
+ if (this._kernelBlurYPostprocess) {
+ this._kernelBlurYPostprocess.dispose();
+ this._kernelBlurYPostprocess = null;
+ }
+ this._blurPostProcesses = [];
+ }
+ _disposeRTTandPostProcesses() {
+ if (this._shadowMap) {
+ this._shadowMap.dispose();
+ this._shadowMap = null;
+ }
+ this._disposeBlurPostProcesses();
+ }
+ _disposeSceneUBOs() {
+ if (this._sceneUBOs) {
+ for (const ubo of this._sceneUBOs) {
+ ubo.dispose();
+ }
+ this._sceneUBOs = [];
+ }
+ }
+ /**
+ * Disposes the ShadowGenerator.
+ * Returns nothing.
+ */
+ dispose() {
+ this._disposeRTTandPostProcesses();
+ this._disposeSceneUBOs();
+ if (this._light) {
+ if (this._light._shadowGenerators) {
+ const iterator = this._light._shadowGenerators.entries();
+ for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) {
+ const [camera, shadowGenerator] = entry.value;
+ if (shadowGenerator === this) {
+ this._light._shadowGenerators.delete(camera);
+ }
+ }
+ if (this._light._shadowGenerators.size === 0) {
+ this._light._shadowGenerators = null;
+ }
+ }
+ this._light._markMeshesAsLightDirty();
+ }
+ this.onBeforeShadowMapRenderMeshObservable.clear();
+ this.onBeforeShadowMapRenderObservable.clear();
+ this.onAfterShadowMapRenderMeshObservable.clear();
+ this.onAfterShadowMapRenderObservable.clear();
+ }
+ /**
+ * Serializes the shadow generator setup to a json object.
+ * @returns The serialized JSON object
+ */
+ serialize() {
+ const serializationObject = {};
+ const shadowMap = this.getShadowMap();
+ if (!shadowMap) {
+ return serializationObject;
+ }
+ serializationObject.className = this.getClassName();
+ serializationObject.lightId = this._light.id;
+ serializationObject.cameraId = this._camera?.id;
+ serializationObject.id = this.id;
+ serializationObject.mapSize = shadowMap.getRenderSize();
+ serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
+ serializationObject.darkness = this.getDarkness();
+ serializationObject.transparencyShadow = this._transparencyShadow;
+ serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
+ serializationObject.bias = this.bias;
+ serializationObject.normalBias = this.normalBias;
+ serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
+ serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
+ serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
+ serializationObject.filteringQuality = this.filteringQuality;
+ serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
+ serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
+ serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
+ serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
+ serializationObject.usePoissonSampling = this.usePoissonSampling;
+ serializationObject.depthScale = this.depthScale;
+ serializationObject.blurBoxOffset = this.blurBoxOffset;
+ serializationObject.blurKernel = this.blurKernel;
+ serializationObject.blurScale = this.blurScale;
+ serializationObject.useKernelBlur = this.useKernelBlur;
+ serializationObject.renderList = [];
+ if (shadowMap.renderList) {
+ for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
+ const mesh = shadowMap.renderList[meshIndex];
+ serializationObject.renderList.push(mesh.id);
+ }
+ }
+ return serializationObject;
+ }
+ /**
+ * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
+ * @param parsedShadowGenerator The JSON object to parse
+ * @param scene The scene to create the shadow map for
+ * @param constr A function that builds a shadow generator or undefined to create an instance of the default shadow generator
+ * @returns The parsed shadow generator
+ */
+ static Parse(parsedShadowGenerator, scene, constr) {
+ const light = scene.getLightById(parsedShadowGenerator.lightId);
+ const camera = parsedShadowGenerator.cameraId !== undefined ? scene.getCameraById(parsedShadowGenerator.cameraId) : null;
+ const shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light, camera) : new ShadowGenerator(parsedShadowGenerator.mapSize, light, undefined, camera);
+ const shadowMap = shadowGenerator.getShadowMap();
+ for (let meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
+ const meshes = scene.getMeshesById(parsedShadowGenerator.renderList[meshIndex]);
+ meshes.forEach(function (mesh) {
+ if (!shadowMap) {
+ return;
+ }
+ if (!shadowMap.renderList) {
+ shadowMap.renderList = [];
+ }
+ shadowMap.renderList.push(mesh);
+ });
+ }
+ if (parsedShadowGenerator.id !== undefined) {
+ shadowGenerator.id = parsedShadowGenerator.id;
+ }
+ shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly;
+ if (parsedShadowGenerator.darkness !== undefined) {
+ shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
+ }
+ if (parsedShadowGenerator.transparencyShadow) {
+ shadowGenerator.setTransparencyShadow(true);
+ }
+ if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
+ shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
+ }
+ if (parsedShadowGenerator.bias !== undefined) {
+ shadowGenerator.bias = parsedShadowGenerator.bias;
+ }
+ if (parsedShadowGenerator.normalBias !== undefined) {
+ shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
+ }
+ if (parsedShadowGenerator.usePercentageCloserFiltering) {
+ shadowGenerator.usePercentageCloserFiltering = true;
+ }
+ else if (parsedShadowGenerator.useContactHardeningShadow) {
+ shadowGenerator.useContactHardeningShadow = true;
+ }
+ else if (parsedShadowGenerator.usePoissonSampling) {
+ shadowGenerator.usePoissonSampling = true;
+ }
+ else if (parsedShadowGenerator.useExponentialShadowMap) {
+ shadowGenerator.useExponentialShadowMap = true;
+ }
+ else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
+ shadowGenerator.useBlurExponentialShadowMap = true;
+ }
+ else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
+ shadowGenerator.useCloseExponentialShadowMap = true;
+ }
+ else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
+ shadowGenerator.useBlurCloseExponentialShadowMap = true;
+ }
+ // Backward compat
+ else if (parsedShadowGenerator.useVarianceShadowMap) {
+ shadowGenerator.useExponentialShadowMap = true;
+ }
+ else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
+ shadowGenerator.useBlurExponentialShadowMap = true;
+ }
+ if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== undefined) {
+ shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
+ }
+ if (parsedShadowGenerator.filteringQuality !== undefined) {
+ shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
+ }
+ if (parsedShadowGenerator.depthScale) {
+ shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
+ }
+ if (parsedShadowGenerator.blurScale) {
+ shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
+ }
+ if (parsedShadowGenerator.blurBoxOffset) {
+ shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
+ }
+ if (parsedShadowGenerator.useKernelBlur) {
+ shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
+ }
+ if (parsedShadowGenerator.blurKernel) {
+ shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
+ }
+ return shadowGenerator;
+ }
+}
+/**
+ * Name of the shadow generator class
+ */
+ShadowGenerator.CLASSNAME = "ShadowGenerator";
+/**
+ * Force all the shadow generators to compile to glsl even on WebGPU engines.
+ * False by default. This is mostly meant for backward compatibility.
+ */
+ShadowGenerator.ForceGLSL = false;
+/**
+ * Shadow generator mode None: no filtering applied.
+ */
+ShadowGenerator.FILTER_NONE = 0;
+/**
+ * Shadow generator mode ESM: Exponential Shadow Mapping.
+ * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
+ */
+ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
+/**
+ * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
+ * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
+ */
+ShadowGenerator.FILTER_POISSONSAMPLING = 2;
+/**
+ * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
+ * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
+ */
+ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
+/**
+ * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
+ * edge artifacts on steep falloff.
+ * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
+ */
+ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
+/**
+ * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
+ * edge artifacts on steep falloff.
+ * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
+ */
+ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
+/**
+ * Shadow generator mode PCF: Percentage Closer Filtering
+ * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
+ * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
+ */
+ShadowGenerator.FILTER_PCF = 6;
+/**
+ * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
+ * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
+ * Contact Hardening
+ */
+ShadowGenerator.FILTER_PCSS = 7;
+/**
+ * Reserved for PCF and PCSS
+ * Highest Quality.
+ *
+ * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
+ *
+ * Execute PCSS with 32 taps blocker search and 64 taps PCF.
+ */
+ShadowGenerator.QUALITY_HIGH = 0;
+/**
+ * Reserved for PCF and PCSS
+ * Good tradeoff for quality/perf cross devices
+ *
+ * Execute PCF on a 3*3 kernel.
+ *
+ * Execute PCSS with 16 taps blocker search and 32 taps PCF.
+ */
+ShadowGenerator.QUALITY_MEDIUM = 1;
+/**
+ * Reserved for PCF and PCSS
+ * The lowest quality but the fastest.
+ *
+ * Execute PCF on a 1*1 kernel.
+ *
+ * Execute PCSS with 16 taps blocker search and 16 taps PCF.
+ */
+ShadowGenerator.QUALITY_LOW = 2;
+/**
+ * Defines the default alpha cutoff value used for transparent alpha tested materials.
+ */
+ShadowGenerator.DEFAULT_ALPHA_CUTOFF = 0.5;
+/**
+ * @internal
+ */
+ShadowGenerator._SceneComponentInitialization = (_) => {
+ throw _WarnImport("ShadowGeneratorSceneComponent");
+};
+
+// Do not edit.
+const name$8g = "clipPlaneFragmentDeclaration";
+const shader$8f = `#ifdef CLIPPLANE
+varying float fClipDistance;
+#endif
+#ifdef CLIPPLANE2
+varying float fClipDistance2;
+#endif
+#ifdef CLIPPLANE3
+varying float fClipDistance3;
+#endif
+#ifdef CLIPPLANE4
+varying float fClipDistance4;
+#endif
+#ifdef CLIPPLANE5
+varying float fClipDistance5;
+#endif
+#ifdef CLIPPLANE6
+varying float fClipDistance6;
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$8g]) {
+ ShaderStore.IncludesShadersStore[name$8g] = shader$8f;
+}
+/** @internal */
+const clipPlaneFragmentDeclaration$1 = { name: name$8g, shader: shader$8f };
+
+const clipPlaneFragmentDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ clipPlaneFragmentDeclaration: clipPlaneFragmentDeclaration$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$8f = "packingFunctions";
+const shader$8e = `vec4 pack(float depth)
+{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
+float unpack(vec4 color)
+{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$8f]) {
+ ShaderStore.IncludesShadersStore[name$8f] = shader$8e;
+}
+/** @internal */
+const packingFunctions$1 = { name: name$8f, shader: shader$8e };
+
+const packingFunctions$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ packingFunctions: packingFunctions$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$8e = "clipPlaneFragment";
+const shader$8d = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
+if (false) {}
+#endif
+#ifdef CLIPPLANE
+else if (fClipDistance>0.0)
+{discard;}
+#endif
+#ifdef CLIPPLANE2
+else if (fClipDistance2>0.0)
+{discard;}
+#endif
+#ifdef CLIPPLANE3
+else if (fClipDistance3>0.0)
+{discard;}
+#endif
+#ifdef CLIPPLANE4
+else if (fClipDistance4>0.0)
+{discard;}
+#endif
+#ifdef CLIPPLANE5
+else if (fClipDistance5>0.0)
+{discard;}
+#endif
+#ifdef CLIPPLANE6
+else if (fClipDistance6>0.0)
+{discard;}
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$8e]) {
+ ShaderStore.IncludesShadersStore[name$8e] = shader$8d;
+}
+/** @internal */
+const clipPlaneFragment$1 = { name: name$8e, shader: shader$8d };
+
+const clipPlaneFragment$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ clipPlaneFragment: clipPlaneFragment$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$8d = "depthPixelShader";
+const shader$8c = `#ifdef ALPHATEST
+varying vec2 vUV;uniform sampler2D diffuseSampler;
+#endif
+#include
+varying float vDepthMetric;
+#ifdef PACKED
+#include
+#endif
+#ifdef STORE_CAMERASPACE_Z
+varying vec4 vViewPos;
+#endif
+#define CUSTOM_FRAGMENT_DEFINITIONS
+void main(void)
+{
+#include
+#ifdef ALPHATEST
+if (texture2D(diffuseSampler,vUV).a<0.4)
+discard;
+#endif
+#ifdef STORE_CAMERASPACE_Z
+#ifdef PACKED
+gl_FragColor=pack(vViewPos.z);
+#else
+gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);
+#endif
+#else
+#ifdef NONLINEARDEPTH
+#ifdef PACKED
+gl_FragColor=pack(gl_FragCoord.z);
+#else
+gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);
+#endif
+#else
+#ifdef PACKED
+gl_FragColor=pack(vDepthMetric);
+#else
+gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);
+#endif
+#endif
+#endif
+}`;
+// Sideeffect
+if (!ShaderStore.ShadersStore[name$8d]) {
+ ShaderStore.ShadersStore[name$8d] = shader$8c;
+}
+/** @internal */
+const depthPixelShader = { name: name$8d, shader: shader$8c };
+
+const depth_fragment$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ depthPixelShader
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$8c = "bonesDeclaration";
+const shader$8b = `#if NUM_BONE_INFLUENCERS>0
+attribute vec4 matricesIndices;attribute vec4 matricesWeights;
+#if NUM_BONE_INFLUENCERS>4
+attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;
+#endif
+#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
+#ifdef BONETEXTURE
+uniform highp sampler2D boneSampler;uniform float boneTextureWidth;
+#else
+uniform mat4 mBones[BonesPerMesh];
+#endif
+#ifdef BONES_VELOCITY_ENABLED
+uniform mat4 mPreviousBones[BonesPerMesh];
+#endif
+#ifdef BONETEXTURE
+#define inline
+mat4 readMatrixFromRawSampler(sampler2D smp,float index)
+{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);}
+#endif
+#endif
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$8c]) {
+ ShaderStore.IncludesShadersStore[name$8c] = shader$8b;
+}
+/** @internal */
+const bonesDeclaration$1 = { name: name$8c, shader: shader$8b };
+
+const bonesDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ bonesDeclaration: bonesDeclaration$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$8b = "bakedVertexAnimationDeclaration";
+const shader$8a = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
+uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;
+#ifdef INSTANCES
+attribute vec4 bakedVertexAnimationSettingsInstanced;
+#endif
+#define inline
+mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)
+{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);}
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$8b]) {
+ ShaderStore.IncludesShadersStore[name$8b] = shader$8a;
+}
+
+// Do not edit.
+const name$8a = "morphTargetsVertexGlobalDeclaration";
+const shader$89 = `#ifdef MORPHTARGETS
+uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];
+#ifdef MORPHTARGETS_TEXTURE
+uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)
+{
+float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;}
+vec4 readVector4FromRawSampler(int targetIndex,float vertexIndex)
+{
+float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV);}
+#endif
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$8a]) {
+ ShaderStore.IncludesShadersStore[name$8a] = shader$89;
+}
+/** @internal */
+const morphTargetsVertexGlobalDeclaration$1 = { name: name$8a, shader: shader$89 };
+
+const morphTargetsVertexGlobalDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ morphTargetsVertexGlobalDeclaration: morphTargetsVertexGlobalDeclaration$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$89 = "morphTargetsVertexDeclaration";
+const shader$88 = `#ifdef MORPHTARGETS
+#ifndef MORPHTARGETS_TEXTURE
+#ifdef MORPHTARGETS_POSITION
+attribute vec3 position{X};
+#endif
+#ifdef MORPHTARGETS_NORMAL
+attribute vec3 normal{X};
+#endif
+#ifdef MORPHTARGETS_TANGENT
+attribute vec3 tangent{X};
+#endif
+#ifdef MORPHTARGETS_UV
+attribute vec2 uv_{X};
+#endif
+#ifdef MORPHTARGETS_UV2
+attribute vec2 uv2_{X};
+#endif
+#elif {X}==0
+uniform int morphTargetCount;
+#endif
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$89]) {
+ ShaderStore.IncludesShadersStore[name$89] = shader$88;
+}
+/** @internal */
+const morphTargetsVertexDeclaration$1 = { name: name$89, shader: shader$88 };
+
+const morphTargetsVertexDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ morphTargetsVertexDeclaration: morphTargetsVertexDeclaration$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$88 = "clipPlaneVertexDeclaration";
+const shader$87 = `#ifdef CLIPPLANE
+uniform vec4 vClipPlane;varying float fClipDistance;
+#endif
+#ifdef CLIPPLANE2
+uniform vec4 vClipPlane2;varying float fClipDistance2;
+#endif
+#ifdef CLIPPLANE3
+uniform vec4 vClipPlane3;varying float fClipDistance3;
+#endif
+#ifdef CLIPPLANE4
+uniform vec4 vClipPlane4;varying float fClipDistance4;
+#endif
+#ifdef CLIPPLANE5
+uniform vec4 vClipPlane5;varying float fClipDistance5;
+#endif
+#ifdef CLIPPLANE6
+uniform vec4 vClipPlane6;varying float fClipDistance6;
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$88]) {
+ ShaderStore.IncludesShadersStore[name$88] = shader$87;
+}
+/** @internal */
+const clipPlaneVertexDeclaration$1 = { name: name$88, shader: shader$87 };
+
+const clipPlaneVertexDeclaration$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ clipPlaneVertexDeclaration: clipPlaneVertexDeclaration$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$87 = "instancesDeclaration";
+const shader$86 = `#ifdef INSTANCES
+attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
+#ifdef INSTANCESCOLOR
+attribute vec4 instanceColor;
+#endif
+#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
+uniform mat4 world;
+#endif
+#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
+attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;
+#ifdef THIN_INSTANCES
+uniform mat4 previousWorld;
+#endif
+#endif
+#else
+#if !defined(WORLD_UBO)
+uniform mat4 world;
+#endif
+#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
+uniform mat4 previousWorld;
+#endif
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$87]) {
+ ShaderStore.IncludesShadersStore[name$87] = shader$86;
+}
+
+// Do not edit.
+const name$86 = "pointCloudVertexDeclaration";
+const shader$85 = `#ifdef POINTSIZE
+uniform float pointSize;
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$86]) {
+ ShaderStore.IncludesShadersStore[name$86] = shader$85;
+}
+
+// Do not edit.
+const name$85 = "morphTargetsVertexGlobal";
+const shader$84 = `#ifdef MORPHTARGETS
+#ifdef MORPHTARGETS_TEXTURE
+float vertexID;
+#endif
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$85]) {
+ ShaderStore.IncludesShadersStore[name$85] = shader$84;
+}
+/** @internal */
+const morphTargetsVertexGlobal$1 = { name: name$85, shader: shader$84 };
+
+const morphTargetsVertexGlobal$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ morphTargetsVertexGlobal: morphTargetsVertexGlobal$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$84 = "morphTargetsVertex";
+const shader$83 = `#ifdef MORPHTARGETS
+#ifdef MORPHTARGETS_TEXTURE
+#if {X}==0
+for (int i=0; i=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;
+#ifdef MORPHTARGETS_POSITION
+positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];
+#endif
+#ifdef MORPHTARGETTEXTURE_HASPOSITIONS
+vertexID+=1.0;
+#endif
+#ifdef MORPHTARGETS_NORMAL
+normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];
+#endif
+#ifdef MORPHTARGETTEXTURE_HASNORMALS
+vertexID+=1.0;
+#endif
+#ifdef MORPHTARGETS_UV
+uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];
+#endif
+#ifdef MORPHTARGETTEXTURE_HASUVS
+vertexID+=1.0;
+#endif
+#ifdef MORPHTARGETS_TANGENT
+tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];
+#endif
+#ifdef MORPHTARGETTEXTURE_HASTANGENTS
+vertexID+=1.0;
+#endif
+#ifdef MORPHTARGETS_UV2
+uv2Updated+=(readVector3FromRawSampler(i,vertexID).xy-uv2)*morphTargetInfluences[i];
+#endif
+#ifdef MORPHTARGETTEXTURE_HASUV2S
+vertexID+=1.0;
+#endif
+#ifdef MORPHTARGETS_COLOR
+colorUpdated+=(readVector4FromRawSampler(i,vertexID)-color)*morphTargetInfluences[i];
+#endif
+}
+#endif
+#else
+#ifdef MORPHTARGETS_POSITION
+positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];
+#endif
+#ifdef MORPHTARGETS_NORMAL
+normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];
+#endif
+#ifdef MORPHTARGETS_TANGENT
+tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];
+#endif
+#ifdef MORPHTARGETS_UV
+uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];
+#endif
+#ifdef MORPHTARGETS_UV2
+uv2Updated+=(uv2_{X}-uv2)*morphTargetInfluences[{X}];
+#endif
+#ifdef MORPHTARGETS_COLOR
+colorUpdated+=(color{X}-color)*morphTargetInfluences[{X}];
+#endif
+#endif
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$84]) {
+ ShaderStore.IncludesShadersStore[name$84] = shader$83;
+}
+/** @internal */
+const morphTargetsVertex$1 = { name: name$84, shader: shader$83 };
+
+const morphTargetsVertex$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ morphTargetsVertex: morphTargetsVertex$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$83 = "instancesVertex";
+const shader$82 = `#ifdef INSTANCES
+mat4 finalWorld=mat4(world0,world1,world2,world3);
+#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
+mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,
+previousWorld2,previousWorld3);
+#endif
+#ifdef THIN_INSTANCES
+finalWorld=world*finalWorld;
+#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
+finalPreviousWorld=previousWorld*finalPreviousWorld;
+#endif
+#endif
+#else
+mat4 finalWorld=world;
+#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
+mat4 finalPreviousWorld=previousWorld;
+#endif
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$83]) {
+ ShaderStore.IncludesShadersStore[name$83] = shader$82;
+}
+
+// Do not edit.
+const name$82 = "bonesVertex";
+const shader$81 = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
+#if NUM_BONE_INFLUENCERS>0
+mat4 influence;
+#ifdef BONETEXTURE
+influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
+#if NUM_BONE_INFLUENCERS>1
+influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
+#endif
+#if NUM_BONE_INFLUENCERS>2
+influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
+#endif
+#if NUM_BONE_INFLUENCERS>3
+influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
+#endif
+#if NUM_BONE_INFLUENCERS>4
+influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
+#endif
+#if NUM_BONE_INFLUENCERS>5
+influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
+#endif
+#if NUM_BONE_INFLUENCERS>6
+influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
+#endif
+#if NUM_BONE_INFLUENCERS>7
+influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
+#endif
+#else
+influence=mBones[int(matricesIndices[0])]*matricesWeights[0];
+#if NUM_BONE_INFLUENCERS>1
+influence+=mBones[int(matricesIndices[1])]*matricesWeights[1];
+#endif
+#if NUM_BONE_INFLUENCERS>2
+influence+=mBones[int(matricesIndices[2])]*matricesWeights[2];
+#endif
+#if NUM_BONE_INFLUENCERS>3
+influence+=mBones[int(matricesIndices[3])]*matricesWeights[3];
+#endif
+#if NUM_BONE_INFLUENCERS>4
+influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
+#endif
+#if NUM_BONE_INFLUENCERS>5
+influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
+#endif
+#if NUM_BONE_INFLUENCERS>6
+influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
+#endif
+#if NUM_BONE_INFLUENCERS>7
+influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
+#endif
+#endif
+finalWorld=finalWorld*influence;
+#endif
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$82]) {
+ ShaderStore.IncludesShadersStore[name$82] = shader$81;
+}
+/** @internal */
+const bonesVertex$1 = { name: name$82, shader: shader$81 };
+
+const bonesVertex$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ bonesVertex: bonesVertex$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$81 = "bakedVertexAnimation";
+const shader$80 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
+{
+#ifdef INSTANCES
+#define BVASNAME bakedVertexAnimationSettingsInstanced
+#else
+#define BVASNAME bakedVertexAnimationSettings
+#endif
+float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
+#if NUM_BONE_INFLUENCERS>1
+VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
+#endif
+#if NUM_BONE_INFLUENCERS>2
+VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
+#endif
+#if NUM_BONE_INFLUENCERS>3
+VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
+#endif
+#if NUM_BONE_INFLUENCERS>4
+VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
+#endif
+#if NUM_BONE_INFLUENCERS>5
+VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
+#endif
+#if NUM_BONE_INFLUENCERS>6
+VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
+#endif
+#if NUM_BONE_INFLUENCERS>7
+VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
+#endif
+finalWorld=finalWorld*VATInfluence;}
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$81]) {
+ ShaderStore.IncludesShadersStore[name$81] = shader$80;
+}
+
+// Do not edit.
+const name$80 = "clipPlaneVertex";
+const shader$7$ = `#ifdef CLIPPLANE
+fClipDistance=dot(worldPos,vClipPlane);
+#endif
+#ifdef CLIPPLANE2
+fClipDistance2=dot(worldPos,vClipPlane2);
+#endif
+#ifdef CLIPPLANE3
+fClipDistance3=dot(worldPos,vClipPlane3);
+#endif
+#ifdef CLIPPLANE4
+fClipDistance4=dot(worldPos,vClipPlane4);
+#endif
+#ifdef CLIPPLANE5
+fClipDistance5=dot(worldPos,vClipPlane5);
+#endif
+#ifdef CLIPPLANE6
+fClipDistance6=dot(worldPos,vClipPlane6);
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$80]) {
+ ShaderStore.IncludesShadersStore[name$80] = shader$7$;
+}
+/** @internal */
+const clipPlaneVertex$1 = { name: name$80, shader: shader$7$ };
+
+const clipPlaneVertex$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ clipPlaneVertex: clipPlaneVertex$1
+}, Symbol.toStringTag, { value: 'Module' }));
+
+// Do not edit.
+const name$7$ = "pointCloudVertex";
+const shader$7_ = `#if defined(POINTSIZE) && !defined(WEBGPU)
+gl_PointSize=pointSize;
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.IncludesShadersStore[name$7$]) {
+ ShaderStore.IncludesShadersStore[name$7$] = shader$7_;
+}
+
+// Do not edit.
+const name$7_ = "depthVertexShader";
+const shader$7Z = `attribute vec3 position;
+#include
+#include
+#include
+#include[0..maxSimultaneousMorphTargets]
+#include
+#include
+uniform mat4 viewProjection;uniform vec2 depthValues;
+#if defined(ALPHATEST) || defined(NEED_UV)
+varying vec2 vUV;uniform mat4 diffuseMatrix;
+#ifdef UV1
+attribute vec2 uv;
+#endif
+#ifdef UV2
+attribute vec2 uv2;
+#endif
+#endif
+#ifdef STORE_CAMERASPACE_Z
+uniform mat4 view;varying vec4 vViewPos;
+#endif
+#include
+varying float vDepthMetric;
+#define CUSTOM_VERTEX_DEFINITIONS
+void main(void)
+{vec3 positionUpdated=position;
+#ifdef UV1
+vec2 uvUpdated=uv;
+#endif
+#ifdef UV2
+vec2 uv2Updated=uv2;
+#endif
+#include
+#include[0..maxSimultaneousMorphTargets]
+#include
+#include
+#include
+vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
+#include
+gl_Position=viewProjection*worldPos;
+#ifdef STORE_CAMERASPACE_Z
+vViewPos=view*worldPos;
+#else
+#ifdef USE_REVERSE_DEPTHBUFFER
+vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));
+#else
+vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));
+#endif
+#endif
+#if defined(ALPHATEST) || defined(BASIC_RENDER)
+#ifdef UV1
+vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
+#endif
+#ifdef UV2
+vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
+#endif
+#endif
+#include
+}
+`;
+// Sideeffect
+if (!ShaderStore.ShadersStore[name$7_]) {
+ ShaderStore.ShadersStore[name$7_] = shader$7Z;
+}
+/** @internal */
+const depthVertexShader = { name: name$7_, shader: shader$7Z };
+
+const depth_vertex$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
+ __proto__: null,
+ depthVertexShader
+}, Symbol.toStringTag, { value: 'Module' }));
+
+/**
+ * This represents a depth renderer in Babylon.
+ * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
+ */
+class DepthRenderer {
+ /**
+ * Gets the shader language used in this material.
+ */
+ get shaderLanguage() {
+ return this._shaderLanguage;
+ }
+ /**
+ * Sets a specific material to be used to render a mesh/a list of meshes by the depth renderer
+ * @param mesh mesh or array of meshes
+ * @param material material to use by the depth render when rendering the mesh(es). If undefined is passed, the specific material created by the depth renderer will be used.
+ */
+ setMaterialForRendering(mesh, material) {
+ this._depthMap.setMaterialForRendering(mesh, material);
+ }
+ /**
+ * Instantiates a depth renderer
+ * @param scene The scene the renderer belongs to
+ * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
+ * @param camera The camera to be used to render the depth map (default: scene's active camera)
+ * @param storeNonLinearDepth Defines whether the depth is stored linearly like in Babylon Shadows or directly like glFragCoord.z
+ * @param samplingMode The sampling mode to be used with the render target (Linear, Nearest...) (default: TRILINEAR_SAMPLINGMODE)
+ * @param storeCameraSpaceZ Defines whether the depth stored is the Z coordinate in camera space. If true, storeNonLinearDepth has no effect. (Default: false)
+ * @param name Name of the render target (default: DepthRenderer)
+ */
+ constructor(scene, type = 1, camera = null, storeNonLinearDepth = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, storeCameraSpaceZ = false, name) {
+ /** Shader language used by the material */
+ this._shaderLanguage = 0 /* ShaderLanguage.GLSL */;
+ /** Enable or disable the depth renderer. When disabled, the depth texture is not updated */
+ this.enabled = true;
+ /** Force writing the transparent objects into the depth map */
+ this.forceDepthWriteTransparentMeshes = false;
+ /**
+ * Specifies that the depth renderer will only be used within
+ * the camera it is created for.
+ * This can help forcing its rendering during the camera processing.
+ */
+ this.useOnlyInActiveCamera = false;
+ /** If true, reverse the culling of materials before writing to the depth texture.
+ * So, basically, when "true", back facing instead of front facing faces are rasterized into the texture
+ */
+ this.reverseCulling = false;
+ this._shadersLoaded = false;
+ this._scene = scene;
+ this._storeNonLinearDepth = storeNonLinearDepth;
+ this._storeCameraSpaceZ = storeCameraSpaceZ;
+ this.isPacked = type === 0;
+ if (this.isPacked) {
+ this.clearColor = new Color4(1.0, 1.0, 1.0, 1.0);
+ }
+ else {
+ this.clearColor = new Color4(storeCameraSpaceZ ? 1e8 : 1.0, 0.0, 0.0, 1.0);
+ }
+ this._initShaderSourceAsync();
+ DepthRenderer._SceneComponentInitialization(this._scene);
+ const engine = scene.getEngine();
+ this._camera = camera;
+ if (samplingMode !== Texture.NEAREST_SAMPLINGMODE) {
+ if (type === 1 && !engine._caps.textureFloatLinearFiltering) {
+ samplingMode = Texture.NEAREST_SAMPLINGMODE;
+ }
+ if (type === 2 && !engine._caps.textureHalfFloatLinearFiltering) {
+ samplingMode = Texture.NEAREST_SAMPLINGMODE;
+ }
+ }
+ // Render target
+ const format = this.isPacked || !engine._features.supportExtendedTextureFormats ? 5 : 6;
+ this._depthMap = new RenderTargetTexture(name ?? "DepthRenderer", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type, false, samplingMode, undefined, undefined, undefined, format);
+ this._depthMap.wrapU = Texture.CLAMP_ADDRESSMODE;
+ this._depthMap.wrapV = Texture.CLAMP_ADDRESSMODE;
+ this._depthMap.refreshRate = 1;
+ this._depthMap.renderParticles = false;
+ this._depthMap.renderList = null;
+ this._depthMap.noPrePassRenderer = true;
+ // Camera to get depth map from to support multiple concurrent cameras
+ this._depthMap.activeCamera = this._camera;
+ this._depthMap.ignoreCameraViewport = true;
+ this._depthMap.useCameraPostProcesses = false;
+ // set default depth value to 1.0 (far away)
+ this._depthMap.onClearObservable.add((engine) => {
+ engine.clear(this.clearColor, true, true, true);
+ });
+ this._depthMap.onBeforeBindObservable.add(() => {
+ engine._debugPushGroup?.("depth renderer", 1);
+ });
+ this._depthMap.onAfterUnbindObservable.add(() => {
+ engine._debugPopGroup?.(1);
+ });
+ this._depthMap.customIsReadyFunction = (mesh, refreshRate, preWarm) => {
+ if ((preWarm || refreshRate === 0) && mesh.subMeshes) {
+ for (let i = 0; i < mesh.subMeshes.length; ++i) {
+ const subMesh = mesh.subMeshes[i];
+ const renderingMesh = subMesh.getRenderingMesh();
+ const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
+ const hardwareInstancedRendering = engine.getCaps().instancedArrays &&
+ ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);
+ if (!this.isReady(subMesh, hardwareInstancedRendering)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ };
+ // Custom render function
+ const renderSubMesh = (subMesh) => {
+ const renderingMesh = subMesh.getRenderingMesh();
+ const effectiveMesh = subMesh.getEffectiveMesh();
+ const scene = this._scene;
+ const engine = scene.getEngine();
+ const material = subMesh.getMaterial();
+ effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
+ if (!material || effectiveMesh.infiniteDistance || material.disableDepthWrite || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) {
+ return;
+ }
+ // Culling
+ const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;
+ let sideOrientation = material._getEffectiveOrientation(renderingMesh);
+ if (detNeg) {
+ sideOrientation =
+ sideOrientation === 0
+ ? 1
+ : 0;
+ }
+ const reverseSideOrientation = sideOrientation === 0;
+ engine.setState(material.backFaceCulling, 0, false, reverseSideOrientation, this.reverseCulling ? !material.cullBackFaces : material.cullBackFaces);
+ // Managing instances
+ const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
+ if (batch.mustReturn) {
+ return;
+ }
+ const hardwareInstancedRendering = engine.getCaps().instancedArrays &&
+ ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);
+ const camera = this._camera || scene.activeCamera;
+ if (this.isReady(subMesh, hardwareInstancedRendering) && camera) {
+ subMesh._renderId = scene.getRenderId();
+ const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId];
+ let drawWrapper = subMesh._getDrawWrapper();
+ if (!drawWrapper && renderingMaterial) {
+ drawWrapper = renderingMaterial._getDrawWrapper();
+ }
+ const cameraIsOrtho = camera.mode === Camera.ORTHOGRAPHIC_CAMERA;
+ if (!drawWrapper) {
+ return;
+ }
+ const effect = drawWrapper.effect;
+ engine.enableEffect(drawWrapper);
+ if (!hardwareInstancedRendering) {
+ renderingMesh._bind(subMesh, effect, material.fillMode);
+ }
+ if (!renderingMaterial) {
+ effect.setMatrix("viewProjection", scene.getTransformMatrix());
+ effect.setMatrix("world", effectiveMesh.getWorldMatrix());
+ if (this._storeCameraSpaceZ) {
+ effect.setMatrix("view", scene.getViewMatrix());
+ }
+ }
+ else {
+ renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);
+ }
+ let minZ, maxZ;
+ if (cameraIsOrtho) {
+ minZ = !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1;
+ maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1;
+ }
+ else {
+ minZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? camera.minZ : engine.isNDCHalfZRange ? 0 : camera.minZ;
+ maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : camera.maxZ;
+ }
+ effect.setFloat2("depthValues", minZ, minZ + maxZ);
+ if (!renderingMaterial) {
+ // Alpha test
+ if (material.needAlphaTestingForMesh(effectiveMesh)) {
+ const alphaTexture = material.getAlphaTestTexture();
+ if (alphaTexture) {
+ effect.setTexture("diffuseSampler", alphaTexture);
+ effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
+ }
+ }
+ // Bones
+ BindBonesParameters(renderingMesh, effect);
+ // Clip planes
+ bindClipPlane(effect, material, scene);
+ // Morph targets
+ BindMorphTargetParameters(renderingMesh, effect);
+ if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
+ renderingMesh.morphTargetManager._bind(effect);
+ }
+ // Baked vertex animations
+ const bvaManager = subMesh.getMesh().bakedVertexAnimationManager;
+ if (bvaManager && bvaManager.isEnabled) {
+ bvaManager.bind(effect, hardwareInstancedRendering);
+ }
+ // Points cloud rendering
+ if (material.pointsCloud) {
+ effect.setFloat("pointSize", material.pointSize);
+ }
+ }
+ // Draw
+ renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world));
+ }
+ };
+ this._depthMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {
+ let index;
+ if (depthOnlySubMeshes.length) {
+ for (index = 0; index < depthOnlySubMeshes.length; index++) {
+ renderSubMesh(depthOnlySubMeshes.data[index]);
+ }
+ }
+ for (index = 0; index < opaqueSubMeshes.length; index++) {
+ renderSubMesh(opaqueSubMeshes.data[index]);
+ }
+ for (index = 0; index < alphaTestSubMeshes.length; index++) {
+ renderSubMesh(alphaTestSubMeshes.data[index]);
+ }
+ if (this.forceDepthWriteTransparentMeshes) {
+ for (index = 0; index < transparentSubMeshes.length; index++) {
+ renderSubMesh(transparentSubMeshes.data[index]);
+ }
+ }
+ else {
+ for (index = 0; index < transparentSubMeshes.length; index++) {
+ transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;
+ }
+ }
+ };
+ }
+ async _initShaderSourceAsync(forceGLSL = false) {
+ const engine = this._scene.getEngine();
+ if (engine.isWebGPU && !forceGLSL && !DepthRenderer.ForceGLSL) {
+ this._shaderLanguage = 1 /* ShaderLanguage.WGSL */;
+ await Promise.all([Promise.resolve().then(() => depth_vertex), Promise.resolve().then(() => depth_fragment)]);
+ }
+ else {
+ await Promise.all([Promise.resolve().then(() => depth_vertex$1), Promise.resolve().then(() => depth_fragment$1)]);
+ }
+ this._shadersLoaded = true;
+ }
+ /**
+ * Creates the depth rendering effect and checks if the effect is ready.
+ * @param subMesh The submesh to be used to render the depth map of
+ * @param useInstances If multiple world instances should be used
+ * @returns if the depth renderer is ready to render the depth map
+ */
+ isReady(subMesh, useInstances) {
+ if (!this._shadersLoaded) {
+ return false;
+ }
+ const engine = this._scene.getEngine();
+ const mesh = subMesh.getMesh();
+ const scene = mesh.getScene();
+ const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId];
+ if (renderingMaterial) {
+ return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);
+ }
+ const material = subMesh.getMaterial();
+ if (!material || material.disableDepthWrite) {
+ return false;
+ }
+ const defines = [];
+ const attribs = [VertexBuffer.PositionKind];
+ let uv1 = false;
+ let uv2 = false;
+ const color = false;
+ // Alpha test
+ if (material.needAlphaTestingForMesh(mesh) && material.getAlphaTestTexture()) {
+ defines.push("#define ALPHATEST");
+ if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
+ attribs.push(VertexBuffer.UVKind);
+ defines.push("#define UV1");
+ uv1 = true;
+ }
+ if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
+ attribs.push(VertexBuffer.UV2Kind);
+ defines.push("#define UV2");
+ uv2 = true;
+ }
+ }
+ // Bones
+ const fallbacks = new EffectFallbacks();
+ if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
+ attribs.push(VertexBuffer.MatricesIndicesKind);
+ attribs.push(VertexBuffer.MatricesWeightsKind);
+ if (mesh.numBoneInfluencers > 4) {
+ attribs.push(VertexBuffer.MatricesIndicesExtraKind);
+ attribs.push(VertexBuffer.MatricesWeightsExtraKind);
+ }
+ defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
+ if (mesh.numBoneInfluencers > 0) {
+ fallbacks.addCPUSkinningFallback(0, mesh);
+ }
+ const skeleton = mesh.skeleton;
+ if (skeleton.isUsingTextureForMatrices) {
+ defines.push("#define BONETEXTURE");
+ }
+ else {
+ defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
+ }
+ }
+ else {
+ defines.push("#define NUM_BONE_INFLUENCERS 0");
+ }
+ // Morph targets
+ const numMorphInfluencers = mesh.morphTargetManager
+ ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph
+ false, // useNormalMorph
+ false, // useTangentMorph
+ uv1, // useUVMorph
+ uv2, // useUV2Morph
+ color // useColorMorph
+ )
+ : 0;
+ // Points cloud rendering
+ if (material.pointsCloud) {
+ defines.push("#define POINTSIZE");
+ }
+ // Instances
+ if (useInstances) {
+ defines.push("#define INSTANCES");
+ PushAttributesForInstances(attribs);
+ if (subMesh.getRenderingMesh().hasThinInstances) {
+ defines.push("#define THIN_INSTANCES");
+ }
+ }
+ // Baked vertex animations
+ const bvaManager = mesh.bakedVertexAnimationManager;
+ if (bvaManager && bvaManager.isEnabled) {
+ defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
+ if (useInstances) {
+ attribs.push("bakedVertexAnimationSettingsInstanced");
+ }
+ }
+ // None linear depth
+ if (this._storeNonLinearDepth) {
+ defines.push("#define NONLINEARDEPTH");
+ }
+ // Store camera space Z coordinate instead of NDC Z
+ if (this._storeCameraSpaceZ) {
+ defines.push("#define STORE_CAMERASPACE_Z");
+ }
+ // Float Mode
+ if (this.isPacked) {
+ defines.push("#define PACKED");
+ }
+ // Clip planes
+ prepareStringDefinesForClipPlanes(material, scene, defines);
+ // Get correct effect
+ const drawWrapper = subMesh._getDrawWrapper(undefined, true);
+ const cachedDefines = drawWrapper.defines;
+ const join = defines.join("\n");
+ if (cachedDefines !== join) {
+ const uniforms = [
+ "world",
+ "mBones",
+ "boneTextureWidth",
+ "pointSize",
+ "viewProjection",
+ "view",
+ "diffuseMatrix",
+ "depthValues",
+ "morphTargetInfluences",
+ "morphTargetCount",
+ "morphTargetTextureInfo",
+ "morphTargetTextureIndices",
+ "bakedVertexAnimationSettings",
+ "bakedVertexAnimationTextureSizeInverted",
+ "bakedVertexAnimationTime",
+ "bakedVertexAnimationTexture",
+ ];
+ const samplers = ["diffuseSampler", "morphTargets", "boneSampler", "bakedVertexAnimationTexture"];
+ addClipPlaneUniforms(uniforms);
+ drawWrapper.setEffect(engine.createEffect("depth", {
+ attributes: attribs,
+ uniformsNames: uniforms,
+ uniformBuffersNames: [],
+ samplers: samplers,
+ defines: join,
+ fallbacks: fallbacks,
+ onCompiled: null,
+ onError: null,
+ indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers },
+ shaderLanguage: this._shaderLanguage,
+ }, engine), join);
+ }
+ return drawWrapper.effect.isReady();
+ }
+ /**
+ * Gets the texture which the depth map will be written to.
+ * @returns The depth map texture
+ */
+ getDepthMap() {
+ return this._depthMap;
+ }
+ /**
+ * Disposes of the depth renderer.
+ */
+ dispose() {
+ const keysToDelete = [];
+ for (const key in this._scene._depthRenderer) {
+ const depthRenderer = this._scene._depthRenderer[key];
+ if (depthRenderer === this) {
+ keysToDelete.push(key);
+ }
+ }
+ if (keysToDelete.length > 0) {
+ this._depthMap.dispose();
+ for (const key of keysToDelete) {
+ delete this._scene._depthRenderer[key];
+ }
+ }
+ }
+}
+/**
+ * Force all the depth renderer to compile to glsl even on WebGPU engines.
+ * False by default. This is mostly meant for backward compatibility.
+ */
+DepthRenderer.ForceGLSL = false;
+/**
+ * @internal
+ */
+DepthRenderer._SceneComponentInitialization = (_) => {
+ throw _WarnImport("DepthRendererSceneComponent");
+};
+
+// Do not edit.
+const name$7Z = "minmaxReduxPixelShader";
+const shader$7Y = `varying vec2 vUV;uniform sampler2D textureSampler;
+#if defined(INITIAL)
+uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)
+{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);
+#ifdef DEPTH_REDUX
+float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
+#else
+float maxz=max(max(max(f1,f2),f3),f4);
+#endif
+glFragColor=vec4(minz,maxz,0.,0.);}
+#elif defined(MAIN)
+uniform vec2 texSize;void main(void)
+{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
+#elif defined(ONEBEFORELAST)
+uniform ivec2 texSize;void main(void)
+{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}
+#elif defined(LAST)
+void main(void)
+{glFragColor=vec4(0.);if (true) {
+discard;}}
+#endif
+`;
+// Sideeffect
+if (!ShaderStore.ShadersStore[name$7Z]) {
+ ShaderStore.ShadersStore[name$7Z] = shader$7Y;
+}
+
+/**
+ * This class computes a min/max reduction from a texture: it means it computes the minimum
+ * and maximum values from all values of the texture.
+ * It is performed on the GPU for better performances, thanks to a succession of post processes.
+ * The source values are read from the red channel of the texture.
+ */
+class MinMaxReducer {
+ /**
+ * Creates a min/max reducer
+ * @param camera The camera to use for the post processes
+ */
+ constructor(camera) {
+ /**
+ * Observable triggered when the computation has been performed
+ */
+ this.onAfterReductionPerformed = new Observable();
+ this._forceFullscreenViewport = true;
+ this._activated = false;
+ this._camera = camera;
+ this._postProcessManager = new PostProcessManager(camera.getScene());
+ this._onContextRestoredObserver = camera.getEngine().onContextRestoredObservable.add(() => {
+ this._postProcessManager._rebuild();
+ });
+ }
+ /**
+ * Gets the texture used to read the values from.
+ */
+ get sourceTexture() {
+ return this._sourceTexture;
+ }
+ /**
+ * Sets the source texture to read the values from.
+ * One must indicate if the texture is a depth texture or not through the depthRedux parameter
+ * because in such textures '1' value must not be taken into account to compute the maximum
+ * as this value is used to clear the texture.
+ * Note that the computation is not activated by calling this function, you must call activate() for that!
+ * @param sourceTexture The texture to read the values from. The values should be in the red channel.
+ * @param depthRedux Indicates if the texture is a depth texture or not
+ * @param type The type of the textures created for the reduction (defaults to TEXTURETYPE_HALF_FLOAT)
+ * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true)
+ */
+ setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) {
+ if (sourceTexture === this._sourceTexture) {
+ return;
+ }
+ this.dispose(false);
+ this._sourceTexture = sourceTexture;
+ this._reductionSteps = [];
+ this._forceFullscreenViewport = forceFullscreenViewport;
+ const scene = this._camera.getScene();
+ // create the first step
+ const reductionInitial = new PostProcess("Initial reduction phase", "minmaxRedux", // shader
+ ["texSize"], ["sourceTexture"], // textures
+ 1.0, // options
+ null, // camera
+ 1, // sampling
+ scene.getEngine(), // engine
+ false, // reusable
+ "#define INITIAL" + (depthRedux ? "\n#define DEPTH_REDUX" : ""), // defines
+ type, undefined, undefined, undefined, 7);
+ reductionInitial.autoClear = false;
+ reductionInitial.forceFullscreenViewport = forceFullscreenViewport;
+ let w = this._sourceTexture.getRenderWidth(), h = this._sourceTexture.getRenderHeight();
+ reductionInitial.onApply = ((w, h) => {
+ return (effect) => {
+ effect.setTexture("sourceTexture", this._sourceTexture);
+ effect.setFloat2("texSize", w, h);
+ };
+ })(w, h);
+ this._reductionSteps.push(reductionInitial);
+ let index = 1;
+ // create the additional steps
+ while (w > 1 || h > 1) {
+ w = Math.max(Math.round(w / 2), 1);
+ h = Math.max(Math.round(h / 2), 1);
+ const reduction = new PostProcess("Reduction phase " + index, "minmaxRedux", // shader
+ ["texSize"], null, { width: w, height: h }, // options
+ null, // camera
+ 1, // sampling
+ scene.getEngine(), // engine
+ false, // reusable
+ "#define " + (w == 1 && h == 1 ? "LAST" : w == 1 || h == 1 ? "ONEBEFORELAST" : "MAIN"), // defines
+ type, undefined, undefined, undefined, 7);
+ reduction.autoClear = false;
+ reduction.forceFullscreenViewport = forceFullscreenViewport;
+ reduction.onApply = ((w, h) => {
+ return (effect) => {
+ if (w == 1 || h == 1) {
+ effect.setInt2("texSize", w, h);
+ }
+ else {
+ effect.setFloat2("texSize", w, h);
+ }
+ };
+ })(w, h);
+ this._reductionSteps.push(reduction);
+ index++;
+ if (w == 1 && h == 1) {
+ const func = (w, h, reduction) => {
+ const buffer = new Float32Array(4 * w * h), minmax = { min: 0, max: 0 };
+ return () => {
+ scene.getEngine()._readTexturePixels(reduction.inputTexture.texture, w, h, -1, 0, buffer, false);
+ minmax.min = buffer[0];
+ minmax.max = buffer[1];
+ this.onAfterReductionPerformed.notifyObservers(minmax);
+ };
+ };
+ reduction.onAfterRenderObservable.add(func(w, h, reduction));
+ }
+ }
+ }
+ /**
+ * Defines the refresh rate of the computation.
+ * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on...
+ */
+ get refreshRate() {
+ return this._sourceTexture ? this._sourceTexture.refreshRate : -1;
+ }
+ set refreshRate(value) {
+ if (this._sourceTexture) {
+ this._sourceTexture.refreshRate = value;
+ }
+ }
+ /**
+ * Gets the activation status of the reducer
+ */
+ get activated() {
+ return this._activated;
+ }
+ /**
+ * Activates the reduction computation.
+ * When activated, the observers registered in onAfterReductionPerformed are
+ * called after the computation is performed
+ */
+ activate() {
+ if (this._onAfterUnbindObserver || !this._sourceTexture) {
+ return;
+ }
+ this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(() => {
+ const engine = this._camera.getScene().getEngine();
+ engine._debugPushGroup?.(`min max reduction`, 1);
+ this._reductionSteps[0].activate(this._camera);
+ this._postProcessManager.directRender(this._reductionSteps, this._reductionSteps[0].inputTexture, this._forceFullscreenViewport);
+ engine.unBindFramebuffer(this._reductionSteps[0].inputTexture, false);
+ engine._debugPopGroup?.(1);
+ });
+ this._activated = true;
+ }
+ /**
+ * Deactivates the reduction computation.
+ */
+ deactivate() {
+ if (!this._onAfterUnbindObserver || !this._sourceTexture) {
+ return;
+ }
+ this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
+ this._onAfterUnbindObserver = null;
+ this._activated = false;
+ }
+ /**
+ * Disposes the min/max reducer
+ * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally.
+ */
+ dispose(disposeAll = true) {
+ if (disposeAll) {
+ this.onAfterReductionPerformed.clear();
+ if (this._onContextRestoredObserver) {
+ this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
+ this._onContextRestoredObserver = null;
+ }
+ }
+ this.deactivate();
+ if (this._reductionSteps) {
+ for (let i = 0; i < this._reductionSteps.length; ++i) {
+ this._reductionSteps[i].dispose();
+ }
+ this._reductionSteps = null;
+ }
+ if (this._postProcessManager && disposeAll) {
+ this._postProcessManager.dispose();
+ }
+ this._sourceTexture = null;
+ }
+}
+
+/**
+ * This class is a small wrapper around the MinMaxReducer class to compute the min/max values of a depth texture
+ */
+class DepthReducer extends MinMaxReducer {
+ /**
+ * Gets the depth renderer used for the computation.
+ * Note that the result is null if you provide your own renderer when calling setDepthRenderer.
+ */
+ get depthRenderer() {
+ return this._depthRenderer;
+ }
+ /**
+ * Creates a depth reducer
+ * @param camera The camera used to render the depth texture
+ */
+ constructor(camera) {
+ super(camera);
+ }
+ /**
+ * Sets the depth renderer to use to generate the depth map
+ * @param depthRenderer The depth renderer to use. If not provided, a new one will be created automatically
+ * @param type The texture type of the depth map (default: TEXTURETYPE_HALF_FLOAT)
+ * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true)
+ */
+ setDepthRenderer(depthRenderer = null, type = 2, forceFullscreenViewport = true) {
+ const scene = this._camera.getScene();
+ if (this._depthRenderer) {
+ delete scene._depthRenderer[this._depthRendererId];
+ this._depthRenderer.dispose();
+ this._depthRenderer = null;
+ }
+ if (depthRenderer === null) {
+ if (!scene._depthRenderer) {
+ scene._depthRenderer = {};
+ }
+ depthRenderer = this._depthRenderer = new DepthRenderer(scene, type, this._camera, false, 1);
+ depthRenderer.enabled = false;
+ this._depthRendererId = "minmax" + this._camera.id;
+ scene._depthRenderer[this._depthRendererId] = depthRenderer;
+ }
+ super.setSourceTexture(depthRenderer.getDepthMap(), true, type, forceFullscreenViewport);
+ }
+ /**
+ * @internal
+ */
+ setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) {
+ super.setSourceTexture(sourceTexture, depthRedux, type, forceFullscreenViewport);
+ }
+ /**
+ * Activates the reduction computation.
+ * When activated, the observers registered in onAfterReductionPerformed are
+ * called after the computation is performed
+ */
+ activate() {
+ if (this._depthRenderer) {
+ this._depthRenderer.enabled = true;
+ }
+ super.activate();
+ }
+ /**
+ * Deactivates the reduction computation.
+ */
+ deactivate() {
+ super.deactivate();
+ if (this._depthRenderer) {
+ this._depthRenderer.enabled = false;
+ }
+ }
+ /**
+ * Disposes the depth reducer
+ * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally.
+ */
+ dispose(disposeAll = true) {
+ super.dispose(disposeAll);
+ if (this._depthRenderer && disposeAll) {
+ const scene = this._depthRenderer.getDepthMap().getScene();
+ if (scene) {
+ delete scene._depthRenderer[this._depthRendererId];
+ }
+ this._depthRenderer.dispose();
+ this._depthRenderer = null;
+ }
+ }
+}
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const UpDir = Vector3.Up();
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const ZeroVec = Vector3.Zero();
+const tmpv1 = new Vector3(), tmpv2 = new Vector3(), tmpMatrix = new Matrix();
+/**
+ * A CSM implementation allowing casting shadows on large scenes.
+ * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows
+ * Based on: https://github.com/TheRealMJP/Shadows and https://johanmedestrom.wordpress.com/2016/03/18/opengl-cascaded-shadow-maps/
+ */
+class CascadedShadowGenerator extends ShadowGenerator {
+ _validateFilter(filter) {
+ if (filter === ShadowGenerator.FILTER_NONE || filter === ShadowGenerator.FILTER_PCF || filter === ShadowGenerator.FILTER_PCSS) {
+ return filter;
+ }
+ Logger.Error('Unsupported filter "' + filter + '"!');
+ return ShadowGenerator.FILTER_NONE;
+ }
+ /**
+ * Gets or set the number of cascades used by the CSM.
+ */
+ get numCascades() {
+ return this._numCascades;
+ }
+ set numCascades(value) {
+ value = Math.min(Math.max(value, CascadedShadowGenerator.MIN_CASCADES_COUNT), CascadedShadowGenerator.MAX_CASCADES_COUNT);
+ if (value === this._numCascades) {
+ return;
+ }
+ this._numCascades = value;
+ this.recreateShadowMap();
+ this._recreateSceneUBOs();
+ }
+ /**
+ * Enables or disables the shadow casters bounding info computation.
+ * If your shadow casters don't move, you can disable this feature.
+ * If it is enabled, the bounding box computation is done every frame.
+ */
+ get freezeShadowCastersBoundingInfo() {
+ return this._freezeShadowCastersBoundingInfo;
+ }
+ set freezeShadowCastersBoundingInfo(freeze) {
+ if (this._freezeShadowCastersBoundingInfoObservable && freeze) {
+ this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);
+ this._freezeShadowCastersBoundingInfoObservable = null;
+ }
+ if (!this._freezeShadowCastersBoundingInfoObservable && !freeze) {
+ this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(() => this._computeShadowCastersBoundingInfo());
+ }
+ this._freezeShadowCastersBoundingInfo = freeze;
+ if (freeze) {
+ this._computeShadowCastersBoundingInfo();
+ }
+ }
+ _computeShadowCastersBoundingInfo() {
+ this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._scbiMax.copyFromFloats(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+ if (this._shadowMap && this._shadowMap.renderList) {
+ const renderList = this._shadowMap.renderList;
+ for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
+ const mesh = renderList[meshIndex];
+ if (!mesh) {
+ continue;
+ }
+ const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox;
+ this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);
+ this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);
+ }
+ }
+ this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax);
+ }
+ /**
+ * Gets or sets the shadow casters bounding info.
+ * If you provide your own shadow casters bounding info, first enable freezeShadowCastersBoundingInfo
+ * so that the system won't overwrite the bounds you provide
+ */
+ get shadowCastersBoundingInfo() {
+ return this._shadowCastersBoundingInfo;
+ }
+ set shadowCastersBoundingInfo(boundingInfo) {
+ this._shadowCastersBoundingInfo = boundingInfo;
+ }
+ /**
+ * Sets the minimal and maximal distances to use when computing the cascade breaks.
+ *
+ * The values of min / max are typically the depth zmin and zmax values of your scene, for a given frame.
+ * If you don't know these values, simply leave them to their defaults and don't call this function.
+ * @param min minimal distance for the breaks (default to 0.)
+ * @param max maximal distance for the breaks (default to 1.)
+ */
+ setMinMaxDistance(min, max) {
+ if (this._minDistance === min && this._maxDistance === max) {
+ return;
+ }
+ if (min > max) {
+ min = 0;
+ max = 1;
+ }
+ if (min < 0) {
+ min = 0;
+ }
+ if (max > 1) {
+ max = 1;
+ }
+ this._minDistance = min;
+ this._maxDistance = max;
+ this._breaksAreDirty = true;
+ }
+ /** Gets the minimal distance used in the cascade break computation */
+ get minDistance() {
+ return this._minDistance;
+ }
+ /** Gets the maximal distance used in the cascade break computation */
+ get maxDistance() {
+ return this._maxDistance;
+ }
+ /**
+ * Gets the class name of that object
+ * @returns "CascadedShadowGenerator"
+ */
+ getClassName() {
+ return CascadedShadowGenerator.CLASSNAME;
+ }
+ /**
+ * Gets a cascade minimum extents
+ * @param cascadeIndex index of the cascade
+ * @returns the minimum cascade extents
+ */
+ getCascadeMinExtents(cascadeIndex) {
+ return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMinExtents[cascadeIndex] : null;
+ }
+ /**
+ * Gets a cascade maximum extents
+ * @param cascadeIndex index of the cascade
+ * @returns the maximum cascade extents
+ */
+ getCascadeMaxExtents(cascadeIndex) {
+ return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null;
+ }
+ /**
+ * Gets the shadow max z distance. It's the limit beyond which shadows are not displayed.
+ * It defaults to camera.maxZ
+ */
+ get shadowMaxZ() {
+ if (!this._getCamera()) {
+ return 0;
+ }
+ return this._shadowMaxZ;
+ }
+ /**
+ * Sets the shadow max z distance.
+ */
+ set shadowMaxZ(value) {
+ const camera = this._getCamera();
+ if (!camera) {
+ this._shadowMaxZ = value;
+ return;
+ }
+ if (this._shadowMaxZ === value || value < camera.minZ || (value > camera.maxZ && camera.maxZ !== 0)) {
+ return;
+ }
+ this._shadowMaxZ = value;
+ this._light._markMeshesAsLightDirty();
+ this._breaksAreDirty = true;
+ }
+ /**
+ * Gets or sets the debug flag.
+ * When enabled, the cascades are materialized by different colors on the screen.
+ */
+ get debug() {
+ return this._debug;
+ }
+ set debug(dbg) {
+ this._debug = dbg;
+ this._light._markMeshesAsLightDirty();
+ }
+ /**
+ * Gets or sets the depth clamping value.
+ *
+ * When enabled, it improves the shadow quality because the near z plane of the light frustum don't need to be adjusted
+ * to account for the shadow casters far away.
+ *
+ * Note that this property is incompatible with PCSS filtering, so it won't be used in that case.
+ */
+ get depthClamp() {
+ return this._depthClamp;
+ }
+ set depthClamp(value) {
+ this._depthClamp = value;
+ }
+ /**
+ * Gets or sets the percentage of blending between two cascades (value between 0. and 1.).
+ * It defaults to 0.1 (10% blending).
+ */
+ get cascadeBlendPercentage() {
+ return this._cascadeBlendPercentage;
+ }
+ set cascadeBlendPercentage(value) {
+ this._cascadeBlendPercentage = value;
+ this._light._markMeshesAsLightDirty();
+ }
+ /**
+ * Gets or set the lambda parameter.
+ * This parameter is used to split the camera frustum and create the cascades.
+ * It's a value between 0. and 1.: If 0, the split is a uniform split of the frustum, if 1 it is a logarithmic split.
+ * For all values in-between, it's a linear combination of the uniform and logarithm split algorithm.
+ */
+ get lambda() {
+ return this._lambda;
+ }
+ set lambda(value) {
+ const lambda = Math.min(Math.max(value, 0), 1);
+ if (this._lambda == lambda) {
+ return;
+ }
+ this._lambda = lambda;
+ this._breaksAreDirty = true;
+ }
+ /**
+ * Gets the view matrix corresponding to a given cascade
+ * @param cascadeNum cascade to retrieve the view matrix from
+ * @returns the cascade view matrix
+ */
+ getCascadeViewMatrix(cascadeNum) {
+ return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._viewMatrices[cascadeNum] : null;
+ }
+ /**
+ * Gets the projection matrix corresponding to a given cascade
+ * @param cascadeNum cascade to retrieve the projection matrix from
+ * @returns the cascade projection matrix
+ */
+ getCascadeProjectionMatrix(cascadeNum) {
+ return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._projectionMatrices[cascadeNum] : null;
+ }
+ /**
+ * Gets the transformation matrix corresponding to a given cascade
+ * @param cascadeNum cascade to retrieve the transformation matrix from
+ * @returns the cascade transformation matrix
+ */
+ getCascadeTransformMatrix(cascadeNum) {
+ return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._transformMatrices[cascadeNum] : null;
+ }
+ /**
+ * Sets the depth renderer to use when autoCalcDepthBounds is enabled.
+ *
+ * Note that if no depth renderer is set, a new one will be automatically created internally when necessary.
+ *
+ * You should call this function if you already have a depth renderer enabled in your scene, to avoid
+ * doing multiple depth rendering each frame. If you provide your own depth renderer, make sure it stores linear depth!
+ * @param depthRenderer The depth renderer to use when autoCalcDepthBounds is enabled. If you pass null or don't call this function at all, a depth renderer will be automatically created
+ */
+ setDepthRenderer(depthRenderer) {
+ this._depthRenderer = depthRenderer;
+ if (this._depthReducer) {
+ this._depthReducer.setDepthRenderer(this._depthRenderer);
+ }
+ }
+ /**
+ * Gets or sets the autoCalcDepthBounds property.
+ *
+ * When enabled, a depth rendering pass is first performed (with an internally created depth renderer or with the one
+ * you provide by calling setDepthRenderer). Then, a min/max reducing is applied on the depth map to compute the
+ * minimal and maximal depth of the map and those values are used as inputs for the setMinMaxDistance() function.
+ * It can greatly enhance the shadow quality, at the expense of more GPU works.
+ * When using this option, you should increase the value of the lambda parameter, and even set it to 1 for best results.
+ */
+ get autoCalcDepthBounds() {
+ return this._autoCalcDepthBounds;
+ }
+ set autoCalcDepthBounds(value) {
+ const camera = this._getCamera();
+ if (!camera) {
+ return;
+ }
+ this._autoCalcDepthBounds = value;
+ if (!value) {
+ if (this._depthReducer) {
+ this._depthReducer.deactivate();
+ }
+ this.setMinMaxDistance(0, 1);
+ return;
+ }
+ if (!this._depthReducer) {
+ this._depthReducer = new DepthReducer(camera);
+ this._depthReducer.onAfterReductionPerformed.add((minmax) => {
+ let min = minmax.min, max = minmax.max;
+ if (min >= max) {
+ min = 0;
+ max = 1;
+ }
+ if (min != this._minDistance || max != this._maxDistance) {
+ this.setMinMaxDistance(min, max);
+ }
+ });
+ this._depthReducer.setDepthRenderer(this._depthRenderer);
+ }
+ this._depthReducer.activate();
+ }
+ /**
+ * Defines the refresh rate of the min/max computation used when autoCalcDepthBounds is set to true
+ * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on...
+ * Note that if you provided your own depth renderer through a call to setDepthRenderer, you are responsible
+ * for setting the refresh rate on the renderer yourself!
+ */
+ get autoCalcDepthBoundsRefreshRate() {
+ return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate ?? -1;
+ }
+ set autoCalcDepthBoundsRefreshRate(value) {
+ if (this._depthReducer?.depthRenderer) {
+ this._depthReducer.depthRenderer.getDepthMap().refreshRate = value;
+ }
+ }
+ /**
+ * Create the cascade breaks according to the lambda, shadowMaxZ and min/max distance properties, as well as the camera near and far planes.
+ * This function is automatically called when updating lambda, shadowMaxZ and min/max distances, however you should call it yourself if
+ * you change the camera near/far planes!
+ */
+ splitFrustum() {
+ this._breaksAreDirty = true;
+ }
+ _splitFrustum() {
+ const camera = this._getCamera();
+ if (!camera) {
+ return;
+ }
+ const near = camera.minZ, far = camera.maxZ || this._shadowMaxZ, // account for infinite far plane (ie. maxZ = 0)
+ cameraRange = far - near, minDistance = this._minDistance, maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance;
+ const minZ = near + minDistance * cameraRange, maxZ = near + maxDistance * cameraRange;
+ const range = maxZ - minZ, ratio = maxZ / minZ;
+ for (let cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) {
+ const p = (cascadeIndex + 1) / this._numCascades, log = minZ * ratio ** p, uniform = minZ + range * p;
+ const d = this._lambda * (log - uniform) + uniform;
+ this._cascades[cascadeIndex].prevBreakDistance = cascadeIndex === 0 ? minDistance : this._cascades[cascadeIndex - 1].breakDistance;
+ this._cascades[cascadeIndex].breakDistance = (d - near) / cameraRange;
+ this._viewSpaceFrustumsZ[cascadeIndex] = d;
+ this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange;
+ }
+ this._breaksAreDirty = false;
+ }
+ _computeMatrices() {
+ const scene = this._scene;
+ const camera = this._getCamera();
+ if (!camera) {
+ return;
+ }
+ Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection);
+ if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
+ this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
+ }
+ this._cachedDirection.copyFrom(this._lightDirection);
+ const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer;
+ for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
+ this._computeFrustumInWorldSpace(cascadeIndex);
+ this._computeCascadeFrustum(cascadeIndex);
+ this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], tmpv1); // tmpv1 = cascadeExtents
+ // Get position of the shadow camera
+ this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]);
+ // Come up with a new orthographic camera for the shadow caster
+ Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]);
+ // Z extents of the current cascade, in cascade view coordinate system
+ let viewMinZ = 0, viewMaxZ = tmpv1.z;
+ // Try to tighten minZ and maxZ based on the bounding box of the shadow casters
+ const boundingInfo = this._shadowCastersBoundingInfo;
+ boundingInfo.update(this._viewMatrices[cascadeIndex]);
+ // Note that after the call to update, the boundingInfo properties that are identified as "world" coordinates are in fact view coordinates for the current cascade!
+ // This is because the boundingInfo properties that are identifed as "local" are in fact world coordinates (see _computeShadowCastersBoundingInfo()), and we multiply them by the current cascade view matrix when we call update.
+ const castersViewMinZ = boundingInfo.boundingBox.minimumWorld.z;
+ const castersViewMaxZ = boundingInfo.boundingBox.maximumWorld.z;
+ if (castersViewMinZ > viewMaxZ) ;
+ else {
+ if (!this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS) {
+ // If we don't use depth clamping, we must define minZ so that all shadow casters are in the cascade frustum
+ viewMinZ = Math.min(viewMinZ, castersViewMinZ);
+ if (this.filter !== ShadowGenerator.FILTER_PCSS) {
+ // We do not need the actual distance between the currently shaded pixel and the occluder when generating shadows, so we can lower the far plane to increase the accuracy of the shadow map.
+ viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ);
+ }
+ }
+ else {
+ // If we use depth clamping (but not PCSS!), we can adjust minZ/maxZ to reduce the range [minZ, maxZ] (and obtain additional precision in the shadow map)
+ viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ);
+ // Thanks to depth clamping, casters won't be Z clipped even if they fall outside the [-1,1] range, so we can move the near plane to 0 if castersViewMinZ < 0.
+ // We will generate negative Z values in the shadow map, but that's okay (they will be clamped to the 0..1 range anyway), except in PCSS case
+ // where we need the actual distance between the currently shader pixel and the occluder: that's why we don't use depth clamping in PCSS case.
+ viewMinZ = Math.max(viewMinZ, castersViewMinZ);
+ // If all the casters are behind the near plane of the cascade, minZ = 0 due to the previous line, and maxZ < 0 at this point.
+ // We need to make sure that maxZ > minZ, so in this case we set maxZ a little higher than minZ. As we are using depth clamping, the casters won't be Z clipped, so we just need to make sure that we have a valid Z range for the cascade.
+ // Having a 0 range is not ok, due to undefined behavior in the calculation in this case.
+ viewMaxZ = Math.max(viewMinZ + 1.0, viewMaxZ);
+ }
+ }
+ Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[cascadeIndex].x, this._cascadeMaxExtents[cascadeIndex].x, this._cascadeMinExtents[cascadeIndex].y, this._cascadeMaxExtents[cascadeIndex].y, useReverseDepthBuffer ? viewMaxZ : viewMinZ, useReverseDepthBuffer ? viewMinZ : viewMaxZ, this._projectionMatrices[cascadeIndex], scene.getEngine().isNDCHalfZRange);
+ this._cascadeMinExtents[cascadeIndex].z = viewMinZ;
+ this._cascadeMaxExtents[cascadeIndex].z = viewMaxZ;
+ this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);
+ // Create the rounding matrix, by projecting the world-space origin and determining
+ // the fractional offset in texel space
+ Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], tmpv1); // tmpv1 = shadowOrigin
+ tmpv1.scaleInPlace(this._mapSize / 2);
+ tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z)); // tmpv2 = roundedOrigin
+ tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize); // tmpv2 = roundOffset
+ Matrix.TranslationToRef(tmpv2.x, tmpv2.y, 0.0, tmpMatrix);
+ this._projectionMatrices[cascadeIndex].multiplyToRef(tmpMatrix, this._projectionMatrices[cascadeIndex]);
+ this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);
+ this._transformMatrices[cascadeIndex].copyToArray(this._transformMatricesAsArray, cascadeIndex * 16);
+ }
+ }
+ // Get the 8 points of the view frustum in world space
+ _computeFrustumInWorldSpace(cascadeIndex) {
+ const camera = this._getCamera();
+ if (!camera) {
+ return;
+ }
+ const prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance, splitDist = this._cascades[cascadeIndex].breakDistance;
+ const isNDCHalfZRange = this._scene.getEngine().isNDCHalfZRange;
+ camera.getViewMatrix(); // make sure the transformation matrix we get when calling 'getTransformationMatrix()' is calculated with an up to date view matrix
+ const cameraInfiniteFarPlane = camera.maxZ === 0;
+ const saveCameraMaxZ = camera.maxZ;
+ if (cameraInfiniteFarPlane) {
+ camera.maxZ = this._shadowMaxZ;
+ camera.getProjectionMatrix(true);
+ }
+ const invViewProj = Matrix.Invert(camera.getTransformationMatrix());
+ if (cameraInfiniteFarPlane) {
+ camera.maxZ = saveCameraMaxZ;
+ camera.getProjectionMatrix(true);
+ }
+ const cornerIndexOffset = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0;
+ for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++cornerIndex) {
+ tmpv1.copyFrom(CascadedShadowGenerator._FrustumCornersNDCSpace[(cornerIndex + cornerIndexOffset) % CascadedShadowGenerator._FrustumCornersNDCSpace.length]);
+ if (isNDCHalfZRange && tmpv1.z === -1) {
+ tmpv1.z = 0;
+ }
+ Vector3.TransformCoordinatesToRef(tmpv1, invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
+ }
+ // Get the corners of the current cascade slice of the view frustum
+ for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length / 2; ++cornerIndex) {
+ tmpv1.copyFrom(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4]).subtractInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
+ tmpv2.copyFrom(tmpv1).scaleInPlace(prevSplitDist); // near corner ray
+ tmpv1.scaleInPlace(splitDist); // far corner ray
+ tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
+ this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(tmpv1);
+ this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(tmpv2);
+ }
+ }
+ _computeCascadeFrustum(cascadeIndex) {
+ this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+ this._cascadeMaxExtents[cascadeIndex].copyFromFloats(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+ this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0);
+ const camera = this._getCamera();
+ if (!camera) {
+ return;
+ }
+ // Calculate the centroid of the view frustum slice
+ for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
+ this._frustumCenter[cascadeIndex].addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
+ }
+ this._frustumCenter[cascadeIndex].scaleInPlace(1 / this._frustumCornersWorldSpace[cascadeIndex].length);
+ if (this.stabilizeCascades) {
+ // Calculate the radius of a bounding sphere surrounding the frustum corners
+ let sphereRadius = 0;
+ for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
+ const dist = this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].subtractToRef(this._frustumCenter[cascadeIndex], tmpv1).length();
+ sphereRadius = Math.max(sphereRadius, dist);
+ }
+ sphereRadius = Math.ceil(sphereRadius * 16) / 16;
+ this._cascadeMaxExtents[cascadeIndex].copyFromFloats(sphereRadius, sphereRadius, sphereRadius);
+ this._cascadeMinExtents[cascadeIndex].copyFromFloats(-sphereRadius, -sphereRadius, -sphereRadius);
+ }
+ else {
+ // Create a temporary view matrix for the light
+ const lightCameraPos = this._frustumCenter[cascadeIndex];
+ this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, tmpv1); // tmpv1 = look at
+ Matrix.LookAtLHToRef(lightCameraPos, tmpv1, UpDir, tmpMatrix); // matrix = lightView
+ // Calculate an AABB around the frustum corners
+ for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
+ Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], tmpMatrix, tmpv1);
+ this._cascadeMinExtents[cascadeIndex].minimizeInPlace(tmpv1);
+ this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(tmpv1);
+ }
+ }
+ }
+ _recreateSceneUBOs() {
+ this._disposeSceneUBOs();
+ if (this._sceneUBOs) {
+ for (let i = 0; i < this._numCascades; ++i) {
+ this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${i})`));
+ }
+ }
+ }
+ /**
+ * Support test.
+ */
+ static get IsSupported() {
+ const engine = EngineStore.LastCreatedEngine;
+ if (!engine) {
+ return false;
+ }
+ return engine._features.supportCSM;
+ }
+ /**
+ * Creates a Cascaded Shadow Generator object.
+ * A ShadowGenerator is the required tool to use the shadows.
+ * Each directional light casting shadows needs to use its own ShadowGenerator.
+ * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows
+ * @param mapSize The size of the texture what stores the shadows. Example : 1024.
+ * @param light The directional light object generating the shadows.
+ * @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
+ * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it
+ * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: true)
+ */
+ constructor(mapSize, light, usefulFloatFirst, camera, useRedTextureType = true) {
+ if (!CascadedShadowGenerator.IsSupported) {
+ Logger.Error("CascadedShadowMap is not supported by the current engine.");
+ return;
+ }
+ super(mapSize, light, usefulFloatFirst, camera, useRedTextureType);
+ this.usePercentageCloserFiltering = true;
+ }
+ _initializeGenerator() {
+ this.penumbraDarkness = this.penumbraDarkness ?? 1.0;
+ this._numCascades = this._numCascades ?? CascadedShadowGenerator.DEFAULT_CASCADES_COUNT;
+ this.stabilizeCascades = this.stabilizeCascades ?? false;
+ this._freezeShadowCastersBoundingInfoObservable = this._freezeShadowCastersBoundingInfoObservable ?? null;
+ this.freezeShadowCastersBoundingInfo = this.freezeShadowCastersBoundingInfo ?? false;
+ this._scbiMin = this._scbiMin ?? new Vector3(0, 0, 0);
+ this._scbiMax = this._scbiMax ?? new Vector3(0, 0, 0);
+ this._shadowCastersBoundingInfo = this._shadowCastersBoundingInfo ?? new BoundingInfo(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
+ this._breaksAreDirty = this._breaksAreDirty ?? true;
+ this._minDistance = this._minDistance ?? 0;
+ this._maxDistance = this._maxDistance ?? 1;
+ this._currentLayer = this._currentLayer ?? 0;
+ this._shadowMaxZ = this._shadowMaxZ ?? this._getCamera()?.maxZ ?? 10000;
+ this._debug = this._debug ?? false;
+ this._depthClamp = this._depthClamp ?? true;
+ this._cascadeBlendPercentage = this._cascadeBlendPercentage ?? 0.1;
+ this._lambda = this._lambda ?? 0.5;
+ this._autoCalcDepthBounds = this._autoCalcDepthBounds ?? false;
+ this._recreateSceneUBOs();
+ super._initializeGenerator();
+ }
+ _createTargetRenderTexture() {
+ const engine = this._scene.getEngine();
+ const size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades };
+ this._shadowMap = new RenderTargetTexture(this._light.name + "_CSMShadowMap", size, this._scene, false, true, this._textureType, false, undefined, false, false, undefined, this._useRedTextureType ? 6 : 5);
+ this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true, undefined, undefined, undefined, `DepthStencilForCSMShadowGenerator-${this._light.name}`);
+ this._shadowMap.noPrePassRenderer = true;
+ }
+ _initializeShadowMap() {
+ super._initializeShadowMap();
+ if (this._shadowMap === null) {
+ return;
+ }
+ this._transformMatricesAsArray = new Float32Array(this._numCascades * 16);
+ this._viewSpaceFrustumsZ = new Array(this._numCascades);
+ this._frustumLengths = new Array(this._numCascades);
+ this._lightSizeUVCorrection = new Array(this._numCascades * 2);
+ this._depthCorrection = new Array(this._numCascades);
+ this._cascades = [];
+ this._viewMatrices = [];
+ this._projectionMatrices = [];
+ this._transformMatrices = [];
+ this._cascadeMinExtents = [];
+ this._cascadeMaxExtents = [];
+ this._frustumCenter = [];
+ this._shadowCameraPos = [];
+ this._frustumCornersWorldSpace = [];
+ for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
+ this._cascades[cascadeIndex] = {
+ prevBreakDistance: 0,
+ breakDistance: 0,
+ };
+ this._viewMatrices[cascadeIndex] = Matrix.Zero();
+ this._projectionMatrices[cascadeIndex] = Matrix.Zero();
+ this._transformMatrices[cascadeIndex] = Matrix.Zero();
+ this._cascadeMinExtents[cascadeIndex] = new Vector3();
+ this._cascadeMaxExtents[cascadeIndex] = new Vector3();
+ this._frustumCenter[cascadeIndex] = new Vector3();
+ this._shadowCameraPos[cascadeIndex] = new Vector3();
+ this._frustumCornersWorldSpace[cascadeIndex] = new Array(CascadedShadowGenerator._FrustumCornersNDCSpace.length);
+ for (let i = 0; i < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++i) {
+ this._frustumCornersWorldSpace[cascadeIndex][i] = new Vector3();
+ }
+ }
+ const engine = this._scene.getEngine();
+ this._shadowMap.onBeforeBindObservable.clear();
+ this._shadowMap.onBeforeRenderObservable.clear();
+ this._shadowMap.onBeforeRenderObservable.add((layer) => {
+ if (this._sceneUBOs) {
+ this._scene.setSceneUniformBuffer(this._sceneUBOs[layer]);
+ }
+ this._currentLayer = layer;
+ if (this._filter === ShadowGenerator.FILTER_PCF) {
+ engine.setColorWrite(false);
+ }
+ this._scene.setTransformMatrix(this.getCascadeViewMatrix(layer), this.getCascadeProjectionMatrix(layer));
+ if (this._useUBO) {
+ this._scene.getSceneUniformBuffer().unbindEffect();
+ this._scene.finalizeSceneUbo();
+ }
+ });
+ this._shadowMap.onBeforeBindObservable.add(() => {
+ this._currentSceneUBO = this._scene.getSceneUniformBuffer();
+ engine._debugPushGroup?.(`cascaded shadow map generation for pass id ${engine.currentRenderPassId}`, 1);
+ if (this._breaksAreDirty) {
+ this._splitFrustum();
+ }
+ this._computeMatrices();
+ });
+ this._splitFrustum();
+ }
+ _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect) {
+ effect.setMatrix("viewProjection", this.getCascadeTransformMatrix(this._currentLayer));
+ }
+ _isReadyCustomDefines(defines) {
+ defines.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? "1" : "0"));
+ }
+ /**
+ * Prepare all the defines in a material relying on a shadow map at the specified light index.
+ * @param defines Defines of the material we want to update
+ * @param lightIndex Index of the light in the enabled light list of the material
+ */
+ prepareDefines(defines, lightIndex) {
+ super.prepareDefines(defines, lightIndex);
+ const scene = this._scene;
+ const light = this._light;
+ if (!scene.shadowsEnabled || !light.shadowEnabled) {
+ return;
+ }
+ defines["SHADOWCSM" + lightIndex] = true;
+ defines["SHADOWCSMDEBUG" + lightIndex] = this.debug;
+ defines["SHADOWCSMNUM_CASCADES" + lightIndex] = this.numCascades;
+ defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = scene.useRightHandedSystem;
+ const camera = this._getCamera();
+ if (camera && this._shadowMaxZ <= (camera.maxZ || this._shadowMaxZ)) {
+ defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = true;
+ }
+ if (this.cascadeBlendPercentage === 0) {
+ defines["SHADOWCSMNOBLEND" + lightIndex] = true;
+ }
+ }
+ /**
+ * Binds the shadow related information inside of an effect (information like near, far, darkness...
+ * defined in the generator but impacting the effect).
+ * @param lightIndex Index of the light in the enabled light list of the material owning the effect
+ * @param effect The effect we are binfing the information for
+ */
+ bindShadowLight(lightIndex, effect) {
+ const light = this._light;
+ const scene = this._scene;
+ if (!scene.shadowsEnabled || !light.shadowEnabled) {
+ return;
+ }
+ const camera = this._getCamera();
+ if (!camera) {
+ return;
+ }
+ const shadowMap = this.getShadowMap();
+ if (!shadowMap) {
+ return;
+ }
+ const width = shadowMap.getSize().width;
+ effect.setMatrices("lightMatrix" + lightIndex, this._transformMatricesAsArray);
+ effect.setArray("viewFrustumZ" + lightIndex, this._viewSpaceFrustumsZ);
+ effect.setFloat("cascadeBlendFactor" + lightIndex, this.cascadeBlendPercentage === 0 ? 10000 : 1 / this.cascadeBlendPercentage);
+ effect.setArray("frustumLengths" + lightIndex, this._frustumLengths);
+ // Only PCF uses depth stencil texture.
+ if (this._filter === ShadowGenerator.FILTER_PCF) {
+ effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMap);
+ light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);
+ }
+ else if (this._filter === ShadowGenerator.FILTER_PCSS) {
+ for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
+ this._lightSizeUVCorrection[cascadeIndex * 2 + 0] =
+ cascadeIndex === 0
+ ? 1
+ : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[cascadeIndex].x - this._cascadeMinExtents[cascadeIndex].x); // x correction
+ this._lightSizeUVCorrection[cascadeIndex * 2 + 1] =
+ cascadeIndex === 0
+ ? 1
+ : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y); // y correction
+ this._depthCorrection[cascadeIndex] =
+ cascadeIndex === 0
+ ? 1
+ : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z);
+ }
+ effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMap);
+ effect.setTexture("depthTexture" + lightIndex, shadowMap);
+ effect.setArray2("lightSizeUVCorrection" + lightIndex, this._lightSizeUVCorrection);
+ effect.setArray("depthCorrection" + lightIndex, this._depthCorrection);
+ effect.setFloat("penumbraDarkness" + lightIndex, this.penumbraDarkness);
+ light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / width, this._contactHardeningLightSizeUVRatio * width, this.frustumEdgeFalloff, lightIndex);
+ }
+ else {
+ effect.setTexture("shadowTexture" + lightIndex, shadowMap);
+ light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);
+ }
+ light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
+ }
+ /**
+ * Gets the transformation matrix of the first cascade used to project the meshes into the map from the light point of view.
+ * (eq to view projection * shadow projection matrices)
+ * @returns The transform matrix used to create the shadow map
+ */
+ getTransformMatrix() {
+ return this.getCascadeTransformMatrix(0);
+ }
+ /**
+ * Disposes the ShadowGenerator.
+ * Returns nothing.
+ */
+ dispose() {
+ super.dispose();
+ if (this._freezeShadowCastersBoundingInfoObservable) {
+ this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);
+ this._freezeShadowCastersBoundingInfoObservable = null;
+ }
+ if (this._depthReducer) {
+ this._depthReducer.dispose();
+ this._depthReducer = null;
+ }
+ }
+ /**
+ * Serializes the shadow generator setup to a json object.
+ * @returns The serialized JSON object
+ */
+ serialize() {
+ const serializationObject = super.serialize();
+ const shadowMap = this.getShadowMap();
+ if (!shadowMap) {
+ return serializationObject;
+ }
+ serializationObject.numCascades = this._numCascades;
+ serializationObject.debug = this._debug;
+ serializationObject.stabilizeCascades = this.stabilizeCascades;
+ serializationObject.lambda = this._lambda;
+ serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage;
+ serializationObject.depthClamp = this._depthClamp;
+ serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds;
+ serializationObject.shadowMaxZ = this._shadowMaxZ;
+ serializationObject.penumbraDarkness = this.penumbraDarkness;
+ serializationObject.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo;
+ serializationObject.minDistance = this.minDistance;
+ serializationObject.maxDistance = this.maxDistance;
+ serializationObject.renderList = [];
+ if (shadowMap.renderList) {
+ for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
+ const mesh = shadowMap.renderList[meshIndex];
+ serializationObject.renderList.push(mesh.id);
+ }
+ }
+ return serializationObject;
+ }
+ /**
+ * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
+ * @param parsedShadowGenerator The JSON object to parse
+ * @param scene The scene to create the shadow map for
+ * @returns The parsed shadow generator
+ */
+ static Parse(parsedShadowGenerator, scene) {
+ const shadowGenerator = ShadowGenerator.Parse(parsedShadowGenerator, scene, (mapSize, light, camera) => new CascadedShadowGenerator(mapSize, light, undefined, camera));
+ if (parsedShadowGenerator.numCascades !== undefined) {
+ shadowGenerator.numCascades = parsedShadowGenerator.numCascades;
+ }
+ if (parsedShadowGenerator.debug !== undefined) {
+ shadowGenerator.debug = parsedShadowGenerator.debug;
+ }
+ if (parsedShadowGenerator.stabilizeCascades !== undefined) {
+ shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades;
+ }
+ if (parsedShadowGenerator.lambda !== undefined) {
+ shadowGenerator.lambda = parsedShadowGenerator.lambda;
+ }
+ if (parsedShadowGenerator.cascadeBlendPercentage !== undefined) {
+ shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage;
+ }
+ if (parsedShadowGenerator.depthClamp !== undefined) {
+ shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp;
+ }
+ if (parsedShadowGenerator.autoCalcDepthBounds !== undefined) {
+ shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds;
+ }
+ if (parsedShadowGenerator.shadowMaxZ !== undefined) {
+ shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ;
+ }
+ if (parsedShadowGenerator.penumbraDarkness !== undefined) {
+ shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness;
+ }
+ if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== undefined) {
+ shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo;
+ }
+ if (parsedShadowGenerator.minDistance !== undefined && parsedShadowGenerator.maxDistance !== undefined) {
+ shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance);
+ }
+ return shadowGenerator;
+ }
+}
+CascadedShadowGenerator._FrustumCornersNDCSpace = [
+ new Vector3(-1, 1, -1),
+ new Vector3(1, 1, -1),
+ new Vector3(1, -1, -1),
+ new Vector3(-1, -1, -1),
+ new Vector3(-1, 1, 1),
+ new Vector3(1, 1, 1),
+ new Vector3(1, -1, 1),
+ new Vector3(-1, -1, 1),
+];
+/**
+ * Name of the CSM class
+ */
+CascadedShadowGenerator.CLASSNAME = "CascadedShadowGenerator";
+/**
+ * Defines the default number of cascades used by the CSM.
+ */
+CascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4;
+/**
+ * Defines the minimum number of cascades used by the CSM.
+ */
+CascadedShadowGenerator.MIN_CASCADES_COUNT = 2;
+/**
+ * Defines the maximum number of cascades used by the CSM.
+ */
+CascadedShadowGenerator.MAX_CASCADES_COUNT = 4;
+/**
+ * @internal
+ */
+CascadedShadowGenerator._SceneComponentInitialization = (_) => {
+ throw _WarnImport("ShadowGeneratorSceneComponent");
+};
+
+/**
+ * Stores the list of available parsers in the application.
+ */
+const _BabylonFileParsers = {};
+/**
+ * Stores the list of available individual parsers in the application.
+ */
+const _IndividualBabylonFileParsers = {};
+/**
+ * Adds a parser in the list of available ones
+ * @param name Defines the name of the parser
+ * @param parser Defines the parser to add
+ */
+function AddParser(name, parser) {
+ _BabylonFileParsers[name] = parser;
+}
+/**
+ * Adds n individual parser in the list of available ones
+ * @param name Defines the name of the parser
+ * @param parser Defines the parser to add
+ */
+function AddIndividualParser(name, parser) {
+ _IndividualBabylonFileParsers[name] = parser;
+}
+/**
+ * Gets an individual parser from the list of available ones
+ * @param name Defines the name of the parser
+ * @returns the requested parser or null
+ */
+function GetIndividualParser(name) {
+ if (_IndividualBabylonFileParsers[name]) {
+ return _IndividualBabylonFileParsers[name];
+ }
+ return null;
+}
+/**
+ * Parser json data and populate both a scene and its associated container object
+ * @param jsonData Defines the data to parse
+ * @param scene Defines the scene to parse the data for
+ * @param container Defines the container attached to the parsing sequence
+ * @param rootUrl Defines the root url of the data
+ */
+function Parse(jsonData, scene, container, rootUrl) {
+ for (const parserName in _BabylonFileParsers) {
+ if (Object.prototype.hasOwnProperty.call(_BabylonFileParsers, parserName)) {
+ _BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
+ }
+ }
+}
+
+// Adds the parser to the scene parsers.
+AddParser(SceneComponentConstants.NAME_SHADOWGENERATOR, (parsedData, scene) => {
+ // Shadows
+ if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
+ for (let index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
+ const parsedShadowGenerator = parsedData.shadowGenerators[index];
+ if (parsedShadowGenerator.className === CascadedShadowGenerator.CLASSNAME) {
+ CascadedShadowGenerator.Parse(parsedShadowGenerator, scene);
+ }
+ else {
+ ShadowGenerator.Parse(parsedShadowGenerator, scene);
+ }
+ // SG would be available on their associated lights
+ }
+ }
+});
+/**
+ * Defines the shadow generator component responsible to manage any shadow generators
+ * in a given scene.
+ */
+class ShadowGeneratorSceneComponent {
+ /**
+ * Creates a new instance of the component for the given scene
+ * @param scene Defines the scene to register the component in
+ */
+ constructor(scene) {
+ /**
+ * The component name helpful to identify the component in the list of scene components.
+ */
+ this.name = SceneComponentConstants.NAME_SHADOWGENERATOR;
+ this.scene = scene;
+ }
+ /**
+ * Registers the component in a given scene
+ */
+ register() {
+ this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
+ }
+ /**
+ * Rebuilds the elements related to this component in case of
+ * context lost for instance.
+ */
+ rebuild() {
+ // Nothing To Do Here.
+ }
+ /**
+ * Serializes the component data to the specified json object
+ * @param serializationObject The object to serialize to
+ */
+ serialize(serializationObject) {
+ // Shadows
+ serializationObject.shadowGenerators = [];
+ const lights = this.scene.lights;
+ for (const light of lights) {
+ if (light.doNotSerialize) {
+ continue;
+ }
+ const shadowGenerators = light.getShadowGenerators();
+ if (shadowGenerators) {
+ const iterator = shadowGenerators.values();
+ for (let key = iterator.next(); key.done !== true; key = iterator.next()) {
+ const shadowGenerator = key.value;
+ if (shadowGenerator.doNotSerialize) {
+ continue;
+ }
+ serializationObject.shadowGenerators.push(shadowGenerator.serialize());
+ }
+ }
+ }
+ }
+ /**
+ * Adds all the elements from the container to the scene
+ * @param container the container holding the elements
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ addFromContainer(container) {
+ // Nothing To Do Here. (directly attached to a light)
+ }
+ /**
+ * Removes all the elements in the container from the scene
+ * @param container contains the elements to remove
+ * @param dispose if the removed element should be disposed (default: false)
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ removeFromContainer(container, dispose) {
+ // Nothing To Do Here. (directly attached to a light)
+ }
+ /**
+ * Rebuilds the elements related to this component in case of
+ * context lost for instance.
+ */
+ dispose() {
+ // Nothing To Do Here.
+ }
+ _gatherRenderTargets(renderTargets) {
+ // Shadows
+ const scene = this.scene;
+ if (this.scene.shadowsEnabled) {
+ for (let lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
+ const light = scene.lights[lightIndex];
+ const shadowGenerators = light.getShadowGenerators();
+ if (light.isEnabled() && light.shadowEnabled && shadowGenerators) {
+ const iterator = shadowGenerators.values();
+ for (let key = iterator.next(); key.done !== true; key = iterator.next()) {
+ const shadowGenerator = key.value;
+ const shadowMap = shadowGenerator.getShadowMap();
+ if (scene.textures.indexOf(shadowMap) !== -1) {
+ renderTargets.push(shadowMap);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+ShadowGenerator._SceneComponentInitialization = (scene) => {
+ let component = scene._getComponent(SceneComponentConstants.NAME_SHADOWGENERATOR);
+ if (!component) {
+ component = new ShadowGeneratorSceneComponent(scene);
+ scene._addComponent(component);
+ }
+};
+
+class AppLight extends Monobehiver {
+ lightList;
+ shadowGenerator;
+ debugMarkers;
+ coneMesh;
+ updateCone;
+ constructor(mainApp) {
+ super(mainApp);
+ this.lightList = [];
+ this.shadowGenerator = null;
+ }
+ /** 初始化灯光并开启阴影 */
+ Awake() {
+ new DirectionalLight(
+ "mainLight",
+ new Vector3(0, -0.5, -1)
+ );
+ }
+}
+
+/**
+ * Gets the file extension from a URL.
+ * @param url The URL to get the file extension from.
+ * @returns The file extension, or an empty string if no extension is found.
+ */
+function GetExtensionFromUrl(url) {
+ const urlWithoutUriParams = url.split("?")[0];
+ const lastDot = urlWithoutUriParams.lastIndexOf(".");
+ const extension = lastDot > -1 ? urlWithoutUriParams.substring(lastDot).toLowerCase() : "";
+ return extension;
+}
+
+AbstractEngine.prototype._partialLoadFile = function (url, index, loadedFiles, onfinish, onErrorCallBack = null) {
+ const onload = (data) => {
+ loadedFiles[index] = data;
+ loadedFiles._internalCount++;
+ if (loadedFiles._internalCount === 6) {
+ onfinish(loadedFiles);
+ }
+ };
+ const onerror = (request, exception) => {
+ if (onErrorCallBack && request) {
+ onErrorCallBack(request.status + " " + request.statusText, exception);
+ }
+ };
+ this._loadFile(url, onload, undefined, undefined, true, onerror);
+};
+AbstractEngine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError = null) {
+ const loadedFiles = [];
+ loadedFiles._internalCount = 0;
+ for (let index = 0; index < 6; index++) {
+ this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError);
+ }
+};
+AbstractEngine.prototype._cascadeLoadImgs = function (scene, texture, onfinish, files, onError = null, mimeType) {
+ const loadedImages = [];
+ loadedImages._internalCount = 0;
+ for (let index = 0; index < 6; index++) {
+ this._partialLoadImg(files[index], index, loadedImages, scene, texture, onfinish, onError, mimeType);
+ }
+};
+AbstractEngine.prototype._partialLoadImg = function (url, index, loadedImages, scene, texture, onfinish, onErrorCallBack = null, mimeType) {
+ const tokenPendingData = RandomGUID();
+ const onload = (img) => {
+ loadedImages[index] = img;
+ loadedImages._internalCount++;
+ if (scene) {
+ scene.removePendingData(tokenPendingData);
+ }
+ if (loadedImages._internalCount === 6 && onfinish) {
+ onfinish(texture, loadedImages);
+ }
+ };
+ const onerror = (message, exception) => {
+ if (scene) {
+ scene.removePendingData(tokenPendingData);
+ }
+ if (onErrorCallBack) {
+ onErrorCallBack(message, exception);
+ }
+ };
+ LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null, mimeType);
+ if (scene) {
+ scene.addPendingData(tokenPendingData);
+ }
+};
+AbstractEngine.prototype.createCubeTextureBase = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, beforeLoadCubeDataCallback = null, imageHandler = null, useSRGBBuffer = false, buffer = null) {
+ const texture = fallback ? fallback : new InternalTexture(this, 7 /* InternalTextureSource.Cube */);
+ texture.isCube = true;
+ texture.url = rootUrl;
+ texture.generateMipMaps = !noMipmap;
+ texture._lodGenerationScale = lodScale;
+ texture._lodGenerationOffset = lodOffset;
+ texture._useSRGBBuffer = !!useSRGBBuffer && this._caps.supportSRGBBuffers && (this.version > 1 || this.isWebGPU || !!noMipmap);
+ if (texture !== fallback) {
+ texture.label = rootUrl.substring(0, 60); // default label, can be overriden by the caller
+ }
+ if (!this._doNotHandleContextLost) {
+ texture._extension = forcedExtension;
+ texture._files = files;
+ texture._buffer = buffer;
+ }
+ const originalRootUrl = rootUrl;
+ if (this._transformTextureUrl && !fallback) {
+ rootUrl = this._transformTextureUrl(rootUrl);
+ }
+ const extension = forcedExtension ?? GetExtensionFromUrl(rootUrl);
+ const loaderPromise = _GetCompatibleTextureLoader(extension);
+ const onInternalError = (request, exception) => {
+ if (rootUrl === originalRootUrl) {
+ if (onError && request) {
+ onError(request.status + " " + request.statusText, exception);
+ }
+ }
+ else {
+ // fall back to the original url if the transformed url fails to load
+ Logger.Warn(`Failed to load ${rootUrl}, falling back to the ${originalRootUrl}`);
+ this.createCubeTextureBase(originalRootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, texture, beforeLoadCubeDataCallback, imageHandler, useSRGBBuffer, buffer);
+ }
+ };
+ if (loaderPromise) {
+ loaderPromise.then((loader) => {
+ const onloaddata = (data) => {
+ if (beforeLoadCubeDataCallback) {
+ beforeLoadCubeDataCallback(texture, data);
+ }
+ loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
+ };
+ if (buffer) {
+ onloaddata(buffer);
+ }
+ else if (files && files.length === 6) {
+ if (loader.supportCascades) {
+ this._cascadeLoadFiles(scene, (images) => onloaddata(images.map((image) => new Uint8Array(image))), files, onError);
+ }
+ else {
+ if (onError) {
+ onError("Textures type does not support cascades.");
+ }
+ else {
+ Logger.Warn("Texture loader does not support cascades.");
+ }
+ }
+ }
+ else {
+ this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data)), undefined, undefined, true, onInternalError);
+ }
+ });
+ }
+ else {
+ if (!files || files.length === 0) {
+ throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");
+ }
+ this._cascadeLoadImgs(scene, texture, (texture, imgs) => {
+ if (imageHandler) {
+ imageHandler(texture, imgs);
+ }
+ }, files, onError);
+ }
+ this._internalTexturesCache.push(texture);
+ return texture;
+};
+
+// The default scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
+const defaultLodScale = 0.8;
+/**
+ * Class for creating a cube texture
+ */
+class CubeTexture extends BaseTexture {
+ /**
+ * Gets or sets the size of the bounding box associated with the cube texture
+ * When defined, the cubemap will switch to local mode
+ * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
+ * @example https://www.babylonjs-playground.com/#RNASML
+ */
+ set boundingBoxSize(value) {
+ if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
+ return;
+ }
+ this._boundingBoxSize = value;
+ const scene = this.getScene();
+ if (scene) {
+ scene.markAllMaterialsAsDirty(1);
+ }
+ }
+ /**
+ * Returns the bounding box size
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode
+ */
+ get boundingBoxSize() {
+ return this._boundingBoxSize;
+ }
+ /**
+ * Sets texture matrix rotation angle around Y axis in radians.
+ */
+ set rotationY(value) {
+ this._rotationY = value;
+ this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY));
+ }
+ /**
+ * Gets texture matrix rotation angle around Y axis radians.
+ */
+ get rotationY() {
+ return this._rotationY;
+ }
+ /**
+ * Are mip maps generated for this texture or not.
+ */
+ get noMipmap() {
+ return this._noMipmap;
+ }
+ /**
+ * Gets the forced extension (if any)
+ */
+ get forcedExtension() {
+ return this._forcedExtension;
+ }
+ /**
+ * Creates a cube texture from an array of image urls
+ * @param files defines an array of image urls
+ * @param scene defines the hosting scene
+ * @param noMipmap specifies if mip maps are not used
+ * @returns a cube texture
+ */
+ static CreateFromImages(files, scene, noMipmap) {
+ let rootUrlKey = "";
+ files.forEach((url) => (rootUrlKey += url));
+ return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
+ }
+ /**
+ * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
+ * @param url defines the url of the prefiltered texture
+ * @param scene defines the scene the texture is attached to
+ * @param forcedExtension defines the extension of the file if different from the url
+ * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
+ * @returns the prefiltered texture
+ */
+ static CreateFromPrefilteredData(url, scene, forcedExtension = null, createPolynomials = true) {
+ const oldValue = scene.useDelayedTextureLoading;
+ scene.useDelayedTextureLoading = false;
+ const result = new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
+ scene.useDelayedTextureLoading = oldValue;
+ return result;
+ }
+ /**
+ * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
+ * as prefiltered data.
+ * @param rootUrl defines the url of the texture or the root name of the six images
+ * @param sceneOrEngine defines the scene or engine the texture is attached to
+ * @param extensionsOrOptions defines the suffixes add to the picture name in case six images are in use like _px.jpg or set of all options to create the cube texture
+ * @param noMipmap defines if mipmaps should be created or not
+ * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz
+ * @param onLoad defines a callback triggered at the end of the file load if no errors occurred
+ * @param onError defines a callback triggered in case of error during load
+ * @param format defines the internal format to use for the texture once loaded
+ * @param prefiltered defines whether or not the texture is created from prefiltered data
+ * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
+ * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
+ * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
+ * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
+ * @param loaderOptions options to be passed to the loader
+ * @param useSRGBBuffer Defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU) (default: false)
+ * @returns the cube texture
+ */
+ constructor(rootUrl, sceneOrEngine, extensionsOrOptions = null, noMipmap = false, files = null, onLoad = null, onError = null, format = 5, prefiltered = false, forcedExtension = null, createPolynomials = false, lodScale = defaultLodScale, lodOffset = 0, loaderOptions, useSRGBBuffer) {
+ super(sceneOrEngine);
+ /**
+ * Observable triggered once the texture has been loaded.
+ */
+ this.onLoadObservable = new Observable();
+ /**
+ * Gets or sets the center of the bounding box associated with the cube texture.
+ * It must define where the camera used to render the texture was set
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode
+ */
+ this.boundingBoxPosition = Vector3.Zero();
+ this._rotationY = 0;
+ /** @internal */
+ this._files = null;
+ this._forcedExtension = null;
+ this._extensions = null;
+ this._textureMatrixRefraction = new Matrix();
+ this._buffer = null;
+ this.name = rootUrl;
+ this.url = rootUrl;
+ this._noMipmap = noMipmap;
+ this.hasAlpha = false;
+ this.isCube = true;
+ this._textureMatrix = Matrix.Identity();
+ this.coordinatesMode = Texture.CUBIC_MODE;
+ let extensions = null;
+ let buffer = null;
+ if (extensionsOrOptions !== null && !Array.isArray(extensionsOrOptions)) {
+ extensions = extensionsOrOptions.extensions ?? null;
+ this._noMipmap = extensionsOrOptions.noMipmap ?? false;
+ files = extensionsOrOptions.files ?? null;
+ buffer = extensionsOrOptions.buffer ?? null;
+ this._format = extensionsOrOptions.format ?? 5;
+ prefiltered = extensionsOrOptions.prefiltered ?? false;
+ forcedExtension = extensionsOrOptions.forcedExtension ?? null;
+ this._createPolynomials = extensionsOrOptions.createPolynomials ?? false;
+ this._lodScale = extensionsOrOptions.lodScale ?? defaultLodScale;
+ this._lodOffset = extensionsOrOptions.lodOffset ?? 0;
+ this._loaderOptions = extensionsOrOptions.loaderOptions;
+ this._useSRGBBuffer = extensionsOrOptions.useSRGBBuffer;
+ onLoad = extensionsOrOptions.onLoad ?? null;
+ onError = extensionsOrOptions.onError ?? null;
+ }
+ else {
+ this._noMipmap = noMipmap;
+ this._format = format;
+ this._createPolynomials = createPolynomials;
+ extensions = extensionsOrOptions;
+ this._loaderOptions = loaderOptions;
+ this._useSRGBBuffer = useSRGBBuffer;
+ this._lodScale = lodScale;
+ this._lodOffset = lodOffset;
+ }
+ if (!rootUrl && !files) {
+ return;
+ }
+ this.updateURL(rootUrl, forcedExtension, onLoad, prefiltered, onError, extensions, this.getScene()?.useDelayedTextureLoading, files, buffer);
+ }
+ /**
+ * Get the current class name of the texture useful for serialization or dynamic coding.
+ * @returns "CubeTexture"
+ */
+ getClassName() {
+ return "CubeTexture";
+ }
+ /**
+ * Update the url (and optional buffer) of this texture if url was null during construction.
+ * @param url the url of the texture
+ * @param forcedExtension defines the extension to use
+ * @param onLoad callback called when the texture is loaded (defaults to null)
+ * @param prefiltered Defines whether the updated texture is prefiltered or not
+ * @param onError callback called if there was an error during the loading process (defaults to null)
+ * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
+ * @param delayLoad defines if the texture should be loaded now (false by default)
+ * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz
+ * @param buffer the buffer to use instead of loading from the url
+ */
+ updateURL(url, forcedExtension = null, onLoad = null, prefiltered = false, onError = null, extensions = null, delayLoad = false, files = null, buffer = null) {
+ if (!this.name || this.name.startsWith("data:")) {
+ this.name = url;
+ }
+ this.url = url;
+ if (forcedExtension) {
+ this._forcedExtension = forcedExtension;
+ }
+ const lastDot = url.lastIndexOf(".");
+ const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : "";
+ const isDDS = extension.indexOf(".dds") === 0;
+ const isEnv = extension.indexOf(".env") === 0;
+ const isBasis = extension.indexOf(".basis") === 0;
+ if (isEnv) {
+ this.gammaSpace = false;
+ this._prefiltered = false;
+ this.anisotropicFilteringLevel = 1;
+ }
+ else {
+ this._prefiltered = prefiltered;
+ if (prefiltered) {
+ this.gammaSpace = false;
+ this.anisotropicFilteringLevel = 1;
+ }
+ }
+ if (files) {
+ this._files = files;
+ }
+ else {
+ if (!isBasis && !isEnv && !isDDS && !extensions) {
+ extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
+ }
+ this._files = this._files || [];
+ this._files.length = 0;
+ if (extensions) {
+ for (let index = 0; index < extensions.length; index++) {
+ this._files.push(url + extensions[index]);
+ }
+ this._extensions = extensions;
+ }
+ }
+ this._buffer = buffer;
+ if (delayLoad) {
+ this.delayLoadState = 4;
+ this._delayedOnLoad = onLoad;
+ this._delayedOnError = onError;
+ }
+ else {
+ this._loadTexture(onLoad, onError);
+ }
+ }
+ /**
+ * Delays loading of the cube texture
+ * @param forcedExtension defines the extension to use
+ */
+ delayLoad(forcedExtension) {
+ if (this.delayLoadState !== 4) {
+ return;
+ }
+ if (forcedExtension) {
+ this._forcedExtension = forcedExtension;
+ }
+ this.delayLoadState = 1;
+ this._loadTexture(this._delayedOnLoad, this._delayedOnError);
+ }
+ /**
+ * Returns the reflection texture matrix
+ * @returns the reflection texture matrix
+ */
+ getReflectionTextureMatrix() {
+ return this._textureMatrix;
+ }
+ /**
+ * Sets the reflection texture matrix
+ * @param value Reflection texture matrix
+ */
+ setReflectionTextureMatrix(value) {
+ if (value.updateFlag === this._textureMatrix.updateFlag) {
+ return;
+ }
+ if (value.isIdentity() !== this._textureMatrix.isIdentity()) {
+ this.getScene()?.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1);
+ }
+ this._textureMatrix = value;
+ if (!this.getScene()?.useRightHandedSystem) {
+ return;
+ }
+ const scale = TmpVectors.Vector3[0];
+ const quat = TmpVectors.Quaternion[0];
+ const trans = TmpVectors.Vector3[1];
+ this._textureMatrix.decompose(scale, quat, trans);
+ quat.z *= -1; // these two operations correspond to negating the x and y euler angles
+ quat.w *= -1;
+ Matrix.ComposeToRef(scale, quat, trans, this._textureMatrixRefraction);
+ }
+ /**
+ * Gets a suitable rotate/transform matrix when the texture is used for refraction.
+ * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode.
+ * @returns The refraction matrix
+ */
+ getRefractionTextureMatrix() {
+ return this.getScene()?.useRightHandedSystem ? this._textureMatrixRefraction : this._textureMatrix;
+ }
+ _loadTexture(onLoad = null, onError = null) {
+ const scene = this.getScene();
+ const oldTexture = this._texture;
+ this._texture = this._getFromCache(this.url, this._noMipmap, undefined, undefined, this._useSRGBBuffer, this.isCube);
+ const onLoadProcessing = () => {
+ this.onLoadObservable.notifyObservers(this);
+ if (oldTexture) {
+ oldTexture.dispose();
+ this.getScene()?.markAllMaterialsAsDirty(1);
+ }
+ if (onLoad) {
+ onLoad();
+ }
+ };
+ const errorHandler = (message, exception) => {
+ this._loadingError = true;
+ this._errorObject = { message, exception };
+ if (onError) {
+ onError(message, exception);
+ }
+ Texture.OnTextureLoadErrorObservable.notifyObservers(this);
+ };
+ if (!this._texture) {
+ if (this._prefiltered) {
+ this._texture = this._getEngine().createPrefilteredCubeTexture(this.url, scene, this._lodScale, this._lodOffset, onLoad, errorHandler, this._format, this._forcedExtension, this._createPolynomials);
+ }
+ else {
+ this._texture = this._getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, onLoad, errorHandler, this._format, this._forcedExtension, false, this._lodScale, this._lodOffset, null, this._loaderOptions, !!this._useSRGBBuffer, this._buffer);
+ }
+ this._texture?.onLoadedObservable.add(() => this.onLoadObservable.notifyObservers(this));
+ }
+ else {
+ if (this._texture.isReady) {
+ Tools.SetImmediate(() => onLoadProcessing());
+ }
+ else {
+ this._texture.onLoadedObservable.add(() => onLoadProcessing());
+ }
+ }
+ }
+ /**
+ * Parses text to create a cube texture
+ * @param parsedTexture define the serialized text to read from
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root url of the cube texture
+ * @returns a cube texture
+ */
+ static Parse(parsedTexture, scene, rootUrl) {
+ const texture = SerializationHelper.Parse(() => {
+ let prefiltered = false;
+ if (parsedTexture.prefiltered) {
+ prefiltered = parsedTexture.prefiltered;
+ }
+ return new CubeTexture(rootUrl + (parsedTexture.url ?? parsedTexture.name), scene, parsedTexture.extensions, false, parsedTexture.files || null, null, null, undefined, prefiltered, parsedTexture.forcedExtension);
+ }, parsedTexture, scene);
+ // Local Cubemaps
+ if (parsedTexture.boundingBoxPosition) {
+ texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition);
+ }
+ if (parsedTexture.boundingBoxSize) {
+ texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize);
+ }
+ // Animations
+ if (parsedTexture.animations) {
+ for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
+ const parsedAnimation = parsedTexture.animations[animationIndex];
+ const internalClass = GetClass("BABYLON.Animation");
+ if (internalClass) {
+ texture.animations.push(internalClass.Parse(parsedAnimation));
+ }
+ }
+ }
+ return texture;
+ }
+ /**
+ * Makes a clone, or deep copy, of the cube texture
+ * @returns a new cube texture
+ */
+ clone() {
+ let uniqueId = 0;
+ const newCubeTexture = SerializationHelper.Clone(() => {
+ const cubeTexture = new CubeTexture(this.url, this.getScene() || this._getEngine(), this._extensions, this._noMipmap, this._files);
+ uniqueId = cubeTexture.uniqueId;
+ return cubeTexture;
+ }, this);
+ newCubeTexture.uniqueId = uniqueId;
+ return newCubeTexture;
+ }
+}
+__decorate([
+ serialize()
+], CubeTexture.prototype, "url", void 0);
+__decorate([
+ serializeAsVector3()
+], CubeTexture.prototype, "boundingBoxPosition", void 0);
+__decorate([
+ serializeAsVector3()
+], CubeTexture.prototype, "boundingBoxSize", null);
+__decorate([
+ serialize("rotationY")
+], CubeTexture.prototype, "rotationY", null);
+__decorate([
+ serialize("files")
+], CubeTexture.prototype, "_files", void 0);
+__decorate([
+ serialize("forcedExtension")
+], CubeTexture.prototype, "_forcedExtension", void 0);
+__decorate([
+ serialize("extensions")
+], CubeTexture.prototype, "_extensions", void 0);
+__decorate([
+ serializeAsMatrix("textureMatrix")
+], CubeTexture.prototype, "_textureMatrix", void 0);
+__decorate([
+ serializeAsMatrix("textureMatrixRefraction")
+], CubeTexture.prototype, "_textureMatrixRefraction", void 0);
+Texture._CubeTextureParser = CubeTexture.Parse;
+// Some exporters relies on Tools.Instantiate
+RegisterClass("BABYLON.CubeTexture", CubeTexture);
+
+class AppEnv extends Monobehiver {
+ object;
+ constructor(mainApp) {
+ super(mainApp);
+ this.object = null;
+ }
+ /** 初始化 - 创建默认HDR环境 */
+ Awake() {
+ this.createHDR();
+ }
+ /**
+ * 创建HDR环境贴图
+ * @param hdrPath HDR文件路径
+ */
+ createHDR() {
+ const envPath = AppConfig.env.envPath;
+ const intensity = AppConfig.env.intensity ?? 1.5;
+ const rotationY = AppConfig.env.rotationY ?? 0;
+ const scene = this.mainApp.appScene.object;
+ if (!scene) return;
+ if (this.object) {
+ this.object.dispose();
+ this.object = null;
+ }
+ const reflectionTexture = CubeTexture.CreateFromPrefilteredData(envPath, scene);
+ reflectionTexture.rotationY = rotationY;
+ scene.environmentIntensity = intensity;
+ scene.environmentTexture = reflectionTexture;
+ this.object = reflectionTexture;
+ scene.backgroundTexture = reflectionTexture;
+ const box = scene.createDefaultSkybox(
+ reflectionTexture,
+ true,
+ 512,
+ 0,
+ true
+ );
+ console.log("box", AppConfig.env.background);
+ if (AppConfig.env.background) {
+ if (box) box.visibility = 1;
+ } else {
+ if (box) box.visibility = 0;
+ }
+ this.object = reflectionTexture;
+ }
+ /**
+ * 修改HDR环境光强度
+ * @param intensity 强度值
+ */
+ changeHDRIntensity(intensity) {
+ if (this.mainApp.appScene.object) {
+ this.mainApp.appScene.object.environmentIntensity = intensity;
+ }
+ }
+ /**
+ * 旋转HDR环境贴图
+ * @param angle 旋转角度(弧度)
+ */
+ rotateHDR(angle) {
+ if (this.object) this.object.rotationY = angle;
+ }
+ /** 清理资源 */
+ clean() {
+ if (this.object) {
+ this.object.dispose();
+ this.object = null;
+ }
+ }
+}
+
+/**
+ * Fetches a resource from the network
+ * @param url defines the url to fetch the resource from
+ * @param options defines the options to use when fetching the resource
+ * @returns a promise that resolves when the resource is fetched
+ * @internal
+ */
+function _FetchAsync(url, options) {
+ const method = options.method || "GET";
+ return new Promise((resolve, reject) => {
+ const request = new WebRequest();
+ request.addEventListener("readystatechange", () => {
+ if (request.readyState == 4) {
+ if (request.status == 200) {
+ const headerValues = {};
+ if (options.responseHeaders) {
+ for (const header of options.responseHeaders) {
+ headerValues[header] = request.getResponseHeader(header) || "";
+ }
+ }
+ resolve({ response: request.response, headerValues: headerValues });
+ }
+ else {
+ reject(`Unable to fetch data from ${url}. Error code: ${request.status}`);
+ }
+ }
+ });
+ request.open(method, url);
+ request.send();
+ });
+}
+
+/**
+ * Mode that determines how to handle old animation groups before loading new ones.
+ */
+var SceneLoaderAnimationGroupLoadingMode;
+(function (SceneLoaderAnimationGroupLoadingMode) {
+ /**
+ * Reset all old animations to initial state then dispose them.
+ */
+ SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Clean"] = 0] = "Clean";
+ /**
+ * Stop all old animations.
+ */
+ SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Stop"] = 1] = "Stop";
+ /**
+ * Restart old animations from first frame.
+ */
+ SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Sync"] = 2] = "Sync";
+ /**
+ * Old animations remains untouched.
+ */
+ SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["NoSync"] = 3] = "NoSync";
+})(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {}));
+function isFactory(pluginOrFactory) {
+ return !!pluginOrFactory.createPlugin;
+}
+function isFile(value) {
+ return !!value.name;
+}
+const onPluginActivatedObservable = new Observable();
+const registeredPlugins = {};
+let showingLoadingScreen = false;
+function getDefaultPlugin() {
+ return registeredPlugins[".babylon"];
+}
+function getPluginForMimeType(mimeType) {
+ for (const registeredPluginKey in registeredPlugins) {
+ const registeredPlugin = registeredPlugins[registeredPluginKey];
+ if (registeredPlugin.mimeType === mimeType) {
+ return registeredPlugin;
+ }
+ }
+ return undefined;
+}
+function getPluginForExtension(extension, returnDefault) {
+ const registeredPlugin = registeredPlugins[extension];
+ if (registeredPlugin) {
+ return registeredPlugin;
+ }
+ Logger.Warn("Unable to find a plugin to load " +
+ extension +
+ " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes");
+ return returnDefault ? getDefaultPlugin() : undefined;
+}
+function isPluginForExtensionAvailable(extension) {
+ return !!registeredPlugins[extension];
+}
+function getPluginForDirectLoad(data) {
+ for (const extension in registeredPlugins) {
+ const plugin = registeredPlugins[extension].plugin;
+ if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
+ return registeredPlugins[extension];
+ }
+ }
+ return getDefaultPlugin();
+}
+function getFilenameExtension(sceneFilename) {
+ const queryStringPosition = sceneFilename.indexOf("?");
+ if (queryStringPosition !== -1) {
+ sceneFilename = sceneFilename.substring(0, queryStringPosition);
+ }
+ const dotPosition = sceneFilename.lastIndexOf(".");
+ return sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
+}
+function getDirectLoad(sceneFilename) {
+ if (sceneFilename.substring(0, 5) === "data:") {
+ return sceneFilename.substring(5);
+ }
+ return null;
+}
+function formatErrorMessage(fileInfo, message, exception) {
+ const fromLoad = fileInfo.rawData ? "binary data" : fileInfo.url;
+ let errorMessage = "Unable to load from " + fromLoad;
+ if (message) {
+ errorMessage += `: ${message}`;
+ }
+ else if (exception) {
+ errorMessage += `: ${exception}`;
+ }
+ return errorMessage;
+}
+async function loadDataAsync(fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension, name, pluginOptions) {
+ const directLoad = getDirectLoad(fileInfo.url);
+ if (fileInfo.rawData && !pluginExtension) {
+ // eslint-disable-next-line no-throw-literal
+ throw "When using ArrayBufferView to load data the file extension must be provided.";
+ }
+ const fileExtension = !directLoad && !pluginExtension ? getFilenameExtension(fileInfo.url) : "";
+ let registeredPlugin = pluginExtension
+ ? getPluginForExtension(pluginExtension, true)
+ : directLoad
+ ? getPluginForDirectLoad(fileInfo.url)
+ : getPluginForExtension(fileExtension, false);
+ if (!registeredPlugin && fileExtension) {
+ if (fileInfo.url && !fileInfo.url.startsWith("blob:")) {
+ // Fetching head content to get the mime type
+ const response = await _FetchAsync(fileInfo.url, { method: "HEAD", responseHeaders: ["Content-Type"] });
+ const mimeType = response.headerValues ? response.headerValues["Content-Type"] : "";
+ if (mimeType) {
+ registeredPlugin = getPluginForMimeType(mimeType);
+ }
+ }
+ if (!registeredPlugin) {
+ registeredPlugin = getDefaultPlugin();
+ }
+ }
+ if (!registeredPlugin) {
+ throw new Error(`No plugin or fallback for ${pluginExtension ?? fileInfo.url}`);
+ }
+ if (pluginOptions?.[registeredPlugin.plugin.name]?.enabled === false) {
+ throw new Error(`The '${registeredPlugin.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);
+ }
+ if (fileInfo.rawData && !registeredPlugin.isBinary) {
+ // eslint-disable-next-line no-throw-literal
+ throw "Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";
+ }
+ const getPluginInstance = (callback) => {
+ // For plugin factories, the plugin is instantiated on each SceneLoader operation. This makes options handling
+ // much simpler as we can just pass the options to the factory, rather than passing options through to every possible
+ // plugin call. Given this, options are only supported for plugins that provide a factory function.
+ if (isFactory(registeredPlugin.plugin)) {
+ const pluginFactory = registeredPlugin.plugin;
+ const partialPlugin = pluginFactory.createPlugin(pluginOptions ?? {});
+ if (partialPlugin instanceof Promise) {
+ partialPlugin.then(callback).catch((error) => {
+ onError("Error instantiating plugin.", error);
+ });
+ // When async factories are used, the plugin instance cannot be returned synchronously.
+ // In this case, the legacy loader functions will return null.
+ return null;
+ }
+ else {
+ callback(partialPlugin);
+ return partialPlugin;
+ }
+ }
+ else {
+ callback(registeredPlugin.plugin);
+ return registeredPlugin.plugin;
+ }
+ };
+ return getPluginInstance((plugin) => {
+ if (!plugin) {
+ // eslint-disable-next-line no-throw-literal
+ throw `The loader plugin corresponding to the '${pluginExtension}' file type has not been found. If using es6, please import the plugin you wish to use before.`;
+ }
+ onPluginActivatedObservable.notifyObservers(plugin);
+ // Check if we have a direct load url. If the plugin is registered to handle
+ // it or it's not a base64 data url, then pass it through the direct load path.
+ if (directLoad && ((plugin.canDirectLoad && plugin.canDirectLoad(fileInfo.url)) || !IsBase64DataUrl(fileInfo.url))) {
+ if (plugin.directLoad) {
+ const result = plugin.directLoad(scene, directLoad);
+ if (result instanceof Promise) {
+ result
+ .then((data) => {
+ onSuccess(plugin, data);
+ })
+ .catch((error) => {
+ onError("Error in directLoad of _loadData: " + error, error);
+ });
+ }
+ else {
+ onSuccess(plugin, result);
+ }
+ }
+ else {
+ onSuccess(plugin, directLoad);
+ }
+ return;
+ }
+ const useArrayBuffer = registeredPlugin.isBinary;
+ const dataCallback = (data, responseURL) => {
+ if (scene.isDisposed) {
+ onError("Scene has been disposed");
+ return;
+ }
+ onSuccess(plugin, data, responseURL);
+ };
+ let request = null;
+ let pluginDisposed = false;
+ plugin.onDisposeObservable?.add(() => {
+ pluginDisposed = true;
+ if (request) {
+ request.abort();
+ request = null;
+ }
+ onDispose();
+ });
+ const manifestChecked = () => {
+ if (pluginDisposed) {
+ return;
+ }
+ const errorCallback = (request, exception) => {
+ onError(request?.statusText, exception);
+ };
+ if (!plugin.loadFile && fileInfo.rawData) {
+ // eslint-disable-next-line no-throw-literal
+ throw "Plugin does not support loading ArrayBufferView.";
+ }
+ request = plugin.loadFile
+ ? plugin.loadFile(scene, fileInfo.rawData || fileInfo.file || fileInfo.url, fileInfo.rootUrl, dataCallback, onProgress, useArrayBuffer, errorCallback, name)
+ : scene._loadFile(fileInfo.file || fileInfo.url, dataCallback, onProgress, true, useArrayBuffer, errorCallback);
+ };
+ const engine = scene.getEngine();
+ let canUseOfflineSupport = engine.enableOfflineSupport;
+ if (canUseOfflineSupport) {
+ // Also check for exceptions
+ let exceptionFound = false;
+ for (const regex of scene.disableOfflineSupportExceptionRules) {
+ if (regex.test(fileInfo.url)) {
+ exceptionFound = true;
+ break;
+ }
+ }
+ canUseOfflineSupport = !exceptionFound;
+ }
+ if (canUseOfflineSupport && AbstractEngine.OfflineProviderFactory) {
+ // Checking if a manifest file has been set for this scene and if offline mode has been requested
+ scene.offlineProvider = AbstractEngine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
+ }
+ else {
+ manifestChecked();
+ }
+ });
+}
+function _getFileInfo(rootUrl, sceneSource) {
+ let url;
+ let name;
+ let file = null;
+ let rawData = null;
+ if (!sceneSource) {
+ url = rootUrl;
+ name = Tools.GetFilename(rootUrl);
+ rootUrl = Tools.GetFolderPath(rootUrl);
+ }
+ else if (isFile(sceneSource)) {
+ url = `file:${sceneSource.name}`;
+ name = sceneSource.name;
+ file = sceneSource;
+ }
+ else if (ArrayBuffer.isView(sceneSource)) {
+ url = "";
+ name = RandomGUID();
+ rawData = sceneSource;
+ }
+ else if (sceneSource.startsWith("data:")) {
+ url = sceneSource;
+ name = "";
+ }
+ else if (rootUrl) {
+ const filename = sceneSource;
+ if (filename.substring(0, 1) === "/") {
+ Tools.Error("Wrong sceneFilename parameter");
+ return null;
+ }
+ url = rootUrl + filename;
+ name = filename;
+ }
+ else {
+ url = sceneSource;
+ name = Tools.GetFilename(sceneSource);
+ rootUrl = Tools.GetFolderPath(sceneSource);
+ }
+ return {
+ url: url,
+ rootUrl: rootUrl,
+ name: name,
+ file: file,
+ rawData,
+ };
+}
+/**
+ * Adds a new plugin to the list of registered plugins
+ * @param plugin defines the plugin to add
+ */
+function RegisterSceneLoaderPlugin(plugin) {
+ if (typeof plugin.extensions === "string") {
+ const extension = plugin.extensions;
+ registeredPlugins[extension.toLowerCase()] = {
+ plugin: plugin,
+ isBinary: false,
+ };
+ }
+ else {
+ const extensions = plugin.extensions;
+ Object.keys(extensions).forEach((extension) => {
+ registeredPlugins[extension.toLowerCase()] = {
+ plugin: plugin,
+ isBinary: extensions[extension].isBinary,
+ mimeType: extensions[extension].mimeType,
+ };
+ });
+ }
+}
+/**
+ * Import meshes into a scene
+ * @param source a string that defines the name of the scene file, or starts with "data:" following by the stringified version of the scene, or a File object, or an ArrayBufferView
+ * @param scene the instance of BABYLON.Scene to append to
+ * @param options an object that configures aspects of how the scene is loaded
+ * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
+ */
+function ImportMeshAsync(source, scene, options) {
+ const { meshNames, rootUrl = "", onProgress, pluginExtension, name, pluginOptions } = options ?? {};
+ return importMeshAsyncCore(meshNames, rootUrl, source, scene, onProgress, pluginExtension, name, pluginOptions);
+}
+async function importMeshAsync(meshNames, rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) {
+ if (!scene) {
+ Logger.Error("No scene available to import mesh to");
+ return null;
+ }
+ const fileInfo = _getFileInfo(rootUrl, sceneFilename);
+ if (!fileInfo) {
+ return null;
+ }
+ const loadingToken = {};
+ scene.addPendingData(loadingToken);
+ const disposeHandler = () => {
+ scene.removePendingData(loadingToken);
+ };
+ const errorHandler = (message, exception) => {
+ const errorMessage = formatErrorMessage(fileInfo, message, exception);
+ if (onError) {
+ onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));
+ }
+ else {
+ Logger.Error(errorMessage);
+ // should the exception be thrown?
+ }
+ disposeHandler();
+ };
+ const progressHandler = onProgress
+ ? (event) => {
+ try {
+ onProgress(event);
+ }
+ catch (e) {
+ errorHandler("Error in onProgress callback: " + e, e);
+ }
+ }
+ : undefined;
+ const successHandler = (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers) => {
+ scene.importedMeshesFiles.push(fileInfo.url);
+ if (onSuccess) {
+ try {
+ onSuccess(meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers);
+ }
+ catch (e) {
+ errorHandler("Error in onSuccess callback: " + e, e);
+ }
+ }
+ scene.removePendingData(loadingToken);
+ };
+ return await loadDataAsync(fileInfo, scene, (plugin, data, responseURL) => {
+ if (plugin.rewriteRootURL) {
+ fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
+ }
+ if (plugin.importMesh) {
+ const syncedPlugin = plugin;
+ const meshes = [];
+ const particleSystems = [];
+ const skeletons = [];
+ if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
+ return;
+ }
+ scene.loadingPluginName = plugin.name;
+ successHandler(meshes, particleSystems, skeletons, [], [], [], [], []);
+ }
+ else {
+ const asyncedPlugin = plugin;
+ asyncedPlugin
+ .importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)
+ .then((result) => {
+ scene.loadingPluginName = plugin.name;
+ successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups, result.transformNodes, result.geometries, result.lights, result.spriteManagers);
+ })
+ .catch((error) => {
+ errorHandler(error.message, error);
+ });
+ }
+ }, progressHandler, errorHandler, disposeHandler, pluginExtension, name, pluginOptions);
+}
+function importMeshAsyncCore(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name, pluginOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ importMeshAsync(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers) => {
+ resolve({
+ meshes: meshes,
+ particleSystems: particleSystems,
+ skeletons: skeletons,
+ animationGroups: animationGroups,
+ transformNodes: transformNodes,
+ geometries: geometries,
+ lights: lights,
+ spriteManagers: spriteManagers,
+ });
+ }, onProgress, (scene, message, exception) => {
+ reject(exception || new Error(message));
+ }, pluginExtension, name, pluginOptions).catch(reject);
+ }
+ catch (error) {
+ reject(error);
+ }
+ });
+}
+// This is the core implementation of load scene
+async function loadSceneImplAsync(rootUrl, sceneFilename = "", engine = EngineStore.LastCreatedEngine, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) {
+ if (!engine) {
+ Tools.Error("No engine available");
+ return;
+ }
+ await appendSceneImplAsync(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension, name, pluginOptions);
+}
+// This function is shared between the new module level loadSceneAsync and the legacy SceneLoader.LoadAsync
+function loadSceneSharedAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name, pluginOptions) {
+ return new Promise((resolve, reject) => {
+ loadSceneImplAsync(rootUrl, sceneFilename, engine, (scene) => {
+ resolve(scene);
+ }, onProgress, (scene, message, exception) => {
+ reject(exception || new Error(message));
+ }, pluginExtension, name, pluginOptions);
+ });
+}
+// This is the core implementation of append scene
+async function appendSceneImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) {
+ if (!scene) {
+ Logger.Error("No scene available to append to");
+ return null;
+ }
+ const fileInfo = _getFileInfo(rootUrl, sceneFilename);
+ if (!fileInfo) {
+ return null;
+ }
+ const loadingToken = {};
+ scene.addPendingData(loadingToken);
+ const disposeHandler = () => {
+ scene.removePendingData(loadingToken);
+ };
+ if (SceneLoaderFlags.ShowLoadingScreen && !showingLoadingScreen) {
+ showingLoadingScreen = true;
+ scene.getEngine().displayLoadingUI();
+ scene.executeWhenReady(() => {
+ scene.getEngine().hideLoadingUI();
+ showingLoadingScreen = false;
+ });
+ }
+ const errorHandler = (message, exception) => {
+ const errorMessage = formatErrorMessage(fileInfo, message, exception);
+ if (onError) {
+ onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));
+ }
+ else {
+ Logger.Error(errorMessage);
+ // should the exception be thrown?
+ }
+ disposeHandler();
+ };
+ const progressHandler = onProgress
+ ? (event) => {
+ try {
+ onProgress(event);
+ }
+ catch (e) {
+ errorHandler("Error in onProgress callback", e);
+ }
+ }
+ : undefined;
+ const successHandler = () => {
+ if (onSuccess) {
+ try {
+ onSuccess(scene);
+ }
+ catch (e) {
+ errorHandler("Error in onSuccess callback", e);
+ }
+ }
+ scene.removePendingData(loadingToken);
+ };
+ return await loadDataAsync(fileInfo, scene, (plugin, data) => {
+ if (plugin.load) {
+ const syncedPlugin = plugin;
+ if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
+ return;
+ }
+ scene.loadingPluginName = plugin.name;
+ successHandler();
+ }
+ else {
+ const asyncedPlugin = plugin;
+ asyncedPlugin
+ .loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)
+ .then(() => {
+ scene.loadingPluginName = plugin.name;
+ successHandler();
+ })
+ .catch((error) => {
+ errorHandler(error.message, error);
+ });
+ }
+ }, progressHandler, errorHandler, disposeHandler, pluginExtension, name, pluginOptions);
+}
+// This function is shared between the new module level appendSceneAsync and the legacy SceneLoader.AppendAsync
+function appendSceneSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name, pluginOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ appendSceneImplAsync(rootUrl, sceneFilename, scene, (scene) => {
+ resolve(scene);
+ }, onProgress, (scene, message, exception) => {
+ reject(exception || new Error(message));
+ }, pluginExtension, name, pluginOptions).catch(reject);
+ }
+ catch (error) {
+ reject(error);
+ }
+ });
+}
+// This is the core implementation of load asset container
+async function loadAssetContainerImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) {
+ if (!scene) {
+ Logger.Error("No scene available to load asset container to");
+ return null;
+ }
+ const fileInfo = _getFileInfo(rootUrl, sceneFilename);
+ if (!fileInfo) {
+ return null;
+ }
+ const loadingToken = {};
+ scene.addPendingData(loadingToken);
+ const disposeHandler = () => {
+ scene.removePendingData(loadingToken);
+ };
+ const errorHandler = (message, exception) => {
+ const errorMessage = formatErrorMessage(fileInfo, message, exception);
+ if (onError) {
+ onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));
+ }
+ else {
+ Logger.Error(errorMessage);
+ // should the exception be thrown?
+ }
+ disposeHandler();
+ };
+ const progressHandler = onProgress
+ ? (event) => {
+ try {
+ onProgress(event);
+ }
+ catch (e) {
+ errorHandler("Error in onProgress callback", e);
+ }
+ }
+ : undefined;
+ const successHandler = (assets) => {
+ if (onSuccess) {
+ try {
+ onSuccess(assets);
+ }
+ catch (e) {
+ errorHandler("Error in onSuccess callback", e);
+ }
+ }
+ scene.removePendingData(loadingToken);
+ };
+ return await loadDataAsync(fileInfo, scene, (plugin, data) => {
+ if (plugin.loadAssetContainer) {
+ const syncedPlugin = plugin;
+ const assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
+ if (!assetContainer) {
+ return;
+ }
+ assetContainer.populateRootNodes();
+ scene.loadingPluginName = plugin.name;
+ successHandler(assetContainer);
+ }
+ else if (plugin.loadAssetContainerAsync) {
+ const asyncedPlugin = plugin;
+ asyncedPlugin
+ .loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)
+ .then((assetContainer) => {
+ assetContainer.populateRootNodes();
+ scene.loadingPluginName = plugin.name;
+ successHandler(assetContainer);
+ })
+ .catch((error) => {
+ errorHandler(error.message, error);
+ });
+ }
+ else {
+ errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
+ }
+ }, progressHandler, errorHandler, disposeHandler, pluginExtension, name, pluginOptions);
+}
+// This function is shared between the new module level loadAssetContainerAsync and the legacy SceneLoader.LoadAssetContainerAsync
+function loadAssetContainerSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name, pluginOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, (assets) => {
+ resolve(assets);
+ }, onProgress, (scene, message, exception) => {
+ reject(exception || new Error(message));
+ }, pluginExtension, name, pluginOptions).catch(reject);
+ }
+ catch (error) {
+ reject(error);
+ }
+ });
+}
+// This is the core implementation of import animations
+async function importAnimationsImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = 0 /* SceneLoaderAnimationGroupLoadingMode.Clean */, targetConverter = null, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "", pluginOptions = {}) {
+ if (!scene) {
+ Logger.Error("No scene available to load animations to");
+ return;
+ }
+ if (overwriteAnimations) {
+ // Reset, stop and dispose all animations before loading new ones
+ for (const animatable of scene.animatables) {
+ animatable.reset();
+ }
+ scene.stopAllAnimations();
+ scene.animationGroups.slice().forEach((animationGroup) => {
+ animationGroup.dispose();
+ });
+ const nodes = scene.getNodes();
+ nodes.forEach((node) => {
+ if (node.animations) {
+ node.animations = [];
+ }
+ });
+ }
+ else {
+ switch (animationGroupLoadingMode) {
+ case 0 /* SceneLoaderAnimationGroupLoadingMode.Clean */:
+ scene.animationGroups.slice().forEach((animationGroup) => {
+ animationGroup.dispose();
+ });
+ break;
+ case 1 /* SceneLoaderAnimationGroupLoadingMode.Stop */:
+ scene.animationGroups.forEach((animationGroup) => {
+ animationGroup.stop();
+ });
+ break;
+ case 2 /* SceneLoaderAnimationGroupLoadingMode.Sync */:
+ scene.animationGroups.forEach((animationGroup) => {
+ animationGroup.reset();
+ animationGroup.restart();
+ });
+ break;
+ case 3 /* SceneLoaderAnimationGroupLoadingMode.NoSync */:
+ // nothing to do
+ break;
+ default:
+ Logger.Error("Unknown animation group loading mode value '" + animationGroupLoadingMode + "'");
+ return;
+ }
+ }
+ const startingIndexForNewAnimatables = scene.animatables.length;
+ const onAssetContainerLoaded = (container) => {
+ container.mergeAnimationsTo(scene, scene.animatables.slice(startingIndexForNewAnimatables), targetConverter);
+ container.dispose();
+ scene.onAnimationFileImportedObservable.notifyObservers(scene);
+ if (onSuccess) {
+ onSuccess(scene);
+ }
+ };
+ await loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, onAssetContainerLoaded, onProgress, onError, pluginExtension, name, pluginOptions);
+}
+// This function is shared between the new module level importAnimationsAsync and the legacy SceneLoader.ImportAnimationsAsync
+function importAnimationsSharedAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name, pluginOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ importAnimationsImplAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, (scene) => {
+ resolve(scene);
+ }, onProgress, (scene, message, exception) => {
+ reject(exception || new Error(message));
+ }, pluginExtension, name, pluginOptions).catch(reject);
+ }
+ catch (error) {
+ reject(error);
+ }
+ });
+}
+/**
+ * Class used to load scene from various file formats using registered plugins
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes
+ * @deprecated The module level functions are more efficient for bundler tree shaking and allow plugin options to be passed through. Future improvements to scene loading will primarily be in the module level functions. The SceneLoader class will remain available, but it will be beneficial to prefer the module level functions.
+ * @see {@link ImportMeshAsync}, {@link LoadSceneAsync}, {@link AppendSceneAsync}, {@link ImportAnimationsAsync}, {@link LoadAssetContainerAsync}
+ */
+class SceneLoader {
+ /**
+ * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
+ */
+ static get ForceFullSceneLoadingForIncremental() {
+ return SceneLoaderFlags.ForceFullSceneLoadingForIncremental;
+ }
+ static set ForceFullSceneLoadingForIncremental(value) {
+ SceneLoaderFlags.ForceFullSceneLoadingForIncremental = value;
+ }
+ /**
+ * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
+ */
+ static get ShowLoadingScreen() {
+ return SceneLoaderFlags.ShowLoadingScreen;
+ }
+ static set ShowLoadingScreen(value) {
+ SceneLoaderFlags.ShowLoadingScreen = value;
+ }
+ /**
+ * Defines the current logging level (while loading the scene)
+ * @ignorenaming
+ */
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static get loggingLevel() {
+ return SceneLoaderFlags.loggingLevel;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ static set loggingLevel(value) {
+ SceneLoaderFlags.loggingLevel = value;
+ }
+ /**
+ * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
+ */
+ static get CleanBoneMatrixWeights() {
+ return SceneLoaderFlags.CleanBoneMatrixWeights;
+ }
+ static set CleanBoneMatrixWeights(value) {
+ SceneLoaderFlags.CleanBoneMatrixWeights = value;
+ }
+ /**
+ * Gets the default plugin (used to load Babylon files)
+ * @returns the .babylon plugin
+ */
+ static GetDefaultPlugin() {
+ return getDefaultPlugin();
+ }
+ // Public functions
+ /**
+ * Gets a plugin that can load the given extension
+ * @param extension defines the extension to load
+ * @returns a plugin or null if none works
+ */
+ static GetPluginForExtension(extension) {
+ return getPluginForExtension(extension, true)?.plugin;
+ }
+ /**
+ * Gets a boolean indicating that the given extension can be loaded
+ * @param extension defines the extension to load
+ * @returns true if the extension is supported
+ */
+ static IsPluginForExtensionAvailable(extension) {
+ return isPluginForExtensionAvailable(extension);
+ }
+ /**
+ * Adds a new plugin to the list of registered plugins
+ * @param plugin defines the plugin to add
+ */
+ static RegisterPlugin(plugin) {
+ RegisterSceneLoaderPlugin(plugin);
+ }
+ /**
+ * Import meshes into a scene
+ * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param scene the instance of BABYLON.Scene to append to
+ * @param onSuccess a callback with a list of imported meshes, particleSystems, skeletons, and animationGroups when import succeeds
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param onError a callback with the scene, a message, and possibly an exception when import fails
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the name of the file, if the data is binary
+ * @deprecated Please use the module level {@link ImportMeshAsync} instead
+ */
+ static ImportMesh(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name) {
+ importMeshAsync(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.(EngineStore.LastCreatedScene, error?.message, error));
+ }
+ /**
+ * Import meshes into a scene
+ * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param scene the instance of BABYLON.Scene to append to
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the name of the file
+ * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
+ * @deprecated Please use the module level {@link ImportMeshAsync} instead
+ */
+ static ImportMeshAsync(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name) {
+ return importMeshAsyncCore(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name);
+ }
+ /**
+ * Load a scene
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param engine is the instance of BABYLON.Engine to use to create the scene
+ * @param onSuccess a callback with the scene when import succeeds
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param onError a callback with the scene, a message, and possibly an exception when import fails
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the filename, if the data is binary
+ * @deprecated Please use the module level {@link LoadSceneAsync} instead
+ */
+ static Load(rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension, name) {
+ loadSceneImplAsync(rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.(EngineStore.LastCreatedScene, error?.message, error));
+ }
+ /**
+ * Load a scene
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param engine is the instance of BABYLON.Engine to use to create the scene
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the filename, if the data is binary
+ * @returns The loaded scene
+ * @deprecated Please use the module level {@link LoadSceneAsync} instead
+ */
+ static LoadAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name) {
+ return loadSceneSharedAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name);
+ }
+ /**
+ * Append a scene
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param scene is the instance of BABYLON.Scene to append to
+ * @param onSuccess a callback with the scene when import succeeds
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param onError a callback with the scene, a message, and possibly an exception when import fails
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the name of the file, if the data is binary
+ * @deprecated Please use the module level {@link AppendSceneAsync} instead
+ */
+ static Append(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name) {
+ appendSceneImplAsync(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.((scene ?? EngineStore.LastCreatedScene), error?.message, error));
+ }
+ /**
+ * Append a scene
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param scene is the instance of BABYLON.Scene to append to
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the name of the file, if the data is binary
+ * @returns The given scene
+ * @deprecated Please use the module level {@link AppendSceneAsync} instead
+ */
+ static AppendAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name) {
+ return appendSceneSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name);
+ }
+ /**
+ * Load a scene into an asset container
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
+ * @param onSuccess a callback with the scene when import succeeds
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param onError a callback with the scene, a message, and possibly an exception when import fails
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the filename, if the data is binary
+ * @deprecated Please use the module level {@link LoadAssetContainerAsync} instead
+ */
+ static LoadAssetContainer(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name) {
+ loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.((scene ?? EngineStore.LastCreatedScene), error?.message, error));
+ }
+ /**
+ * Load a scene into an asset container
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
+ * @param scene is the instance of Scene to append to
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the filename, if the data is binary
+ * @returns The loaded asset container
+ * @deprecated Please use the module level {@link LoadAssetContainerAsync} instead
+ */
+ static LoadAssetContainerAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name) {
+ return loadAssetContainerSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name);
+ }
+ /**
+ * Import animations from a file into a scene
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
+ * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise
+ * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones
+ * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)
+ * @param onSuccess a callback with the scene when import succeeds
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param onError a callback with the scene, a message, and possibly an exception when import fails
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the filename, if the data is binary
+ * @deprecated Please use the module level {@link ImportAnimationsAsync} instead
+ */
+ static ImportAnimations(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name) {
+ importAnimationsImplAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name).catch((error) => onError?.((scene ?? EngineStore.LastCreatedScene), error?.message, error));
+ }
+ /**
+ * Import animations from a file into a scene
+ * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
+ * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
+ * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
+ * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise
+ * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones
+ * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)
+ * @param onSuccess a callback with the scene when import succeeds
+ * @param onProgress a callback with a progress event for each file being loaded
+ * @param onError a callback with the scene, a message, and possibly an exception when import fails
+ * @param pluginExtension the extension used to determine the plugin
+ * @param name defines the filename, if the data is binary
+ * @returns the updated scene with imported animations
+ * @deprecated Please use the module level {@link ImportAnimationsAsync} instead
+ */
+ static ImportAnimationsAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ onSuccess, onProgress,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ onError, pluginExtension, name) {
+ return importAnimationsSharedAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name);
+ }
+}
+/**
+ * No logging while loading
+ */
+SceneLoader.NO_LOGGING = 0;
+/**
+ * Minimal logging while loading
+ */
+SceneLoader.MINIMAL_LOGGING = 1;
+/**
+ * Summary logging while loading
+ */
+SceneLoader.SUMMARY_LOGGING = 2;
+/**
+ * Detailed logging while loading
+ */
+SceneLoader.DETAILED_LOGGING = 3;
+// Members
+/**
+ * Event raised when a plugin is used to load a scene
+ */
+SceneLoader.OnPluginActivatedObservable = onPluginActivatedObservable;
+
+Mesh._instancedMeshFactory = (name, mesh) => {
+ const instance = new InstancedMesh(name, mesh);
+ if (mesh.instancedBuffers) {
+ instance.instancedBuffers = {};
+ for (const key in mesh.instancedBuffers) {
+ instance.instancedBuffers[key] = mesh.instancedBuffers[key];
+ }
+ }
+ return instance;
+};
+/**
+ * Creates an instance based on a source mesh.
+ */
+class InstancedMesh extends AbstractMesh {
+ /**
+ * Creates a new InstancedMesh object from the mesh source.
+ * @param name defines the name of the instance
+ * @param source the mesh to create the instance from
+ */
+ constructor(name, source) {
+ super(name, source.getScene());
+ /** @internal */
+ this._indexInSourceMeshInstanceArray = -1;
+ /** @internal */
+ this._distanceToCamera = 0;
+ source.addInstance(this);
+ this._sourceMesh = source;
+ this._unIndexed = source._unIndexed;
+ this.position.copyFrom(source.position);
+ this.rotation.copyFrom(source.rotation);
+ this.scaling.copyFrom(source.scaling);
+ if (source.rotationQuaternion) {
+ this.rotationQuaternion = source.rotationQuaternion.clone();
+ }
+ this.animations = source.animations.slice();
+ for (const range of source.getAnimationRanges()) {
+ if (range != null) {
+ this.createAnimationRange(range.name, range.from, range.to);
+ }
+ }
+ this.infiniteDistance = source.infiniteDistance;
+ this.setPivotMatrix(source.getPivotMatrix());
+ this.refreshBoundingInfo(true, true);
+ this._syncSubMeshes();
+ }
+ /**
+ * @returns the string "InstancedMesh".
+ */
+ getClassName() {
+ return "InstancedMesh";
+ }
+ /** Gets the list of lights affecting that mesh */
+ get lightSources() {
+ return this._sourceMesh._lightSources;
+ }
+ _resyncLightSources() {
+ // Do nothing as all the work will be done by source mesh
+ }
+ _resyncLightSource() {
+ // Do nothing as all the work will be done by source mesh
+ }
+ _removeLightSource() {
+ // Do nothing as all the work will be done by source mesh
+ }
+ // Methods
+ /**
+ * If the source mesh receives shadows
+ */
+ get receiveShadows() {
+ return this._sourceMesh.receiveShadows;
+ }
+ set receiveShadows(_value) {
+ if (this._sourceMesh?.receiveShadows !== _value) {
+ Tools.Warn("Setting receiveShadows on an instanced mesh has no effect");
+ }
+ }
+ /**
+ * The material of the source mesh
+ */
+ get material() {
+ return this._sourceMesh.material;
+ }
+ set material(_value) {
+ if (this._sourceMesh?.material !== _value) {
+ Tools.Warn("Setting material on an instanced mesh has no effect");
+ }
+ }
+ /**
+ * Visibility of the source mesh
+ */
+ get visibility() {
+ return this._sourceMesh.visibility;
+ }
+ set visibility(_value) {
+ if (this._sourceMesh?.visibility !== _value) {
+ Tools.Warn("Setting visibility on an instanced mesh has no effect");
+ }
+ }
+ /**
+ * Skeleton of the source mesh
+ */
+ get skeleton() {
+ return this._sourceMesh.skeleton;
+ }
+ set skeleton(_value) {
+ if (this._sourceMesh?.skeleton !== _value) {
+ Tools.Warn("Setting skeleton on an instanced mesh has no effect");
+ }
+ }
+ /**
+ * Rendering ground id of the source mesh
+ */
+ get renderingGroupId() {
+ return this._sourceMesh.renderingGroupId;
+ }
+ set renderingGroupId(value) {
+ if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
+ return;
+ }
+ //no-op with warning
+ Logger.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
+ }
+ /**
+ * @returns the total number of vertices (integer).
+ */
+ getTotalVertices() {
+ return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 0;
+ }
+ /**
+ * Returns a positive integer : the total number of indices in this mesh geometry.
+ * @returns the number of indices or zero if the mesh has no geometry.
+ */
+ getTotalIndices() {
+ return this._sourceMesh.getTotalIndices();
+ }
+ /**
+ * The source mesh of the instance
+ */
+ get sourceMesh() {
+ return this._sourceMesh;
+ }
+ /**
+ * Gets the mesh internal Geometry object
+ */
+ get geometry() {
+ return this._sourceMesh._geometry;
+ }
+ /**
+ * Creates a new InstancedMesh object from the mesh model.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances
+ * @param name defines the name of the new instance
+ * @returns a new InstancedMesh
+ */
+ createInstance(name) {
+ return this._sourceMesh.createInstance(name);
+ }
+ /**
+ * Is this node ready to be used/rendered
+ * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
+ * @returns {boolean} is it ready
+ */
+ isReady(completeCheck = false) {
+ return this._sourceMesh.isReady(completeCheck, true);
+ }
+ /**
+ * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
+ * @param kind kind of verticies to retrieve (eg. positions, normals, uvs, etc.)
+ * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
+ * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
+ * @returns a float array or a Float32Array of the requested kind of data : positions, normals, uvs, etc.
+ */
+ getVerticesData(kind, copyWhenShared, forceCopy) {
+ return this._sourceMesh.getVerticesData(kind, copyWhenShared, forceCopy);
+ }
+ copyVerticesData(kind, vertexData) {
+ this._sourceMesh.copyVerticesData(kind, vertexData);
+ }
+ /**
+ * Sets the vertex data of the mesh geometry for the requested `kind`.
+ * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
+ * The `data` are either a numeric array either a Float32Array.
+ * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initially none) or updater.
+ * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
+ * Note that a new underlying VertexBuffer object is created each call.
+ * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
+ *
+ * Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ *
+ * Returns the Mesh.
+ * @param kind defines vertex data kind
+ * @param data defines the data source
+ * @param updatable defines if the data must be flagged as updatable (false as default)
+ * @param stride defines the vertex stride (optional)
+ * @returns the current mesh
+ */
+ setVerticesData(kind, data, updatable, stride) {
+ if (this.sourceMesh) {
+ this.sourceMesh.setVerticesData(kind, data, updatable, stride);
+ }
+ return this.sourceMesh;
+ }
+ /**
+ * Updates the existing vertex data of the mesh geometry for the requested `kind`.
+ * If the mesh has no geometry, it is simply returned as it is.
+ * The `data` are either a numeric array either a Float32Array.
+ * No new underlying VertexBuffer object is created.
+ * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
+ * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
+ *
+ * Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ *
+ * Returns the Mesh.
+ * @param kind defines vertex data kind
+ * @param data defines the data source
+ * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
+ * @param makeItUnique defines it the updated vertex buffer must be flagged as unique (false by default)
+ * @returns the source mesh
+ */
+ updateVerticesData(kind, data, updateExtends, makeItUnique) {
+ if (this.sourceMesh) {
+ this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
+ }
+ return this.sourceMesh;
+ }
+ /**
+ * Sets the mesh indices.
+ * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
+ * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
+ * This method creates a new index buffer each call.
+ * Returns the Mesh.
+ * @param indices the source data
+ * @param totalVertices defines the total number of vertices referenced by indices (could be null)
+ * @returns source mesh
+ */
+ setIndices(indices, totalVertices = null) {
+ if (this.sourceMesh) {
+ this.sourceMesh.setIndices(indices, totalVertices);
+ }
+ return this.sourceMesh;
+ }
+ /**
+ * Boolean : True if the mesh owns the requested kind of data.
+ * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
+ * - VertexBuffer.PositionKind
+ * - VertexBuffer.UVKind
+ * - VertexBuffer.UV2Kind
+ * - VertexBuffer.UV3Kind
+ * - VertexBuffer.UV4Kind
+ * - VertexBuffer.UV5Kind
+ * - VertexBuffer.UV6Kind
+ * - VertexBuffer.ColorKind
+ * - VertexBuffer.MatricesIndicesKind
+ * - VertexBuffer.MatricesIndicesExtraKind
+ * - VertexBuffer.MatricesWeightsKind
+ * - VertexBuffer.MatricesWeightsExtraKind
+ * @returns true if data kind is present
+ */
+ isVerticesDataPresent(kind) {
+ return this._sourceMesh.isVerticesDataPresent(kind);
+ }
+ /**
+ * @returns an array of indices (IndicesArray).
+ */
+ getIndices() {
+ return this._sourceMesh.getIndices();
+ }
+ get _positions() {
+ return this._sourceMesh._positions;
+ }
+ refreshBoundingInfo(applySkeletonOrOptions = false, applyMorph = false) {
+ if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) {
+ return this;
+ }
+ let options;
+ if (typeof applySkeletonOrOptions === "object") {
+ options = applySkeletonOrOptions;
+ }
+ else {
+ options = {
+ applySkeleton: applySkeletonOrOptions,
+ applyMorph: applyMorph,
+ };
+ }
+ const bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;
+ this._refreshBoundingInfo(this._sourceMesh._getData(options, null, VertexBuffer.PositionKind), bias);
+ return this;
+ }
+ /** @internal */
+ _preActivate() {
+ if (this._currentLOD) {
+ this._currentLOD._preActivate();
+ }
+ return this;
+ }
+ /**
+ * @internal
+ */
+ _activate(renderId, intermediateRendering) {
+ super._activate(renderId, intermediateRendering);
+ if (!this._sourceMesh.subMeshes) {
+ Logger.Warn("Instances should only be created for meshes with geometry.");
+ }
+ if (this._currentLOD) {
+ const differentSign = this._currentLOD._getWorldMatrixDeterminant() >= 0 !== this._getWorldMatrixDeterminant() >= 0;
+ if (differentSign) {
+ this._internalAbstractMeshDataInfo._actAsRegularMesh = true;
+ return true;
+ }
+ this._internalAbstractMeshDataInfo._actAsRegularMesh = false;
+ this._currentLOD._registerInstanceForRenderId(this, renderId);
+ if (intermediateRendering) {
+ if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate) {
+ this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = true;
+ return true;
+ }
+ }
+ else {
+ if (!this._currentLOD._internalAbstractMeshDataInfo._isActive) {
+ this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = true;
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ /** @internal */
+ _postActivate() {
+ if (this._sourceMesh.edgesShareWithInstances && this._sourceMesh._edgesRenderer && this._sourceMesh._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {
+ // we are using the edge renderer of the source mesh
+ this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer);
+ this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix());
+ }
+ else if (this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {
+ // we are using the edge renderer defined for this instance
+ this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer);
+ }
+ }
+ getWorldMatrix() {
+ if (this._currentLOD && this._currentLOD.billboardMode !== TransformNode.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) {
+ if (!this._billboardWorldMatrix) {
+ this._billboardWorldMatrix = new Matrix();
+ }
+ const tempMaster = this._currentLOD._masterMesh;
+ this._currentLOD._masterMesh = this;
+ TmpVectors.Vector3[7].copyFrom(this._currentLOD.position);
+ this._currentLOD.position.set(0, 0, 0);
+ this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(true));
+ this._currentLOD.position.copyFrom(TmpVectors.Vector3[7]);
+ this._currentLOD._masterMesh = tempMaster;
+ return this._billboardWorldMatrix;
+ }
+ return super.getWorldMatrix();
+ }
+ get isAnInstance() {
+ return true;
+ }
+ /**
+ * Returns the current associated LOD AbstractMesh.
+ * @param camera defines the camera to use to pick the LOD level
+ * @returns a Mesh or `null` if no LOD is associated with the AbstractMesh
+ */
+ getLOD(camera) {
+ if (!camera) {
+ return this;
+ }
+ const sourceMeshLODLevels = this.sourceMesh.getLODLevels();
+ if (!sourceMeshLODLevels || sourceMeshLODLevels.length === 0) {
+ this._currentLOD = this.sourceMesh;
+ }
+ else {
+ const boundingInfo = this.getBoundingInfo();
+ this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
+ }
+ return this._currentLOD;
+ }
+ /**
+ * @internal
+ */
+ _preActivateForIntermediateRendering(renderId) {
+ return this.sourceMesh._preActivateForIntermediateRendering(renderId);
+ }
+ /** @internal */
+ _syncSubMeshes() {
+ this.releaseSubMeshes();
+ if (this._sourceMesh.subMeshes) {
+ for (let index = 0; index < this._sourceMesh.subMeshes.length; index++) {
+ this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
+ }
+ }
+ return this;
+ }
+ /** @internal */
+ _generatePointsArray() {
+ return this._sourceMesh._generatePointsArray();
+ }
+ /** @internal */
+ _updateBoundingInfo() {
+ if (this.hasBoundingInfo) {
+ this.getBoundingInfo().update(this.worldMatrixFromCache);
+ }
+ else {
+ this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
+ }
+ this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
+ return this;
+ }
+ /**
+ * Creates a new InstancedMesh from the current mesh.
+ *
+ * Returns the clone.
+ * @param name the cloned mesh name
+ * @param newParent the optional Node to parent the clone to.
+ * @param doNotCloneChildren if `true` the model children aren't cloned.
+ * @param newSourceMesh if set this mesh will be used as the source mesh instead of ths instance's one
+ * @returns the clone
+ */
+ clone(name, newParent = null, doNotCloneChildren, newSourceMesh) {
+ const result = (newSourceMesh || this._sourceMesh).createInstance(name);
+ // Deep copy
+ DeepCopier.DeepCopy(this, result, [
+ "name",
+ "subMeshes",
+ "uniqueId",
+ "parent",
+ "lightSources",
+ "receiveShadows",
+ "material",
+ "visibility",
+ "skeleton",
+ "sourceMesh",
+ "isAnInstance",
+ "facetNb",
+ "isFacetDataEnabled",
+ "isBlocked",
+ "useBones",
+ "hasInstances",
+ "collider",
+ "edgesRenderer",
+ "forward",
+ "up",
+ "right",
+ "absolutePosition",
+ "absoluteScaling",
+ "absoluteRotationQuaternion",
+ "isWorldMatrixFrozen",
+ "nonUniformScaling",
+ "behaviors",
+ "worldMatrixFromCache",
+ "hasThinInstances",
+ "hasBoundingInfo",
+ ], []);
+ // Bounding info
+ this.refreshBoundingInfo();
+ // Parent
+ if (newParent) {
+ result.parent = newParent;
+ }
+ if (!doNotCloneChildren) {
+ // Children
+ for (let index = 0; index < this.getScene().meshes.length; index++) {
+ const mesh = this.getScene().meshes[index];
+ if (mesh.parent === this) {
+ mesh.clone(mesh.name, result);
+ }
+ }
+ }
+ result.computeWorldMatrix(true);
+ this.onClonedObservable.notifyObservers(result);
+ return result;
+ }
+ /**
+ * Disposes the InstancedMesh.
+ * Returns nothing.
+ * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
+ * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
+ */
+ dispose(doNotRecurse, disposeMaterialAndTextures = false) {
+ // Remove from mesh
+ this._sourceMesh.removeInstance(this);
+ super.dispose(doNotRecurse, disposeMaterialAndTextures);
+ }
+ /**
+ * @internal
+ */
+ _serializeAsParent(serializationObject) {
+ super._serializeAsParent(serializationObject);
+ serializationObject.parentId = this._sourceMesh.uniqueId;
+ serializationObject.parentInstanceIndex = this._indexInSourceMeshInstanceArray;
+ }
+ /**
+ * Instantiate (when possible) or clone that node with its hierarchy
+ * @param newParent defines the new parent to use for the instance (or clone)
+ * @param options defines options to configure how copy is done
+ * @param options.doNotInstantiate defines if the model must be instantiated or just cloned
+ * @param options.newSourcedMesh newSourcedMesh the new source mesh for the instance (or clone)
+ * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created
+ * @returns an instance (or a clone) of the current node with its hierarchy
+ */
+ instantiateHierarchy(newParent = null, options, onNewNodeCreated) {
+ const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true, options && options.newSourcedMesh);
+ if (clone) {
+ if (onNewNodeCreated) {
+ onNewNodeCreated(this, clone);
+ }
+ }
+ for (const child of this.getChildTransformNodes(true)) {
+ child.instantiateHierarchy(clone, options, onNewNodeCreated);
+ }
+ return clone;
+ }
+}
+Mesh.prototype.registerInstancedBuffer = function (kind, stride) {
+ // Remove existing one
+ this._userInstancedBuffersStorage?.vertexBuffers[kind]?.dispose();
+ // Creates the instancedBuffer field if not present
+ if (!this.instancedBuffers) {
+ this.instancedBuffers = {};
+ for (const instance of this.instances) {
+ instance.instancedBuffers = {};
+ }
+ }
+ if (!this._userInstancedBuffersStorage) {
+ this._userInstancedBuffersStorage = {
+ data: {},
+ vertexBuffers: {},
+ strides: {},
+ sizes: {},
+ vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined,
+ };
+ }
+ // Creates an empty property for this kind
+ this.instancedBuffers[kind] = null;
+ this._userInstancedBuffersStorage.strides[kind] = stride;
+ this._userInstancedBuffersStorage.sizes[kind] = stride * 32; // Initial size
+ this._userInstancedBuffersStorage.data[kind] = new Float32Array(this._userInstancedBuffersStorage.sizes[kind]);
+ this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true);
+ for (const instance of this.instances) {
+ instance.instancedBuffers[kind] = null;
+ }
+ this._invalidateInstanceVertexArrayObject();
+ this._markSubMeshesAsAttributesDirty();
+};
+Mesh.prototype._processInstancedBuffers = function (visibleInstances, renderSelf) {
+ const instanceCount = visibleInstances ? visibleInstances.length : 0;
+ for (const kind in this.instancedBuffers) {
+ let size = this._userInstancedBuffersStorage.sizes[kind];
+ const stride = this._userInstancedBuffersStorage.strides[kind];
+ // Resize if required
+ const expectedSize = (instanceCount + 1) * stride;
+ while (size < expectedSize) {
+ size *= 2;
+ }
+ if (this._userInstancedBuffersStorage.data[kind].length != size) {
+ this._userInstancedBuffersStorage.data[kind] = new Float32Array(size);
+ this._userInstancedBuffersStorage.sizes[kind] = size;
+ if (this._userInstancedBuffersStorage.vertexBuffers[kind]) {
+ this._userInstancedBuffersStorage.vertexBuffers[kind].dispose();
+ this._userInstancedBuffersStorage.vertexBuffers[kind] = null;
+ }
+ }
+ const data = this._userInstancedBuffersStorage.data[kind];
+ // Update data buffer
+ let offset = 0;
+ if (renderSelf) {
+ const value = this.instancedBuffers[kind];
+ if (value.toArray) {
+ value.toArray(data, offset);
+ }
+ else if (value.copyToArray) {
+ value.copyToArray(data, offset);
+ }
+ else {
+ data[offset] = value;
+ }
+ offset += stride;
+ }
+ for (let instanceIndex = 0; instanceIndex < instanceCount; instanceIndex++) {
+ const instance = visibleInstances[instanceIndex];
+ const value = instance.instancedBuffers[kind];
+ if (value.toArray) {
+ value.toArray(data, offset);
+ }
+ else if (value.copyToArray) {
+ value.copyToArray(data, offset);
+ }
+ else {
+ data[offset] = value;
+ }
+ offset += stride;
+ }
+ // Update vertex buffer
+ if (!this._userInstancedBuffersStorage.vertexBuffers[kind]) {
+ this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true);
+ this._invalidateInstanceVertexArrayObject();
+ }
+ else {
+ this._userInstancedBuffersStorage.vertexBuffers[kind].updateDirectly(data, 0);
+ }
+ }
+};
+Mesh.prototype._invalidateInstanceVertexArrayObject = function () {
+ if (!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === undefined) {
+ return;
+ }
+ for (const kind in this._userInstancedBuffersStorage.vertexArrayObjects) {
+ this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[kind]);
+ }
+ this._userInstancedBuffersStorage.vertexArrayObjects = {};
+};
+Mesh.prototype._disposeInstanceSpecificData = function () {
+ if (this._instanceDataStorage.instancesBuffer) {
+ this._instanceDataStorage.instancesBuffer.dispose();
+ this._instanceDataStorage.instancesBuffer = null;
+ }
+ while (this.instances.length) {
+ this.instances[0].dispose();
+ }
+ for (const kind in this.instancedBuffers) {
+ if (this._userInstancedBuffersStorage.vertexBuffers[kind]) {
+ this._userInstancedBuffersStorage.vertexBuffers[kind].dispose();
+ }
+ }
+ this._invalidateInstanceVertexArrayObject();
+ this.instancedBuffers = {};
+};
+// Register Class Name
+RegisterClass("BABYLON.InstancedMesh", InstancedMesh);
+
+/**
+ * Root class for AssetContainer and KeepAssets
+ */
+class AbstractAssetContainer {
+ constructor() {
+ /**
+ * Gets the list of root nodes (ie. nodes with no parent)
+ */
+ this.rootNodes = [];
+ /** All of the cameras added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras
+ */
+ this.cameras = [];
+ /**
+ * All of the lights added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ */
+ this.lights = [];
+ /**
+ * All of the (abstract) meshes added to this scene
+ */
+ this.meshes = [];
+ /**
+ * The list of skeletons added to the scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons
+ */
+ this.skeletons = [];
+ /**
+ * All of the particle systems added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro
+ */
+ this.particleSystems = [];
+ /**
+ * Gets a list of Animations associated with the scene
+ */
+ this.animations = [];
+ /**
+ * All of the animation groups added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations
+ */
+ this.animationGroups = [];
+ /**
+ * All of the multi-materials added to this scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials
+ */
+ this.multiMaterials = [];
+ /**
+ * All of the materials added to this scene
+ * In the context of a Scene, it is not supposed to be modified manually.
+ * Any addition or removal should be done using the addMaterial and removeMaterial Scene methods.
+ * Note also that the order of the Material within the array is not significant and might change.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction
+ */
+ this.materials = [];
+ /**
+ * The list of morph target managers added to the scene
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph
+ */
+ this.morphTargetManagers = [];
+ /**
+ * The list of geometries used in the scene.
+ */
+ this.geometries = [];
+ /**
+ * All of the transform nodes added to this scene
+ * In the context of a Scene, it is not supposed to be modified manually.
+ * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
+ * Note also that the order of the TransformNode within the array is not significant and might change.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node
+ */
+ this.transformNodes = [];
+ /**
+ * ActionManagers available on the scene.
+ * @deprecated
+ */
+ this.actionManagers = [];
+ /**
+ * Textures to keep.
+ */
+ this.textures = [];
+ /** @internal */
+ this._environmentTexture = null;
+ /**
+ * The list of postprocesses added to the scene
+ */
+ this.postProcesses = [];
+ /**
+ * The list of sounds
+ */
+ this.sounds = null;
+ /**
+ * The list of effect layers added to the scene
+ */
+ this.effectLayers = [];
+ /**
+ * The list of layers added to the scene
+ */
+ this.layers = [];
+ /**
+ * The list of reflection probes added to the scene
+ */
+ this.reflectionProbes = [];
+ }
+ /**
+ * Texture used in all pbr material as the reflection texture.
+ * As in the majority of the scene they are the same (exception for multi room and so on),
+ * this is easier to reference from here than from all the materials.
+ */
+ get environmentTexture() {
+ return this._environmentTexture;
+ }
+ set environmentTexture(value) {
+ this._environmentTexture = value;
+ }
+ /**
+ * @returns all meshes, lights, cameras, transformNodes and bones
+ */
+ getNodes() {
+ let nodes = [];
+ nodes = nodes.concat(this.meshes);
+ nodes = nodes.concat(this.lights);
+ nodes = nodes.concat(this.cameras);
+ nodes = nodes.concat(this.transformNodes); // dummies
+ this.skeletons.forEach((skeleton) => (nodes = nodes.concat(skeleton.bones)));
+ return nodes;
+ }
+}
+/**
+ * Set of assets to keep when moving a scene into an asset container.
+ */
+class KeepAssets extends AbstractAssetContainer {
+}
+/**
+ * Class used to store the output of the AssetContainer.instantiateAllMeshesToScene function
+ */
+class InstantiatedEntries {
+ constructor() {
+ /**
+ * List of new root nodes (eg. nodes with no parent)
+ */
+ this.rootNodes = [];
+ /**
+ * List of new skeletons
+ */
+ this.skeletons = [];
+ /**
+ * List of new animation groups
+ */
+ this.animationGroups = [];
+ }
+ /**
+ * Disposes the instantiated entries from the scene
+ */
+ dispose() {
+ this.rootNodes.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.rootNodes.length = 0;
+ this.skeletons.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.skeletons.length = 0;
+ this.animationGroups.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.animationGroups.length = 0;
+ }
+}
+/**
+ * Container with a set of assets that can be added or removed from a scene.
+ */
+class AssetContainer extends AbstractAssetContainer {
+ /**
+ * Instantiates an AssetContainer.
+ * @param scene The scene the AssetContainer belongs to.
+ */
+ constructor(scene) {
+ super();
+ this._wasAddedToScene = false;
+ scene = scene || EngineStore.LastCreatedScene;
+ if (!scene) {
+ return;
+ }
+ this.scene = scene;
+ this["proceduralTextures"] = [];
+ scene.onDisposeObservable.add(() => {
+ if (!this._wasAddedToScene) {
+ this.dispose();
+ }
+ });
+ this._onContextRestoredObserver = scene.getEngine().onContextRestoredObservable.add(() => {
+ for (const geometry of this.geometries) {
+ geometry._rebuild();
+ }
+ for (const mesh of this.meshes) {
+ mesh._rebuild();
+ }
+ for (const system of this.particleSystems) {
+ system.rebuild();
+ }
+ for (const texture of this.textures) {
+ texture._rebuild();
+ }
+ });
+ }
+ /**
+ * Given a list of nodes, return a topological sorting of them.
+ * @param nodes
+ * @returns a sorted array of nodes
+ */
+ _topologicalSort(nodes) {
+ const nodesUidMap = new Map();
+ for (const node of nodes) {
+ nodesUidMap.set(node.uniqueId, node);
+ }
+ const dependencyGraph = {
+ dependsOn: new Map(), // given a node id, what are the ids of the nodes it depends on
+ dependedBy: new Map(), // given a node id, what are the ids of the nodes that depend on it
+ };
+ // Build the dependency graph given the list of nodes
+ // First pass: Initialize the empty dependency graph
+ for (const node of nodes) {
+ const nodeId = node.uniqueId;
+ dependencyGraph.dependsOn.set(nodeId, new Set());
+ dependencyGraph.dependedBy.set(nodeId, new Set());
+ }
+ // Second pass: Populate the dependency graph. We assume that we
+ // don't need to check for cycles here, as the scene graph cannot
+ // contain cycles. Our graph also already contains all transitive
+ // dependencies because getDescendants returns the transitive
+ // dependencies by default.
+ for (const node of nodes) {
+ const nodeId = node.uniqueId;
+ const dependsOn = dependencyGraph.dependsOn.get(nodeId);
+ if (node instanceof InstancedMesh) {
+ const masterMesh = node.sourceMesh;
+ if (nodesUidMap.has(masterMesh.uniqueId)) {
+ dependsOn.add(masterMesh.uniqueId);
+ dependencyGraph.dependedBy.get(masterMesh.uniqueId).add(nodeId);
+ }
+ }
+ const dependedBy = dependencyGraph.dependedBy.get(nodeId);
+ for (const child of node.getDescendants()) {
+ const childId = child.uniqueId;
+ if (nodesUidMap.has(childId)) {
+ dependedBy.add(childId);
+ const childDependsOn = dependencyGraph.dependsOn.get(childId);
+ childDependsOn.add(nodeId);
+ }
+ }
+ }
+ // Third pass: Topological sort
+ const sortedNodes = [];
+ // First: Find all nodes that have no dependencies
+ const leaves = [];
+ for (const node of nodes) {
+ const nodeId = node.uniqueId;
+ if (dependencyGraph.dependsOn.get(nodeId).size === 0) {
+ leaves.push(node);
+ nodesUidMap.delete(nodeId);
+ }
+ }
+ const visitList = leaves;
+ while (visitList.length > 0) {
+ const nodeToVisit = visitList.shift();
+ sortedNodes.push(nodeToVisit);
+ // Remove the node from the dependency graph
+ // When a node is visited, we know that dependsOn is empty.
+ // So we only need to remove the node from dependedBy.
+ const dependedByVisitedNode = dependencyGraph.dependedBy.get(nodeToVisit.uniqueId);
+ // Array.from(x.values()) is to make the TS compiler happy
+ for (const dependedByVisitedNodeId of Array.from(dependedByVisitedNode.values())) {
+ const dependsOnDependedByVisitedNode = dependencyGraph.dependsOn.get(dependedByVisitedNodeId);
+ dependsOnDependedByVisitedNode.delete(nodeToVisit.uniqueId);
+ if (dependsOnDependedByVisitedNode.size === 0 && nodesUidMap.get(dependedByVisitedNodeId)) {
+ visitList.push(nodesUidMap.get(dependedByVisitedNodeId));
+ nodesUidMap.delete(dependedByVisitedNodeId);
+ }
+ }
+ }
+ if (nodesUidMap.size > 0) {
+ Logger.Error("SceneSerializer._topologicalSort: There were unvisited nodes:");
+ nodesUidMap.forEach((node) => Logger.Error(node.name));
+ }
+ return sortedNodes;
+ }
+ _addNodeAndDescendantsToList(list, addedIds, rootNode, predicate) {
+ if (!rootNode || (predicate && !predicate(rootNode)) || addedIds.has(rootNode.uniqueId)) {
+ return;
+ }
+ list.push(rootNode);
+ addedIds.add(rootNode.uniqueId);
+ for (const child of rootNode.getDescendants(true)) {
+ this._addNodeAndDescendantsToList(list, addedIds, child, predicate);
+ }
+ }
+ /**
+ * Check if a specific node is contained in this asset container.
+ * @param node the node to check
+ * @returns true if the node is contained in this container, otherwise false.
+ */
+ _isNodeInContainer(node) {
+ if (node instanceof AbstractMesh && this.meshes.indexOf(node) !== -1) {
+ return true;
+ }
+ if (node instanceof TransformNode && this.transformNodes.indexOf(node) !== -1) {
+ return true;
+ }
+ if (node instanceof Light && this.lights.indexOf(node) !== -1) {
+ return true;
+ }
+ if (node instanceof Camera && this.cameras.indexOf(node) !== -1) {
+ return true;
+ }
+ return false;
+ }
+ /**
+ * For every node in the scene, check if its parent node is also in the scene.
+ * @returns true if every node's parent is also in the scene, otherwise false.
+ */
+ _isValidHierarchy() {
+ for (const node of this.meshes) {
+ if (node.parent && !this._isNodeInContainer(node.parent)) {
+ Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);
+ return false;
+ }
+ }
+ for (const node of this.transformNodes) {
+ if (node.parent && !this._isNodeInContainer(node.parent)) {
+ Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);
+ return false;
+ }
+ }
+ for (const node of this.lights) {
+ if (node.parent && !this._isNodeInContainer(node.parent)) {
+ Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);
+ return false;
+ }
+ }
+ for (const node of this.cameras) {
+ if (node.parent && !this._isNodeInContainer(node.parent)) {
+ Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Instantiate or clone all meshes and add the new ones to the scene.
+ * Skeletons and animation groups will all be cloned
+ * @param nameFunction defines an optional function used to get new names for clones
+ * @param cloneMaterials defines an optional boolean that defines if materials must be cloned as well (false by default)
+ * @param options defines an optional list of options to control how to instantiate / clone models
+ * @param options.doNotInstantiate defines if the model must be instantiated or just cloned
+ * @param options.predicate defines a predicate used to filter whih mesh to instantiate/clone
+ * @returns a list of rootNodes, skeletons and animation groups that were duplicated
+ */
+ instantiateModelsToScene(nameFunction, cloneMaterials = false, options) {
+ if (!this._isValidHierarchy()) {
+ Tools.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");
+ }
+ const conversionMap = {};
+ const storeMap = {};
+ const result = new InstantiatedEntries();
+ const alreadySwappedSkeletons = [];
+ const alreadySwappedMaterials = [];
+ const localOptions = {
+ doNotInstantiate: true,
+ ...options,
+ };
+ const onClone = (source, clone) => {
+ conversionMap[source.uniqueId] = clone.uniqueId;
+ storeMap[clone.uniqueId] = clone;
+ if (nameFunction) {
+ clone.name = nameFunction(source.name);
+ }
+ if (clone instanceof Mesh) {
+ const clonedMesh = clone;
+ if (clonedMesh.morphTargetManager) {
+ const oldMorphTargetManager = source.morphTargetManager;
+ clonedMesh.morphTargetManager = oldMorphTargetManager.clone();
+ for (let index = 0; index < oldMorphTargetManager.numTargets; index++) {
+ const oldTarget = oldMorphTargetManager.getTarget(index);
+ const newTarget = clonedMesh.morphTargetManager.getTarget(index);
+ conversionMap[oldTarget.uniqueId] = newTarget.uniqueId;
+ storeMap[newTarget.uniqueId] = newTarget;
+ }
+ }
+ }
+ };
+ const nodesToSort = [];
+ const idsOnSortList = new Set();
+ for (const transformNode of this.transformNodes) {
+ if (transformNode.parent === null) {
+ this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, transformNode, localOptions.predicate);
+ }
+ }
+ for (const mesh of this.meshes) {
+ if (mesh.parent === null) {
+ this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, mesh, localOptions.predicate);
+ }
+ }
+ // Topologically sort nodes by parenting/instancing relationships so that all resources are in place
+ // when a given node is instantiated.
+ const sortedNodes = this._topologicalSort(nodesToSort);
+ const onNewCreated = (source, clone) => {
+ onClone(source, clone);
+ if (source.parent) {
+ const replicatedParentId = conversionMap[source.parent.uniqueId];
+ const replicatedParent = storeMap[replicatedParentId];
+ if (replicatedParent) {
+ clone.parent = replicatedParent;
+ }
+ else {
+ clone.parent = source.parent;
+ }
+ }
+ if (clone.position && source.position) {
+ clone.position.copyFrom(source.position);
+ }
+ if (clone.rotationQuaternion && source.rotationQuaternion) {
+ clone.rotationQuaternion.copyFrom(source.rotationQuaternion);
+ }
+ if (clone.rotation && source.rotation) {
+ clone.rotation.copyFrom(source.rotation);
+ }
+ if (clone.scaling && source.scaling) {
+ clone.scaling.copyFrom(source.scaling);
+ }
+ if (clone.material) {
+ const mesh = clone;
+ if (mesh.material) {
+ if (cloneMaterials) {
+ const sourceMaterial = source.material;
+ if (alreadySwappedMaterials.indexOf(sourceMaterial) === -1) {
+ let swap = sourceMaterial.clone(nameFunction ? nameFunction(sourceMaterial.name) : "Clone of " + sourceMaterial.name);
+ alreadySwappedMaterials.push(sourceMaterial);
+ conversionMap[sourceMaterial.uniqueId] = swap.uniqueId;
+ storeMap[swap.uniqueId] = swap;
+ if (sourceMaterial.getClassName() === "MultiMaterial") {
+ const multi = sourceMaterial;
+ for (const material of multi.subMaterials) {
+ if (!material) {
+ continue;
+ }
+ swap = material.clone(nameFunction ? nameFunction(material.name) : "Clone of " + material.name);
+ alreadySwappedMaterials.push(material);
+ conversionMap[material.uniqueId] = swap.uniqueId;
+ storeMap[swap.uniqueId] = swap;
+ }
+ multi.subMaterials = multi.subMaterials.map((m) => m && storeMap[conversionMap[m.uniqueId]]);
+ }
+ }
+ if (mesh.getClassName() !== "InstancedMesh") {
+ mesh.material = storeMap[conversionMap[sourceMaterial.uniqueId]];
+ }
+ }
+ else {
+ if (mesh.material.getClassName() === "MultiMaterial") {
+ if (this.scene.multiMaterials.indexOf(mesh.material) === -1) {
+ this.scene.addMultiMaterial(mesh.material);
+ }
+ }
+ else {
+ if (this.scene.materials.indexOf(mesh.material) === -1) {
+ this.scene.addMaterial(mesh.material);
+ }
+ }
+ }
+ }
+ }
+ if (clone.parent === null) {
+ result.rootNodes.push(clone);
+ }
+ };
+ sortedNodes.forEach((node) => {
+ if (node.getClassName() === "InstancedMesh") {
+ const instancedNode = node;
+ const sourceMesh = instancedNode.sourceMesh;
+ const replicatedSourceId = conversionMap[sourceMesh.uniqueId];
+ const replicatedSource = typeof replicatedSourceId === "number" ? storeMap[replicatedSourceId] : sourceMesh;
+ const replicatedInstancedNode = replicatedSource.createInstance(instancedNode.name);
+ onNewCreated(instancedNode, replicatedInstancedNode);
+ }
+ else {
+ // Mesh or TransformNode
+ let canInstance = true;
+ if (node.getClassName() === "TransformNode" ||
+ node.getClassName() === "Node" ||
+ node.skeleton ||
+ !node.getTotalVertices ||
+ node.getTotalVertices() === 0) {
+ // Transform nodes, skinned meshes, and meshes with no vertices can never be instanced!
+ canInstance = false;
+ }
+ else if (localOptions.doNotInstantiate) {
+ if (typeof localOptions.doNotInstantiate === "function") {
+ canInstance = !localOptions.doNotInstantiate(node);
+ }
+ else {
+ canInstance = !localOptions.doNotInstantiate;
+ }
+ }
+ const replicatedNode = canInstance ? node.createInstance(`instance of ${node.name}`) : node.clone(`Clone of ${node.name}`, null, true);
+ if (!replicatedNode) {
+ throw new Error(`Could not clone or instantiate node on Asset Container ${node.name}`);
+ }
+ onNewCreated(node, replicatedNode);
+ }
+ });
+ this.skeletons.forEach((s) => {
+ if (localOptions.predicate && !localOptions.predicate(s)) {
+ return;
+ }
+ const clone = s.clone(nameFunction ? nameFunction(s.name) : "Clone of " + s.name);
+ for (const m of this.meshes) {
+ if (m.skeleton === s && !m.isAnInstance) {
+ const copy = storeMap[conversionMap[m.uniqueId]];
+ if (!copy || copy.isAnInstance) {
+ continue;
+ }
+ copy.skeleton = clone;
+ if (alreadySwappedSkeletons.indexOf(clone) !== -1) {
+ continue;
+ }
+ alreadySwappedSkeletons.push(clone);
+ // Check if bones are mesh linked
+ for (const bone of clone.bones) {
+ if (bone._linkedTransformNode) {
+ bone._linkedTransformNode = storeMap[conversionMap[bone._linkedTransformNode.uniqueId]];
+ }
+ }
+ }
+ }
+ result.skeletons.push(clone);
+ });
+ this.animationGroups.forEach((o) => {
+ if (localOptions.predicate && !localOptions.predicate(o)) {
+ return;
+ }
+ const clone = o.clone(nameFunction ? nameFunction(o.name) : "Clone of " + o.name, (oldTarget) => {
+ const newTarget = storeMap[conversionMap[oldTarget.uniqueId]];
+ return newTarget || oldTarget;
+ });
+ result.animationGroups.push(clone);
+ });
+ return result;
+ }
+ /**
+ * Adds all the assets from the container to the scene.
+ */
+ addAllToScene() {
+ if (this._wasAddedToScene) {
+ return;
+ }
+ if (!this._isValidHierarchy()) {
+ Tools.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid.");
+ }
+ this._wasAddedToScene = true;
+ this.addToScene(null);
+ if (this.environmentTexture) {
+ this.scene.environmentTexture = this.environmentTexture;
+ }
+ for (const component of this.scene._serializableComponents) {
+ component.addFromContainer(this);
+ }
+ this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
+ this._onContextRestoredObserver = null;
+ }
+ /**
+ * Adds assets from the container to the scene.
+ * @param predicate defines a predicate used to select which entity will be added (can be null)
+ */
+ addToScene(predicate = null) {
+ const addedNodes = [];
+ this.cameras.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addCamera(o);
+ addedNodes.push(o);
+ });
+ this.lights.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addLight(o);
+ addedNodes.push(o);
+ });
+ this.meshes.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addMesh(o);
+ addedNodes.push(o);
+ });
+ this.skeletons.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addSkeleton(o);
+ });
+ this.animations.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addAnimation(o);
+ });
+ this.animationGroups.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addAnimationGroup(o);
+ });
+ this.multiMaterials.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addMultiMaterial(o);
+ });
+ this.materials.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addMaterial(o);
+ });
+ this.morphTargetManagers.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addMorphTargetManager(o);
+ });
+ this.geometries.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addGeometry(o);
+ });
+ this.transformNodes.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addTransformNode(o);
+ addedNodes.push(o);
+ });
+ this.actionManagers.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addActionManager(o);
+ });
+ this.textures.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addTexture(o);
+ });
+ this.reflectionProbes.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.addReflectionProbe(o);
+ });
+ for (const addedNode of addedNodes) {
+ // If node was added to the scene, but parent is not in the scene, break the relationship
+ if (addedNode.parent && this.scene.getNodes().indexOf(addedNode.parent) === -1) {
+ // Use setParent to keep transform if possible
+ if (addedNode.setParent) {
+ addedNode.setParent(null);
+ }
+ else {
+ addedNode.parent = null;
+ }
+ }
+ }
+ }
+ /**
+ * Removes all the assets in the container from the scene
+ */
+ removeAllFromScene() {
+ if (!this._isValidHierarchy()) {
+ Tools.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid.");
+ }
+ this._wasAddedToScene = false;
+ this.removeFromScene(null);
+ if (this.environmentTexture === this.scene.environmentTexture) {
+ this.scene.environmentTexture = null;
+ }
+ for (const component of this.scene._serializableComponents) {
+ component.removeFromContainer(this);
+ }
+ }
+ /**
+ * Removes assets in the container from the scene
+ * @param predicate defines a predicate used to select which entity will be added (can be null)
+ */
+ removeFromScene(predicate = null) {
+ this.cameras.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeCamera(o);
+ });
+ this.lights.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeLight(o);
+ });
+ this.meshes.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeMesh(o, true);
+ });
+ this.skeletons.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeSkeleton(o);
+ });
+ this.animations.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeAnimation(o);
+ });
+ this.animationGroups.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeAnimationGroup(o);
+ });
+ this.multiMaterials.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeMultiMaterial(o);
+ });
+ this.materials.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeMaterial(o);
+ });
+ this.morphTargetManagers.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeMorphTargetManager(o);
+ });
+ this.geometries.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeGeometry(o);
+ });
+ this.transformNodes.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeTransformNode(o);
+ });
+ this.actionManagers.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeActionManager(o);
+ });
+ this.textures.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeTexture(o);
+ });
+ this.reflectionProbes.forEach((o) => {
+ if (predicate && !predicate(o)) {
+ return;
+ }
+ this.scene.removeReflectionProbe(o);
+ });
+ }
+ /**
+ * Disposes all the assets in the container
+ */
+ dispose() {
+ this.cameras.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.cameras.length = 0;
+ this.lights.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.lights.length = 0;
+ this.meshes.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.meshes.length = 0;
+ this.skeletons.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.skeletons.length = 0;
+ this.animationGroups.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.animationGroups.length = 0;
+ this.multiMaterials.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.multiMaterials.length = 0;
+ this.materials.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.materials.length = 0;
+ this.geometries.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.geometries.length = 0;
+ this.transformNodes.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.transformNodes.length = 0;
+ this.actionManagers.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.actionManagers.length = 0;
+ this.textures.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.textures.length = 0;
+ this.reflectionProbes.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.reflectionProbes.length = 0;
+ this.morphTargetManagers.slice(0).forEach((o) => {
+ o.dispose();
+ });
+ this.morphTargetManagers.length = 0;
+ if (this.environmentTexture) {
+ this.environmentTexture.dispose();
+ this.environmentTexture = null;
+ }
+ for (const component of this.scene._serializableComponents) {
+ component.removeFromContainer(this, true);
+ }
+ if (this._onContextRestoredObserver) {
+ this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
+ this._onContextRestoredObserver = null;
+ }
+ }
+ _moveAssets(sourceAssets, targetAssets, keepAssets) {
+ if (!sourceAssets || !targetAssets) {
+ return;
+ }
+ for (const asset of sourceAssets) {
+ let move = true;
+ if (keepAssets) {
+ for (const keepAsset of keepAssets) {
+ if (asset === keepAsset) {
+ move = false;
+ break;
+ }
+ }
+ }
+ if (move) {
+ targetAssets.push(asset);
+ asset._parentContainer = this;
+ }
+ }
+ }
+ /**
+ * Removes all the assets contained in the scene and adds them to the container.
+ * @param keepAssets Set of assets to keep in the scene. (default: empty)
+ */
+ moveAllFromScene(keepAssets) {
+ this._wasAddedToScene = false;
+ if (keepAssets === undefined) {
+ keepAssets = new KeepAssets();
+ }
+ for (const key in this) {
+ if (Object.prototype.hasOwnProperty.call(this, key)) {
+ this[key] = this[key] || (key === "_environmentTexture" ? null : []);
+ this._moveAssets(this.scene[key], this[key], keepAssets[key]);
+ }
+ }
+ this.environmentTexture = this.scene.environmentTexture;
+ this.removeAllFromScene();
+ }
+ /**
+ * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
+ * @returns the root mesh
+ */
+ createRootMesh() {
+ const rootMesh = new Mesh("assetContainerRootMesh", this.scene);
+ this.meshes.forEach((m) => {
+ if (!m.parent) {
+ rootMesh.addChild(m);
+ }
+ });
+ this.meshes.unshift(rootMesh);
+ return rootMesh;
+ }
+ /**
+ * Merge animations (direct and animation groups) from this asset container into a scene
+ * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
+ * @param animatables set of animatables to retarget to a node from the scene
+ * @param targetConverter defines a function used to convert animation targets from the asset container to the scene (default: search node by name)
+ * @returns an array of the new AnimationGroup added to the scene (empty array if none)
+ */
+ mergeAnimationsTo(scene = EngineStore.LastCreatedScene, animatables, targetConverter = null) {
+ if (!scene) {
+ Logger.Error("No scene available to merge animations to");
+ return [];
+ }
+ const _targetConverter = targetConverter
+ ? targetConverter
+ : (target) => {
+ let node = null;
+ const targetProperty = target.animations.length ? target.animations[0].targetProperty : "";
+ /*
+ BabylonJS adds special naming to targets that are children of nodes.
+ This name attempts to remove that special naming to get the parent nodes name in case the target
+ can't be found in the node tree
+
+ Ex: Torso_primitive0 likely points to a Mesh primitive. We take away primitive0 and are left with "Torso" which is the name
+ of the primitive's parent.
+ */
+ const name = target.name.split(".").join("").split("_primitive")[0];
+ switch (targetProperty) {
+ case "position":
+ case "rotationQuaternion":
+ node = scene.getTransformNodeByName(target.name) || scene.getTransformNodeByName(name);
+ break;
+ case "influence":
+ node = scene.getMorphTargetByName(target.name) || scene.getMorphTargetByName(name);
+ break;
+ default:
+ node = scene.getNodeByName(target.name) || scene.getNodeByName(name);
+ }
+ return node;
+ };
+ // Copy new node animations
+ const nodesInAC = this.getNodes();
+ nodesInAC.forEach((nodeInAC) => {
+ const nodeInScene = _targetConverter(nodeInAC);
+ if (nodeInScene !== null) {
+ // Remove old animations with same target property as a new one
+ for (const animationInAC of nodeInAC.animations) {
+ // Doing treatment on an array for safety measure
+ const animationsWithSameProperty = nodeInScene.animations.filter((animationInScene) => {
+ return animationInScene.targetProperty === animationInAC.targetProperty;
+ });
+ for (const animationWithSameProperty of animationsWithSameProperty) {
+ const index = nodeInScene.animations.indexOf(animationWithSameProperty, 0);
+ if (index > -1) {
+ nodeInScene.animations.splice(index, 1);
+ }
+ }
+ }
+ // Append new animations
+ nodeInScene.animations = nodeInScene.animations.concat(nodeInAC.animations);
+ }
+ });
+ const newAnimationGroups = [];
+ // Copy new animation groups
+ this.animationGroups.slice().forEach((animationGroupInAC) => {
+ // Clone the animation group and all its animatables
+ newAnimationGroups.push(animationGroupInAC.clone(animationGroupInAC.name, _targetConverter));
+ // Remove animatables related to the asset container
+ animationGroupInAC.animatables.forEach((animatable) => {
+ animatable.stop();
+ });
+ });
+ // Retarget animatables
+ animatables.forEach((animatable) => {
+ const target = _targetConverter(animatable.target);
+ if (target) {
+ // Clone the animatable and retarget it
+ scene.beginAnimation(target, animatable.fromFrame, animatable.toFrame, animatable.loopAnimation, animatable.speedRatio, animatable.onAnimationEnd ? animatable.onAnimationEnd : undefined, undefined, true, undefined, animatable.onAnimationLoop ? animatable.onAnimationLoop : undefined);
+ // Stop animation for the target in the asset container
+ scene.stopAnimation(animatable.target);
+ }
+ });
+ return newAnimationGroups;
+ }
+ /**
+ * @since 6.15.0
+ * This method checks for any node that has no parent
+ * and is not in the rootNodes array, and adds the node
+ * there, if so.
+ */
+ populateRootNodes() {
+ this.rootNodes.length = 0;
+ this.meshes.forEach((m) => {
+ if (!m.parent && this.rootNodes.indexOf(m) === -1) {
+ this.rootNodes.push(m);
+ }
+ });
+ this.transformNodes.forEach((t) => {
+ if (!t.parent && this.rootNodes.indexOf(t) === -1) {
+ this.rootNodes.push(t);
+ }
+ });
+ this.lights.forEach((l) => {
+ if (!l.parent && this.rootNodes.indexOf(l) === -1) {
+ this.rootNodes.push(l);
+ }
+ });
+ this.cameras.forEach((c) => {
+ if (!c.parent && this.rootNodes.indexOf(c) === -1) {
+ this.rootNodes.push(c);
+ }
+ });
+ }
+ /**
+ * @since 6.26.0
+ * Given a root asset, this method will traverse its hierarchy and add it, its children and any materials/skeletons/animation groups to the container.
+ * @param root root node
+ */
+ addAllAssetsToContainer(root) {
+ if (!root) {
+ return;
+ }
+ const nodesToVisit = [];
+ const visitedNodes = new Set();
+ nodesToVisit.push(root);
+ while (nodesToVisit.length > 0) {
+ const nodeToVisit = nodesToVisit.pop();
+ if (nodeToVisit instanceof Mesh) {
+ if (nodeToVisit.geometry && this.geometries.indexOf(nodeToVisit.geometry) === -1) {
+ this.geometries.push(nodeToVisit.geometry);
+ }
+ this.meshes.push(nodeToVisit);
+ }
+ else if (nodeToVisit instanceof TransformNode) {
+ this.transformNodes.push(nodeToVisit);
+ }
+ else if (nodeToVisit instanceof Light) {
+ this.lights.push(nodeToVisit);
+ }
+ else if (nodeToVisit instanceof Camera) {
+ this.cameras.push(nodeToVisit);
+ }
+ if (nodeToVisit instanceof AbstractMesh) {
+ if (nodeToVisit.material && this.materials.indexOf(nodeToVisit.material) === -1) {
+ this.materials.push(nodeToVisit.material);
+ for (const texture of nodeToVisit.material.getActiveTextures()) {
+ if (this.textures.indexOf(texture) === -1) {
+ this.textures.push(texture);
+ }
+ }
+ }
+ if (nodeToVisit.skeleton && this.skeletons.indexOf(nodeToVisit.skeleton) === -1) {
+ this.skeletons.push(nodeToVisit.skeleton);
+ }
+ if (nodeToVisit.morphTargetManager && this.morphTargetManagers.indexOf(nodeToVisit.morphTargetManager) === -1) {
+ this.morphTargetManagers.push(nodeToVisit.morphTargetManager);
+ }
+ }
+ for (const child of nodeToVisit.getChildren()) {
+ if (!visitedNodes.has(child)) {
+ nodesToVisit.push(child);
+ }
+ }
+ visitedNodes.add(nodeToVisit);
+ }
+ this.populateRootNodes();
+ }
+ /**
+ * Get from a list of objects by tags
+ * @param list the list of objects to use
+ * @param tagsQuery the query to use
+ * @param filter a predicate to filter for tags
+ * @returns
+ */
+ _getByTags(list, tagsQuery, filter) {
+ if (tagsQuery === undefined) {
+ // returns the complete list (could be done with Tags.MatchesQuery but no need to have a for-loop here)
+ return list;
+ }
+ const listByTags = [];
+ for (const i in list) {
+ const item = list[i];
+ if (Tags && Tags.MatchesQuery(item, tagsQuery) && (!filter || filter(item))) {
+ listByTags.push(item);
+ }
+ }
+ return listByTags;
+ }
+ /**
+ * Get a list of meshes by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of Mesh
+ */
+ getMeshesByTags(tagsQuery, filter) {
+ return this._getByTags(this.meshes, tagsQuery, filter);
+ }
+ /**
+ * Get a list of cameras by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of Camera
+ */
+ getCamerasByTags(tagsQuery, filter) {
+ return this._getByTags(this.cameras, tagsQuery, filter);
+ }
+ /**
+ * Get a list of lights by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of Light
+ */
+ getLightsByTags(tagsQuery, filter) {
+ return this._getByTags(this.lights, tagsQuery, filter);
+ }
+ /**
+ * Get a list of materials by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of Material
+ */
+ getMaterialsByTags(tagsQuery, filter) {
+ return this._getByTags(this.materials, tagsQuery, filter).concat(this._getByTags(this.multiMaterials, tagsQuery, filter));
+ }
+ /**
+ * Get a list of transform nodes by tags
+ * @param tagsQuery defines the tags query to use
+ * @param filter defines a predicate used to filter results
+ * @returns an array of TransformNode
+ */
+ getTransformNodesByTags(tagsQuery, filter) {
+ return this._getByTags(this.transformNodes, tagsQuery, filter);
+ }
+}
+
+/**
+ * Utility class for reading from a data buffer
+ */
+class DataReader {
+ /**
+ * Constructor
+ * @param buffer The buffer to read
+ */
+ constructor(buffer) {
+ /**
+ * The current byte offset from the beginning of the data buffer.
+ */
+ this.byteOffset = 0;
+ this.buffer = buffer;
+ }
+ /**
+ * Loads the given byte length.
+ * @param byteLength The byte length to load
+ * @returns A promise that resolves when the load is complete
+ */
+ loadAsync(byteLength) {
+ return this.buffer.readAsync(this.byteOffset, byteLength).then((data) => {
+ this._dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
+ this._dataByteOffset = 0;
+ });
+ }
+ /**
+ * Read a unsigned 32-bit integer from the currently loaded data range.
+ * @returns The 32-bit integer read
+ */
+ readUint32() {
+ const value = this._dataView.getUint32(this._dataByteOffset, true);
+ this._dataByteOffset += 4;
+ this.byteOffset += 4;
+ return value;
+ }
+ /**
+ * Read a byte array from the currently loaded data range.
+ * @param byteLength The byte length to read
+ * @returns The byte array read
+ */
+ readUint8Array(byteLength) {
+ const value = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._dataByteOffset, byteLength);
+ this._dataByteOffset += byteLength;
+ this.byteOffset += byteLength;
+ return value;
+ }
+ /**
+ * Read a string from the currently loaded data range.
+ * @param byteLength The byte length to read
+ * @returns The string read
+ */
+ readString(byteLength) {
+ return Decode(this.readUint8Array(byteLength));
+ }
+ /**
+ * Skips the given byte length the currently loaded data range.
+ * @param byteLength The byte length to skip
+ */
+ skipBytes(byteLength) {
+ this._dataByteOffset += byteLength;
+ this.byteOffset += byteLength;
+ }
+}
+
+function validateAsync(data, rootUrl, fileName, getExternalResource) {
+ const options = {
+ externalResourceFunction: getExternalResource,
+ };
+ if (fileName) {
+ options.uri = rootUrl === "file:" ? fileName : rootUrl + fileName;
+ }
+ return ArrayBuffer.isView(data) ? GLTFValidator.validateBytes(data, options) : GLTFValidator.validateString(data, options);
+}
+/**
+ * The worker function that gets converted to a blob url to pass into a worker.
+ */
+function workerFunc() {
+ const pendingExternalResources = [];
+ onmessage = (message) => {
+ const data = message.data;
+ switch (data.id) {
+ case "init": {
+ importScripts(data.url);
+ break;
+ }
+ case "validate": {
+ validateAsync(data.data, data.rootUrl, data.fileName, (uri) => new Promise((resolve, reject) => {
+ const index = pendingExternalResources.length;
+ pendingExternalResources.push({ resolve, reject });
+ postMessage({ id: "getExternalResource", index: index, uri: uri });
+ })).then((value) => {
+ postMessage({ id: "validate.resolve", value: value });
+ }, (reason) => {
+ postMessage({ id: "validate.reject", reason: reason });
+ });
+ break;
+ }
+ case "getExternalResource.resolve": {
+ pendingExternalResources[data.index].resolve(data.value);
+ break;
+ }
+ case "getExternalResource.reject": {
+ pendingExternalResources[data.index].reject(data.reason);
+ break;
+ }
+ }
+ };
+}
+/**
+ * glTF validation
+ */
+class GLTFValidation {
+ /**
+ * Validate a glTF asset using the glTF-Validator.
+ * @param data The JSON of a glTF or the array buffer of a binary glTF
+ * @param rootUrl The root url for the glTF
+ * @param fileName The file name for the glTF
+ * @param getExternalResource The callback to get external resources for the glTF validator
+ * @returns A promise that resolves with the glTF validation results once complete
+ */
+ static ValidateAsync(data, rootUrl, fileName, getExternalResource) {
+ if (typeof Worker === "function") {
+ return new Promise((resolve, reject) => {
+ const workerContent = `${validateAsync}(${workerFunc})()`;
+ const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" }));
+ const worker = new Worker(workerBlobUrl);
+ const onError = (error) => {
+ worker.removeEventListener("error", onError);
+ worker.removeEventListener("message", onMessage);
+ reject(error);
+ };
+ const onMessage = (message) => {
+ const data = message.data;
+ switch (data.id) {
+ case "getExternalResource": {
+ getExternalResource(data.uri).then((value) => {
+ worker.postMessage({ id: "getExternalResource.resolve", index: data.index, value: value }, [value.buffer]);
+ }, (reason) => {
+ worker.postMessage({ id: "getExternalResource.reject", index: data.index, reason: reason });
+ });
+ break;
+ }
+ case "validate.resolve": {
+ worker.removeEventListener("error", onError);
+ worker.removeEventListener("message", onMessage);
+ resolve(data.value);
+ worker.terminate();
+ break;
+ }
+ case "validate.reject": {
+ worker.removeEventListener("error", onError);
+ worker.removeEventListener("message", onMessage);
+ reject(data.reason);
+ worker.terminate();
+ }
+ }
+ };
+ worker.addEventListener("error", onError);
+ worker.addEventListener("message", onMessage);
+ worker.postMessage({ id: "init", url: Tools.GetBabylonScriptURL(this.Configuration.url) });
+ if (ArrayBuffer.isView(data)) {
+ // Slice the data to avoid copying the whole array buffer.
+ const slicedData = data.slice();
+ worker.postMessage({ id: "validate", data: slicedData, rootUrl: rootUrl, fileName: fileName }, [slicedData.buffer]);
+ }
+ else {
+ worker.postMessage({ id: "validate", data: data, rootUrl: rootUrl, fileName: fileName });
+ }
+ });
+ }
+ else {
+ if (!this._LoadScriptPromise) {
+ this._LoadScriptPromise = Tools.LoadBabylonScriptAsync(this.Configuration.url);
+ }
+ return this._LoadScriptPromise.then(() => {
+ return validateAsync(data, rootUrl, fileName, getExternalResource);
+ });
+ }
+ }
+}
+/**
+ * The configuration. Defaults to `{ url: "https://cdn.babylonjs.com/gltf_validator.js" }`.
+ */
+GLTFValidation.Configuration = {
+ url: `${Tools._DefaultCdnUrl}/gltf_validator.js`,
+};
+
+const GLTFMagicBase64Encoded = "Z2xURg"; // "glTF" base64 encoded (without the quotes!)
+const GLTFFileLoaderMetadata = {
+ name: "gltf",
+ extensions: {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ ".gltf": { isBinary: false, mimeType: "model/gltf+json" },
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ ".glb": { isBinary: true, mimeType: "model/gltf-binary" },
+ },
+ canDirectLoad(data) {
+ return ((data.indexOf("asset") !== -1 && data.indexOf("version") !== -1) ||
+ data.startsWith("data:base64," + GLTFMagicBase64Encoded) || // this is technically incorrect, but will continue to support for backcompat.
+ data.startsWith("data:;base64," + GLTFMagicBase64Encoded) ||
+ data.startsWith("data:application/octet-stream;base64," + GLTFMagicBase64Encoded) ||
+ data.startsWith("data:model/gltf-binary;base64," + GLTFMagicBase64Encoded));
+ },
+};
+
+function readAsync(arrayBuffer, byteOffset, byteLength) {
+ try {
+ return Promise.resolve(new Uint8Array(arrayBuffer, byteOffset, byteLength));
+ }
+ catch (e) {
+ return Promise.reject(e);
+ }
+}
+function readViewAsync(arrayBufferView, byteOffset, byteLength) {
+ try {
+ if (byteOffset < 0 || byteOffset >= arrayBufferView.byteLength) {
+ throw new RangeError("Offset is out of range.");
+ }
+ if (byteOffset + byteLength > arrayBufferView.byteLength) {
+ throw new RangeError("Length is out of range.");
+ }
+ return Promise.resolve(new Uint8Array(arrayBufferView.buffer, arrayBufferView.byteOffset + byteOffset, byteLength));
+ }
+ catch (e) {
+ return Promise.reject(e);
+ }
+}
+/**
+ * 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 || (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 || (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 || (GLTFLoaderState = {}));
+class GLTFLoaderOptions {
+ constructor() {
+ // ----------
+ // 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 load node animations. Defaults to true.
+ * NOTE: The animation of this node will still load if the node is also a joint of a skin and `loadSkins` is true.
+ */
+ this.loadNodeAnimations = true;
+ /**
+ * Defines if the loader should load skins. Defaults to true.
+ */
+ this.loadSkins = true;
+ /**
+ * Defines if the loader should load morph targets. Defaults to true.
+ */
+ this.loadMorphTargets = true;
+ /**
+ * 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;
+ /**
+ * Defines if the loader should use range requests when load binary glTF files from HTTP.
+ * Enabling will disable offline support and glTF validator.
+ * Defaults to false.
+ */
+ this.useRangeRequests = false;
+ /**
+ * Defines if the loader should create instances when multiple glTF nodes point to the same glTF mesh. Defaults to true.
+ */
+ this.createInstances = true;
+ /**
+ * Defines if the loader should always compute the bounding boxes of meshes and not use the min/max values from the position accessor. Defaults to false.
+ */
+ this.alwaysComputeBoundingBox = false;
+ /**
+ * If true, load all materials defined in the file, even if not used by any mesh. Defaults to false.
+ */
+ this.loadAllMaterials = false;
+ /**
+ * If true, load only the materials defined in the file. Defaults to false.
+ */
+ this.loadOnlyMaterials = false;
+ /**
+ * If true, do not load any materials defined in the file. Defaults to false.
+ */
+ this.skipMaterials = false;
+ /**
+ * If true, load the color (gamma encoded) textures into sRGB buffers (if supported by the GPU), which will yield more accurate results when sampling the texture. Defaults to true.
+ */
+ this.useSRGBBuffers = true;
+ /**
+ * When loading glTF animations, which are defined in seconds, target them to this FPS. Defaults to 60.
+ */
+ this.targetFps = 60;
+ /**
+ * Defines if the loader should always compute the nearest common ancestor of the skeleton joints instead of using `skin.skeleton`. Defaults to false.
+ * Set this to true if loading assets with invalid `skin.skeleton` values.
+ */
+ this.alwaysComputeSkeletonRootNode = false;
+ /**
+ * If true, the loader will derive the name for Babylon textures from the glTF texture name, image name, or image url. Defaults to false.
+ * Note that it is possible for multiple Babylon textures to share the same name when the Babylon textures load from the same glTF texture or image.
+ */
+ this.useGltfTextureNames = false;
+ /**
+ * Function called before loading a url referenced by the asset.
+ * @param url url referenced by the asset
+ * @returns Async url to load
+ */
+ this.preprocessUrlAsync = (url) => Promise.resolve(url);
+ /**
+ * Defines options for glTF extensions.
+ */
+ this.extensionOptions = {};
+ }
+ // eslint-disable-next-line babylonjs/available
+ copyFrom(options) {
+ if (options) {
+ this.onParsed = options.onParsed;
+ this.coordinateSystemMode = options.coordinateSystemMode ?? this.coordinateSystemMode;
+ this.animationStartMode = options.animationStartMode ?? this.animationStartMode;
+ this.loadNodeAnimations = options.loadNodeAnimations ?? this.loadNodeAnimations;
+ this.loadSkins = options.loadSkins ?? this.loadSkins;
+ this.loadMorphTargets = options.loadMorphTargets ?? this.loadMorphTargets;
+ this.compileMaterials = options.compileMaterials ?? this.compileMaterials;
+ this.useClipPlane = options.useClipPlane ?? this.useClipPlane;
+ this.compileShadowGenerators = options.compileShadowGenerators ?? this.compileShadowGenerators;
+ this.transparencyAsCoverage = options.transparencyAsCoverage ?? this.transparencyAsCoverage;
+ this.useRangeRequests = options.useRangeRequests ?? this.useRangeRequests;
+ this.createInstances = options.createInstances ?? this.createInstances;
+ this.alwaysComputeBoundingBox = options.alwaysComputeBoundingBox ?? this.alwaysComputeBoundingBox;
+ this.loadAllMaterials = options.loadAllMaterials ?? this.loadAllMaterials;
+ this.loadOnlyMaterials = options.loadOnlyMaterials ?? this.loadOnlyMaterials;
+ this.skipMaterials = options.skipMaterials ?? this.skipMaterials;
+ this.useSRGBBuffers = options.useSRGBBuffers ?? this.useSRGBBuffers;
+ this.targetFps = options.targetFps ?? this.targetFps;
+ this.alwaysComputeSkeletonRootNode = options.alwaysComputeSkeletonRootNode ?? this.alwaysComputeSkeletonRootNode;
+ this.useGltfTextureNames = options.useGltfTextureNames ?? this.useGltfTextureNames;
+ this.preprocessUrlAsync = options.preprocessUrlAsync ?? this.preprocessUrlAsync;
+ this.customRootNode = options.customRootNode;
+ this.onMeshLoaded = options.onMeshLoaded;
+ this.onSkinLoaded = options.onSkinLoaded;
+ this.onTextureLoaded = options.onTextureLoaded;
+ this.onMaterialLoaded = options.onMaterialLoaded;
+ this.onCameraLoaded = options.onCameraLoaded;
+ this.extensionOptions = options.extensionOptions ?? this.extensionOptions;
+ }
+ }
+}
+/**
+ * File loader for loading glTF files into a scene.
+ */
+class GLTFFileLoader extends GLTFLoaderOptions {
+ /**
+ * Creates a new glTF file loader.
+ * @param options The options for the loader
+ */
+ constructor(options) {
+ super();
+ // --------------------
+ // Begin Common options
+ // --------------------
+ /**
+ * Raised when the asset has been parsed
+ */
+ this.onParsedObservable = new Observable();
+ // --------------
+ // End V1 options
+ // --------------
+ /**
+ * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
+ * Note that the observable is raised as soon as the mesh object is created, meaning some data may not have been setup yet for this mesh (vertex data, morph targets, material, ...)
+ */
+ this.onMeshLoadedObservable = new Observable();
+ /**
+ * Observable raised when the loader creates a skin after parsing the glTF properties of the skin node.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/glTF/glTFSkinning#ignoring-the-transform-of-the-skinned-mesh
+ * @param node - the transform node that corresponds to the original glTF skin node used for animations
+ * @param skinnedNode - the transform node that is the skinned mesh itself or the parent of the skinned meshes
+ */
+ this.onSkinLoadedObservable = new Observable();
+ /**
+ * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
+ */
+ this.onTextureLoadedObservable = new Observable();
+ /**
+ * Observable raised when the loader creates a material after parsing the glTF properties of the material.
+ */
+ this.onMaterialLoadedObservable = new Observable();
+ /**
+ * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
+ */
+ this.onCameraLoadedObservable = new 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 Observable();
+ /**
+ * Observable raised when an error occurs.
+ */
+ this.onErrorObservable = new Observable();
+ /**
+ * Observable raised after the loader is disposed.
+ */
+ this.onDisposeObservable = new Observable();
+ /**
+ * Observable raised after a loader extension is created.
+ * Set additional options for a loader extension in this event.
+ */
+ this.onExtensionLoadedObservable = new 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 Observable();
+ this._loader = null;
+ this._state = null;
+ this._requests = new Array();
+ /**
+ * Name of the loader ("gltf")
+ */
+ this.name = GLTFFileLoaderMetadata.name;
+ /** @internal */
+ this.extensions = GLTFFileLoaderMetadata.extensions;
+ /**
+ * Observable raised when the loader state changes.
+ */
+ this.onLoaderStateChangedObservable = new Observable();
+ this._logIndentLevel = 0;
+ this._loggingEnabled = false;
+ /** @internal */
+ this._log = this._logDisabled;
+ this._capturePerformanceCounters = false;
+ /** @internal */
+ this._startPerformanceCounter = this._startPerformanceCounterDisabled;
+ /** @internal */
+ this._endPerformanceCounter = this._endPerformanceCounterDisabled;
+ this.copyFrom(options);
+ }
+ /**
+ * Raised when the asset has been parsed
+ */
+ set onParsed(callback) {
+ if (this._onParsedObserver) {
+ this.onParsedObservable.remove(this._onParsedObserver);
+ }
+ if (callback) {
+ this._onParsedObserver = this.onParsedObservable.add(callback);
+ }
+ }
+ /**
+ * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
+ * Note that the callback is called as soon as the mesh object is created, meaning some data may not have been setup yet for this mesh (vertex data, morph targets, material, ...)
+ */
+ set onMeshLoaded(callback) {
+ if (this._onMeshLoadedObserver) {
+ this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
+ }
+ if (callback) {
+ this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
+ }
+ }
+ /**
+ * Callback raised when the loader creates a skin after parsing the glTF properties of the skin node.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/glTF/glTFSkinning#ignoring-the-transform-of-the-skinned-mesh
+ */
+ set onSkinLoaded(callback) {
+ if (this._onSkinLoadedObserver) {
+ this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver);
+ }
+ if (callback) {
+ this._onSkinLoadedObserver = this.onSkinLoadedObservable.add((data) => callback(data.node, data.skinnedNode));
+ }
+ }
+ /**
+ * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
+ */
+ set onTextureLoaded(callback) {
+ if (this._onTextureLoadedObserver) {
+ this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
+ }
+ if (callback) {
+ this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
+ }
+ }
+ /**
+ * Callback raised when the loader creates a material after parsing the glTF properties of the material.
+ */
+ set onMaterialLoaded(callback) {
+ if (this._onMaterialLoadedObserver) {
+ this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
+ }
+ if (callback) {
+ this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
+ }
+ }
+ /**
+ * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
+ */
+ set onCameraLoaded(callback) {
+ if (this._onCameraLoadedObserver) {
+ this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
+ }
+ if (callback) {
+ this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
+ }
+ }
+ /**
+ * 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 onComplete(callback) {
+ if (this._onCompleteObserver) {
+ this.onCompleteObservable.remove(this._onCompleteObserver);
+ }
+ this._onCompleteObserver = this.onCompleteObservable.add(callback);
+ }
+ /**
+ * Callback raised when an error occurs.
+ */
+ set onError(callback) {
+ if (this._onErrorObserver) {
+ this.onErrorObservable.remove(this._onErrorObserver);
+ }
+ this._onErrorObserver = this.onErrorObservable.add(callback);
+ }
+ /**
+ * Callback raised after the loader is disposed.
+ */
+ set onDispose(callback) {
+ if (this._onDisposeObserver) {
+ this.onDisposeObservable.remove(this._onDisposeObserver);
+ }
+ this._onDisposeObserver = this.onDisposeObservable.add(callback);
+ }
+ /**
+ * Callback raised after a loader extension is created.
+ */
+ set onExtensionLoaded(callback) {
+ if (this._onExtensionLoadedObserver) {
+ this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
+ }
+ this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
+ }
+ /**
+ * Defines if the loader logging is enabled.
+ */
+ get loggingEnabled() {
+ return this._loggingEnabled;
+ }
+ set loggingEnabled(value) {
+ if (this._loggingEnabled === value) {
+ return;
+ }
+ this._loggingEnabled = value;
+ if (this._loggingEnabled) {
+ this._log = this._logEnabled;
+ }
+ else {
+ this._log = this._logDisabled;
+ }
+ }
+ /**
+ * Defines if the loader should capture performance counters.
+ */
+ get capturePerformanceCounters() {
+ return this._capturePerformanceCounters;
+ }
+ set capturePerformanceCounters(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;
+ }
+ }
+ /**
+ * Callback raised after a loader extension is created.
+ */
+ set onValidated(callback) {
+ if (this._onValidatedObserver) {
+ this.onValidatedObservable.remove(this._onValidatedObserver);
+ }
+ this._onValidatedObserver = this.onValidatedObservable.add(callback);
+ }
+ /**
+ * Disposes the loader, releases resources during load, and cancels any outstanding requests.
+ */
+ dispose() {
+ if (this._loader) {
+ this._loader.dispose();
+ this._loader = null;
+ }
+ for (const request of this._requests) {
+ request.abort();
+ }
+ this._requests.length = 0;
+ delete this._progressCallback;
+ this.preprocessUrlAsync = (url) => Promise.resolve(url);
+ this.onMeshLoadedObservable.clear();
+ this.onSkinLoadedObservable.clear();
+ this.onTextureLoadedObservable.clear();
+ this.onMaterialLoadedObservable.clear();
+ this.onCameraLoadedObservable.clear();
+ this.onCompleteObservable.clear();
+ this.onExtensionLoadedObservable.clear();
+ this.onDisposeObservable.notifyObservers(undefined);
+ this.onDisposeObservable.clear();
+ }
+ /**
+ * @internal
+ */
+ loadFile(scene, fileOrUrl, rootUrl, onSuccess, onProgress, useArrayBuffer, onError, name) {
+ if (ArrayBuffer.isView(fileOrUrl)) {
+ this._loadBinary(scene, fileOrUrl, rootUrl, onSuccess, onError, name);
+ return null;
+ }
+ this._progressCallback = onProgress;
+ const fileName = fileOrUrl.name || Tools.GetFilename(fileOrUrl);
+ if (useArrayBuffer) {
+ if (this.useRangeRequests) {
+ if (this.validate) {
+ Logger.Warn("glTF validation is not supported when range requests are enabled");
+ }
+ const fileRequest = {
+ abort: () => { },
+ onCompleteObservable: new Observable(),
+ };
+ const dataBuffer = {
+ readAsync: (byteOffset, byteLength) => {
+ return new Promise((resolve, reject) => {
+ this._loadFile(scene, fileOrUrl, (data) => {
+ resolve(new Uint8Array(data));
+ }, true, (error) => {
+ reject(error);
+ }, (webRequest) => {
+ webRequest.setRequestHeader("Range", `bytes=${byteOffset}-${byteOffset + byteLength - 1}`);
+ });
+ });
+ },
+ byteLength: 0,
+ };
+ this._unpackBinaryAsync(new DataReader(dataBuffer)).then((loaderData) => {
+ fileRequest.onCompleteObservable.notifyObservers(fileRequest);
+ onSuccess(loaderData);
+ }, onError ? (error) => onError(undefined, error) : undefined);
+ return fileRequest;
+ }
+ return this._loadFile(scene, fileOrUrl, (data) => {
+ this._validate(scene, new Uint8Array(data, 0, data.byteLength), rootUrl, fileName);
+ this._unpackBinaryAsync(new DataReader({
+ readAsync: (byteOffset, byteLength) => readAsync(data, byteOffset, byteLength),
+ byteLength: data.byteLength,
+ })).then((loaderData) => {
+ onSuccess(loaderData);
+ }, onError ? (error) => onError(undefined, error) : undefined);
+ }, true, onError);
+ }
+ else {
+ return this._loadFile(scene, fileOrUrl, (data) => {
+ try {
+ this._validate(scene, data, rootUrl, fileName);
+ onSuccess({ json: this._parseJson(data) });
+ }
+ catch {
+ if (onError) {
+ onError();
+ }
+ }
+ }, false, onError);
+ }
+ }
+ _loadBinary(scene, data, rootUrl, onSuccess, onError, fileName) {
+ this._validate(scene, new Uint8Array(data.buffer, data.byteOffset, data.byteLength), rootUrl, fileName);
+ this._unpackBinaryAsync(new DataReader({
+ readAsync: (byteOffset, byteLength) => readViewAsync(data, byteOffset, byteLength),
+ byteLength: data.byteLength,
+ })).then((loaderData) => {
+ onSuccess(loaderData);
+ }, onError ? (error) => onError(undefined, error) : undefined);
+ }
+ /**
+ * @internal
+ */
+ importMeshAsync(meshesNames, scene, data, rootUrl, onProgress, fileName) {
+ return Promise.resolve().then(() => {
+ this.onParsedObservable.notifyObservers(data);
+ this.onParsedObservable.clear();
+ this._log(`Loading ${fileName || ""}`);
+ this._loader = this._getLoader(data);
+ return this._loader.importMeshAsync(meshesNames, scene, null, data, rootUrl, onProgress, fileName);
+ });
+ }
+ /**
+ * @internal
+ */
+ loadAsync(scene, data, rootUrl, onProgress, fileName) {
+ return Promise.resolve().then(() => {
+ this.onParsedObservable.notifyObservers(data);
+ this.onParsedObservable.clear();
+ this._log(`Loading ${fileName || ""}`);
+ this._loader = this._getLoader(data);
+ return this._loader.loadAsync(scene, data, rootUrl, onProgress, fileName);
+ });
+ }
+ /**
+ * @internal
+ */
+ loadAssetContainerAsync(scene, data, rootUrl, onProgress, fileName) {
+ return Promise.resolve().then(() => {
+ this.onParsedObservable.notifyObservers(data);
+ this.onParsedObservable.clear();
+ this._log(`Loading ${fileName || ""}`);
+ this._loader = this._getLoader(data);
+ // Prepare the asset container.
+ const container = new AssetContainer(scene);
+ // Get materials/textures when loading to add to container
+ const materials = [];
+ this.onMaterialLoadedObservable.add((material) => {
+ materials.push(material);
+ });
+ const textures = [];
+ this.onTextureLoadedObservable.add((texture) => {
+ textures.push(texture);
+ });
+ const cameras = [];
+ this.onCameraLoadedObservable.add((camera) => {
+ cameras.push(camera);
+ });
+ const morphTargetManagers = [];
+ this.onMeshLoadedObservable.add((mesh) => {
+ if (mesh.morphTargetManager) {
+ morphTargetManagers.push(mesh.morphTargetManager);
+ }
+ });
+ return this._loader.importMeshAsync(null, scene, container, data, rootUrl, onProgress, fileName).then((result) => {
+ Array.prototype.push.apply(container.geometries, result.geometries);
+ 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);
+ Array.prototype.push.apply(container.materials, materials);
+ Array.prototype.push.apply(container.textures, textures);
+ Array.prototype.push.apply(container.lights, result.lights);
+ Array.prototype.push.apply(container.transformNodes, result.transformNodes);
+ Array.prototype.push.apply(container.cameras, cameras);
+ Array.prototype.push.apply(container.morphTargetManagers, morphTargetManagers);
+ return container;
+ });
+ });
+ }
+ /**
+ * @internal
+ */
+ canDirectLoad(data) {
+ return GLTFFileLoaderMetadata.canDirectLoad(data);
+ }
+ /**
+ * @internal
+ */
+ directLoad(scene, data) {
+ if (data.startsWith("base64," + GLTFMagicBase64Encoded) || // this is technically incorrect, but will continue to support for backcompat.
+ data.startsWith(";base64," + GLTFMagicBase64Encoded) ||
+ data.startsWith("application/octet-stream;base64," + GLTFMagicBase64Encoded) ||
+ data.startsWith("model/gltf-binary;base64," + GLTFMagicBase64Encoded)) {
+ const arrayBuffer = DecodeBase64UrlToBinary(data);
+ this._validate(scene, new Uint8Array(arrayBuffer, 0, arrayBuffer.byteLength));
+ return this._unpackBinaryAsync(new DataReader({
+ readAsync: (byteOffset, byteLength) => readAsync(arrayBuffer, byteOffset, byteLength),
+ byteLength: arrayBuffer.byteLength,
+ }));
+ }
+ this._validate(scene, data);
+ return Promise.resolve({ json: this._parseJson(data) });
+ }
+ /** @internal */
+ createPlugin(options) {
+ return new GLTFFileLoader(options[GLTFFileLoaderMetadata.name]);
+ }
+ /**
+ * The loader state or null if the loader is not active.
+ */
+ get loaderState() {
+ return this._state;
+ }
+ /**
+ * Returns a promise that resolves when the asset is completely loaded.
+ * @returns a promise that resolves when the asset is completely loaded.
+ */
+ whenCompleteAsync() {
+ return new Promise((resolve, reject) => {
+ this.onCompleteObservable.addOnce(() => {
+ resolve();
+ });
+ this.onErrorObservable.addOnce((reason) => {
+ reject(reason);
+ });
+ });
+ }
+ /**
+ * @internal
+ */
+ _setState(state) {
+ if (this._state === state) {
+ return;
+ }
+ this._state = state;
+ this.onLoaderStateChangedObservable.notifyObservers(this._state);
+ this._log(GLTFLoaderState[this._state]);
+ }
+ /**
+ * @internal
+ */
+ _loadFile(scene, fileOrUrl, onSuccess, useArrayBuffer, onError, onOpened) {
+ const request = scene._loadFile(fileOrUrl, onSuccess, (event) => {
+ this._onProgress(event, request);
+ }, true, useArrayBuffer, onError, onOpened);
+ request.onCompleteObservable.add(() => {
+ // Force the length computable to be true since we can guarantee the data is loaded.
+ request._lengthComputable = true;
+ request._total = request._loaded;
+ });
+ this._requests.push(request);
+ return request;
+ }
+ _onProgress(event, request) {
+ if (!this._progressCallback) {
+ return;
+ }
+ request._lengthComputable = event.lengthComputable;
+ request._loaded = event.loaded;
+ request._total = event.total;
+ let lengthComputable = true;
+ let loaded = 0;
+ let total = 0;
+ for (const request of this._requests) {
+ if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
+ return;
+ }
+ lengthComputable = lengthComputable && request._lengthComputable;
+ loaded += request._loaded;
+ total += request._total;
+ }
+ this._progressCallback({
+ lengthComputable: lengthComputable,
+ loaded: loaded,
+ total: lengthComputable ? total : 0,
+ });
+ }
+ _validate(scene, data, rootUrl = "", fileName = "") {
+ if (!this.validate) {
+ return;
+ }
+ this._startPerformanceCounter("Validate JSON");
+ GLTFValidation.ValidateAsync(data, rootUrl, fileName, (uri) => {
+ return this.preprocessUrlAsync(rootUrl + uri).then((url) => {
+ return scene._loadFileAsync(url, undefined, true, true).then((data) => {
+ return new Uint8Array(data, 0, data.byteLength);
+ });
+ });
+ }).then((result) => {
+ this._endPerformanceCounter("Validate JSON");
+ this.onValidatedObservable.notifyObservers(result);
+ this.onValidatedObservable.clear();
+ }, (reason) => {
+ this._endPerformanceCounter("Validate JSON");
+ Tools.Warn(`Failed to validate: ${reason.message}`);
+ this.onValidatedObservable.clear();
+ });
+ }
+ _getLoader(loaderData) {
+ const 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}`);
+ const version = GLTFFileLoader._parseVersion(asset.version);
+ if (!version) {
+ throw new Error("Invalid version: " + asset.version);
+ }
+ if (asset.minVersion !== undefined) {
+ const 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);
+ }
+ }
+ const createLoaders = {
+ 1: GLTFFileLoader._CreateGLTF1Loader,
+ 2: GLTFFileLoader._CreateGLTF2Loader,
+ };
+ const createLoader = createLoaders[version.major];
+ if (!createLoader) {
+ throw new Error("Unsupported version: " + asset.version);
+ }
+ return createLoader(this);
+ }
+ _parseJson(json) {
+ this._startPerformanceCounter("Parse JSON");
+ this._log(`JSON length: ${json.length}`);
+ const parsed = JSON.parse(json);
+ this._endPerformanceCounter("Parse JSON");
+ return parsed;
+ }
+ _unpackBinaryAsync(dataReader) {
+ this._startPerformanceCounter("Unpack Binary");
+ // Read magic + version + length + json length + json format
+ return dataReader.loadAsync(20).then(() => {
+ const Binary = {
+ Magic: 0x46546c67,
+ };
+ const magic = dataReader.readUint32();
+ if (magic !== Binary.Magic) {
+ throw new RuntimeError("Unexpected magic: " + magic, ErrorCodes.GLTFLoaderUnexpectedMagicError);
+ }
+ const version = dataReader.readUint32();
+ if (this.loggingEnabled) {
+ this._log(`Binary version: ${version}`);
+ }
+ const length = dataReader.readUint32();
+ if (!this.useRangeRequests && length !== dataReader.buffer.byteLength) {
+ Logger.Warn(`Length in header does not match actual data length: ${length} != ${dataReader.buffer.byteLength}`);
+ }
+ let unpacked;
+ switch (version) {
+ case 1: {
+ unpacked = this._unpackBinaryV1Async(dataReader, length);
+ break;
+ }
+ case 2: {
+ unpacked = this._unpackBinaryV2Async(dataReader, length);
+ break;
+ }
+ default: {
+ throw new Error("Unsupported version: " + version);
+ }
+ }
+ this._endPerformanceCounter("Unpack Binary");
+ return unpacked;
+ });
+ }
+ _unpackBinaryV1Async(dataReader, length) {
+ const ContentFormat = {
+ JSON: 0,
+ };
+ const contentLength = dataReader.readUint32();
+ const contentFormat = dataReader.readUint32();
+ if (contentFormat !== ContentFormat.JSON) {
+ throw new Error(`Unexpected content format: ${contentFormat}`);
+ }
+ const bodyLength = length - dataReader.byteOffset;
+ const data = { json: this._parseJson(dataReader.readString(contentLength)), bin: null };
+ if (bodyLength !== 0) {
+ const startByteOffset = dataReader.byteOffset;
+ data.bin = {
+ readAsync: (byteOffset, byteLength) => dataReader.buffer.readAsync(startByteOffset + byteOffset, byteLength),
+ byteLength: bodyLength,
+ };
+ }
+ return Promise.resolve(data);
+ }
+ _unpackBinaryV2Async(dataReader, length) {
+ const ChunkFormat = {
+ JSON: 0x4e4f534a,
+ BIN: 0x004e4942,
+ };
+ // Read the JSON chunk header.
+ const chunkLength = dataReader.readUint32();
+ const chunkFormat = dataReader.readUint32();
+ if (chunkFormat !== ChunkFormat.JSON) {
+ throw new Error("First chunk format is not JSON");
+ }
+ // Bail if there are no other chunks.
+ if (dataReader.byteOffset + chunkLength === length) {
+ return dataReader.loadAsync(chunkLength).then(() => {
+ return { json: this._parseJson(dataReader.readString(chunkLength)), bin: null };
+ });
+ }
+ // Read the JSON chunk and the length and type of the next chunk.
+ return dataReader.loadAsync(chunkLength + 8).then(() => {
+ const data = { json: this._parseJson(dataReader.readString(chunkLength)), bin: null };
+ const readAsync = () => {
+ const chunkLength = dataReader.readUint32();
+ const chunkFormat = dataReader.readUint32();
+ switch (chunkFormat) {
+ case ChunkFormat.JSON: {
+ throw new Error("Unexpected JSON chunk");
+ }
+ case ChunkFormat.BIN: {
+ const startByteOffset = dataReader.byteOffset;
+ data.bin = {
+ readAsync: (byteOffset, byteLength) => dataReader.buffer.readAsync(startByteOffset + byteOffset, byteLength),
+ byteLength: chunkLength,
+ };
+ dataReader.skipBytes(chunkLength);
+ break;
+ }
+ default: {
+ // ignore unrecognized chunkFormat
+ dataReader.skipBytes(chunkLength);
+ break;
+ }
+ }
+ if (dataReader.byteOffset !== length) {
+ return dataReader.loadAsync(8).then(readAsync);
+ }
+ return Promise.resolve(data);
+ };
+ return readAsync();
+ });
+ }
+ static _parseVersion(version) {
+ if (version === "1.0" || version === "1.0.1") {
+ return {
+ major: 1,
+ minor: 0,
+ };
+ }
+ const match = (version + "").match(/^(\d+)\.(\d+)/);
+ if (!match) {
+ return null;
+ }
+ return {
+ major: parseInt(match[1]),
+ minor: parseInt(match[2]),
+ };
+ }
+ static _compareVersion(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;
+ }
+ /**
+ * @internal
+ */
+ _logOpen(message) {
+ this._log(message);
+ this._logIndentLevel++;
+ }
+ /** @internal */
+ _logClose() {
+ --this._logIndentLevel;
+ }
+ _logEnabled(message) {
+ const spaces = GLTFFileLoader._logSpaces.substring(0, this._logIndentLevel * 2);
+ Logger.Log(`${spaces}${message}`);
+ }
+ _logDisabled(message) { }
+ _startPerformanceCounterEnabled(counterName) {
+ Tools.StartPerformanceCounter(counterName);
+ }
+ _startPerformanceCounterDisabled(counterName) { }
+ _endPerformanceCounterEnabled(counterName) {
+ Tools.EndPerformanceCounter(counterName);
+ }
+ _endPerformanceCounterDisabled(counterName) { }
+}
+// ------------------
+// End Common options
+// ------------------
+// ----------------
+// Begin 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.
+ * @internal
+ */
+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.
+ * @internal
+ */
+GLTFFileLoader.HomogeneousCoordinates = false;
+GLTFFileLoader._logSpaces = " ";
+RegisterSceneLoaderPlugin(new GLTFFileLoader());
+
+/**
+ * Enums
+ * @internal
+ */
+var EComponentType;
+(function (EComponentType) {
+ EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
+ EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
+ EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
+ EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
+ EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
+})(EComponentType || (EComponentType = {}));
+/** @internal */
+var EShaderType;
+(function (EShaderType) {
+ EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
+ EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
+})(EShaderType || (EShaderType = {}));
+/** @internal */
+var EParameterType;
+(function (EParameterType) {
+ EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
+ EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
+ EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
+ EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
+ EParameterType[EParameterType["INT"] = 5124] = "INT";
+ EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
+ EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
+ EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
+ EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
+ EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
+ EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
+ EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
+ EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
+ EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
+ EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
+ EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
+ EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
+ EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
+ EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
+ EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
+ EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
+})(EParameterType || (EParameterType = {}));
+/** @internal */
+var ETextureWrapMode;
+(function (ETextureWrapMode) {
+ ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
+ ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
+ ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
+})(ETextureWrapMode || (ETextureWrapMode = {}));
+/** @internal */
+var ETextureFilterType;
+(function (ETextureFilterType) {
+ ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
+ ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
+ ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
+ ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
+ ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
+ ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
+})(ETextureFilterType || (ETextureFilterType = {}));
+/** @internal */
+var ETextureFormat;
+(function (ETextureFormat) {
+ ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
+ ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
+ ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
+ ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
+ ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
+})(ETextureFormat || (ETextureFormat = {}));
+/** @internal */
+var ECullingType;
+(function (ECullingType) {
+ ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
+ ECullingType[ECullingType["BACK"] = 1029] = "BACK";
+ ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
+})(ECullingType || (ECullingType = {}));
+/** @internal */
+var EBlendingFunction;
+(function (EBlendingFunction) {
+ EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
+ EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
+ EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
+ EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
+ EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
+ EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
+ EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
+ EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
+ EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
+ EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
+ EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
+ EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
+ EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
+ EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
+ EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
+})(EBlendingFunction || (EBlendingFunction = {}));
+
+/**
+ * Manage the keyboard inputs to control the movement of a free camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class FreeCameraKeyboardMoveInput {
+ constructor() {
+ /**
+ * Gets or Set the list of keyboard keys used to control the forward move of the camera.
+ */
+ this.keysUp = [38];
+ /**
+ * Gets or Set the list of keyboard keys used to control the upward move of the camera.
+ */
+ this.keysUpward = [33];
+ /**
+ * Gets or Set the list of keyboard keys used to control the backward move of the camera.
+ */
+ this.keysDown = [40];
+ /**
+ * Gets or Set the list of keyboard keys used to control the downward move of the camera.
+ */
+ this.keysDownward = [34];
+ /**
+ * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
+ */
+ this.keysLeft = [37];
+ /**
+ * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
+ */
+ this.keysRight = [39];
+ /**
+ * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
+ */
+ this.rotationSpeed = 0.5;
+ /**
+ * Gets or Set the list of keyboard keys used to control the left rotation move of the camera.
+ */
+ this.keysRotateLeft = [];
+ /**
+ * Gets or Set the list of keyboard keys used to control the right rotation move of the camera.
+ */
+ this.keysRotateRight = [];
+ /**
+ * Gets or Set the list of keyboard keys used to control the up rotation move of the camera.
+ */
+ this.keysRotateUp = [];
+ /**
+ * Gets or Set the list of keyboard keys used to control the down rotation move of the camera.
+ */
+ this.keysRotateDown = [];
+ this._keys = new Array();
+ }
+ /**
+ * Attach the input controls to a specific dom element to get the input from.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(noPreventDefault) {
+ // eslint-disable-next-line prefer-rest-params
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
+ if (this._onCanvasBlurObserver) {
+ return;
+ }
+ this._scene = this.camera.getScene();
+ this._engine = this._scene.getEngine();
+ this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {
+ this._keys.length = 0;
+ });
+ this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {
+ const evt = info.event;
+ if (!evt.metaKey) {
+ if (info.type === KeyboardEventTypes.KEYDOWN) {
+ if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
+ this.keysDown.indexOf(evt.keyCode) !== -1 ||
+ this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+ this.keysRight.indexOf(evt.keyCode) !== -1 ||
+ this.keysUpward.indexOf(evt.keyCode) !== -1 ||
+ this.keysDownward.indexOf(evt.keyCode) !== -1 ||
+ this.keysRotateLeft.indexOf(evt.keyCode) !== -1 ||
+ this.keysRotateRight.indexOf(evt.keyCode) !== -1 ||
+ this.keysRotateUp.indexOf(evt.keyCode) !== -1 ||
+ this.keysRotateDown.indexOf(evt.keyCode) !== -1) {
+ const index = this._keys.indexOf(evt.keyCode);
+ if (index === -1) {
+ this._keys.push(evt.keyCode);
+ }
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ }
+ }
+ else {
+ if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
+ this.keysDown.indexOf(evt.keyCode) !== -1 ||
+ this.keysLeft.indexOf(evt.keyCode) !== -1 ||
+ this.keysRight.indexOf(evt.keyCode) !== -1 ||
+ this.keysUpward.indexOf(evt.keyCode) !== -1 ||
+ this.keysDownward.indexOf(evt.keyCode) !== -1 ||
+ this.keysRotateLeft.indexOf(evt.keyCode) !== -1 ||
+ this.keysRotateRight.indexOf(evt.keyCode) !== -1 ||
+ this.keysRotateUp.indexOf(evt.keyCode) !== -1 ||
+ this.keysRotateDown.indexOf(evt.keyCode) !== -1) {
+ const index = this._keys.indexOf(evt.keyCode);
+ if (index >= 0) {
+ this._keys.splice(index, 1);
+ }
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ }
+ }
+ }
+ });
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ if (this._scene) {
+ if (this._onKeyboardObserver) {
+ this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
+ }
+ if (this._onCanvasBlurObserver) {
+ this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
+ }
+ this._onKeyboardObserver = null;
+ this._onCanvasBlurObserver = null;
+ }
+ this._keys.length = 0;
+ }
+ /**
+ * Update the current camera state depending on the inputs that have been used this frame.
+ * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
+ */
+ checkInputs() {
+ if (this._onKeyboardObserver) {
+ const camera = this.camera;
+ // Keyboard
+ for (let index = 0; index < this._keys.length; index++) {
+ const keyCode = this._keys[index];
+ const speed = camera._computeLocalCameraSpeed();
+ if (this.keysLeft.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(-speed, 0, 0);
+ }
+ else if (this.keysUp.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(0, 0, speed);
+ }
+ else if (this.keysRight.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(speed, 0, 0);
+ }
+ else if (this.keysDown.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(0, 0, -speed);
+ }
+ else if (this.keysUpward.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(0, speed, 0);
+ }
+ else if (this.keysDownward.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(0, -speed, 0);
+ }
+ else if (this.keysRotateLeft.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(0, 0, 0);
+ camera.cameraRotation.y -= this._getLocalRotation();
+ }
+ else if (this.keysRotateRight.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(0, 0, 0);
+ camera.cameraRotation.y += this._getLocalRotation();
+ }
+ else if (this.keysRotateUp.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(0, 0, 0);
+ camera.cameraRotation.x -= this._getLocalRotation();
+ }
+ else if (this.keysRotateDown.indexOf(keyCode) !== -1) {
+ camera._localDirection.copyFromFloats(0, 0, 0);
+ camera.cameraRotation.x += this._getLocalRotation();
+ }
+ if (camera.getScene().useRightHandedSystem) {
+ camera._localDirection.z *= -1;
+ }
+ camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
+ Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
+ camera.cameraDirection.addInPlace(camera._transformedDirection);
+ }
+ }
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "FreeCameraKeyboardMoveInput";
+ }
+ /** @internal */
+ _onLostFocus() {
+ this._keys.length = 0;
+ }
+ /**
+ * Get the friendly name associated with the input class.
+ * @returns the input friendly name
+ */
+ getSimpleName() {
+ return "keyboard";
+ }
+ _getLocalRotation() {
+ const handednessMultiplier = this.camera._calculateHandednessMultiplier();
+ const rotation = ((this.rotationSpeed * this._engine.getDeltaTime()) / 1000) * handednessMultiplier;
+ return rotation;
+ }
+}
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysUpward", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysDownward", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "rotationSpeed", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysRotateLeft", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysRotateRight", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysRotateUp", void 0);
+__decorate([
+ serialize()
+], FreeCameraKeyboardMoveInput.prototype, "keysRotateDown", void 0);
+CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
+
+/**
+ * Manage the mouse inputs to control the movement of a free camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class FreeCameraMouseInput {
+ /**
+ * Manage the mouse inputs to control the movement of a free camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ * @param touchEnabled Defines if touch is enabled or not
+ */
+ constructor(
+ /**
+ * [true] Define if touch is enabled in the mouse input
+ */
+ touchEnabled = true) {
+ this.touchEnabled = touchEnabled;
+ /**
+ * Defines the buttons associated with the input to handle camera move.
+ */
+ this.buttons = [0, 1, 2];
+ /**
+ * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
+ */
+ this.angularSensibility = 2000.0;
+ this._previousPosition = null;
+ /**
+ * Observable for when a pointer move event occurs containing the move offset
+ */
+ this.onPointerMovedObservable = new Observable();
+ /**
+ * @internal
+ * If the camera should be rotated automatically based on pointer movement
+ */
+ this._allowCameraRotation = true;
+ this._currentActiveButton = -1;
+ this._activePointerId = -1;
+ }
+ /**
+ * Attach the input controls to a specific dom element to get the input from.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(noPreventDefault) {
+ // eslint-disable-next-line prefer-rest-params
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
+ const engine = this.camera.getEngine();
+ const element = engine.getInputElement();
+ if (!this._pointerInput) {
+ this._pointerInput = (p) => {
+ const evt = p.event;
+ const isTouch = evt.pointerType === "touch";
+ if (!this.touchEnabled && isTouch) {
+ return;
+ }
+ if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) {
+ return;
+ }
+ const srcElement = evt.target;
+ if (p.type === PointerEventTypes.POINTERDOWN) {
+ // If the input is touch with more than one touch OR if the input is mouse and there is already an active button, return
+ if ((isTouch && this._activePointerId !== -1) || (!isTouch && this._currentActiveButton !== -1)) {
+ return;
+ }
+ this._activePointerId = evt.pointerId;
+ try {
+ srcElement?.setPointerCapture(evt.pointerId);
+ }
+ catch (e) {
+ //Nothing to do with the error. Execution will continue.
+ }
+ if (this._currentActiveButton === -1) {
+ this._currentActiveButton = evt.button;
+ }
+ this._previousPosition = {
+ x: evt.clientX,
+ y: evt.clientY,
+ };
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ element && element.focus();
+ }
+ // This is required to move while pointer button is down
+ if (engine.isPointerLock && this._onMouseMove) {
+ this._onMouseMove(p.event);
+ }
+ }
+ else if (p.type === PointerEventTypes.POINTERUP) {
+ // If input is touch with a different touch id OR if input is mouse with a different button, return
+ if ((isTouch && this._activePointerId !== evt.pointerId) || (!isTouch && this._currentActiveButton !== evt.button)) {
+ return;
+ }
+ try {
+ srcElement?.releasePointerCapture(evt.pointerId);
+ }
+ catch (e) {
+ //Nothing to do with the error.
+ }
+ this._currentActiveButton = -1;
+ this._previousPosition = null;
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ this._activePointerId = -1;
+ }
+ else if (p.type === PointerEventTypes.POINTERMOVE && (this._activePointerId === evt.pointerId || !isTouch)) {
+ if (engine.isPointerLock && this._onMouseMove) {
+ this._onMouseMove(p.event);
+ }
+ else if (this._previousPosition) {
+ const handednessMultiplier = this.camera._calculateHandednessMultiplier();
+ const offsetX = (evt.clientX - this._previousPosition.x) * handednessMultiplier;
+ const offsetY = evt.clientY - this._previousPosition.y;
+ if (this._allowCameraRotation) {
+ this.camera.cameraRotation.y += offsetX / this.angularSensibility;
+ this.camera.cameraRotation.x += offsetY / this.angularSensibility;
+ }
+ this.onPointerMovedObservable.notifyObservers({ offsetX: offsetX, offsetY: offsetY });
+ this._previousPosition = {
+ x: evt.clientX,
+ y: evt.clientY,
+ };
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ }
+ }
+ };
+ }
+ this._onMouseMove = (evt) => {
+ if (!engine.isPointerLock) {
+ return;
+ }
+ const handednessMultiplier = this.camera._calculateHandednessMultiplier();
+ const offsetX = evt.movementX * handednessMultiplier;
+ this.camera.cameraRotation.y += offsetX / this.angularSensibility;
+ const offsetY = evt.movementY;
+ this.camera.cameraRotation.x += offsetY / this.angularSensibility;
+ this._previousPosition = null;
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ };
+ this._observer = this.camera
+ .getScene()
+ ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);
+ if (element) {
+ this._contextMenuBind = (evt) => this.onContextMenu(evt);
+ element.addEventListener("contextmenu", this._contextMenuBind, false); // TODO: We need to figure out how to handle this for Native
+ }
+ }
+ /**
+ * Called on JS contextmenu event.
+ * Override this method to provide functionality.
+ * @param evt the context menu event
+ */
+ onContextMenu(evt) {
+ evt.preventDefault();
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ if (this._observer) {
+ this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
+ if (this._contextMenuBind) {
+ const engine = this.camera.getEngine();
+ const element = engine.getInputElement();
+ element && element.removeEventListener("contextmenu", this._contextMenuBind);
+ }
+ if (this.onPointerMovedObservable) {
+ this.onPointerMovedObservable.clear();
+ }
+ this._observer = null;
+ this._onMouseMove = null;
+ this._previousPosition = null;
+ }
+ this._activePointerId = -1;
+ this._currentActiveButton = -1;
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "FreeCameraMouseInput";
+ }
+ /**
+ * Get the friendly name associated with the input class.
+ * @returns the input friendly name
+ */
+ getSimpleName() {
+ return "mouse";
+ }
+}
+__decorate([
+ serialize()
+], FreeCameraMouseInput.prototype, "buttons", void 0);
+__decorate([
+ serialize()
+], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
+CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
+
+/**
+ * Base class for mouse wheel input..
+ * See FollowCameraMouseWheelInput in src/Cameras/Inputs/freeCameraMouseWheelInput.ts
+ * for example usage.
+ */
+class BaseCameraMouseWheelInput {
+ constructor() {
+ /**
+ * How fast is the camera moves in relation to X axis mouseWheel events.
+ * Use negative value to reverse direction.
+ */
+ this.wheelPrecisionX = 3.0;
+ /**
+ * How fast is the camera moves in relation to Y axis mouseWheel events.
+ * Use negative value to reverse direction.
+ */
+ this.wheelPrecisionY = 3.0;
+ /**
+ * How fast is the camera moves in relation to Z axis mouseWheel events.
+ * Use negative value to reverse direction.
+ */
+ this.wheelPrecisionZ = 3.0;
+ /**
+ * Observable for when a mouse wheel move event occurs.
+ */
+ this.onChangedObservable = new Observable();
+ /**
+ * Incremental value of multiple mouse wheel movements of the X axis.
+ * Should be zero-ed when read.
+ */
+ this._wheelDeltaX = 0;
+ /**
+ * Incremental value of multiple mouse wheel movements of the Y axis.
+ * Should be zero-ed when read.
+ */
+ this._wheelDeltaY = 0;
+ /**
+ * Incremental value of multiple mouse wheel movements of the Z axis.
+ * Should be zero-ed when read.
+ */
+ this._wheelDeltaZ = 0;
+ /**
+ * Firefox uses a different scheme to report scroll distances to other
+ * browsers. Rather than use complicated methods to calculate the exact
+ * multiple we need to apply, let's just cheat and use a constant.
+ * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode
+ * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line
+ */
+ this._ffMultiplier = 12;
+ /**
+ * Different event attributes for wheel data fall into a few set ranges.
+ * Some relevant but dated date here:
+ * https://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers
+ */
+ this._normalize = 120;
+ }
+ /**
+ * Attach the input controls to a specific dom element to get the input from.
+ * @param noPreventDefault Defines whether event caught by the controls
+ * should call preventdefault().
+ * (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(noPreventDefault) {
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
+ this._wheel = (pointer) => {
+ // sanity check - this should be a PointerWheel event.
+ if (pointer.type !== PointerEventTypes.POINTERWHEEL) {
+ return;
+ }
+ const event = pointer.event;
+ const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? this._ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly
+ this._wheelDeltaX += (this.wheelPrecisionX * platformScale * event.deltaX) / this._normalize;
+ this._wheelDeltaY -= (this.wheelPrecisionY * platformScale * event.deltaY) / this._normalize;
+ this._wheelDeltaZ += (this.wheelPrecisionZ * platformScale * event.deltaZ) / this._normalize;
+ if (event.preventDefault) {
+ if (!noPreventDefault) {
+ event.preventDefault();
+ }
+ }
+ };
+ this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ if (this._observer) {
+ this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
+ this._observer = null;
+ this._wheel = null;
+ }
+ if (this.onChangedObservable) {
+ this.onChangedObservable.clear();
+ }
+ }
+ /**
+ * Called for each rendered frame.
+ */
+ checkInputs() {
+ this.onChangedObservable.notifyObservers({
+ wheelDeltaX: this._wheelDeltaX,
+ wheelDeltaY: this._wheelDeltaY,
+ wheelDeltaZ: this._wheelDeltaZ,
+ });
+ // Clear deltas.
+ this._wheelDeltaX = 0;
+ this._wheelDeltaY = 0;
+ this._wheelDeltaZ = 0;
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "BaseCameraMouseWheelInput";
+ }
+ /**
+ * Get the friendly name associated with the input class.
+ * @returns the input friendly name
+ */
+ getSimpleName() {
+ return "mousewheel";
+ }
+}
+__decorate([
+ serialize()
+], BaseCameraMouseWheelInput.prototype, "wheelPrecisionX", void 0);
+__decorate([
+ serialize()
+], BaseCameraMouseWheelInput.prototype, "wheelPrecisionY", void 0);
+__decorate([
+ serialize()
+], BaseCameraMouseWheelInput.prototype, "wheelPrecisionZ", void 0);
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+var _CameraProperty;
+(function (_CameraProperty) {
+ _CameraProperty[_CameraProperty["MoveRelative"] = 0] = "MoveRelative";
+ _CameraProperty[_CameraProperty["RotateRelative"] = 1] = "RotateRelative";
+ _CameraProperty[_CameraProperty["MoveScene"] = 2] = "MoveScene";
+})(_CameraProperty || (_CameraProperty = {}));
+/**
+ * Manage the mouse wheel inputs to control a free camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput {
+ constructor() {
+ super(...arguments);
+ this._moveRelative = Vector3.Zero();
+ this._rotateRelative = Vector3.Zero();
+ this._moveScene = Vector3.Zero();
+ /**
+ * These are set to the desired default behaviour.
+ */
+ this._wheelXAction = _CameraProperty.MoveRelative;
+ this._wheelXActionCoordinate = 0 /* Coordinate.X */;
+ this._wheelYAction = _CameraProperty.MoveRelative;
+ this._wheelYActionCoordinate = 2 /* Coordinate.Z */;
+ this._wheelZAction = null;
+ this._wheelZActionCoordinate = null;
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "FreeCameraMouseWheelInput";
+ }
+ /**
+ * Set which movement axis (relative to camera's orientation) the mouse
+ * wheel's X axis controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelXMoveRelative(axis) {
+ if (axis === null && this._wheelXAction !== _CameraProperty.MoveRelative) {
+ // Attempting to clear different _wheelXAction.
+ return;
+ }
+ this._wheelXAction = _CameraProperty.MoveRelative;
+ this._wheelXActionCoordinate = axis;
+ }
+ /**
+ * Get the configured movement axis (relative to camera's orientation) the
+ * mouse wheel's X axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelXMoveRelative() {
+ if (this._wheelXAction !== _CameraProperty.MoveRelative) {
+ return null;
+ }
+ return this._wheelXActionCoordinate;
+ }
+ /**
+ * Set which movement axis (relative to camera's orientation) the mouse
+ * wheel's Y axis controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelYMoveRelative(axis) {
+ if (axis === null && this._wheelYAction !== _CameraProperty.MoveRelative) {
+ // Attempting to clear different _wheelYAction.
+ return;
+ }
+ this._wheelYAction = _CameraProperty.MoveRelative;
+ this._wheelYActionCoordinate = axis;
+ }
+ /**
+ * Get the configured movement axis (relative to camera's orientation) the
+ * mouse wheel's Y axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelYMoveRelative() {
+ if (this._wheelYAction !== _CameraProperty.MoveRelative) {
+ return null;
+ }
+ return this._wheelYActionCoordinate;
+ }
+ /**
+ * Set which movement axis (relative to camera's orientation) the mouse
+ * wheel's Z axis controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelZMoveRelative(axis) {
+ if (axis === null && this._wheelZAction !== _CameraProperty.MoveRelative) {
+ // Attempting to clear different _wheelZAction.
+ return;
+ }
+ this._wheelZAction = _CameraProperty.MoveRelative;
+ this._wheelZActionCoordinate = axis;
+ }
+ /**
+ * Get the configured movement axis (relative to camera's orientation) the
+ * mouse wheel's Z axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelZMoveRelative() {
+ if (this._wheelZAction !== _CameraProperty.MoveRelative) {
+ return null;
+ }
+ return this._wheelZActionCoordinate;
+ }
+ /**
+ * Set which rotation axis (relative to camera's orientation) the mouse
+ * wheel's X axis controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelXRotateRelative(axis) {
+ if (axis === null && this._wheelXAction !== _CameraProperty.RotateRelative) {
+ // Attempting to clear different _wheelXAction.
+ return;
+ }
+ this._wheelXAction = _CameraProperty.RotateRelative;
+ this._wheelXActionCoordinate = axis;
+ }
+ /**
+ * Get the configured rotation axis (relative to camera's orientation) the
+ * mouse wheel's X axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelXRotateRelative() {
+ if (this._wheelXAction !== _CameraProperty.RotateRelative) {
+ return null;
+ }
+ return this._wheelXActionCoordinate;
+ }
+ /**
+ * Set which rotation axis (relative to camera's orientation) the mouse
+ * wheel's Y axis controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelYRotateRelative(axis) {
+ if (axis === null && this._wheelYAction !== _CameraProperty.RotateRelative) {
+ // Attempting to clear different _wheelYAction.
+ return;
+ }
+ this._wheelYAction = _CameraProperty.RotateRelative;
+ this._wheelYActionCoordinate = axis;
+ }
+ /**
+ * Get the configured rotation axis (relative to camera's orientation) the
+ * mouse wheel's Y axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelYRotateRelative() {
+ if (this._wheelYAction !== _CameraProperty.RotateRelative) {
+ return null;
+ }
+ return this._wheelYActionCoordinate;
+ }
+ /**
+ * Set which rotation axis (relative to camera's orientation) the mouse
+ * wheel's Z axis controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelZRotateRelative(axis) {
+ if (axis === null && this._wheelZAction !== _CameraProperty.RotateRelative) {
+ // Attempting to clear different _wheelZAction.
+ return;
+ }
+ this._wheelZAction = _CameraProperty.RotateRelative;
+ this._wheelZActionCoordinate = axis;
+ }
+ /**
+ * Get the configured rotation axis (relative to camera's orientation) the
+ * mouse wheel's Z axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelZRotateRelative() {
+ if (this._wheelZAction !== _CameraProperty.RotateRelative) {
+ return null;
+ }
+ return this._wheelZActionCoordinate;
+ }
+ /**
+ * Set which movement axis (relative to the scene) the mouse wheel's X axis
+ * controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelXMoveScene(axis) {
+ if (axis === null && this._wheelXAction !== _CameraProperty.MoveScene) {
+ // Attempting to clear different _wheelXAction.
+ return;
+ }
+ this._wheelXAction = _CameraProperty.MoveScene;
+ this._wheelXActionCoordinate = axis;
+ }
+ /**
+ * Get the configured movement axis (relative to the scene) the mouse wheel's
+ * X axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelXMoveScene() {
+ if (this._wheelXAction !== _CameraProperty.MoveScene) {
+ return null;
+ }
+ return this._wheelXActionCoordinate;
+ }
+ /**
+ * Set which movement axis (relative to the scene) the mouse wheel's Y axis
+ * controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelYMoveScene(axis) {
+ if (axis === null && this._wheelYAction !== _CameraProperty.MoveScene) {
+ // Attempting to clear different _wheelYAction.
+ return;
+ }
+ this._wheelYAction = _CameraProperty.MoveScene;
+ this._wheelYActionCoordinate = axis;
+ }
+ /**
+ * Get the configured movement axis (relative to the scene) the mouse wheel's
+ * Y axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelYMoveScene() {
+ if (this._wheelYAction !== _CameraProperty.MoveScene) {
+ return null;
+ }
+ return this._wheelYActionCoordinate;
+ }
+ /**
+ * Set which movement axis (relative to the scene) the mouse wheel's Z axis
+ * controls.
+ * @param axis The axis to be moved. Set null to clear.
+ */
+ set wheelZMoveScene(axis) {
+ if (axis === null && this._wheelZAction !== _CameraProperty.MoveScene) {
+ // Attempting to clear different _wheelZAction.
+ return;
+ }
+ this._wheelZAction = _CameraProperty.MoveScene;
+ this._wheelZActionCoordinate = axis;
+ }
+ /**
+ * Get the configured movement axis (relative to the scene) the mouse wheel's
+ * Z axis controls.
+ * @returns The configured axis or null if none.
+ */
+ get wheelZMoveScene() {
+ if (this._wheelZAction !== _CameraProperty.MoveScene) {
+ return null;
+ }
+ return this._wheelZActionCoordinate;
+ }
+ /**
+ * Called for each rendered frame.
+ */
+ checkInputs() {
+ if (this._wheelDeltaX === 0 && this._wheelDeltaY === 0 && this._wheelDeltaZ == 0) {
+ return;
+ }
+ // Clear the camera properties that we might be updating.
+ this._moveRelative.setAll(0);
+ this._rotateRelative.setAll(0);
+ this._moveScene.setAll(0);
+ // Set the camera properties that are to be updated.
+ this._updateCamera();
+ if (this.camera.getScene().useRightHandedSystem) {
+ // TODO: Does this need done for worldUpdate too?
+ this._moveRelative.z *= -1;
+ }
+ // Convert updates relative to camera to world position update.
+ const cameraTransformMatrix = Matrix.Zero();
+ this.camera.getViewMatrix().invertToRef(cameraTransformMatrix);
+ const transformedDirection = Vector3.Zero();
+ Vector3.TransformNormalToRef(this._moveRelative, cameraTransformMatrix, transformedDirection);
+ // Apply updates to camera position.
+ this.camera.cameraRotation.x += this._rotateRelative.x / 200;
+ this.camera.cameraRotation.y += this._rotateRelative.y / 200;
+ this.camera.cameraDirection.addInPlace(transformedDirection);
+ this.camera.cameraDirection.addInPlace(this._moveScene);
+ // Call the base class implementation to handle observers and do cleanup.
+ super.checkInputs();
+ }
+ /**
+ * Update the camera according to any configured properties for the 3
+ * mouse-wheel axis.
+ */
+ _updateCamera() {
+ // Do the camera updates for each of the 3 touch-wheel axis.
+ this._updateCameraProperty(this._wheelDeltaX, this._wheelXAction, this._wheelXActionCoordinate);
+ this._updateCameraProperty(this._wheelDeltaY, this._wheelYAction, this._wheelYActionCoordinate);
+ this._updateCameraProperty(this._wheelDeltaZ, this._wheelZAction, this._wheelZActionCoordinate);
+ }
+ /**
+ * Update one property of the camera.
+ * @param value
+ * @param cameraProperty
+ * @param coordinate
+ */
+ _updateCameraProperty(
+ /* Mouse-wheel delta. */
+ value,
+ /* Camera property to be changed. */
+ cameraProperty,
+ /* Axis of Camera property to be changed. */
+ coordinate) {
+ if (value === 0) {
+ // Mouse wheel has not moved.
+ return;
+ }
+ if (cameraProperty === null || coordinate === null) {
+ // Mouse wheel axis not configured.
+ return;
+ }
+ let action = null;
+ switch (cameraProperty) {
+ case _CameraProperty.MoveRelative:
+ action = this._moveRelative;
+ break;
+ case _CameraProperty.RotateRelative:
+ action = this._rotateRelative;
+ break;
+ case _CameraProperty.MoveScene:
+ action = this._moveScene;
+ break;
+ }
+ switch (coordinate) {
+ case 0 /* Coordinate.X */:
+ action.set(value, 0, 0);
+ break;
+ case 1 /* Coordinate.Y */:
+ action.set(0, value, 0);
+ break;
+ case 2 /* Coordinate.Z */:
+ action.set(0, 0, value);
+ break;
+ }
+ }
+}
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelXMoveRelative", null);
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelYMoveRelative", null);
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelZMoveRelative", null);
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelXRotateRelative", null);
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelYRotateRelative", null);
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelZRotateRelative", null);
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelXMoveScene", null);
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelYMoveScene", null);
+__decorate([
+ serialize()
+], FreeCameraMouseWheelInput.prototype, "wheelZMoveScene", null);
+CameraInputTypes["FreeCameraMouseWheelInput"] = FreeCameraMouseWheelInput;
+
+/**
+ * Manage the touch inputs to control the movement of a free camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class FreeCameraTouchInput {
+ /**
+ * Manage the touch inputs to control the movement of a free camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ * @param allowMouse Defines if mouse events can be treated as touch events
+ */
+ constructor(
+ /**
+ * [false] Define if mouse events can be treated as touch events
+ */
+ allowMouse = false) {
+ this.allowMouse = allowMouse;
+ /**
+ * Defines the touch sensibility for rotation.
+ * The lower the faster.
+ */
+ this.touchAngularSensibility = 200000.0;
+ /**
+ * Defines the touch sensibility for move.
+ * The lower the faster.
+ */
+ this.touchMoveSensibility = 250.0;
+ /**
+ * Swap touch actions so that one touch is used for rotation and multiple for movement
+ */
+ this.singleFingerRotate = false;
+ this._offsetX = null;
+ this._offsetY = null;
+ this._pointerPressed = new Array();
+ this._isSafari = Tools.IsSafari();
+ }
+ /**
+ * Attach the input controls to a specific dom element to get the input from.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(noPreventDefault) {
+ // eslint-disable-next-line prefer-rest-params
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
+ let previousPosition = null;
+ if (this._pointerInput === undefined) {
+ this._onLostFocus = () => {
+ this._offsetX = null;
+ this._offsetY = null;
+ };
+ this._pointerInput = (p) => {
+ const evt = p.event;
+ const isMouseEvent = evt.pointerType === "mouse" || (this._isSafari && typeof evt.pointerType === "undefined");
+ if (!this.allowMouse && isMouseEvent) {
+ return;
+ }
+ if (p.type === PointerEventTypes.POINTERDOWN) {
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ this._pointerPressed.push(evt.pointerId);
+ if (this._pointerPressed.length !== 1) {
+ return;
+ }
+ previousPosition = {
+ x: evt.clientX,
+ y: evt.clientY,
+ };
+ }
+ else if (p.type === PointerEventTypes.POINTERUP) {
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ const index = this._pointerPressed.indexOf(evt.pointerId);
+ if (index === -1) {
+ return;
+ }
+ this._pointerPressed.splice(index, 1);
+ if (index != 0) {
+ return;
+ }
+ previousPosition = null;
+ this._offsetX = null;
+ this._offsetY = null;
+ }
+ else if (p.type === PointerEventTypes.POINTERMOVE) {
+ if (!noPreventDefault) {
+ evt.preventDefault();
+ }
+ if (!previousPosition) {
+ return;
+ }
+ const index = this._pointerPressed.indexOf(evt.pointerId);
+ if (index != 0) {
+ return;
+ }
+ this._offsetX = evt.clientX - previousPosition.x;
+ this._offsetY = -(evt.clientY - previousPosition.y);
+ }
+ };
+ }
+ this._observer = this.camera
+ .getScene()
+ ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);
+ if (this._onLostFocus) {
+ const engine = this.camera.getEngine();
+ const element = engine.getInputElement();
+ element && element.addEventListener("blur", this._onLostFocus);
+ }
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ if (this._pointerInput) {
+ if (this._observer) {
+ this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
+ this._observer = null;
+ }
+ if (this._onLostFocus) {
+ const engine = this.camera.getEngine();
+ const element = engine.getInputElement();
+ element && element.removeEventListener("blur", this._onLostFocus);
+ this._onLostFocus = null;
+ }
+ this._pointerPressed.length = 0;
+ this._offsetX = null;
+ this._offsetY = null;
+ }
+ }
+ /**
+ * Update the current camera state depending on the inputs that have been used this frame.
+ * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
+ */
+ checkInputs() {
+ if (this._offsetX === null || this._offsetY === null) {
+ return;
+ }
+ if (this._offsetX === 0 && this._offsetY === 0) {
+ return;
+ }
+ const camera = this.camera;
+ const handednessMultiplier = camera._calculateHandednessMultiplier();
+ camera.cameraRotation.y = (handednessMultiplier * this._offsetX) / this.touchAngularSensibility;
+ const rotateCamera = (this.singleFingerRotate && this._pointerPressed.length === 1) || (!this.singleFingerRotate && this._pointerPressed.length > 1);
+ if (rotateCamera) {
+ camera.cameraRotation.x = -this._offsetY / this.touchAngularSensibility;
+ }
+ else {
+ const speed = camera._computeLocalCameraSpeed();
+ const direction = new Vector3(0, 0, this.touchMoveSensibility !== 0 ? (speed * this._offsetY) / this.touchMoveSensibility : 0);
+ Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
+ camera.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
+ }
+ }
+ /**
+ * Gets the class name of the current input.
+ * @returns the class name
+ */
+ getClassName() {
+ return "FreeCameraTouchInput";
+ }
+ /**
+ * Get the friendly name associated with the input class.
+ * @returns the input friendly name
+ */
+ getSimpleName() {
+ return "touch";
+ }
+}
+__decorate([
+ serialize()
+], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
+__decorate([
+ serialize()
+], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
+CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
+
+/**
+ * Default Inputs manager for the FreeCamera.
+ * It groups all the default supported inputs for ease of use.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs
+ */
+class FreeCameraInputsManager extends CameraInputsManager {
+ /**
+ * Instantiates a new FreeCameraInputsManager.
+ * @param camera Defines the camera the inputs belong to
+ */
+ constructor(camera) {
+ super(camera);
+ /**
+ * @internal
+ */
+ this._mouseInput = null;
+ /**
+ * @internal
+ */
+ this._mouseWheelInput = null;
+ }
+ /**
+ * Add keyboard input support to the input manager.
+ * @returns the current input manager
+ */
+ addKeyboard() {
+ this.add(new FreeCameraKeyboardMoveInput());
+ return this;
+ }
+ /**
+ * Add mouse input support to the input manager.
+ * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
+ * @returns the current input manager
+ */
+ addMouse(touchEnabled = true) {
+ if (!this._mouseInput) {
+ this._mouseInput = new FreeCameraMouseInput(touchEnabled);
+ this.add(this._mouseInput);
+ }
+ return this;
+ }
+ /**
+ * Removes the mouse input support from the manager
+ * @returns the current input manager
+ */
+ removeMouse() {
+ if (this._mouseInput) {
+ this.remove(this._mouseInput);
+ }
+ return this;
+ }
+ /**
+ * Add mouse wheel input support to the input manager.
+ * @returns the current input manager
+ */
+ addMouseWheel() {
+ if (!this._mouseWheelInput) {
+ this._mouseWheelInput = new FreeCameraMouseWheelInput();
+ this.add(this._mouseWheelInput);
+ }
+ return this;
+ }
+ /**
+ * Removes the mouse wheel input support from the manager
+ * @returns the current input manager
+ */
+ removeMouseWheel() {
+ if (this._mouseWheelInput) {
+ this.remove(this._mouseWheelInput);
+ }
+ return this;
+ }
+ /**
+ * Add touch input support to the input manager.
+ * @returns the current input manager
+ */
+ addTouch() {
+ this.add(new FreeCameraTouchInput());
+ return this;
+ }
+ /**
+ * Remove all attached input methods from a camera
+ */
+ clear() {
+ super.clear();
+ this._mouseInput = null;
+ }
+}
+
+/**
+ * This represents a free type of camera. It can be useful in First Person Shooter game for instance.
+ * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera
+ */
+class FreeCamera extends TargetCamera {
+ /**
+ * Gets the input sensibility for a mouse input. (default is 2000.0)
+ * Higher values reduce sensitivity.
+ */
+ get angularSensibility() {
+ const mouse = this.inputs.attached["mouse"];
+ if (mouse) {
+ return mouse.angularSensibility;
+ }
+ return 0;
+ }
+ /**
+ * Sets the input sensibility for a mouse input. (default is 2000.0)
+ * Higher values reduce sensitivity.
+ */
+ set angularSensibility(value) {
+ const mouse = this.inputs.attached["mouse"];
+ if (mouse) {
+ mouse.angularSensibility = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the forward move of the camera.
+ */
+ get keysUp() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysUp;
+ }
+ return [];
+ }
+ set keysUp(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysUp = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the upward move of the camera.
+ */
+ get keysUpward() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysUpward;
+ }
+ return [];
+ }
+ set keysUpward(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysUpward = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the backward move of the camera.
+ */
+ get keysDown() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysDown;
+ }
+ return [];
+ }
+ set keysDown(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysDown = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the downward move of the camera.
+ */
+ get keysDownward() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysDownward;
+ }
+ return [];
+ }
+ set keysDownward(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysDownward = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
+ */
+ get keysLeft() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysLeft;
+ }
+ return [];
+ }
+ set keysLeft(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysLeft = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
+ */
+ get keysRight() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysRight;
+ }
+ return [];
+ }
+ set keysRight(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysRight = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the left rotation move of the camera.
+ */
+ get keysRotateLeft() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysRotateLeft;
+ }
+ return [];
+ }
+ set keysRotateLeft(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysRotateLeft = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the right rotation move of the camera.
+ */
+ get keysRotateRight() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysRotateRight;
+ }
+ return [];
+ }
+ set keysRotateRight(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysRotateRight = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the up rotation move of the camera.
+ */
+ get keysRotateUp() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysRotateUp;
+ }
+ return [];
+ }
+ set keysRotateUp(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysRotateUp = value;
+ }
+ }
+ /**
+ * Gets or Set the list of keyboard keys used to control the down rotation move of the camera.
+ */
+ get keysRotateDown() {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ return keyboard.keysRotateDown;
+ }
+ return [];
+ }
+ set keysRotateDown(value) {
+ const keyboard = this.inputs.attached["keyboard"];
+ if (keyboard) {
+ keyboard.keysRotateDown = value;
+ }
+ }
+ /**
+ * Instantiates a Free Camera.
+ * This represents a free type of camera. It can be useful in First Person Shooter game for instance.
+ * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera
+ * @param name Define the name of the camera in the scene
+ * @param position Define the start position of the camera in the scene
+ * @param scene Define the scene the camera belongs to
+ * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined
+ */
+ constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {
+ super(name, position, scene, setActiveOnSceneIfNoneActive);
+ /**
+ * Define the collision ellipsoid of the camera.
+ * This is helpful to simulate a camera body like the player body around the camera
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera
+ */
+ this.ellipsoid = new Vector3(0.5, 1, 0.5);
+ /**
+ * Define an offset for the position of the ellipsoid around the camera.
+ * This can be helpful to determine the center of the body near the gravity center of the body
+ * instead of its head.
+ */
+ this.ellipsoidOffset = new Vector3(0, 0, 0);
+ /**
+ * Enable or disable collisions of the camera with the rest of the scene objects.
+ */
+ this.checkCollisions = false;
+ /**
+ * Enable or disable gravity on the camera.
+ */
+ this.applyGravity = false;
+ this._needMoveForGravity = false;
+ this._oldPosition = Vector3.Zero();
+ this._diffPosition = Vector3.Zero();
+ this._newPosition = Vector3.Zero();
+ // Collisions
+ this._collisionMask = -1;
+ this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {
+ this._newPosition.copyFrom(newPosition);
+ this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
+ if (this._diffPosition.length() > AbstractEngine.CollisionsEpsilon) {
+ this.position.addToRef(this._diffPosition, this._deferredPositionUpdate);
+ if (!this._deferOnly) {
+ this.position.copyFrom(this._deferredPositionUpdate);
+ }
+ else {
+ this._deferredUpdated = true;
+ }
+ // call onCollide, if defined. Note that in case of deferred update, the actual position change might happen in the next frame.
+ if (this.onCollide && collidedMesh) {
+ this.onCollide(collidedMesh);
+ }
+ }
+ };
+ this.inputs = new FreeCameraInputsManager(this);
+ this.inputs.addKeyboard().addMouse();
+ }
+ /**
+ * Attached controls to the current camera.
+ * @param ignored defines an ignored parameter kept for backward compatibility.
+ * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
+ */
+ attachControl(ignored, noPreventDefault) {
+ // eslint-disable-next-line prefer-rest-params
+ noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
+ this.inputs.attachElement(noPreventDefault);
+ }
+ /**
+ * Detach the current controls from the specified dom element.
+ */
+ detachControl() {
+ this.inputs.detachElement();
+ this.cameraDirection = new Vector3(0, 0, 0);
+ this.cameraRotation = new Vector2(0, 0);
+ }
+ /**
+ * Define a collision mask to limit the list of object the camera can collide with
+ */
+ get collisionMask() {
+ return this._collisionMask;
+ }
+ set collisionMask(mask) {
+ this._collisionMask = !isNaN(mask) ? mask : -1;
+ }
+ /**
+ * @internal
+ */
+ _collideWithWorld(displacement) {
+ let globalPosition;
+ if (this.parent) {
+ globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
+ }
+ else {
+ globalPosition = this.position;
+ }
+ globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
+ this._oldPosition.addInPlace(this.ellipsoidOffset);
+ const coordinator = this.getScene().collisionCoordinator;
+ if (!this._collider) {
+ this._collider = coordinator.createCollider();
+ }
+ this._collider._radius = this.ellipsoid;
+ this._collider.collisionMask = this._collisionMask;
+ //no need for clone, as long as gravity is not on.
+ let actualDisplacement = displacement;
+ //add gravity to the direction to prevent the dual-collision checking
+ if (this.applyGravity) {
+ //this prevents mending with cameraDirection, a global variable of the free camera class.
+ actualDisplacement = displacement.add(this.getScene().gravity);
+ }
+ coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
+ }
+ /** @internal */
+ _checkInputs() {
+ if (!this._localDirection) {
+ this._localDirection = Vector3.Zero();
+ this._transformedDirection = Vector3.Zero();
+ }
+ this.inputs.checkInputs();
+ super._checkInputs();
+ }
+ /**
+ * Enable movement without a user input. This allows gravity to always be applied.
+ */
+ set needMoveForGravity(value) {
+ this._needMoveForGravity = value;
+ }
+ /**
+ * When true, gravity is applied whether there is user input or not.
+ */
+ get needMoveForGravity() {
+ return this._needMoveForGravity;
+ }
+ /** @internal */
+ _decideIfNeedsToMove() {
+ return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
+ }
+ /** @internal */
+ _updatePosition() {
+ if (this.checkCollisions && this.getScene().collisionsEnabled) {
+ this._collideWithWorld(this.cameraDirection);
+ }
+ else {
+ super._updatePosition();
+ }
+ }
+ /**
+ * Destroy the camera and release the current resources hold by it.
+ */
+ dispose() {
+ this.inputs.clear();
+ super.dispose();
+ }
+ /**
+ * Gets the current object class name.
+ * @returns the class name
+ */
+ getClassName() {
+ return "FreeCamera";
+ }
+}
+__decorate([
+ serializeAsVector3()
+], FreeCamera.prototype, "ellipsoid", void 0);
+__decorate([
+ serializeAsVector3()
+], FreeCamera.prototype, "ellipsoidOffset", void 0);
+__decorate([
+ serialize()
+], FreeCamera.prototype, "checkCollisions", void 0);
+__decorate([
+ serialize()
+], FreeCamera.prototype, "applyGravity", void 0);
+// Register Class Name
+RegisterClass("BABYLON.FreeCamera", FreeCamera);
+
+/**
+ * Class used to store bone information
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons
+ */
+class Bone extends Node$2 {
+ /** @internal */
+ get _matrix() {
+ this._compose();
+ return this._localMatrix;
+ }
+ /** @internal */
+ set _matrix(value) {
+ // skip if the matrices are the same
+ if (value.updateFlag === this._localMatrix.updateFlag && !this._needToCompose) {
+ return;
+ }
+ this._needToCompose = false; // in case there was a pending compose
+ this._localMatrix.copyFrom(value);
+ this._markAsDirtyAndDecompose();
+ }
+ /**
+ * Create a new bone
+ * @param name defines the bone name
+ * @param skeleton defines the parent skeleton
+ * @param parentBone defines the parent (can be null if the bone is the root)
+ * @param localMatrix defines the local matrix (default: identity)
+ * @param restMatrix defines the rest matrix (default: localMatrix)
+ * @param bindMatrix defines the bind matrix (default: localMatrix)
+ * @param index defines index of the bone in the hierarchy (default: null)
+ */
+ constructor(
+ /**
+ * defines the bone name
+ */
+ name, skeleton, parentBone = null, localMatrix = null, restMatrix = null, bindMatrix = null, index = null) {
+ super(name, skeleton.getScene(), false);
+ this.name = name;
+ /**
+ * Gets the list of child bones
+ */
+ this.children = [];
+ /** Gets the animations associated with this bone */
+ this.animations = [];
+ /**
+ * @internal Internal only
+ * Set this value to map this bone to a different index in the transform matrices
+ * Set this value to -1 to exclude the bone from the transform matrices
+ */
+ this._index = null;
+ this._scalingDeterminant = 1;
+ this._needToDecompose = true;
+ this._needToCompose = false;
+ /** @internal */
+ this._linkedTransformNode = null;
+ /** @internal */
+ this._waitingTransformNodeId = null;
+ this._skeleton = skeleton;
+ this._localMatrix = localMatrix?.clone() ?? Matrix.Identity();
+ this._restMatrix = restMatrix ?? this._localMatrix.clone();
+ this._bindMatrix = bindMatrix ?? this._localMatrix.clone();
+ this._index = index;
+ this._absoluteMatrix = new Matrix();
+ this._absoluteBindMatrix = new Matrix();
+ this._absoluteInverseBindMatrix = new Matrix();
+ this._finalMatrix = new Matrix();
+ skeleton.bones.push(this);
+ this.setParent(parentBone, false);
+ this._updateAbsoluteBindMatrices();
+ }
+ /**
+ * Gets the current object class name.
+ * @returns the class name
+ */
+ getClassName() {
+ return "Bone";
+ }
+ // Members
+ /**
+ * Gets the parent skeleton
+ * @returns a skeleton
+ */
+ getSkeleton() {
+ return this._skeleton;
+ }
+ get parent() {
+ return this._parentNode;
+ }
+ /**
+ * Gets parent bone
+ * @returns a bone or null if the bone is the root of the bone hierarchy
+ */
+ getParent() {
+ return this.parent;
+ }
+ /**
+ * Returns an array containing the children of the bone
+ * @returns an array containing the children of the bone (can be empty if the bone has no children)
+ */
+ getChildren() {
+ return this.children;
+ }
+ /**
+ * Gets the node index in matrix array generated for rendering
+ * @returns the node index
+ */
+ getIndex() {
+ return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index;
+ }
+ set parent(newParent) {
+ this.setParent(newParent);
+ }
+ /**
+ * Sets the parent bone
+ * @param parent defines the parent (can be null if the bone is the root)
+ * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be updated
+ */
+ setParent(parent, updateAbsoluteBindMatrices = true) {
+ if (this.parent === parent) {
+ return;
+ }
+ if (this.parent) {
+ const index = this.parent.children.indexOf(this);
+ if (index !== -1) {
+ this.parent.children.splice(index, 1);
+ }
+ }
+ this._parentNode = parent;
+ if (this.parent) {
+ this.parent.children.push(this);
+ }
+ if (updateAbsoluteBindMatrices) {
+ this._updateAbsoluteBindMatrices();
+ }
+ this.markAsDirty();
+ }
+ /**
+ * Gets the local matrix
+ * @returns the local matrix
+ */
+ getLocalMatrix() {
+ this._compose();
+ return this._localMatrix;
+ }
+ /**
+ * Gets the bind matrix
+ * @returns the bind matrix
+ */
+ getBindMatrix() {
+ return this._bindMatrix;
+ }
+ /**
+ * Gets the bind matrix.
+ * @returns the bind matrix
+ * @deprecated Please use getBindMatrix instead
+ */
+ getBaseMatrix() {
+ return this.getBindMatrix();
+ }
+ /**
+ * Gets the rest matrix
+ * @returns the rest matrix
+ */
+ getRestMatrix() {
+ return this._restMatrix;
+ }
+ /**
+ * Gets the rest matrix
+ * @returns the rest matrix
+ * @deprecated Please use getRestMatrix instead
+ */
+ getRestPose() {
+ return this.getRestMatrix();
+ }
+ /**
+ * Sets the rest matrix
+ * @param matrix the local-space rest matrix to set for this bone
+ */
+ setRestMatrix(matrix) {
+ this._restMatrix.copyFrom(matrix);
+ }
+ /**
+ * Sets the rest matrix
+ * @param matrix the local-space rest to set for this bone
+ * @deprecated Please use setRestMatrix instead
+ */
+ setRestPose(matrix) {
+ this.setRestMatrix(matrix);
+ }
+ /**
+ * Gets the bind matrix
+ * @returns the bind matrix
+ * @deprecated Please use getBindMatrix instead
+ */
+ getBindPose() {
+ return this.getBindMatrix();
+ }
+ /**
+ * Sets the bind matrix
+ * This will trigger a recomputation of the absolute bind and absolute inverse bind matrices for this bone and its children
+ * Note that the local matrix will also be set with the matrix passed in parameter!
+ * @param matrix the local-space bind matrix to set for this bone
+ */
+ setBindMatrix(matrix) {
+ this.updateMatrix(matrix);
+ }
+ /**
+ * Sets the bind matrix
+ * @param matrix the local-space bind to set for this bone
+ * @deprecated Please use setBindMatrix instead
+ */
+ setBindPose(matrix) {
+ this.setBindMatrix(matrix);
+ }
+ /**
+ * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders)
+ * @returns the final world matrix
+ */
+ getFinalMatrix() {
+ return this._finalMatrix;
+ }
+ /**
+ * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders)
+ * @deprecated Please use getFinalMatrix instead
+ * @returns the final world matrix
+ */
+ getWorldMatrix() {
+ return this.getFinalMatrix();
+ }
+ /**
+ * Sets the local matrix to the rest matrix
+ */
+ returnToRest() {
+ if (this._linkedTransformNode) {
+ const localScaling = TmpVectors.Vector3[0];
+ const localRotation = TmpVectors.Quaternion[0];
+ const localPosition = TmpVectors.Vector3[1];
+ this.getRestMatrix().decompose(localScaling, localRotation, localPosition);
+ this._linkedTransformNode.position.copyFrom(localPosition);
+ this._linkedTransformNode.rotationQuaternion = this._linkedTransformNode.rotationQuaternion ?? Quaternion.Identity();
+ this._linkedTransformNode.rotationQuaternion.copyFrom(localRotation);
+ this._linkedTransformNode.scaling.copyFrom(localScaling);
+ }
+ else {
+ this._matrix = this._restMatrix;
+ }
+ }
+ /**
+ * Gets the inverse of the bind matrix, in world space (relative to the skeleton root)
+ * @returns the inverse bind matrix, in world space
+ */
+ getAbsoluteInverseBindMatrix() {
+ return this._absoluteInverseBindMatrix;
+ }
+ /**
+ * Gets the inverse of the bind matrix, in world space (relative to the skeleton root)
+ * @returns the inverse bind matrix, in world space
+ * @deprecated Please use getAbsoluteInverseBindMatrix instead
+ */
+ getInvertedAbsoluteTransform() {
+ return this.getAbsoluteInverseBindMatrix();
+ }
+ /**
+ * Gets the bone matrix, in world space (relative to the skeleton root)
+ * @returns the bone matrix, in world space
+ */
+ getAbsoluteMatrix() {
+ return this._absoluteMatrix;
+ }
+ /**
+ * Gets the bone matrix, in world space (relative to the skeleton root)
+ * @returns the bone matrix, in world space
+ * @deprecated Please use getAbsoluteMatrix instead
+ */
+ getAbsoluteTransform() {
+ return this._absoluteMatrix;
+ }
+ /**
+ * Links with the given transform node.
+ * The local matrix of this bone is overwritten by the transform of the node every frame.
+ * @param transformNode defines the transform node to link to
+ */
+ linkTransformNode(transformNode) {
+ if (this._linkedTransformNode) {
+ this._skeleton._numBonesWithLinkedTransformNode--;
+ }
+ this._linkedTransformNode = transformNode;
+ if (this._linkedTransformNode) {
+ this._skeleton._numBonesWithLinkedTransformNode++;
+ }
+ }
+ // Properties (matches TransformNode properties)
+ /**
+ * Gets the node used to drive the bone's transformation
+ * @returns a transform node or null
+ */
+ getTransformNode() {
+ return this._linkedTransformNode;
+ }
+ /** Gets or sets current position (in local space) */
+ get position() {
+ this._decompose();
+ return this._localPosition;
+ }
+ set position(newPosition) {
+ this._decompose();
+ this._localPosition.copyFrom(newPosition);
+ this._markAsDirtyAndCompose();
+ }
+ /** Gets or sets current rotation (in local space) */
+ get rotation() {
+ return this.getRotation();
+ }
+ set rotation(newRotation) {
+ this.setRotation(newRotation);
+ }
+ /** Gets or sets current rotation quaternion (in local space) */
+ get rotationQuaternion() {
+ this._decompose();
+ return this._localRotation;
+ }
+ set rotationQuaternion(newRotation) {
+ this.setRotationQuaternion(newRotation);
+ }
+ /** Gets or sets current scaling (in local space) */
+ get scaling() {
+ return this.getScale();
+ }
+ set scaling(newScaling) {
+ this.setScale(newScaling);
+ }
+ /**
+ * Gets the animation properties override
+ */
+ get animationPropertiesOverride() {
+ return this._skeleton.animationPropertiesOverride;
+ }
+ // Methods
+ _decompose() {
+ if (!this._needToDecompose) {
+ return;
+ }
+ this._needToDecompose = false;
+ if (!this._localScaling) {
+ this._localScaling = Vector3.Zero();
+ this._localRotation = Quaternion.Zero();
+ this._localPosition = Vector3.Zero();
+ }
+ this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
+ }
+ _compose() {
+ if (!this._needToCompose) {
+ return;
+ }
+ if (!this._localScaling) {
+ this._needToCompose = false;
+ return;
+ }
+ this._needToCompose = false;
+ Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
+ }
+ /**
+ * Update the bind (and optionally the local) matrix
+ * @param bindMatrix defines the new matrix to set to the bind/local matrix, in local space
+ * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be recomputed (default: true)
+ * @param updateLocalMatrix defines if the local matrix should also be updated with the matrix passed in parameter (default: true)
+ */
+ updateMatrix(bindMatrix, updateAbsoluteBindMatrices = true, updateLocalMatrix = true) {
+ this._bindMatrix.copyFrom(bindMatrix);
+ if (updateAbsoluteBindMatrices) {
+ this._updateAbsoluteBindMatrices();
+ }
+ if (updateLocalMatrix) {
+ this._matrix = bindMatrix;
+ }
+ else {
+ this.markAsDirty();
+ }
+ }
+ /**
+ * @internal
+ */
+ _updateAbsoluteBindMatrices(bindMatrix, updateChildren = true) {
+ if (!bindMatrix) {
+ bindMatrix = this._bindMatrix;
+ }
+ if (this.parent) {
+ bindMatrix.multiplyToRef(this.parent._absoluteBindMatrix, this._absoluteBindMatrix);
+ }
+ else {
+ this._absoluteBindMatrix.copyFrom(bindMatrix);
+ }
+ this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix);
+ if (updateChildren) {
+ for (let index = 0; index < this.children.length; index++) {
+ this.children[index]._updateAbsoluteBindMatrices();
+ }
+ }
+ this._scalingDeterminant = this._absoluteBindMatrix.determinant() < 0 ? -1 : 1;
+ }
+ /**
+ * Flag the bone as dirty (Forcing it to update everything)
+ * @returns this bone
+ */
+ markAsDirty() {
+ this._currentRenderId++;
+ this._childUpdateId++;
+ this._skeleton._markAsDirty();
+ return this;
+ }
+ /** @internal */
+ _markAsDirtyAndCompose() {
+ this.markAsDirty();
+ this._needToCompose = true;
+ }
+ _markAsDirtyAndDecompose() {
+ this.markAsDirty();
+ this._needToDecompose = true;
+ }
+ _updatePosition(vec, space = 0 /* Space.LOCAL */, tNode, translationMode = true) {
+ const lm = this.getLocalMatrix();
+ if (space == 0 /* Space.LOCAL */) {
+ if (translationMode) {
+ lm.addAtIndex(12, vec.x);
+ lm.addAtIndex(13, vec.y);
+ lm.addAtIndex(14, vec.z);
+ }
+ else {
+ lm.setTranslationFromFloats(vec.x, vec.y, vec.z);
+ }
+ }
+ else {
+ let wm = null;
+ //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()
+ if (tNode) {
+ wm = tNode.getWorldMatrix();
+ }
+ this._skeleton.computeAbsoluteMatrices();
+ const tmat = Bone._TmpMats[0];
+ const tvec = Bone._TmpVecs[0];
+ if (this.parent) {
+ if (tNode && wm) {
+ tmat.copyFrom(this.parent.getAbsoluteMatrix());
+ tmat.multiplyToRef(wm, tmat);
+ }
+ else {
+ tmat.copyFrom(this.parent.getAbsoluteMatrix());
+ }
+ }
+ else {
+ Matrix.IdentityToRef(tmat);
+ }
+ if (translationMode) {
+ tmat.setTranslationFromFloats(0, 0, 0);
+ }
+ tmat.invert();
+ Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
+ if (translationMode) {
+ lm.addAtIndex(12, tvec.x);
+ lm.addAtIndex(13, tvec.y);
+ lm.addAtIndex(14, tvec.z);
+ }
+ else {
+ lm.setTranslationFromFloats(tvec.x, tvec.y, tvec.z);
+ }
+ }
+ this._markAsDirtyAndDecompose();
+ }
+ /**
+ * Translate the bone in local or world space
+ * @param vec The amount to translate the bone
+ * @param space The space that the translation is in (default: Space.LOCAL)
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ translate(vec, space = 0 /* Space.LOCAL */, tNode) {
+ this._updatePosition(vec, space, tNode, true);
+ }
+ /**
+ * Set the position of the bone in local or world space
+ * @param position The position to set the bone
+ * @param space The space that the position is in (default: Space.LOCAL)
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ setPosition(position, space = 0 /* Space.LOCAL */, tNode) {
+ this._updatePosition(position, space, tNode, false);
+ }
+ /**
+ * Set the absolute position of the bone (world space)
+ * @param position The position to set the bone
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ setAbsolutePosition(position, tNode) {
+ this.setPosition(position, 1 /* Space.WORLD */, tNode);
+ }
+ /**
+ * Scale the bone on the x, y and z axes (in local space)
+ * @param x The amount to scale the bone on the x axis
+ * @param y The amount to scale the bone on the y axis
+ * @param z The amount to scale the bone on the z axis
+ * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
+ */
+ scale(x, y, z, scaleChildren = false) {
+ const locMat = this.getLocalMatrix();
+ // Apply new scaling on top of current local matrix
+ const scaleMat = Bone._TmpMats[0];
+ Matrix.ScalingToRef(x, y, z, scaleMat);
+ scaleMat.multiplyToRef(locMat, locMat);
+ // Invert scaling matrix and apply the inverse to all children
+ scaleMat.invert();
+ for (const child of this.children) {
+ const cm = child.getLocalMatrix();
+ cm.multiplyToRef(scaleMat, cm);
+ cm.multiplyAtIndex(12, x);
+ cm.multiplyAtIndex(13, y);
+ cm.multiplyAtIndex(14, z);
+ child._markAsDirtyAndDecompose();
+ }
+ this._markAsDirtyAndDecompose();
+ if (scaleChildren) {
+ for (const child of this.children) {
+ child.scale(x, y, z, scaleChildren);
+ }
+ }
+ }
+ /**
+ * Set the bone scaling in local space
+ * @param scale defines the scaling vector
+ */
+ setScale(scale) {
+ this._decompose();
+ this._localScaling.copyFrom(scale);
+ this._markAsDirtyAndCompose();
+ }
+ /**
+ * Gets the current scaling in local space
+ * @returns the current scaling vector
+ */
+ getScale() {
+ this._decompose();
+ return this._localScaling;
+ }
+ /**
+ * Gets the current scaling in local space and stores it in a target vector
+ * @param result defines the target vector
+ */
+ getScaleToRef(result) {
+ this._decompose();
+ result.copyFrom(this._localScaling);
+ }
+ /**
+ * Set the yaw, pitch, and roll of the bone in local or world space
+ * @param yaw The rotation of the bone on the y axis
+ * @param pitch The rotation of the bone on the x axis
+ * @param roll The rotation of the bone on the z axis
+ * @param space The space that the axes of rotation are in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ setYawPitchRoll(yaw, pitch, roll, space = 0 /* Space.LOCAL */, tNode) {
+ if (space === 0 /* Space.LOCAL */) {
+ const quat = Bone._TmpQuat;
+ Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
+ this.setRotationQuaternion(quat, space, tNode);
+ return;
+ }
+ const rotMatInv = Bone._TmpMats[0];
+ if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {
+ return;
+ }
+ const rotMat = Bone._TmpMats[1];
+ Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
+ rotMatInv.multiplyToRef(rotMat, rotMat);
+ this._rotateWithMatrix(rotMat, space, tNode);
+ }
+ /**
+ * Add a rotation to the bone on an axis in local or world space
+ * @param axis The axis to rotate the bone on
+ * @param amount The amount to rotate the bone
+ * @param space The space that the axis is in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ rotate(axis, amount, space = 0 /* Space.LOCAL */, tNode) {
+ const rmat = Bone._TmpMats[0];
+ rmat.setTranslationFromFloats(0, 0, 0);
+ Matrix.RotationAxisToRef(axis, amount, rmat);
+ this._rotateWithMatrix(rmat, space, tNode);
+ }
+ /**
+ * Set the rotation of the bone to a particular axis angle in local or world space
+ * @param axis The axis to rotate the bone on
+ * @param angle The angle that the bone should be rotated to
+ * @param space The space that the axis is in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ setAxisAngle(axis, angle, space = 0 /* Space.LOCAL */, tNode) {
+ if (space === 0 /* Space.LOCAL */) {
+ const quat = Bone._TmpQuat;
+ Quaternion.RotationAxisToRef(axis, angle, quat);
+ this.setRotationQuaternion(quat, space, tNode);
+ return;
+ }
+ const rotMatInv = Bone._TmpMats[0];
+ if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {
+ return;
+ }
+ const rotMat = Bone._TmpMats[1];
+ Matrix.RotationAxisToRef(axis, angle, rotMat);
+ rotMatInv.multiplyToRef(rotMat, rotMat);
+ this._rotateWithMatrix(rotMat, space, tNode);
+ }
+ /**
+ * Set the euler rotation of the bone in local or world space
+ * @param rotation The euler rotation that the bone should be set to
+ * @param space The space that the rotation is in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ setRotation(rotation, space = 0 /* Space.LOCAL */, tNode) {
+ this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, tNode);
+ }
+ /**
+ * Set the quaternion rotation of the bone in local or world space
+ * @param quat The quaternion rotation that the bone should be set to
+ * @param space The space that the rotation is in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ setRotationQuaternion(quat, space = 0 /* Space.LOCAL */, tNode) {
+ if (space === 0 /* Space.LOCAL */) {
+ this._decompose();
+ this._localRotation.copyFrom(quat);
+ this._markAsDirtyAndCompose();
+ return;
+ }
+ const rotMatInv = Bone._TmpMats[0];
+ if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {
+ return;
+ }
+ const rotMat = Bone._TmpMats[1];
+ Matrix.FromQuaternionToRef(quat, rotMat);
+ rotMatInv.multiplyToRef(rotMat, rotMat);
+ this._rotateWithMatrix(rotMat, space, tNode);
+ }
+ /**
+ * Set the rotation matrix of the bone in local or world space
+ * @param rotMat The rotation matrix that the bone should be set to
+ * @param space The space that the rotation is in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ */
+ setRotationMatrix(rotMat, space = 0 /* Space.LOCAL */, tNode) {
+ if (space === 0 /* Space.LOCAL */) {
+ const quat = Bone._TmpQuat;
+ Quaternion.FromRotationMatrixToRef(rotMat, quat);
+ this.setRotationQuaternion(quat, space, tNode);
+ return;
+ }
+ const rotMatInv = Bone._TmpMats[0];
+ if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {
+ return;
+ }
+ const rotMat2 = Bone._TmpMats[1];
+ rotMat2.copyFrom(rotMat);
+ rotMatInv.multiplyToRef(rotMat, rotMat2);
+ this._rotateWithMatrix(rotMat2, space, tNode);
+ }
+ _rotateWithMatrix(rmat, space = 0 /* Space.LOCAL */, tNode) {
+ const lmat = this.getLocalMatrix();
+ const lx = lmat.m[12];
+ const ly = lmat.m[13];
+ const lz = lmat.m[14];
+ const parent = this.getParent();
+ const parentScale = Bone._TmpMats[3];
+ const parentScaleInv = Bone._TmpMats[4];
+ if (parent && space == 1 /* Space.WORLD */) {
+ if (tNode) {
+ parentScale.copyFrom(tNode.getWorldMatrix());
+ parent.getAbsoluteMatrix().multiplyToRef(parentScale, parentScale);
+ }
+ else {
+ parentScale.copyFrom(parent.getAbsoluteMatrix());
+ }
+ parentScaleInv.copyFrom(parentScale);
+ parentScaleInv.invert();
+ lmat.multiplyToRef(parentScale, lmat);
+ lmat.multiplyToRef(rmat, lmat);
+ lmat.multiplyToRef(parentScaleInv, lmat);
+ }
+ else {
+ if (space == 1 /* Space.WORLD */ && tNode) {
+ parentScale.copyFrom(tNode.getWorldMatrix());
+ parentScaleInv.copyFrom(parentScale);
+ parentScaleInv.invert();
+ lmat.multiplyToRef(parentScale, lmat);
+ lmat.multiplyToRef(rmat, lmat);
+ lmat.multiplyToRef(parentScaleInv, lmat);
+ }
+ else {
+ lmat.multiplyToRef(rmat, lmat);
+ }
+ }
+ lmat.setTranslationFromFloats(lx, ly, lz);
+ this.computeAbsoluteMatrices();
+ this._markAsDirtyAndDecompose();
+ }
+ _getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode) {
+ const scaleMatrix = Bone._TmpMats[2];
+ rotMatInv.copyFrom(this.getAbsoluteMatrix());
+ if (tNode) {
+ rotMatInv.multiplyToRef(tNode.getWorldMatrix(), rotMatInv);
+ Matrix.ScalingToRef(tNode.scaling.x, tNode.scaling.y, tNode.scaling.z, scaleMatrix);
+ }
+ else {
+ Matrix.IdentityToRef(scaleMatrix);
+ }
+ rotMatInv.invert();
+ if (isNaN(rotMatInv.m[0])) {
+ // Matrix failed to invert.
+ // This can happen if scale is zero for example.
+ return false;
+ }
+ scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);
+ rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
+ return true;
+ }
+ /**
+ * Get the position of the bone in local or world space
+ * @param space The space that the returned position is in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @returns The position of the bone
+ */
+ getPosition(space = 0 /* Space.LOCAL */, tNode = null) {
+ const pos = Vector3.Zero();
+ this.getPositionToRef(space, tNode, pos);
+ return pos;
+ }
+ /**
+ * Copy the position of the bone to a vector3 in local or world space
+ * @param space The space that the returned position is in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @param result The vector3 to copy the position to
+ */
+ getPositionToRef(space = 0 /* Space.LOCAL */, tNode, result) {
+ if (space == 0 /* Space.LOCAL */) {
+ const lm = this.getLocalMatrix();
+ result.x = lm.m[12];
+ result.y = lm.m[13];
+ result.z = lm.m[14];
+ }
+ else {
+ let wm = null;
+ //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()
+ if (tNode) {
+ wm = tNode.getWorldMatrix();
+ }
+ this._skeleton.computeAbsoluteMatrices();
+ let tmat = Bone._TmpMats[0];
+ if (tNode && wm) {
+ tmat.copyFrom(this.getAbsoluteMatrix());
+ tmat.multiplyToRef(wm, tmat);
+ }
+ else {
+ tmat = this.getAbsoluteMatrix();
+ }
+ result.x = tmat.m[12];
+ result.y = tmat.m[13];
+ result.z = tmat.m[14];
+ }
+ }
+ /**
+ * Get the absolute position of the bone (world space)
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @returns The absolute position of the bone
+ */
+ getAbsolutePosition(tNode = null) {
+ const pos = Vector3.Zero();
+ this.getPositionToRef(1 /* Space.WORLD */, tNode, pos);
+ return pos;
+ }
+ /**
+ * Copy the absolute position of the bone (world space) to the result param
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @param result The vector3 to copy the absolute position to
+ */
+ getAbsolutePositionToRef(tNode, result) {
+ this.getPositionToRef(1 /* Space.WORLD */, tNode, result);
+ }
+ /**
+ * Compute the absolute matrices of this bone and its children
+ */
+ computeAbsoluteMatrices() {
+ this._compose();
+ if (this.parent) {
+ this._localMatrix.multiplyToRef(this.parent._absoluteMatrix, this._absoluteMatrix);
+ }
+ else {
+ this._absoluteMatrix.copyFrom(this._localMatrix);
+ const poseMatrix = this._skeleton.getPoseMatrix();
+ if (poseMatrix) {
+ this._absoluteMatrix.multiplyToRef(poseMatrix, this._absoluteMatrix);
+ }
+ }
+ const children = this.children;
+ const len = children.length;
+ for (let i = 0; i < len; i++) {
+ children[i].computeAbsoluteMatrices();
+ }
+ }
+ /**
+ * Compute the absolute matrices of this bone and its children
+ * @deprecated Please use computeAbsoluteMatrices instead
+ */
+ computeAbsoluteTransforms() {
+ this.computeAbsoluteMatrices();
+ }
+ /**
+ * Get the world direction from an axis that is in the local space of the bone
+ * @param localAxis The local direction that is used to compute the world direction
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @returns The world direction
+ */
+ getDirection(localAxis, tNode = null) {
+ const result = Vector3.Zero();
+ this.getDirectionToRef(localAxis, tNode, result);
+ return result;
+ }
+ /**
+ * Copy the world direction to a vector3 from an axis that is in the local space of the bone
+ * @param localAxis The local direction that is used to compute the world direction
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @param result The vector3 that the world direction will be copied to
+ */
+ getDirectionToRef(localAxis, tNode = null, result) {
+ let wm = null;
+ //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()
+ if (tNode) {
+ wm = tNode.getWorldMatrix();
+ }
+ this._skeleton.computeAbsoluteMatrices();
+ const mat = Bone._TmpMats[0];
+ mat.copyFrom(this.getAbsoluteMatrix());
+ if (tNode && wm) {
+ mat.multiplyToRef(wm, mat);
+ }
+ Vector3.TransformNormalToRef(localAxis, mat, result);
+ result.normalize();
+ }
+ /**
+ * Get the euler rotation of the bone in local or world space
+ * @param space The space that the rotation should be in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @returns The euler rotation
+ */
+ getRotation(space = 0 /* Space.LOCAL */, tNode = null) {
+ const result = Vector3.Zero();
+ this.getRotationToRef(space, tNode, result);
+ return result;
+ }
+ /**
+ * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
+ * @param space The space that the rotation should be in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @param result The vector3 that the rotation should be copied to
+ */
+ getRotationToRef(space = 0 /* Space.LOCAL */, tNode = null, result) {
+ const quat = Bone._TmpQuat;
+ this.getRotationQuaternionToRef(space, tNode, quat);
+ quat.toEulerAnglesToRef(result);
+ }
+ /**
+ * Get the quaternion rotation of the bone in either local or world space
+ * @param space The space that the rotation should be in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @returns The quaternion rotation
+ */
+ getRotationQuaternion(space = 0 /* Space.LOCAL */, tNode = null) {
+ const result = Quaternion.Identity();
+ this.getRotationQuaternionToRef(space, tNode, result);
+ return result;
+ }
+ /**
+ * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
+ * @param space The space that the rotation should be in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @param result The quaternion that the rotation should be copied to
+ */
+ getRotationQuaternionToRef(space = 0 /* Space.LOCAL */, tNode = null, result) {
+ if (space == 0 /* Space.LOCAL */) {
+ this._decompose();
+ result.copyFrom(this._localRotation);
+ }
+ else {
+ const mat = Bone._TmpMats[0];
+ const amat = this.getAbsoluteMatrix();
+ if (tNode) {
+ amat.multiplyToRef(tNode.getWorldMatrix(), mat);
+ }
+ else {
+ mat.copyFrom(amat);
+ }
+ mat.multiplyAtIndex(0, this._scalingDeterminant);
+ mat.multiplyAtIndex(1, this._scalingDeterminant);
+ mat.multiplyAtIndex(2, this._scalingDeterminant);
+ mat.decompose(undefined, result, undefined);
+ }
+ }
+ /**
+ * Get the rotation matrix of the bone in local or world space
+ * @param space The space that the rotation should be in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @returns The rotation matrix
+ */
+ getRotationMatrix(space = 0 /* Space.LOCAL */, tNode) {
+ const result = Matrix.Identity();
+ this.getRotationMatrixToRef(space, tNode, result);
+ return result;
+ }
+ /**
+ * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
+ * @param space The space that the rotation should be in
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @param result The quaternion that the rotation should be copied to
+ */
+ getRotationMatrixToRef(space = 0 /* Space.LOCAL */, tNode, result) {
+ if (space == 0 /* Space.LOCAL */) {
+ this.getLocalMatrix().getRotationMatrixToRef(result);
+ }
+ else {
+ const mat = Bone._TmpMats[0];
+ const amat = this.getAbsoluteMatrix();
+ if (tNode) {
+ amat.multiplyToRef(tNode.getWorldMatrix(), mat);
+ }
+ else {
+ mat.copyFrom(amat);
+ }
+ mat.multiplyAtIndex(0, this._scalingDeterminant);
+ mat.multiplyAtIndex(1, this._scalingDeterminant);
+ mat.multiplyAtIndex(2, this._scalingDeterminant);
+ mat.getRotationMatrixToRef(result);
+ }
+ }
+ /**
+ * Get the world position of a point that is in the local space of the bone
+ * @param position The local position
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @returns The world position
+ */
+ getAbsolutePositionFromLocal(position, tNode = null) {
+ const result = Vector3.Zero();
+ this.getAbsolutePositionFromLocalToRef(position, tNode, result);
+ return result;
+ }
+ /**
+ * Get the world position of a point that is in the local space of the bone and copy it to the result param
+ * @param position The local position
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @param result The vector3 that the world position should be copied to
+ */
+ getAbsolutePositionFromLocalToRef(position, tNode = null, result) {
+ let wm = null;
+ //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()
+ if (tNode) {
+ wm = tNode.getWorldMatrix();
+ }
+ this._skeleton.computeAbsoluteMatrices();
+ const tmat = Bone._TmpMats[0];
+ tmat.copyFrom(this.getAbsoluteMatrix());
+ if (tNode && wm) {
+ tmat.multiplyToRef(wm, tmat);
+ }
+ Vector3.TransformCoordinatesToRef(position, tmat, result);
+ }
+ /**
+ * Get the local position of a point that is in world space
+ * @param position The world position
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @returns The local position
+ */
+ getLocalPositionFromAbsolute(position, tNode = null) {
+ const result = Vector3.Zero();
+ this.getLocalPositionFromAbsoluteToRef(position, tNode, result);
+ return result;
+ }
+ /**
+ * Get the local position of a point that is in world space and copy it to the result param
+ * @param position The world position
+ * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD
+ * @param result The vector3 that the local position should be copied to
+ */
+ getLocalPositionFromAbsoluteToRef(position, tNode = null, result) {
+ let wm = null;
+ //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()
+ if (tNode) {
+ wm = tNode.getWorldMatrix();
+ }
+ this._skeleton.computeAbsoluteMatrices();
+ const tmat = Bone._TmpMats[0];
+ tmat.copyFrom(this.getAbsoluteMatrix());
+ if (tNode && wm) {
+ tmat.multiplyToRef(wm, tmat);
+ }
+ tmat.invert();
+ Vector3.TransformCoordinatesToRef(position, tmat, result);
+ }
+ /**
+ * Set the current local matrix as the restMatrix for this bone.
+ */
+ setCurrentPoseAsRest() {
+ this.setRestMatrix(this.getLocalMatrix());
+ }
+ /**
+ * Releases associated resources
+ */
+ dispose() {
+ this._linkedTransformNode = null;
+ const index = this._skeleton.bones.indexOf(this);
+ if (index !== -1) {
+ this._skeleton.bones.splice(index, 1);
+ }
+ if (this._parentNode && this._parentNode.children) {
+ const children = this._parentNode.children;
+ const index = children.indexOf(this);
+ if (index !== -1) {
+ children.splice(index, 1);
+ }
+ }
+ super.dispose();
+ }
+}
+Bone._TmpVecs = BuildArray(2, Vector3.Zero);
+Bone._TmpQuat = Quaternion.Identity();
+Bone._TmpMats = BuildArray(5, Matrix.Identity);
+
+/**
+ * Raw texture can help creating a texture directly from an array of data.
+ * This can be super useful if you either get the data from an uncompressed source or
+ * if you wish to create your texture pixel by pixel.
+ */
+class RawTexture extends Texture {
+ /**
+ * Instantiates a new RawTexture.
+ * Raw texture can help creating a texture directly from an array of data.
+ * This can be super useful if you either get the data from an uncompressed source or
+ * if you wish to create your texture pixel by pixel.
+ * @param data define the array of data to use to create the texture (null to create an empty texture)
+ * @param width define the width of the texture
+ * @param height define the height of the texture
+ * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps define whether mip maps should be generated or not
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).
+ * @param waitDataToBeReady If set to true Rawtexture will wait data to be set in order to be flaged as ready.
+ */
+ constructor(data, width, height,
+ /**
+ * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
+ */
+ format, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags, useSRGBBuffer, waitDataToBeReady) {
+ super(null, sceneOrEngine, !generateMipMaps, invertY, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, creationFlags);
+ this.format = format;
+ if (!this._engine) {
+ return;
+ }
+ if (!this._engine._caps.textureFloatLinearFiltering && type === 1) {
+ samplingMode = 1;
+ }
+ if (!this._engine._caps.textureHalfFloatLinearFiltering && type === 2) {
+ samplingMode = 1;
+ }
+ this._texture = this._engine.createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type, creationFlags ?? 0, useSRGBBuffer ?? false);
+ this.wrapU = Texture.CLAMP_ADDRESSMODE;
+ this.wrapV = Texture.CLAMP_ADDRESSMODE;
+ this._waitingForData = !!waitDataToBeReady && !data;
+ }
+ /**
+ * Updates the texture underlying data.
+ * @param data Define the new data of the texture
+ */
+ update(data) {
+ this._getEngine().updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type, this._texture._useSRGBBuffer);
+ this._waitingForData = false;
+ }
+ /**
+ * Clones the texture.
+ * @returns the cloned texture
+ */
+ clone() {
+ if (!this._texture) {
+ return super.clone();
+ }
+ const rawTexture = new RawTexture(null, this.getSize().width, this.getSize().height, this.format, this.getScene(), this._texture.generateMipMaps, this._invertY, this.samplingMode, this._texture.type, this._texture._creationFlags, this._useSRGBBuffer);
+ rawTexture._texture = this._texture;
+ this._texture.incrementReferences();
+ return rawTexture;
+ }
+ isReady() {
+ return super.isReady() && !this._waitingForData;
+ }
+ /**
+ * Creates a luminance texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @returns the luminance texture
+ */
+ static CreateLuminanceTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {
+ return new RawTexture(data, width, height, 1, sceneOrEngine, generateMipMaps, invertY, samplingMode);
+ }
+ /**
+ * Creates a luminance alpha texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @returns the luminance alpha texture
+ */
+ static CreateLuminanceAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {
+ return new RawTexture(data, width, height, 2, sceneOrEngine, generateMipMaps, invertY, samplingMode);
+ }
+ /**
+ * Creates an alpha texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @returns the alpha texture
+ */
+ static CreateAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {
+ return new RawTexture(data, width, height, 0, sceneOrEngine, generateMipMaps, invertY, samplingMode);
+ }
+ /**
+ * Creates a RGB texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).
+ * @returns the RGB alpha texture
+ */
+ static CreateRGBTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) {
+ return new RawTexture(data, width, height, 4, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer);
+ }
+ /**
+ * Creates a RGBA texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).
+ * @param waitDataToBeReady if set to true this will force texture to wait for data to be set before it is considered ready.
+ * @returns the RGBA texture
+ */
+ static CreateRGBATexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false, waitDataToBeReady = false) {
+ return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer, waitDataToBeReady);
+ }
+ /**
+ * Creates a RGBA storage texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
+ * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).
+ * @returns the RGBA texture
+ */
+ static CreateRGBAStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, useSRGBBuffer = false) {
+ return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1, useSRGBBuffer);
+ }
+ /**
+ * Creates a R texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
+ * @returns the R texture
+ */
+ static CreateRTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) {
+ return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type);
+ }
+ /**
+ * Creates a R storage texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param sceneOrEngine defines the scene or engine the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
+ * @returns the R texture
+ */
+ static CreateRStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) {
+ return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1);
+ }
+}
+
+/**
+ * Class used to handle skinning animations
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons
+ */
+class Skeleton {
+ /**
+ * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true).
+ * Please note that this option is not available if the hardware does not support it
+ */
+ get useTextureToStoreBoneMatrices() {
+ return this._useTextureToStoreBoneMatrices;
+ }
+ set useTextureToStoreBoneMatrices(value) {
+ this._useTextureToStoreBoneMatrices = value;
+ this._markAsDirty();
+ }
+ /**
+ * Gets or sets the animation properties override
+ */
+ get animationPropertiesOverride() {
+ if (!this._animationPropertiesOverride) {
+ return this._scene.animationPropertiesOverride;
+ }
+ return this._animationPropertiesOverride;
+ }
+ set animationPropertiesOverride(value) {
+ this._animationPropertiesOverride = value;
+ }
+ /**
+ * Gets a boolean indicating that the skeleton effectively stores matrices into a texture
+ */
+ get isUsingTextureForMatrices() {
+ return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones;
+ }
+ /**
+ * Gets the unique ID of this skeleton
+ */
+ get uniqueId() {
+ return this._uniqueId;
+ }
+ /**
+ * Creates a new skeleton
+ * @param name defines the skeleton name
+ * @param id defines the skeleton Id
+ * @param scene defines the hosting scene
+ */
+ constructor(
+ /** defines the skeleton name */
+ name,
+ /** defines the skeleton Id */
+ id, scene) {
+ this.name = name;
+ this.id = id;
+ /**
+ * Defines the list of child bones
+ */
+ this.bones = [];
+ /**
+ * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
+ */
+ this.needInitialSkinMatrix = false;
+ this._isDirty = true;
+ this._meshesWithPoseMatrix = new Array();
+ this._identity = Matrix.Identity();
+ this._currentRenderId = -1;
+ this._ranges = {};
+ this._absoluteTransformIsDirty = true;
+ this._canUseTextureForBones = false;
+ this._uniqueId = 0;
+ /** @internal */
+ this._numBonesWithLinkedTransformNode = 0;
+ /** @internal */
+ this._hasWaitingData = null;
+ /** @internal */
+ this._parentContainer = null;
+ /**
+ * Specifies if the skeleton should be serialized
+ */
+ this.doNotSerialize = false;
+ this._useTextureToStoreBoneMatrices = true;
+ this._animationPropertiesOverride = null;
+ // Events
+ /**
+ * An observable triggered before computing the skeleton's matrices
+ */
+ this.onBeforeComputeObservable = new Observable();
+ this.bones = [];
+ this._scene = scene || EngineStore.LastCreatedScene;
+ this._uniqueId = this._scene.getUniqueId();
+ this._scene.addSkeleton(this);
+ //make sure it will recalculate the matrix next time prepare is called.
+ this._isDirty = true;
+ const engineCaps = this._scene.getEngine().getCaps();
+ this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;
+ }
+ /**
+ * Gets the current object class name.
+ * @returns the class name
+ */
+ getClassName() {
+ return "Skeleton";
+ }
+ /**
+ * Returns an array containing the root bones
+ * @returns an array containing the root bones
+ */
+ getChildren() {
+ return this.bones.filter((b) => !b.getParent());
+ }
+ // Members
+ /**
+ * Gets the list of transform matrices to send to shaders (one matrix per bone)
+ * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
+ * @returns a Float32Array containing matrices data
+ */
+ getTransformMatrices(mesh) {
+ if (this.needInitialSkinMatrix) {
+ if (!mesh) {
+ throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");
+ }
+ if (!mesh._bonesTransformMatrices) {
+ this.prepare(true);
+ }
+ return mesh._bonesTransformMatrices;
+ }
+ if (!this._transformMatrices || this._isDirty) {
+ this.prepare(!this._transformMatrices);
+ }
+ return this._transformMatrices;
+ }
+ /**
+ * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone)
+ * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
+ * @returns a raw texture containing the data
+ */
+ getTransformMatrixTexture(mesh) {
+ if (this.needInitialSkinMatrix && mesh._transformMatrixTexture) {
+ return mesh._transformMatrixTexture;
+ }
+ return this._transformMatrixTexture;
+ }
+ /**
+ * Gets the current hosting scene
+ * @returns a scene object
+ */
+ getScene() {
+ return this._scene;
+ }
+ // Methods
+ /**
+ * Gets a string representing the current skeleton data
+ * @param fullDetails defines a boolean indicating if we want a verbose version
+ * @returns a string representing the current skeleton data
+ */
+ toString(fullDetails) {
+ let ret = `Name: ${this.name}, nBones: ${this.bones.length}`;
+ ret += `, nAnimationRanges: ${this._ranges ? Object.keys(this._ranges).length : "none"}`;
+ if (fullDetails) {
+ ret += ", Ranges: {";
+ let first = true;
+ for (const name in this._ranges) {
+ if (first) {
+ ret += ", ";
+ first = false;
+ }
+ ret += name;
+ }
+ ret += "}";
+ }
+ return ret;
+ }
+ /**
+ * Get bone's index searching by name
+ * @param name defines bone's name to search for
+ * @returns the indice of the bone. Returns -1 if not found
+ */
+ getBoneIndexByName(name) {
+ for (let boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
+ if (this.bones[boneIndex].name === name) {
+ return boneIndex;
+ }
+ }
+ return -1;
+ }
+ /**
+ * Create a new animation range
+ * @param name defines the name of the range
+ * @param from defines the start key
+ * @param to defines the end key
+ */
+ createAnimationRange(name, from, to) {
+ // check name not already in use
+ if (!this._ranges[name]) {
+ this._ranges[name] = new AnimationRange(name, from, to);
+ for (let i = 0, nBones = this.bones.length; i < nBones; i++) {
+ if (this.bones[i].animations[0]) {
+ this.bones[i].animations[0].createRange(name, from, to);
+ }
+ }
+ }
+ }
+ /**
+ * Delete a specific animation range
+ * @param name defines the name of the range
+ * @param deleteFrames defines if frames must be removed as well
+ */
+ deleteAnimationRange(name, deleteFrames = true) {
+ for (let i = 0, nBones = this.bones.length; i < nBones; i++) {
+ if (this.bones[i].animations[0]) {
+ this.bones[i].animations[0].deleteRange(name, deleteFrames);
+ }
+ }
+ this._ranges[name] = null; // said much faster than 'delete this._range[name]'
+ }
+ /**
+ * Gets a specific animation range
+ * @param name defines the name of the range to look for
+ * @returns the requested animation range or null if not found
+ */
+ getAnimationRange(name) {
+ return this._ranges[name] || null;
+ }
+ /**
+ * Gets the list of all animation ranges defined on this skeleton
+ * @returns an array
+ */
+ getAnimationRanges() {
+ const animationRanges = [];
+ let name;
+ for (name in this._ranges) {
+ animationRanges.push(this._ranges[name]);
+ }
+ return animationRanges;
+ }
+ /**
+ * Copy animation range from a source skeleton.
+ * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
+ * @param source defines the source skeleton
+ * @param name defines the name of the range to copy
+ * @param rescaleAsRequired defines if rescaling must be applied if required
+ * @returns true if operation was successful
+ */
+ copyAnimationRange(source, name, rescaleAsRequired = false) {
+ if (this._ranges[name] || !source.getAnimationRange(name)) {
+ return false;
+ }
+ let ret = true;
+ const frameOffset = this._getHighestAnimationFrame() + 1;
+ // make a dictionary of source skeleton's bones, so exact same order or doubly nested loop is not required
+ const boneDict = {};
+ const sourceBones = source.bones;
+ let nBones;
+ let i;
+ for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
+ boneDict[sourceBones[i].name] = sourceBones[i];
+ }
+ if (this.bones.length !== sourceBones.length) {
+ Logger.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${sourceBones.length}`);
+ ret = false;
+ }
+ const skelDimensionsRatio = rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
+ for (i = 0, nBones = this.bones.length; i < nBones; i++) {
+ const boneName = this.bones[i].name;
+ const sourceBone = boneDict[boneName];
+ if (sourceBone) {
+ ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
+ }
+ else {
+ Logger.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
+ ret = false;
+ }
+ }
+ // do not call createAnimationRange(), since it also is done to bones, which was already done
+ const range = source.getAnimationRange(name);
+ if (range) {
+ this._ranges[name] = new AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
+ }
+ return ret;
+ }
+ /**
+ * Forces the skeleton to go to rest pose
+ */
+ returnToRest() {
+ for (const bone of this.bones) {
+ if (bone._index !== -1) {
+ bone.returnToRest();
+ }
+ }
+ }
+ _getHighestAnimationFrame() {
+ let ret = 0;
+ for (let i = 0, nBones = this.bones.length; i < nBones; i++) {
+ if (this.bones[i].animations[0]) {
+ const highest = this.bones[i].animations[0].getHighestFrame();
+ if (ret < highest) {
+ ret = highest;
+ }
+ }
+ }
+ return ret;
+ }
+ /**
+ * Begin a specific animation range
+ * @param name defines the name of the range to start
+ * @param loop defines if looping must be turned on (false by default)
+ * @param speedRatio defines the speed ratio to apply (1 by default)
+ * @param onAnimationEnd defines a callback which will be called when animation will end
+ * @returns a new animatable
+ */
+ beginAnimation(name, loop, speedRatio, onAnimationEnd) {
+ const range = this.getAnimationRange(name);
+ if (!range) {
+ return null;
+ }
+ return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
+ }
+ /**
+ * Convert the keyframes for a range of animation on a skeleton to be relative to a given reference frame.
+ * @param skeleton defines the Skeleton containing the animation range to convert
+ * @param referenceFrame defines the frame that keyframes in the range will be relative to
+ * @param range defines the name of the AnimationRange belonging to the Skeleton to convert
+ * @returns the original skeleton
+ */
+ static MakeAnimationAdditive(skeleton, referenceFrame = 0, range) {
+ const rangeValue = skeleton.getAnimationRange(range);
+ // We can't make a range additive if it doesn't exist
+ if (!rangeValue) {
+ return null;
+ }
+ // Find any current scene-level animatable belonging to the target that matches the range
+ const sceneAnimatables = skeleton._scene.getAllAnimatablesByTarget(skeleton);
+ let rangeAnimatable = null;
+ for (let index = 0; index < sceneAnimatables.length; index++) {
+ const sceneAnimatable = sceneAnimatables[index];
+ if (sceneAnimatable.fromFrame === rangeValue?.from && sceneAnimatable.toFrame === rangeValue?.to) {
+ rangeAnimatable = sceneAnimatable;
+ break;
+ }
+ }
+ // Convert the animations belonging to the skeleton to additive keyframes
+ const animatables = skeleton.getAnimatables();
+ for (let index = 0; index < animatables.length; index++) {
+ const animatable = animatables[index];
+ const animations = animatable.animations;
+ if (!animations) {
+ continue;
+ }
+ for (let animIndex = 0; animIndex < animations.length; animIndex++) {
+ Animation.MakeAnimationAdditive(animations[animIndex], referenceFrame, range);
+ }
+ }
+ // Mark the scene-level animatable as additive
+ if (rangeAnimatable) {
+ rangeAnimatable.isAdditive = true;
+ }
+ return skeleton;
+ }
+ /** @internal */
+ _markAsDirty() {
+ this._isDirty = true;
+ this._absoluteTransformIsDirty = true;
+ }
+ /**
+ * @internal
+ */
+ _registerMeshWithPoseMatrix(mesh) {
+ this._meshesWithPoseMatrix.push(mesh);
+ }
+ /**
+ * @internal
+ */
+ _unregisterMeshWithPoseMatrix(mesh) {
+ const index = this._meshesWithPoseMatrix.indexOf(mesh);
+ if (index > -1) {
+ this._meshesWithPoseMatrix.splice(index, 1);
+ }
+ }
+ _computeTransformMatrices(targetMatrix, initialSkinMatrix) {
+ this.onBeforeComputeObservable.notifyObservers(this);
+ for (let index = 0; index < this.bones.length; index++) {
+ const bone = this.bones[index];
+ bone._childUpdateId++;
+ const parentBone = bone.getParent();
+ if (parentBone) {
+ bone.getLocalMatrix().multiplyToRef(parentBone.getFinalMatrix(), bone.getFinalMatrix());
+ }
+ else {
+ if (initialSkinMatrix) {
+ bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getFinalMatrix());
+ }
+ else {
+ bone.getFinalMatrix().copyFrom(bone.getLocalMatrix());
+ }
+ }
+ if (bone._index !== -1) {
+ const mappedIndex = bone._index === null ? index : bone._index;
+ bone.getAbsoluteInverseBindMatrix().multiplyToArray(bone.getFinalMatrix(), targetMatrix, mappedIndex * 16);
+ }
+ }
+ this._identity.copyToArray(targetMatrix, this.bones.length * 16);
+ }
+ /**
+ * Build all resources required to render a skeleton
+ * @param dontCheckFrameId defines a boolean indicating if prepare should be run without checking first the current frame id (default: false)
+ */
+ prepare(dontCheckFrameId = false) {
+ if (!dontCheckFrameId) {
+ const currentRenderId = this.getScene().getRenderId();
+ if (this._currentRenderId === currentRenderId) {
+ return;
+ }
+ this._currentRenderId = currentRenderId;
+ }
+ // Update the local matrix of bones with linked transform nodes.
+ if (this._numBonesWithLinkedTransformNode > 0) {
+ for (const bone of this.bones) {
+ if (bone._linkedTransformNode) {
+ const node = bone._linkedTransformNode;
+ bone.position = node.position;
+ if (node.rotationQuaternion) {
+ bone.rotationQuaternion = node.rotationQuaternion;
+ }
+ else {
+ bone.rotation = node.rotation;
+ }
+ bone.scaling = node.scaling;
+ }
+ }
+ }
+ if (this.needInitialSkinMatrix) {
+ for (const mesh of this._meshesWithPoseMatrix) {
+ const poseMatrix = mesh.getPoseMatrix();
+ let needsUpdate = this._isDirty;
+ if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
+ mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
+ needsUpdate = true;
+ }
+ if (!needsUpdate) {
+ continue;
+ }
+ if (this._synchronizedWithMesh !== mesh) {
+ this._synchronizedWithMesh = mesh;
+ // Prepare bones
+ for (const bone of this.bones) {
+ if (!bone.getParent()) {
+ const matrix = bone.getBindMatrix();
+ matrix.multiplyToRef(poseMatrix, TmpVectors.Matrix[1]);
+ bone._updateAbsoluteBindMatrices(TmpVectors.Matrix[1]);
+ }
+ }
+ if (this.isUsingTextureForMatrices) {
+ const textureWidth = (this.bones.length + 1) * 4;
+ if (!mesh._transformMatrixTexture || mesh._transformMatrixTexture.getSize().width !== textureWidth) {
+ if (mesh._transformMatrixTexture) {
+ mesh._transformMatrixTexture.dispose();
+ }
+ mesh._transformMatrixTexture = RawTexture.CreateRGBATexture(mesh._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1);
+ }
+ }
+ }
+ this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
+ if (this.isUsingTextureForMatrices && mesh._transformMatrixTexture) {
+ mesh._transformMatrixTexture.update(mesh._bonesTransformMatrices);
+ }
+ }
+ }
+ else {
+ if (!this._isDirty) {
+ return;
+ }
+ if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
+ this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
+ if (this.isUsingTextureForMatrices) {
+ if (this._transformMatrixTexture) {
+ this._transformMatrixTexture.dispose();
+ }
+ this._transformMatrixTexture = RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1);
+ }
+ }
+ this._computeTransformMatrices(this._transformMatrices, null);
+ if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {
+ this._transformMatrixTexture.update(this._transformMatrices);
+ }
+ }
+ this._isDirty = false;
+ }
+ /**
+ * Gets the list of animatables currently running for this skeleton
+ * @returns an array of animatables
+ */
+ getAnimatables() {
+ if (!this._animatables || this._animatables.length !== this.bones.length) {
+ this._animatables = [];
+ for (let index = 0; index < this.bones.length; index++) {
+ this._animatables.push(this.bones[index]);
+ }
+ }
+ return this._animatables;
+ }
+ /**
+ * Clone the current skeleton
+ * @param name defines the name of the new skeleton
+ * @param id defines the id of the new skeleton
+ * @returns the new skeleton
+ */
+ clone(name, id) {
+ const result = new Skeleton(name, id || name, this._scene);
+ result.needInitialSkinMatrix = this.needInitialSkinMatrix;
+ for (let index = 0; index < this.bones.length; index++) {
+ const source = this.bones[index];
+ let parentBone = null;
+ const parent = source.getParent();
+ if (parent) {
+ const parentIndex = this.bones.indexOf(parent);
+ parentBone = result.bones[parentIndex];
+ }
+ const bone = new Bone(source.name, result, parentBone, source.getBindMatrix().clone(), source.getRestMatrix().clone());
+ bone._index = source._index;
+ if (source._linkedTransformNode) {
+ bone.linkTransformNode(source._linkedTransformNode);
+ }
+ DeepCopier.DeepCopy(source.animations, bone.animations);
+ }
+ if (this._ranges) {
+ result._ranges = {};
+ for (const rangeName in this._ranges) {
+ const range = this._ranges[rangeName];
+ if (range) {
+ result._ranges[rangeName] = range.clone();
+ }
+ }
+ }
+ this._isDirty = true;
+ result.prepare(true);
+ return result;
+ }
+ /**
+ * Enable animation blending for this skeleton
+ * @param blendingSpeed defines the blending speed to apply
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending
+ */
+ enableBlending(blendingSpeed = 0.01) {
+ this.bones.forEach((bone) => {
+ bone.animations.forEach((animation) => {
+ animation.enableBlending = true;
+ animation.blendingSpeed = blendingSpeed;
+ });
+ });
+ }
+ /**
+ * Releases all resources associated with the current skeleton
+ */
+ dispose() {
+ this._meshesWithPoseMatrix.length = 0;
+ // Animations
+ this.getScene().stopAnimation(this);
+ // Remove from scene
+ this.getScene().removeSkeleton(this);
+ if (this._parentContainer) {
+ const index = this._parentContainer.skeletons.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.skeletons.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ if (this._transformMatrixTexture) {
+ this._transformMatrixTexture.dispose();
+ this._transformMatrixTexture = null;
+ }
+ }
+ /**
+ * Serialize the skeleton in a JSON object
+ * @returns a JSON object
+ */
+ serialize() {
+ const serializationObject = {};
+ serializationObject.name = this.name;
+ serializationObject.id = this.id;
+ if (this.dimensionsAtRest) {
+ serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
+ }
+ serializationObject.bones = [];
+ serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
+ for (let index = 0; index < this.bones.length; index++) {
+ const bone = this.bones[index];
+ const parent = bone.getParent();
+ const serializedBone = {
+ parentBoneIndex: parent ? this.bones.indexOf(parent) : -1,
+ index: bone.getIndex(),
+ name: bone.name,
+ id: bone.id,
+ matrix: bone.getBindMatrix().asArray(),
+ rest: bone.getRestMatrix().asArray(),
+ linkedTransformNodeId: bone.getTransformNode()?.id,
+ };
+ serializationObject.bones.push(serializedBone);
+ if (bone.length) {
+ serializedBone.length = bone.length;
+ }
+ if (bone.metadata) {
+ serializedBone.metadata = bone.metadata;
+ }
+ if (bone.animations && bone.animations.length > 0) {
+ serializedBone.animation = bone.animations[0].serialize();
+ }
+ serializationObject.ranges = [];
+ for (const name in this._ranges) {
+ const source = this._ranges[name];
+ if (!source) {
+ continue;
+ }
+ const range = {};
+ range.name = name;
+ range.from = source.from;
+ range.to = source.to;
+ serializationObject.ranges.push(range);
+ }
+ }
+ return serializationObject;
+ }
+ /**
+ * Creates a new skeleton from serialized data
+ * @param parsedSkeleton defines the serialized data
+ * @param scene defines the hosting scene
+ * @returns a new skeleton
+ */
+ static Parse(parsedSkeleton, scene) {
+ const skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
+ if (parsedSkeleton.dimensionsAtRest) {
+ skeleton.dimensionsAtRest = Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
+ }
+ skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
+ let index;
+ for (index = 0; index < parsedSkeleton.bones.length; index++) {
+ const parsedBone = parsedSkeleton.bones[index];
+ const parsedBoneIndex = parsedSkeleton.bones[index].index;
+ let parentBone = null;
+ if (parsedBone.parentBoneIndex > -1) {
+ parentBone = skeleton.bones[parsedBone.parentBoneIndex];
+ }
+ const rest = parsedBone.rest ? Matrix.FromArray(parsedBone.rest) : null;
+ const bone = new Bone(parsedBone.name, skeleton, parentBone, Matrix.FromArray(parsedBone.matrix), rest, null, parsedBoneIndex);
+ if (parsedBone.id !== undefined && parsedBone.id !== null) {
+ bone.id = parsedBone.id;
+ }
+ if (parsedBone.length) {
+ bone.length = parsedBone.length;
+ }
+ if (parsedBone.metadata) {
+ bone.metadata = parsedBone.metadata;
+ }
+ if (parsedBone.animation) {
+ bone.animations.push(Animation.Parse(parsedBone.animation));
+ }
+ if (parsedBone.linkedTransformNodeId !== undefined && parsedBone.linkedTransformNodeId !== null) {
+ skeleton._hasWaitingData = true;
+ bone._waitingTransformNodeId = parsedBone.linkedTransformNodeId;
+ }
+ }
+ // placed after bones, so createAnimationRange can cascade down
+ if (parsedSkeleton.ranges) {
+ for (index = 0; index < parsedSkeleton.ranges.length; index++) {
+ const data = parsedSkeleton.ranges[index];
+ skeleton.createAnimationRange(data.name, data.from, data.to);
+ }
+ }
+ return skeleton;
+ }
+ /**
+ * Compute all node absolute matrices
+ * @param forceUpdate defines if computation must be done even if cache is up to date
+ */
+ computeAbsoluteMatrices(forceUpdate = false) {
+ if (this._absoluteTransformIsDirty || forceUpdate) {
+ this.bones[0].computeAbsoluteMatrices();
+ this._absoluteTransformIsDirty = false;
+ }
+ }
+ /**
+ * Compute all node absolute matrices
+ * @param forceUpdate defines if computation must be done even if cache is up to date
+ * @deprecated Please use computeAbsoluteMatrices instead
+ */
+ computeAbsoluteTransforms(forceUpdate = false) {
+ this.computeAbsoluteMatrices(forceUpdate);
+ }
+ /**
+ * Gets the root pose matrix
+ * @returns a matrix
+ */
+ getPoseMatrix() {
+ let poseMatrix = null;
+ if (this._meshesWithPoseMatrix.length > 0) {
+ poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
+ }
+ return poseMatrix;
+ }
+ /**
+ * Sorts bones per internal index
+ */
+ sortBones() {
+ const bones = [];
+ const visited = new Array(this.bones.length);
+ for (let index = 0; index < this.bones.length; index++) {
+ this._sortBones(index, bones, visited);
+ }
+ this.bones = bones;
+ }
+ _sortBones(index, bones, visited) {
+ if (visited[index]) {
+ return;
+ }
+ visited[index] = true;
+ const bone = this.bones[index];
+ if (!bone)
+ return;
+ if (bone._index === undefined) {
+ bone._index = index;
+ }
+ const parentBone = bone.getParent();
+ if (parentBone) {
+ this._sortBones(this.bones.indexOf(parentBone), bones, visited);
+ }
+ bones.push(bone);
+ }
+ /**
+ * Set the current local matrix as the restPose for all bones in the skeleton.
+ */
+ setCurrentPoseAsRest() {
+ this.bones.forEach((b) => {
+ b.setCurrentPoseAsRest();
+ });
+ }
+}
+
+/**
+ * Configuration needed for prepass-capable materials
+ */
+class PrePassConfiguration {
+ constructor() {
+ /**
+ * Previous world matrices of meshes carrying this material
+ * Used for computing velocity
+ */
+ this.previousWorldMatrices = {};
+ /**
+ * Previous bones of meshes carrying this material
+ * Used for computing velocity
+ */
+ this.previousBones = {};
+ }
+ /**
+ * Add the required uniforms to the current list.
+ * @param uniforms defines the current uniform list.
+ */
+ static AddUniforms(uniforms) {
+ uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones");
+ }
+ /**
+ * Add the required samplers to the current list.
+ * @param samplers defines the current sampler list.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ static AddSamplers(samplers) {
+ // pass
+ }
+ /**
+ * Binds the material data.
+ * @param effect defines the effect to update
+ * @param scene defines the scene the material belongs to.
+ * @param mesh The mesh
+ * @param world World matrix of this mesh
+ * @param isFrozen Is the material frozen
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ bindForSubMesh(effect, scene, mesh, world, isFrozen) {
+ if (scene.prePassRenderer && scene.prePassRenderer.enabled && scene.prePassRenderer.currentRTisSceneRT) {
+ if (scene.prePassRenderer.getIndex(2) !== -1 ||
+ scene.prePassRenderer.getIndex(11) !== -1) {
+ if (!this.previousWorldMatrices[mesh.uniqueId]) {
+ this.previousWorldMatrices[mesh.uniqueId] = world.clone();
+ }
+ if (!this.previousViewProjection) {
+ this.previousViewProjection = scene.getTransformMatrix().clone();
+ this.currentViewProjection = scene.getTransformMatrix().clone();
+ }
+ const engine = scene.getEngine();
+ if (this.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) {
+ // First update of the prepass configuration for this rendering pass
+ this._lastUpdateFrameId = engine.frameId;
+ this.previousViewProjection.copyFrom(this.currentViewProjection);
+ this.currentViewProjection.copyFrom(scene.getTransformMatrix());
+ }
+ else if (this._lastUpdateFrameId !== engine.frameId) {
+ // The scene transformation did not change from the previous frame (so no camera motion), we must update previousViewProjection accordingly
+ this._lastUpdateFrameId = engine.frameId;
+ this.previousViewProjection.copyFrom(this.currentViewProjection);
+ }
+ effect.setMatrix("previousWorld", this.previousWorldMatrices[mesh.uniqueId]);
+ effect.setMatrix("previousViewProjection", this.previousViewProjection);
+ this.previousWorldMatrices[mesh.uniqueId] = world.clone();
+ }
+ }
+ }
+}
+
+/**
+ * Manages the defines for the Material
+ */
+class MaterialDefines {
+ /**
+ * Creates a new instance
+ * @param externalProperties list of external properties to inject into the object
+ */
+ constructor(externalProperties) {
+ /** @internal */
+ this._keys = [];
+ this._isDirty = true;
+ /** @internal */
+ this._areLightsDirty = true;
+ /** @internal */
+ this._areLightsDisposed = false;
+ /** @internal */
+ this._areAttributesDirty = true;
+ /** @internal */
+ this._areTexturesDirty = true;
+ /** @internal */
+ this._areFresnelDirty = true;
+ /** @internal */
+ this._areMiscDirty = true;
+ /** @internal */
+ this._arePrePassDirty = true;
+ /** @internal */
+ this._areImageProcessingDirty = true;
+ /** @internal */
+ this._normals = false;
+ /** @internal */
+ this._uvs = false;
+ /** @internal */
+ this._needNormals = false;
+ /** @internal */
+ this._needUVs = false;
+ this._externalProperties = externalProperties;
+ // Initialize External Properties
+ if (externalProperties) {
+ for (const prop in externalProperties) {
+ if (Object.prototype.hasOwnProperty.call(externalProperties, prop)) {
+ this._setDefaultValue(prop);
+ }
+ }
+ }
+ }
+ /**
+ * Specifies if the material needs to be re-calculated
+ */
+ get isDirty() {
+ return this._isDirty;
+ }
+ /**
+ * Marks the material to indicate that it has been re-calculated
+ */
+ markAsProcessed() {
+ this._isDirty = false;
+ this._areAttributesDirty = false;
+ this._areTexturesDirty = false;
+ this._areFresnelDirty = false;
+ this._areLightsDirty = false;
+ this._areLightsDisposed = false;
+ this._areMiscDirty = false;
+ this._arePrePassDirty = false;
+ this._areImageProcessingDirty = false;
+ }
+ /**
+ * Marks the material to indicate that it needs to be re-calculated
+ */
+ markAsUnprocessed() {
+ this._isDirty = true;
+ }
+ /**
+ * Marks the material to indicate all of its defines need to be re-calculated
+ */
+ markAllAsDirty() {
+ this._areTexturesDirty = true;
+ this._areAttributesDirty = true;
+ this._areLightsDirty = true;
+ this._areFresnelDirty = true;
+ this._areMiscDirty = true;
+ this._arePrePassDirty = true;
+ this._areImageProcessingDirty = true;
+ this._isDirty = true;
+ }
+ /**
+ * Marks the material to indicate that image processing needs to be re-calculated
+ */
+ markAsImageProcessingDirty() {
+ this._areImageProcessingDirty = true;
+ this._isDirty = true;
+ }
+ /**
+ * Marks the material to indicate the lights need to be re-calculated
+ * @param disposed Defines whether the light is dirty due to dispose or not
+ */
+ markAsLightDirty(disposed = false) {
+ this._areLightsDirty = true;
+ this._areLightsDisposed = this._areLightsDisposed || disposed;
+ this._isDirty = true;
+ }
+ /**
+ * Marks the attribute state as changed
+ */
+ markAsAttributesDirty() {
+ this._areAttributesDirty = true;
+ this._isDirty = true;
+ }
+ /**
+ * Marks the texture state as changed
+ */
+ markAsTexturesDirty() {
+ this._areTexturesDirty = true;
+ this._isDirty = true;
+ }
+ /**
+ * Marks the fresnel state as changed
+ */
+ markAsFresnelDirty() {
+ this._areFresnelDirty = true;
+ this._isDirty = true;
+ }
+ /**
+ * Marks the misc state as changed
+ */
+ markAsMiscDirty() {
+ this._areMiscDirty = true;
+ this._isDirty = true;
+ }
+ /**
+ * Marks the prepass state as changed
+ */
+ markAsPrePassDirty() {
+ this._arePrePassDirty = true;
+ this._isDirty = true;
+ }
+ /**
+ * Rebuilds the material defines
+ */
+ rebuild() {
+ this._keys.length = 0;
+ for (const key of Object.keys(this)) {
+ if (key[0] === "_") {
+ continue;
+ }
+ this._keys.push(key);
+ }
+ if (this._externalProperties) {
+ for (const name in this._externalProperties) {
+ if (this._keys.indexOf(name) === -1) {
+ this._keys.push(name);
+ }
+ }
+ }
+ }
+ /**
+ * Specifies if two material defines are equal
+ * @param other - A material define instance to compare to
+ * @returns - Boolean indicating if the material defines are equal (true) or not (false)
+ */
+ isEqual(other) {
+ if (this._keys.length !== other._keys.length) {
+ return false;
+ }
+ for (let index = 0; index < this._keys.length; index++) {
+ const prop = this._keys[index];
+ if (this[prop] !== other[prop]) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Clones this instance's defines to another instance
+ * @param other - material defines to clone values to
+ */
+ cloneTo(other) {
+ if (this._keys.length !== other._keys.length) {
+ other._keys = this._keys.slice(0);
+ }
+ for (let index = 0; index < this._keys.length; index++) {
+ const prop = this._keys[index];
+ other[prop] = this[prop];
+ }
+ }
+ /**
+ * Resets the material define values
+ */
+ reset() {
+ this._keys.forEach((prop) => this._setDefaultValue(prop));
+ }
+ _setDefaultValue(prop) {
+ const type = this._externalProperties?.[prop]?.type ?? typeof this[prop];
+ const defValue = this._externalProperties?.[prop]?.default;
+ switch (type) {
+ case "number":
+ this[prop] = defValue ?? 0;
+ break;
+ case "string":
+ this[prop] = defValue ?? "";
+ break;
+ default:
+ this[prop] = defValue ?? false;
+ break;
+ }
+ }
+ /**
+ * Converts the material define values to a string
+ * @returns - String of material define information
+ */
+ toString() {
+ let result = "";
+ for (let index = 0; index < this._keys.length; index++) {
+ const prop = this._keys[index];
+ const value = this[prop];
+ const type = typeof value;
+ switch (type) {
+ case "number":
+ case "string":
+ result += "#define " + prop + " " + value + "\n";
+ break;
+ default:
+ if (value) {
+ result += "#define " + prop + "\n";
+ }
+ break;
+ }
+ }
+ return result;
+ }
+}
+
+/**
+ * Base class of materials working in push mode in babylon JS
+ * @internal
+ */
+class PushMaterial extends Material {
+ constructor(name, scene, storeEffectOnSubMeshes = true, forceGLSL = false) {
+ super(name, scene, undefined, forceGLSL);
+ this._normalMatrix = new Matrix();
+ this._storeEffectOnSubMeshes = storeEffectOnSubMeshes;
+ }
+ getEffect() {
+ return this._storeEffectOnSubMeshes ? this._activeEffect : super.getEffect();
+ }
+ isReady(mesh, useInstances) {
+ if (!mesh) {
+ return false;
+ }
+ if (!this._storeEffectOnSubMeshes) {
+ return true;
+ }
+ if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
+ return true;
+ }
+ return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
+ }
+ _isReadyForSubMesh(subMesh) {
+ const defines = subMesh.materialDefines;
+ if (!this.checkReadyOnEveryCall && subMesh.effect && defines) {
+ if (defines._renderId === this.getScene().getRenderId()) {
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * Binds the given world matrix to the active effect
+ *
+ * @param world the matrix to bind
+ */
+ bindOnlyWorldMatrix(world) {
+ this._activeEffect.setMatrix("world", world);
+ }
+ /**
+ * Binds the given normal matrix to the active effect
+ *
+ * @param normalMatrix the matrix to bind
+ */
+ bindOnlyNormalMatrix(normalMatrix) {
+ this._activeEffect.setMatrix("normalMatrix", normalMatrix);
+ }
+ bind(world, mesh) {
+ if (!mesh) {
+ return;
+ }
+ this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
+ }
+ _afterBind(mesh, effect = null, subMesh) {
+ super._afterBind(mesh, effect, subMesh);
+ this.getScene()._cachedEffect = effect;
+ if (subMesh) {
+ subMesh._drawWrapper._forceRebindOnNextCall = false;
+ }
+ else {
+ this._drawWrapper._forceRebindOnNextCall = false;
+ }
+ }
+ _mustRebind(scene, effect, subMesh, visibility = 1) {
+ return subMesh._drawWrapper._forceRebindOnNextCall || scene.isCachedMaterialInvalid(this, effect, visibility);
+ }
+ dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
+ this._activeEffect = undefined;
+ super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
+ }
+}
+
+/**
+ * This groups all the flags used to control the materials channel.
+ */
+class MaterialFlags {
+ /**
+ * Are diffuse textures enabled in the application.
+ */
+ static get DiffuseTextureEnabled() {
+ return this._DiffuseTextureEnabled;
+ }
+ static set DiffuseTextureEnabled(value) {
+ if (this._DiffuseTextureEnabled === value) {
+ return;
+ }
+ this._DiffuseTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Is the OpenPBR Base Weight texture enabled in the application.
+ */
+ static get BaseWeightTextureEnabled() {
+ return this._BaseWeightTextureEnabled;
+ }
+ static set BaseWeightTextureEnabled(value) {
+ if (this._BaseWeightTextureEnabled === value) {
+ return;
+ }
+ this._BaseWeightTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are detail textures enabled in the application.
+ */
+ static get DetailTextureEnabled() {
+ return this._DetailTextureEnabled;
+ }
+ static set DetailTextureEnabled(value) {
+ if (this._DetailTextureEnabled === value) {
+ return;
+ }
+ this._DetailTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are decal maps enabled in the application.
+ */
+ static get DecalMapEnabled() {
+ return this._DecalMapEnabled;
+ }
+ static set DecalMapEnabled(value) {
+ if (this._DecalMapEnabled === value) {
+ return;
+ }
+ this._DecalMapEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are ambient textures enabled in the application.
+ */
+ static get AmbientTextureEnabled() {
+ return this._AmbientTextureEnabled;
+ }
+ static set AmbientTextureEnabled(value) {
+ if (this._AmbientTextureEnabled === value) {
+ return;
+ }
+ this._AmbientTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are opacity textures enabled in the application.
+ */
+ static get OpacityTextureEnabled() {
+ return this._OpacityTextureEnabled;
+ }
+ static set OpacityTextureEnabled(value) {
+ if (this._OpacityTextureEnabled === value) {
+ return;
+ }
+ this._OpacityTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are reflection textures enabled in the application.
+ */
+ static get ReflectionTextureEnabled() {
+ return this._ReflectionTextureEnabled;
+ }
+ static set ReflectionTextureEnabled(value) {
+ if (this._ReflectionTextureEnabled === value) {
+ return;
+ }
+ this._ReflectionTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are emissive textures enabled in the application.
+ */
+ static get EmissiveTextureEnabled() {
+ return this._EmissiveTextureEnabled;
+ }
+ static set EmissiveTextureEnabled(value) {
+ if (this._EmissiveTextureEnabled === value) {
+ return;
+ }
+ this._EmissiveTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are specular textures enabled in the application.
+ */
+ static get SpecularTextureEnabled() {
+ return this._SpecularTextureEnabled;
+ }
+ static set SpecularTextureEnabled(value) {
+ if (this._SpecularTextureEnabled === value) {
+ return;
+ }
+ this._SpecularTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are bump textures enabled in the application.
+ */
+ static get BumpTextureEnabled() {
+ return this._BumpTextureEnabled;
+ }
+ static set BumpTextureEnabled(value) {
+ if (this._BumpTextureEnabled === value) {
+ return;
+ }
+ this._BumpTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are lightmap textures enabled in the application.
+ */
+ static get LightmapTextureEnabled() {
+ return this._LightmapTextureEnabled;
+ }
+ static set LightmapTextureEnabled(value) {
+ if (this._LightmapTextureEnabled === value) {
+ return;
+ }
+ this._LightmapTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are refraction textures enabled in the application.
+ */
+ static get RefractionTextureEnabled() {
+ return this._RefractionTextureEnabled;
+ }
+ static set RefractionTextureEnabled(value) {
+ if (this._RefractionTextureEnabled === value) {
+ return;
+ }
+ this._RefractionTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are color grading textures enabled in the application.
+ */
+ static get ColorGradingTextureEnabled() {
+ return this._ColorGradingTextureEnabled;
+ }
+ static set ColorGradingTextureEnabled(value) {
+ if (this._ColorGradingTextureEnabled === value) {
+ return;
+ }
+ this._ColorGradingTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are fresnels enabled in the application.
+ */
+ static get FresnelEnabled() {
+ return this._FresnelEnabled;
+ }
+ static set FresnelEnabled(value) {
+ if (this._FresnelEnabled === value) {
+ return;
+ }
+ this._FresnelEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(4);
+ }
+ /**
+ * Are clear coat textures enabled in the application.
+ */
+ static get ClearCoatTextureEnabled() {
+ return this._ClearCoatTextureEnabled;
+ }
+ static set ClearCoatTextureEnabled(value) {
+ if (this._ClearCoatTextureEnabled === value) {
+ return;
+ }
+ this._ClearCoatTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are clear coat bump textures enabled in the application.
+ */
+ static get ClearCoatBumpTextureEnabled() {
+ return this._ClearCoatBumpTextureEnabled;
+ }
+ static set ClearCoatBumpTextureEnabled(value) {
+ if (this._ClearCoatBumpTextureEnabled === value) {
+ return;
+ }
+ this._ClearCoatBumpTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are clear coat tint textures enabled in the application.
+ */
+ static get ClearCoatTintTextureEnabled() {
+ return this._ClearCoatTintTextureEnabled;
+ }
+ static set ClearCoatTintTextureEnabled(value) {
+ if (this._ClearCoatTintTextureEnabled === value) {
+ return;
+ }
+ this._ClearCoatTintTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are sheen textures enabled in the application.
+ */
+ static get SheenTextureEnabled() {
+ return this._SheenTextureEnabled;
+ }
+ static set SheenTextureEnabled(value) {
+ if (this._SheenTextureEnabled === value) {
+ return;
+ }
+ this._SheenTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are anisotropic textures enabled in the application.
+ */
+ static get AnisotropicTextureEnabled() {
+ return this._AnisotropicTextureEnabled;
+ }
+ static set AnisotropicTextureEnabled(value) {
+ if (this._AnisotropicTextureEnabled === value) {
+ return;
+ }
+ this._AnisotropicTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are thickness textures enabled in the application.
+ */
+ static get ThicknessTextureEnabled() {
+ return this._ThicknessTextureEnabled;
+ }
+ static set ThicknessTextureEnabled(value) {
+ if (this._ThicknessTextureEnabled === value) {
+ return;
+ }
+ this._ThicknessTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are refraction intensity textures enabled in the application.
+ */
+ static get RefractionIntensityTextureEnabled() {
+ return this._ThicknessTextureEnabled;
+ }
+ static set RefractionIntensityTextureEnabled(value) {
+ if (this._RefractionIntensityTextureEnabled === value) {
+ return;
+ }
+ this._RefractionIntensityTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are translucency intensity textures enabled in the application.
+ */
+ static get TranslucencyIntensityTextureEnabled() {
+ return this._TranslucencyIntensityTextureEnabled;
+ }
+ static set TranslucencyIntensityTextureEnabled(value) {
+ if (this._TranslucencyIntensityTextureEnabled === value) {
+ return;
+ }
+ this._TranslucencyIntensityTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are translucency tint textures enabled in the application.
+ */
+ static get TranslucencyColorTextureEnabled() {
+ return this._TranslucencyColorTextureEnabled;
+ }
+ static set TranslucencyColorTextureEnabled(value) {
+ if (this._TranslucencyColorTextureEnabled === value) {
+ return;
+ }
+ this._TranslucencyColorTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+ /**
+ * Are translucency intensity textures enabled in the application.
+ */
+ static get IridescenceTextureEnabled() {
+ return this._IridescenceTextureEnabled;
+ }
+ static set IridescenceTextureEnabled(value) {
+ if (this._IridescenceTextureEnabled === value) {
+ return;
+ }
+ this._IridescenceTextureEnabled = value;
+ AbstractEngine.MarkAllMaterialsAsDirty(1);
+ }
+}
+// Flags used to enable or disable a type of texture for all Standard Materials
+MaterialFlags._DiffuseTextureEnabled = true;
+MaterialFlags._BaseWeightTextureEnabled = true;
+MaterialFlags._DetailTextureEnabled = true;
+MaterialFlags._DecalMapEnabled = true;
+MaterialFlags._AmbientTextureEnabled = true;
+MaterialFlags._OpacityTextureEnabled = true;
+MaterialFlags._ReflectionTextureEnabled = true;
+MaterialFlags._EmissiveTextureEnabled = true;
+MaterialFlags._SpecularTextureEnabled = true;
+MaterialFlags._BumpTextureEnabled = true;
+MaterialFlags._LightmapTextureEnabled = true;
+MaterialFlags._RefractionTextureEnabled = true;
+MaterialFlags._ColorGradingTextureEnabled = true;
+MaterialFlags._FresnelEnabled = true;
+MaterialFlags._ClearCoatTextureEnabled = true;
+MaterialFlags._ClearCoatBumpTextureEnabled = true;
+MaterialFlags._ClearCoatTintTextureEnabled = true;
+MaterialFlags._SheenTextureEnabled = true;
+MaterialFlags._AnisotropicTextureEnabled = true;
+MaterialFlags._ThicknessTextureEnabled = true;
+MaterialFlags._RefractionIntensityTextureEnabled = true;
+MaterialFlags._TranslucencyIntensityTextureEnabled = true;
+MaterialFlags._TranslucencyColorTextureEnabled = true;
+MaterialFlags._IridescenceTextureEnabled = true;
+
+const rxOption = new RegExp("^([gimus]+)!");
+/**
+ * Class that manages the plugins of a material
+ * @since 5.0
+ */
+class MaterialPluginManager {
+ /**
+ * Creates a new instance of the plugin manager
+ * @param material material that this manager will manage the plugins for
+ */
+ constructor(material) {
+ /** @internal */
+ this._plugins = [];
+ this._activePlugins = [];
+ this._activePluginsForExtraEvents = [];
+ this._material = material;
+ this._scene = material.getScene();
+ this._engine = this._scene.getEngine();
+ }
+ /**
+ * @internal
+ */
+ _addPlugin(plugin) {
+ for (let i = 0; i < this._plugins.length; ++i) {
+ if (this._plugins[i].name === plugin.name) {
+ return false;
+ }
+ }
+ if (this._material._uniformBufferLayoutBuilt) {
+ this._material.resetDrawCache();
+ this._material._createUniformBuffer();
+ }
+ if (!plugin.isCompatible(this._material.shaderLanguage)) {
+ // eslint-disable-next-line no-throw-literal
+ throw `The plugin "${plugin.name}" can't be added to the material "${this._material.name}" because the plugin is not compatible with the shader language of the material.`;
+ }
+ const pluginClassName = plugin.getClassName();
+ if (!MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]) {
+ MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName] = "MATERIALPLUGIN_" + ++MaterialPluginManager._MaterialPluginCounter;
+ }
+ this._material._callbackPluginEventGeneric = (id, info) => this._handlePluginEvent(id, info);
+ this._plugins.push(plugin);
+ this._plugins.sort((a, b) => a.priority - b.priority);
+ this._codeInjectionPoints = {};
+ const defineNamesFromPlugins = {};
+ defineNamesFromPlugins[MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]] = {
+ type: "boolean",
+ default: true,
+ };
+ for (const plugin of this._plugins) {
+ plugin.collectDefines(defineNamesFromPlugins);
+ this._collectPointNames("vertex", plugin.getCustomCode("vertex", this._material.shaderLanguage));
+ this._collectPointNames("fragment", plugin.getCustomCode("fragment", this._material.shaderLanguage));
+ }
+ this._defineNamesFromPlugins = defineNamesFromPlugins;
+ return true;
+ }
+ /**
+ * @internal
+ */
+ _activatePlugin(plugin) {
+ if (this._activePlugins.indexOf(plugin) === -1) {
+ this._activePlugins.push(plugin);
+ this._activePlugins.sort((a, b) => a.priority - b.priority);
+ this._material._callbackPluginEventIsReadyForSubMesh = this._handlePluginEventIsReadyForSubMesh.bind(this);
+ this._material._callbackPluginEventPrepareDefinesBeforeAttributes = this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this);
+ this._material._callbackPluginEventPrepareDefines = this._handlePluginEventPrepareDefines.bind(this);
+ this._material._callbackPluginEventBindForSubMesh = this._handlePluginEventBindForSubMesh.bind(this);
+ if (plugin.registerForExtraEvents) {
+ this._activePluginsForExtraEvents.push(plugin);
+ this._activePluginsForExtraEvents.sort((a, b) => a.priority - b.priority);
+ this._material._callbackPluginEventHasRenderTargetTextures = this._handlePluginEventHasRenderTargetTextures.bind(this);
+ this._material._callbackPluginEventFillRenderTargetTextures = this._handlePluginEventFillRenderTargetTextures.bind(this);
+ this._material._callbackPluginEventHardBindForSubMesh = this._handlePluginEventHardBindForSubMesh.bind(this);
+ }
+ }
+ }
+ /**
+ * Gets a plugin from the list of plugins managed by this manager
+ * @param name name of the plugin
+ * @returns the plugin if found, else null
+ */
+ getPlugin(name) {
+ for (let i = 0; i < this._plugins.length; ++i) {
+ if (this._plugins[i].name === name) {
+ return this._plugins[i];
+ }
+ }
+ return null;
+ }
+ _handlePluginEventIsReadyForSubMesh(eventData) {
+ let isReady = true;
+ for (const plugin of this._activePlugins) {
+ isReady = isReady && plugin.isReadyForSubMesh(eventData.defines, this._scene, this._engine, eventData.subMesh);
+ }
+ eventData.isReadyForSubMesh = isReady;
+ }
+ _handlePluginEventPrepareDefinesBeforeAttributes(eventData) {
+ for (const plugin of this._activePlugins) {
+ plugin.prepareDefinesBeforeAttributes(eventData.defines, this._scene, eventData.mesh);
+ }
+ }
+ _handlePluginEventPrepareDefines(eventData) {
+ for (const plugin of this._activePlugins) {
+ plugin.prepareDefines(eventData.defines, this._scene, eventData.mesh);
+ }
+ }
+ _handlePluginEventHardBindForSubMesh(eventData) {
+ for (const plugin of this._activePluginsForExtraEvents) {
+ plugin.hardBindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh);
+ }
+ }
+ _handlePluginEventBindForSubMesh(eventData) {
+ for (const plugin of this._activePlugins) {
+ plugin.bindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh);
+ }
+ }
+ _handlePluginEventHasRenderTargetTextures(eventData) {
+ let hasRenderTargetTextures = false;
+ for (const plugin of this._activePluginsForExtraEvents) {
+ hasRenderTargetTextures = plugin.hasRenderTargetTextures();
+ if (hasRenderTargetTextures) {
+ break;
+ }
+ }
+ eventData.hasRenderTargetTextures = hasRenderTargetTextures;
+ }
+ _handlePluginEventFillRenderTargetTextures(eventData) {
+ for (const plugin of this._activePluginsForExtraEvents) {
+ plugin.fillRenderTargetTextures(eventData.renderTargets);
+ }
+ }
+ _handlePluginEvent(id, info) {
+ switch (id) {
+ case 512 /* MaterialPluginEvent.GetActiveTextures */: {
+ const eventData = info;
+ for (const plugin of this._activePlugins) {
+ plugin.getActiveTextures(eventData.activeTextures);
+ }
+ break;
+ }
+ case 256 /* MaterialPluginEvent.GetAnimatables */: {
+ const eventData = info;
+ for (const plugin of this._activePlugins) {
+ plugin.getAnimatables(eventData.animatables);
+ }
+ break;
+ }
+ case 1024 /* MaterialPluginEvent.HasTexture */: {
+ const eventData = info;
+ let hasTexture = false;
+ for (const plugin of this._activePlugins) {
+ hasTexture = plugin.hasTexture(eventData.texture);
+ if (hasTexture) {
+ break;
+ }
+ }
+ eventData.hasTexture = hasTexture;
+ break;
+ }
+ case 2 /* MaterialPluginEvent.Disposed */: {
+ const eventData = info;
+ for (const plugin of this._plugins) {
+ plugin.dispose(eventData.forceDisposeTextures);
+ }
+ break;
+ }
+ case 4 /* MaterialPluginEvent.GetDefineNames */: {
+ const eventData = info;
+ eventData.defineNames = this._defineNamesFromPlugins;
+ break;
+ }
+ case 128 /* MaterialPluginEvent.PrepareEffect */: {
+ const eventData = info;
+ for (const plugin of this._activePlugins) {
+ eventData.fallbackRank = plugin.addFallbacks(eventData.defines, eventData.fallbacks, eventData.fallbackRank);
+ plugin.getAttributes(eventData.attributes, this._scene, eventData.mesh);
+ }
+ if (this._uniformList.length > 0) {
+ eventData.uniforms.push(...this._uniformList);
+ }
+ if (this._samplerList.length > 0) {
+ eventData.samplers.push(...this._samplerList);
+ }
+ if (this._uboList.length > 0) {
+ eventData.uniformBuffersNames.push(...this._uboList);
+ }
+ eventData.customCode = this._injectCustomCode(eventData, eventData.customCode);
+ break;
+ }
+ case 8 /* MaterialPluginEvent.PrepareUniformBuffer */: {
+ const eventData = info;
+ this._uboDeclaration = "";
+ this._vertexDeclaration = "";
+ this._fragmentDeclaration = "";
+ this._uniformList = [];
+ this._samplerList = [];
+ this._uboList = [];
+ const isWebGPU = this._material.shaderLanguage === 1 /* ShaderLanguage.WGSL */;
+ for (const plugin of this._plugins) {
+ const uniforms = plugin.getUniforms(this._material.shaderLanguage);
+ if (uniforms) {
+ if (uniforms.ubo) {
+ for (const uniform of uniforms.ubo) {
+ if (uniform.size && uniform.type) {
+ const arraySize = uniform.arraySize ?? 0;
+ eventData.ubo.addUniform(uniform.name, uniform.size, arraySize);
+ if (isWebGPU) {
+ let type;
+ switch (uniform.type) {
+ case "mat4":
+ type = "mat4x4f";
+ break;
+ case "float":
+ type = "f32";
+ break;
+ default:
+ type = `${uniform.type}f`;
+ break;
+ }
+ this._uboDeclaration += `uniform ${uniform.name}: ${type}${arraySize > 0 ? `[${arraySize}]` : ""};\n`;
+ }
+ else {
+ this._uboDeclaration += `${uniform.type} ${uniform.name}${arraySize > 0 ? `[${arraySize}]` : ""};\n`;
+ }
+ }
+ this._uniformList.push(uniform.name);
+ }
+ }
+ if (uniforms.vertex) {
+ this._vertexDeclaration += uniforms.vertex + "\n";
+ }
+ if (uniforms.fragment) {
+ this._fragmentDeclaration += uniforms.fragment + "\n";
+ }
+ }
+ plugin.getSamplers(this._samplerList);
+ plugin.getUniformBuffersNames(this._uboList);
+ }
+ break;
+ }
+ }
+ }
+ _collectPointNames(shaderType, customCode) {
+ if (!customCode) {
+ return;
+ }
+ for (const pointName in customCode) {
+ if (!this._codeInjectionPoints[shaderType]) {
+ this._codeInjectionPoints[shaderType] = {};
+ }
+ this._codeInjectionPoints[shaderType][pointName] = true;
+ }
+ }
+ _injectCustomCode(eventData, existingCallback) {
+ return (shaderType, code) => {
+ if (existingCallback) {
+ code = existingCallback(shaderType, code);
+ }
+ if (this._uboDeclaration) {
+ code = code.replace("#define ADDITIONAL_UBO_DECLARATION", this._uboDeclaration);
+ }
+ if (this._vertexDeclaration) {
+ code = code.replace("#define ADDITIONAL_VERTEX_DECLARATION", this._vertexDeclaration);
+ }
+ if (this._fragmentDeclaration) {
+ code = code.replace("#define ADDITIONAL_FRAGMENT_DECLARATION", this._fragmentDeclaration);
+ }
+ const points = this._codeInjectionPoints?.[shaderType];
+ if (!points) {
+ return code;
+ }
+ let processorOptions = null;
+ for (let pointName in points) {
+ let injectedCode = "";
+ for (const plugin of this._activePlugins) {
+ let customCode = plugin.getCustomCode(shaderType, this._material.shaderLanguage)?.[pointName];
+ if (!customCode) {
+ continue;
+ }
+ if (plugin.resolveIncludes) {
+ if (processorOptions === null) {
+ const shaderLanguage = 0 /* ShaderLanguage.GLSL */;
+ processorOptions = {
+ defines: [], // not used by _ProcessIncludes
+ indexParameters: eventData.indexParameters,
+ isFragment: false,
+ shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader,
+ processor: undefined, // not used by _ProcessIncludes
+ supportsUniformBuffers: this._engine.supportsUniformBuffers,
+ shadersRepository: ShaderStore.GetShadersRepository(shaderLanguage),
+ includesShadersStore: ShaderStore.GetIncludesShadersStore(shaderLanguage),
+ version: undefined, // not used by _ProcessIncludes
+ platformName: this._engine.shaderPlatformName,
+ processingContext: undefined, // not used by _ProcessIncludes
+ isNDCHalfZRange: this._engine.isNDCHalfZRange,
+ useReverseDepthBuffer: this._engine.useReverseDepthBuffer,
+ processCodeAfterIncludes: undefined, // not used by _ProcessIncludes
+ };
+ }
+ processorOptions.isFragment = shaderType === "fragment";
+ _ProcessIncludes(customCode, processorOptions, (code) => (customCode = code));
+ }
+ injectedCode += customCode + "\n";
+ }
+ if (injectedCode.length > 0) {
+ if (pointName.charAt(0) === "!") {
+ // pointName is a regular expression
+ pointName = pointName.substring(1);
+ let regexFlags = "g";
+ if (pointName.charAt(0) === "!") {
+ // no flags
+ regexFlags = "";
+ pointName = pointName.substring(1);
+ }
+ else {
+ // get the flag(s)
+ const matchOption = rxOption.exec(pointName);
+ if (matchOption && matchOption.length >= 2) {
+ regexFlags = matchOption[1];
+ pointName = pointName.substring(regexFlags.length + 1);
+ }
+ }
+ if (regexFlags.indexOf("g") < 0) {
+ // we force the "g" flag so that the regexp object is stateful!
+ regexFlags += "g";
+ }
+ const sourceCode = code;
+ const rx = new RegExp(pointName, regexFlags);
+ let match = rx.exec(sourceCode);
+ while (match !== null) {
+ let newCode = injectedCode;
+ for (let i = 0; i < match.length; ++i) {
+ newCode = newCode.replace("$" + i, match[i]);
+ }
+ code = code.replace(match[0], newCode);
+ match = rx.exec(sourceCode);
+ }
+ }
+ else {
+ const fullPointName = "#define " + pointName;
+ code = code.replace(fullPointName, "\n" + injectedCode + "\n" + fullPointName);
+ }
+ }
+ }
+ return code;
+ };
+ }
+}
+/** Map a plugin class name to a #define name (used in the vertex/fragment shaders as a marker of the plugin usage) */
+MaterialPluginManager._MaterialPluginClassToMainDefine = {};
+MaterialPluginManager._MaterialPluginCounter = 0;
+(() => {
+ EngineStore.OnEnginesDisposedObservable.add(() => {
+ UnregisterAllMaterialPlugins();
+ });
+})();
+const plugins = [];
+let inited = false;
+let observer = null;
+/**
+ * Registers a new material plugin through a factory, or updates it. This makes the plugin available to all materials instantiated after its registration.
+ * @param pluginName The plugin name
+ * @param factory The factory function which allows to create the plugin
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function RegisterMaterialPlugin(pluginName, factory) {
+ if (!inited) {
+ observer = Material.OnEventObservable.add((material) => {
+ for (const [, factory] of plugins) {
+ factory(material);
+ }
+ }, 1 /* MaterialPluginEvent.Created */);
+ inited = true;
+ }
+ const existing = plugins.filter(([name, _factory]) => name === pluginName);
+ if (existing.length > 0) {
+ existing[0][1] = factory;
+ }
+ else {
+ plugins.push([pluginName, factory]);
+ }
+}
+/**
+ * Clear the list of global material plugins
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function UnregisterAllMaterialPlugins() {
+ plugins.length = 0;
+ inited = false;
+ Material.OnEventObservable.remove(observer);
+ observer = null;
+}
+
+/**
+ * Base class for material plugins.
+ * @since 5.0
+ */
+class MaterialPluginBase {
+ /**
+ * Gets a boolean indicating that the plugin is compatible with a given shader language.
+ * @param shaderLanguage The shader language to use.
+ * @returns true if the plugin is compatible with the shader language
+ */
+ isCompatible(shaderLanguage) {
+ switch (shaderLanguage) {
+ case 0 /* ShaderLanguage.GLSL */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ _enable(enable) {
+ if (enable) {
+ this._pluginManager._activatePlugin(this);
+ }
+ }
+ /**
+ * Creates a new material plugin
+ * @param material parent material of the plugin
+ * @param name name of the plugin
+ * @param priority priority of the plugin
+ * @param defines list of defines used by the plugin. The value of the property is the default value for this property
+ * @param addToPluginList true to add the plugin to the list of plugins managed by the material plugin manager of the material (default: true)
+ * @param enable true to enable the plugin (it is handy if the plugin does not handle properties to switch its current activation)
+ * @param resolveIncludes Indicates that any #include directive in the plugin code must be replaced by the corresponding code (default: false)
+ */
+ constructor(material, name, priority, defines, addToPluginList = true, enable = false, resolveIncludes = false) {
+ /**
+ * Defines the priority of the plugin. Lower numbers run first.
+ */
+ this.priority = 500;
+ /**
+ * Indicates that any #include directive in the plugin code must be replaced by the corresponding code.
+ */
+ this.resolveIncludes = false;
+ /**
+ * Indicates that this plugin should be notified for the extra events (HasRenderTargetTextures / FillRenderTargetTextures / HardBindForSubMesh)
+ */
+ this.registerForExtraEvents = false;
+ /**
+ * Specifies if the material plugin should be serialized, `true` to skip serialization
+ */
+ this.doNotSerialize = false;
+ this._material = material;
+ this.name = name;
+ this.priority = priority;
+ this.resolveIncludes = resolveIncludes;
+ if (!material.pluginManager) {
+ material.pluginManager = new MaterialPluginManager(material);
+ material.onDisposeObservable.add(() => {
+ material.pluginManager = undefined;
+ });
+ }
+ this._pluginDefineNames = defines;
+ this._pluginManager = material.pluginManager;
+ if (addToPluginList) {
+ this._pluginManager._addPlugin(this);
+ }
+ if (enable) {
+ this._enable(true);
+ }
+ this.markAllDefinesAsDirty = material._dirtyCallbacks[127];
+ }
+ /**
+ * Gets the current class name useful for serialization or dynamic coding.
+ * @returns The class name.
+ */
+ getClassName() {
+ return "MaterialPluginBase";
+ }
+ /**
+ * Specifies that the submesh is ready to be used.
+ * @param _defines the list of "defines" to update.
+ * @param _scene defines the scene the material belongs to.
+ * @param _engine the engine this scene belongs to.
+ * @param _subMesh the submesh to check for readiness
+ * @returns - boolean indicating that the submesh is ready or not.
+ */
+ isReadyForSubMesh(_defines, _scene, _engine, _subMesh) {
+ return true;
+ }
+ /**
+ * Binds the material data (this function is called even if mustRebind() returns false)
+ * @param _uniformBuffer defines the Uniform buffer to fill in.
+ * @param _scene defines the scene the material belongs to.
+ * @param _engine defines the engine the material belongs to.
+ * @param _subMesh the submesh to bind data for
+ */
+ hardBindForSubMesh(_uniformBuffer, _scene, _engine, _subMesh) { }
+ /**
+ * Binds the material data.
+ * @param _uniformBuffer defines the Uniform buffer to fill in.
+ * @param _scene defines the scene the material belongs to.
+ * @param _engine the engine this scene belongs to.
+ * @param _subMesh the submesh to bind data for
+ */
+ bindForSubMesh(_uniformBuffer, _scene, _engine, _subMesh) { }
+ /**
+ * Disposes the resources of the material.
+ * @param _forceDisposeTextures - Forces the disposal of all textures.
+ */
+ dispose(_forceDisposeTextures) { }
+ /**
+ * Returns a list of custom shader code fragments to customize the shader.
+ * @param _shaderType "vertex" or "fragment"
+ * @param _shaderLanguage The shader language to use.
+ * @returns null if no code to be added, or a list of pointName =\> code.
+ * Note that `pointName` can also be a regular expression if it starts with a `!`.
+ * In that case, the string found by the regular expression (if any) will be
+ * replaced by the code provided.
+ */
+ getCustomCode(_shaderType, _shaderLanguage = 0 /* ShaderLanguage.GLSL */) {
+ return null;
+ }
+ /**
+ * Collects all defines.
+ * @param defines The object to append to.
+ */
+ collectDefines(defines) {
+ if (!this._pluginDefineNames) {
+ return;
+ }
+ for (const key of Object.keys(this._pluginDefineNames)) {
+ if (key[0] === "_") {
+ continue;
+ }
+ const type = typeof this._pluginDefineNames[key];
+ defines[key] = {
+ type: type === "number" ? "number" : type === "string" ? "string" : type === "boolean" ? "boolean" : "object",
+ default: this._pluginDefineNames[key],
+ };
+ }
+ }
+ /**
+ * Sets the defines for the next rendering. Called before PrepareDefinesForAttributes is called.
+ * @param _defines the list of "defines" to update.
+ * @param _scene defines the scene to the material belongs to.
+ * @param _mesh the mesh being rendered
+ */
+ prepareDefinesBeforeAttributes(_defines, _scene, _mesh) { }
+ /**
+ * Sets the defines for the next rendering
+ * @param _defines the list of "defines" to update.
+ * @param _scene defines the scene to the material belongs to.
+ * @param _mesh the mesh being rendered
+ */
+ prepareDefines(_defines, _scene, _mesh) { }
+ /**
+ * Checks to see if a texture is used in the material.
+ * @param _texture - Base texture to use.
+ * @returns - Boolean specifying if a texture is used in the material.
+ */
+ hasTexture(_texture) {
+ return false;
+ }
+ /**
+ * Gets a boolean indicating that current material needs to register RTT
+ * @returns true if this uses a render target otherwise false.
+ */
+ hasRenderTargetTextures() {
+ return false;
+ }
+ /**
+ * Fills the list of render target textures.
+ * @param _renderTargets the list of render targets to update
+ */
+ fillRenderTargetTextures(_renderTargets) { }
+ /**
+ * Returns an array of the actively used textures.
+ * @param _activeTextures Array of BaseTextures
+ */
+ getActiveTextures(_activeTextures) { }
+ /**
+ * Returns the animatable textures.
+ * @param _animatables Array of animatable textures.
+ */
+ getAnimatables(_animatables) { }
+ /**
+ * Add fallbacks to the effect fallbacks list.
+ * @param defines defines the Base texture to use.
+ * @param fallbacks defines the current fallback list.
+ * @param currentRank defines the current fallback rank.
+ * @returns the new fallback rank.
+ */
+ addFallbacks(defines, fallbacks, currentRank) {
+ return currentRank;
+ }
+ /**
+ * Gets the samplers used by the plugin.
+ * @param _samplers list that the sampler names should be added to.
+ */
+ getSamplers(_samplers) { }
+ /**
+ * Gets the attributes used by the plugin.
+ * @param _attributes list that the attribute names should be added to.
+ * @param _scene the scene that the material belongs to.
+ * @param _mesh the mesh being rendered.
+ */
+ getAttributes(_attributes, _scene, _mesh) { }
+ /**
+ * Gets the uniform buffers names added by the plugin.
+ * @param _ubos list that the ubo names should be added to.
+ */
+ getUniformBuffersNames(_ubos) { }
+ /**
+ * Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos)
+ * @param _shaderLanguage The shader language to use.
+ * @returns the description of the uniforms
+ */
+ getUniforms(_shaderLanguage = 0 /* ShaderLanguage.GLSL */) {
+ return {};
+ }
+ /**
+ * Makes a duplicate of the current configuration into another one.
+ * @param plugin define the config where to copy the info
+ */
+ copyTo(plugin) {
+ SerializationHelper.Clone(() => plugin, this);
+ }
+ /**
+ * Serializes this plugin configuration.
+ * @returns - An object with the serialized config.
+ */
+ serialize() {
+ return SerializationHelper.Serialize(this);
+ }
+ /**
+ * Parses a plugin configuration from a serialized object.
+ * @param source - Serialized object.
+ * @param scene Defines the scene we are parsing for
+ * @param rootUrl Defines the rootUrl to load from
+ */
+ parse(source, scene, rootUrl) {
+ SerializationHelper.Parse(() => this, source, scene, rootUrl);
+ }
+}
+__decorate([
+ serialize()
+], MaterialPluginBase.prototype, "name", void 0);
+__decorate([
+ serialize()
+], MaterialPluginBase.prototype, "priority", void 0);
+__decorate([
+ serialize()
+], MaterialPluginBase.prototype, "resolveIncludes", void 0);
+__decorate([
+ serialize()
+], MaterialPluginBase.prototype, "registerForExtraEvents", void 0);
+// Register Class Name
+RegisterClass("BABYLON.MaterialPluginBase", MaterialPluginBase);
+
+/**
+ * @internal
+ */
+class MaterialDetailMapDefines extends MaterialDefines {
+ constructor() {
+ super(...arguments);
+ this.DETAIL = false;
+ this.DETAILDIRECTUV = 0;
+ this.DETAIL_NORMALBLENDMETHOD = 0;
+ }
+}
+/**
+ * Plugin that implements the detail map component of a material
+ *
+ * Inspired from:
+ * Unity: https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@9.0/manual/Mask-Map-and-Detail-Map.html and https://docs.unity3d.com/Manual/StandardShaderMaterialParameterDetail.html
+ * Unreal: https://docs.unrealengine.com/en-US/Engine/Rendering/Materials/HowTo/DetailTexturing/index.html
+ * Cryengine: https://docs.cryengine.com/display/SDKDOC2/Detail+Maps
+ */
+class DetailMapConfiguration extends MaterialPluginBase {
+ /** @internal */
+ _markAllSubMeshesAsTexturesDirty() {
+ this._enable(this._isEnabled);
+ this._internalMarkAllSubMeshesAsTexturesDirty();
+ }
+ /**
+ * Gets a boolean indicating that the plugin is compatible with a given shader language.
+ * @returns true if the plugin is compatible with the shader language
+ */
+ isCompatible() {
+ return true;
+ }
+ constructor(material, addToPluginList = true) {
+ super(material, "DetailMap", 140, new MaterialDetailMapDefines(), addToPluginList);
+ this._texture = null;
+ /**
+ * Defines how strongly the detail diffuse/albedo channel is blended with the regular diffuse/albedo texture
+ * Bigger values mean stronger blending
+ */
+ this.diffuseBlendLevel = 1;
+ /**
+ * Defines how strongly the detail roughness channel is blended with the regular roughness value
+ * Bigger values mean stronger blending. Only used with PBR materials
+ */
+ this.roughnessBlendLevel = 1;
+ /**
+ * Defines how strong the bump effect from the detail map is
+ * Bigger values mean stronger effect
+ */
+ this.bumpLevel = 1;
+ this._normalBlendMethod = Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT;
+ this._isEnabled = false;
+ /**
+ * Enable or disable the detail map on this material
+ */
+ this.isEnabled = false;
+ this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
+ }
+ isReadyForSubMesh(defines, scene, engine) {
+ if (!this._isEnabled) {
+ return true;
+ }
+ if (defines._areTexturesDirty && scene.texturesEnabled) {
+ if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled) {
+ // Detail texture cannot be not blocking.
+ if (!this._texture.isReady()) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ prepareDefines(defines, scene) {
+ if (this._isEnabled) {
+ defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;
+ const engine = scene.getEngine();
+ if (defines._areTexturesDirty) {
+ if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && this._isEnabled) {
+ PrepareDefinesForMergedUV(this._texture, defines, "DETAIL");
+ defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;
+ }
+ else {
+ defines.DETAIL = false;
+ }
+ }
+ }
+ else {
+ defines.DETAIL = false;
+ }
+ }
+ bindForSubMesh(uniformBuffer, scene) {
+ if (!this._isEnabled) {
+ return;
+ }
+ const isFrozen = this._material.isFrozen;
+ if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
+ if (this._texture && MaterialFlags.DetailTextureEnabled) {
+ uniformBuffer.updateFloat4("vDetailInfos", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel);
+ BindTextureMatrix(this._texture, uniformBuffer, "detail");
+ }
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.DetailTextureEnabled) {
+ uniformBuffer.setTexture("detailSampler", this._texture);
+ }
+ }
+ }
+ hasTexture(texture) {
+ if (this._texture === texture) {
+ return true;
+ }
+ return false;
+ }
+ getActiveTextures(activeTextures) {
+ if (this._texture) {
+ activeTextures.push(this._texture);
+ }
+ }
+ getAnimatables(animatables) {
+ if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
+ animatables.push(this._texture);
+ }
+ }
+ dispose(forceDisposeTextures) {
+ if (forceDisposeTextures) {
+ this._texture?.dispose();
+ }
+ }
+ getClassName() {
+ return "DetailMapConfiguration";
+ }
+ getSamplers(samplers) {
+ samplers.push("detailSampler");
+ }
+ getUniforms() {
+ return {
+ ubo: [
+ { name: "vDetailInfos", size: 4, type: "vec4" },
+ { name: "detailMatrix", size: 16, type: "mat4" },
+ ],
+ };
+ }
+}
+__decorate([
+ serializeAsTexture("detailTexture"),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], DetailMapConfiguration.prototype, "texture", void 0);
+__decorate([
+ serialize()
+], DetailMapConfiguration.prototype, "diffuseBlendLevel", void 0);
+__decorate([
+ serialize()
+], DetailMapConfiguration.prototype, "roughnessBlendLevel", void 0);
+__decorate([
+ serialize()
+], DetailMapConfiguration.prototype, "bumpLevel", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], DetailMapConfiguration.prototype, "normalBlendMethod", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], DetailMapConfiguration.prototype, "isEnabled", void 0);
+
+/**
+ * Type of clear operation to perform on a geometry texture.
+ */
+var GeometryRenderingTextureClearType;
+(function (GeometryRenderingTextureClearType) {
+ /**
+ * Clear the texture with zero.
+ */
+ GeometryRenderingTextureClearType[GeometryRenderingTextureClearType["Zero"] = 0] = "Zero";
+ /**
+ * Clear the texture with one.
+ */
+ GeometryRenderingTextureClearType[GeometryRenderingTextureClearType["One"] = 1] = "One";
+ /**
+ * Clear the texture with the maximum view Z value.
+ */
+ GeometryRenderingTextureClearType[GeometryRenderingTextureClearType["MaxViewZ"] = 2] = "MaxViewZ";
+})(GeometryRenderingTextureClearType || (GeometryRenderingTextureClearType = {}));
+/**
+ * Helper class to manage geometry rendering.
+ */
+class MaterialHelperGeometryRendering {
+ /**
+ * Creates a new geometry rendering configuration.
+ * @param renderPassId Render pass id the configuration is created for.
+ * @returns The created configuration.
+ */
+ static CreateConfiguration(renderPassId) {
+ MaterialHelperGeometryRendering._Configurations[renderPassId] = {
+ defines: {},
+ previousWorldMatrices: {},
+ previousViewProjection: Matrix.Zero(),
+ currentViewProjection: Matrix.Zero(),
+ previousBones: {},
+ lastUpdateFrameId: -1,
+ excludedSkinnedMesh: [],
+ reverseCulling: false,
+ };
+ return MaterialHelperGeometryRendering._Configurations[renderPassId];
+ }
+ /**
+ * Deletes a geometry rendering configuration.
+ * @param renderPassId The render pass id of the configuration to delete.
+ */
+ static DeleteConfiguration(renderPassId) {
+ delete MaterialHelperGeometryRendering._Configurations[renderPassId];
+ }
+ /**
+ * Gets a geometry rendering configuration.
+ * @param renderPassId The render pass id of the configuration to get.
+ * @returns The configuration.
+ */
+ static GetConfiguration(renderPassId) {
+ return MaterialHelperGeometryRendering._Configurations[renderPassId];
+ }
+ /**
+ * Adds uniforms and samplers for geometry rendering.
+ * @param uniforms The array of uniforms to add to.
+ * @param _samplers The array of samplers to add to.
+ */
+ static AddUniformsAndSamplers(uniforms, _samplers) {
+ uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones");
+ }
+ /**
+ * Marks a list of meshes as dirty for geometry rendering.
+ * @param renderPassId The render pass id the meshes are marked as dirty for.
+ * @param meshes The list of meshes to mark as dirty.
+ */
+ static MarkAsDirty(renderPassId, meshes) {
+ for (const mesh of meshes) {
+ if (!mesh.subMeshes) {
+ continue;
+ }
+ for (const subMesh of mesh.subMeshes) {
+ subMesh._removeDrawWrapper(renderPassId);
+ }
+ }
+ }
+ /**
+ * Prepares defines for geometry rendering.
+ * @param renderPassId The render pass id the defines are prepared for.
+ * @param mesh The mesh the defines are prepared for.
+ * @param defines The defines to update according to the geometry rendering configuration.
+ */
+ static PrepareDefines(renderPassId, mesh, defines) {
+ if (!defines._arePrePassDirty) {
+ return;
+ }
+ const configuration = MaterialHelperGeometryRendering._Configurations[renderPassId];
+ if (!configuration) {
+ return;
+ }
+ defines["PREPASS"] = true;
+ defines["PREPASS_COLOR"] = false;
+ defines["PREPASS_COLOR_INDEX"] = -1;
+ let numMRT = 0;
+ for (let i = 0; i < MaterialHelperGeometryRendering.GeometryTextureDescriptions.length; i++) {
+ const geometryTextureDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[i];
+ const defineName = geometryTextureDescription.define;
+ const defineIndex = geometryTextureDescription.defineIndex;
+ const index = configuration.defines[defineIndex];
+ if (index !== undefined) {
+ defines[defineName] = true;
+ defines[defineIndex] = index;
+ numMRT++;
+ }
+ else {
+ defines[defineName] = false;
+ delete defines[defineIndex];
+ }
+ }
+ defines["SCENE_MRT_COUNT"] = numMRT;
+ defines["BONES_VELOCITY_ENABLED"] =
+ mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton && !mesh.skeleton.isUsingTextureForMatrices && configuration.excludedSkinnedMesh.indexOf(mesh) === -1;
+ }
+ /**
+ * Binds geometry rendering data for a mesh.
+ * @param renderPassId The render pass id the geometry rendering data is bound for.
+ * @param effect The effect to bind the geometry rendering data to.
+ * @param mesh The mesh to bind the geometry rendering data for.
+ * @param world The world matrix of the mesh.
+ * @param material The material of the mesh.
+ */
+ static Bind(renderPassId, effect, mesh, world, material) {
+ const configuration = MaterialHelperGeometryRendering._Configurations[renderPassId];
+ if (!configuration) {
+ return;
+ }
+ const scene = mesh.getScene();
+ const engine = scene.getEngine();
+ if (configuration.reverseCulling) {
+ engine.setStateCullFaceType(scene._mirroredCameraPosition ? material.cullBackFaces : !material.cullBackFaces);
+ }
+ if (configuration.defines["PREPASS_VELOCITY_INDEX"] !== undefined || configuration.defines["PREPASS_VELOCITY_LINEAR_INDEX"] !== undefined) {
+ if (!configuration.previousWorldMatrices[mesh.uniqueId]) {
+ configuration.previousWorldMatrices[mesh.uniqueId] = world.clone();
+ }
+ if (!configuration.previousViewProjection) {
+ configuration.previousViewProjection = scene.getTransformMatrix().clone();
+ configuration.currentViewProjection = scene.getTransformMatrix().clone();
+ }
+ if (configuration.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) {
+ // First update of the prepass configuration for this rendering pass
+ configuration.lastUpdateFrameId = engine.frameId;
+ configuration.previousViewProjection.copyFrom(configuration.currentViewProjection);
+ configuration.currentViewProjection.copyFrom(scene.getTransformMatrix());
+ }
+ else if (configuration.lastUpdateFrameId !== engine.frameId) {
+ // The scene transformation did not change from the previous frame (so no camera motion), we must update previousViewProjection accordingly
+ configuration.lastUpdateFrameId = engine.frameId;
+ configuration.previousViewProjection.copyFrom(configuration.currentViewProjection);
+ }
+ effect.setMatrix("previousWorld", configuration.previousWorldMatrices[mesh.uniqueId]);
+ effect.setMatrix("previousViewProjection", configuration.previousViewProjection);
+ configuration.previousWorldMatrices[mesh.uniqueId] = world.clone();
+ if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
+ const skeleton = mesh.skeleton;
+ if (!skeleton.isUsingTextureForMatrices || effect.getUniformIndex("boneTextureWidth") === -1) {
+ const matrices = skeleton.getTransformMatrices(mesh);
+ if (matrices) {
+ if (!configuration.previousBones[mesh.uniqueId]) {
+ configuration.previousBones[mesh.uniqueId] = matrices.slice();
+ }
+ effect.setMatrices("mPreviousBones", configuration.previousBones[mesh.uniqueId]);
+ configuration.previousBones[mesh.uniqueId].set(matrices);
+ }
+ }
+ }
+ }
+ }
+}
+/**
+ * Descriptions of the geometry textures.
+ */
+MaterialHelperGeometryRendering.GeometryTextureDescriptions = [
+ {
+ type: 0,
+ name: "Irradiance",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_IRRADIANCE",
+ defineIndex: "PREPASS_IRRADIANCE_INDEX",
+ },
+ {
+ type: 1,
+ name: "WorldPosition",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_POSITION",
+ defineIndex: "PREPASS_POSITION_INDEX",
+ },
+ {
+ type: 2,
+ name: "Velocity",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_VELOCITY",
+ defineIndex: "PREPASS_VELOCITY_INDEX",
+ },
+ {
+ type: 3,
+ name: "Reflectivity",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_REFLECTIVITY",
+ defineIndex: "PREPASS_REFLECTIVITY_INDEX",
+ },
+ {
+ type: 5,
+ name: "ViewDepth",
+ clearType: 2 /* GeometryRenderingTextureClearType.MaxViewZ */,
+ define: "PREPASS_DEPTH",
+ defineIndex: "PREPASS_DEPTH_INDEX",
+ },
+ {
+ type: 6,
+ name: "ViewNormal",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_NORMAL",
+ defineIndex: "PREPASS_NORMAL_INDEX",
+ },
+ {
+ type: 7,
+ name: "AlbedoSqrt",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_ALBEDO_SQRT",
+ defineIndex: "PREPASS_ALBEDO_SQRT_INDEX",
+ },
+ {
+ type: 8,
+ name: "WorldNormal",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_WORLD_NORMAL",
+ defineIndex: "PREPASS_WORLD_NORMAL_INDEX",
+ },
+ {
+ type: 9,
+ name: "LocalPosition",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_LOCAL_POSITION",
+ defineIndex: "PREPASS_LOCAL_POSITION_INDEX",
+ },
+ {
+ type: 10,
+ name: "ScreenDepth",
+ clearType: 1 /* GeometryRenderingTextureClearType.One */,
+ define: "PREPASS_SCREENSPACE_DEPTH",
+ defineIndex: "PREPASS_SCREENSPACE_DEPTH_INDEX",
+ },
+ {
+ type: 11,
+ name: "LinearVelocity",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_VELOCITY_LINEAR",
+ defineIndex: "PREPASS_VELOCITY_LINEAR_INDEX",
+ },
+ {
+ type: 12,
+ name: "Albedo",
+ clearType: 0 /* GeometryRenderingTextureClearType.Zero */,
+ define: "PREPASS_ALBEDO",
+ defineIndex: "PREPASS_ALBEDO_INDEX",
+ },
+];
+MaterialHelperGeometryRendering._Configurations = {};
+
+const onCreatedEffectParameters$3 = { effect: null, subMesh: null };
+/** @internal */
+class StandardMaterialDefines extends MaterialDefines {
+ /**
+ * Initializes the Standard Material defines.
+ * @param externalProperties The external properties
+ */
+ constructor(externalProperties) {
+ super(externalProperties);
+ this.MAINUV1 = false;
+ this.MAINUV2 = false;
+ this.MAINUV3 = false;
+ this.MAINUV4 = false;
+ this.MAINUV5 = false;
+ this.MAINUV6 = false;
+ this.DIFFUSE = false;
+ this.DIFFUSEDIRECTUV = 0;
+ this.BAKED_VERTEX_ANIMATION_TEXTURE = false;
+ this.AMBIENT = false;
+ this.AMBIENTDIRECTUV = 0;
+ this.OPACITY = false;
+ this.OPACITYDIRECTUV = 0;
+ this.OPACITYRGB = false;
+ this.REFLECTION = false;
+ this.EMISSIVE = false;
+ this.EMISSIVEDIRECTUV = 0;
+ this.SPECULAR = false;
+ this.SPECULARDIRECTUV = 0;
+ this.BUMP = false;
+ this.BUMPDIRECTUV = 0;
+ this.PARALLAX = false;
+ this.PARALLAX_RHS = false;
+ this.PARALLAXOCCLUSION = false;
+ this.SPECULAROVERALPHA = false;
+ this.CLIPPLANE = false;
+ this.CLIPPLANE2 = false;
+ this.CLIPPLANE3 = false;
+ this.CLIPPLANE4 = false;
+ this.CLIPPLANE5 = false;
+ this.CLIPPLANE6 = false;
+ this.ALPHATEST = false;
+ this.DEPTHPREPASS = false;
+ this.ALPHAFROMDIFFUSE = false;
+ this.POINTSIZE = false;
+ this.FOG = false;
+ this.SPECULARTERM = false;
+ this.DIFFUSEFRESNEL = false;
+ this.OPACITYFRESNEL = false;
+ this.REFLECTIONFRESNEL = false;
+ this.REFRACTIONFRESNEL = false;
+ this.EMISSIVEFRESNEL = false;
+ this.FRESNEL = false;
+ this.NORMAL = false;
+ this.TANGENT = false;
+ this.UV1 = false;
+ this.UV2 = false;
+ this.UV3 = false;
+ this.UV4 = false;
+ this.UV5 = false;
+ this.UV6 = false;
+ this.VERTEXCOLOR = false;
+ this.VERTEXALPHA = false;
+ this.NUM_BONE_INFLUENCERS = 0;
+ this.BonesPerMesh = 0;
+ this.BONETEXTURE = false;
+ this.BONES_VELOCITY_ENABLED = false;
+ this.INSTANCES = false;
+ this.THIN_INSTANCES = false;
+ this.INSTANCESCOLOR = false;
+ this.GLOSSINESS = false;
+ this.ROUGHNESS = false;
+ this.EMISSIVEASILLUMINATION = false;
+ this.LINKEMISSIVEWITHDIFFUSE = false;
+ this.REFLECTIONFRESNELFROMSPECULAR = false;
+ this.LIGHTMAP = false;
+ this.LIGHTMAPDIRECTUV = 0;
+ this.OBJECTSPACE_NORMALMAP = false;
+ this.USELIGHTMAPASSHADOWMAP = false;
+ this.REFLECTIONMAP_3D = false;
+ this.REFLECTIONMAP_SPHERICAL = false;
+ this.REFLECTIONMAP_PLANAR = false;
+ this.REFLECTIONMAP_CUBIC = false;
+ this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
+ this.USE_LOCAL_REFRACTIONMAP_CUBIC = false;
+ this.REFLECTIONMAP_PROJECTION = false;
+ this.REFLECTIONMAP_SKYBOX = false;
+ this.REFLECTIONMAP_EXPLICIT = false;
+ this.REFLECTIONMAP_EQUIRECTANGULAR = false;
+ this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
+ this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
+ this.REFLECTIONMAP_OPPOSITEZ = false;
+ this.INVERTCUBICMAP = false;
+ this.LOGARITHMICDEPTH = false;
+ this.REFRACTION = false;
+ this.REFRACTIONMAP_3D = false;
+ this.REFLECTIONOVERALPHA = false;
+ this.TWOSIDEDLIGHTING = false;
+ this.SHADOWFLOAT = false;
+ this.MORPHTARGETS = false;
+ this.MORPHTARGETS_POSITION = false;
+ this.MORPHTARGETS_NORMAL = false;
+ this.MORPHTARGETS_TANGENT = false;
+ this.MORPHTARGETS_UV = false;
+ this.MORPHTARGETS_UV2 = false;
+ this.MORPHTARGETS_COLOR = false;
+ this.MORPHTARGETTEXTURE_HASPOSITIONS = false;
+ this.MORPHTARGETTEXTURE_HASNORMALS = false;
+ this.MORPHTARGETTEXTURE_HASTANGENTS = false;
+ this.MORPHTARGETTEXTURE_HASUVS = false;
+ this.MORPHTARGETTEXTURE_HASUV2S = false;
+ this.MORPHTARGETTEXTURE_HASCOLORS = false;
+ this.NUM_MORPH_INFLUENCERS = 0;
+ this.MORPHTARGETS_TEXTURE = false;
+ this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
+ this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
+ this.ALPHATEST_AFTERALLALPHACOMPUTATIONS = false;
+ this.ALPHABLEND = true;
+ this.PREPASS = false;
+ this.PREPASS_COLOR = false;
+ this.PREPASS_COLOR_INDEX = -1;
+ this.PREPASS_IRRADIANCE = false;
+ this.PREPASS_IRRADIANCE_INDEX = -1;
+ this.PREPASS_ALBEDO = false;
+ this.PREPASS_ALBEDO_INDEX = -1;
+ this.PREPASS_ALBEDO_SQRT = false;
+ this.PREPASS_ALBEDO_SQRT_INDEX = -1;
+ this.PREPASS_DEPTH = false;
+ this.PREPASS_DEPTH_INDEX = -1;
+ this.PREPASS_SCREENSPACE_DEPTH = false;
+ this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1;
+ this.PREPASS_NORMAL = false;
+ this.PREPASS_NORMAL_INDEX = -1;
+ this.PREPASS_NORMAL_WORLDSPACE = false;
+ this.PREPASS_WORLD_NORMAL = false;
+ this.PREPASS_WORLD_NORMAL_INDEX = -1;
+ this.PREPASS_POSITION = false;
+ this.PREPASS_POSITION_INDEX = -1;
+ this.PREPASS_LOCAL_POSITION = false;
+ this.PREPASS_LOCAL_POSITION_INDEX = -1;
+ this.PREPASS_VELOCITY = false;
+ this.PREPASS_VELOCITY_INDEX = -1;
+ this.PREPASS_VELOCITY_LINEAR = false;
+ this.PREPASS_VELOCITY_LINEAR_INDEX = -1;
+ this.PREPASS_REFLECTIVITY = false;
+ this.PREPASS_REFLECTIVITY_INDEX = -1;
+ this.SCENE_MRT_COUNT = 0;
+ this.RGBDLIGHTMAP = false;
+ this.RGBDREFLECTION = false;
+ this.RGBDREFRACTION = false;
+ this.IMAGEPROCESSING = false;
+ this.VIGNETTE = false;
+ this.VIGNETTEBLENDMODEMULTIPLY = false;
+ this.VIGNETTEBLENDMODEOPAQUE = false;
+ this.TONEMAPPING = 0;
+ this.CONTRAST = false;
+ this.COLORCURVES = false;
+ this.COLORGRADING = false;
+ this.COLORGRADING3D = false;
+ this.SAMPLER3DGREENDEPTH = false;
+ this.SAMPLER3DBGRMAP = false;
+ this.DITHER = false;
+ this.IMAGEPROCESSINGPOSTPROCESS = false;
+ this.SKIPFINALCOLORCLAMP = false;
+ this.MULTIVIEW = false;
+ this.ORDER_INDEPENDENT_TRANSPARENCY = false;
+ this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false;
+ this.CAMERA_ORTHOGRAPHIC = false;
+ this.CAMERA_PERSPECTIVE = false;
+ this.AREALIGHTSUPPORTED = true;
+ /**
+ * If the reflection texture on this material is in linear color space
+ * @internal
+ */
+ this.IS_REFLECTION_LINEAR = false;
+ /**
+ * If the refraction texture on this material is in linear color space
+ * @internal
+ */
+ this.IS_REFRACTION_LINEAR = false;
+ this.EXPOSURE = false;
+ this.DECAL_AFTER_DETAIL = false;
+ this.rebuild();
+ }
+ setReflectionMode(modeToEnable) {
+ const modes = [
+ "REFLECTIONMAP_CUBIC",
+ "REFLECTIONMAP_EXPLICIT",
+ "REFLECTIONMAP_PLANAR",
+ "REFLECTIONMAP_PROJECTION",
+ "REFLECTIONMAP_PROJECTION",
+ "REFLECTIONMAP_SKYBOX",
+ "REFLECTIONMAP_SPHERICAL",
+ "REFLECTIONMAP_EQUIRECTANGULAR",
+ "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
+ "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED",
+ ];
+ for (const mode of modes) {
+ this[mode] = mode === modeToEnable;
+ }
+ }
+}
+/**
+ * This is the default material used in Babylon. It is the best trade off between quality
+ * and performances.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction
+ */
+class StandardMaterial extends PushMaterial {
+ /**
+ * Gets the image processing configuration used either in this material.
+ */
+ get imageProcessingConfiguration() {
+ return this._imageProcessingConfiguration;
+ }
+ /**
+ * Sets the Default image processing configuration used either in the this material.
+ *
+ * If sets to null, the scene one is in use.
+ */
+ set imageProcessingConfiguration(value) {
+ this._attachImageProcessingConfiguration(value);
+ // Ensure the effect will be rebuilt.
+ this._markAllSubMeshesAsTexturesDirty();
+ }
+ /**
+ * Attaches a new image processing configuration to the Standard Material.
+ * @param configuration
+ */
+ _attachImageProcessingConfiguration(configuration) {
+ if (configuration === this._imageProcessingConfiguration) {
+ return;
+ }
+ // Detaches observer
+ if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
+ this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
+ }
+ // Pick the scene configuration if needed
+ if (!configuration) {
+ this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
+ }
+ else {
+ this._imageProcessingConfiguration = configuration;
+ }
+ // Attaches observer
+ if (this._imageProcessingConfiguration) {
+ this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
+ this._markAllSubMeshesAsImageProcessingDirty();
+ });
+ }
+ }
+ /**
+ * Can this material render to prepass
+ */
+ get isPrePassCapable() {
+ return !this.disableDepthWrite;
+ }
+ /**
+ * Gets whether the color curves effect is enabled.
+ */
+ get cameraColorCurvesEnabled() {
+ return this.imageProcessingConfiguration.colorCurvesEnabled;
+ }
+ /**
+ * Sets whether the color curves effect is enabled.
+ */
+ set cameraColorCurvesEnabled(value) {
+ this.imageProcessingConfiguration.colorCurvesEnabled = value;
+ }
+ /**
+ * Gets whether the color grading effect is enabled.
+ */
+ get cameraColorGradingEnabled() {
+ return this.imageProcessingConfiguration.colorGradingEnabled;
+ }
+ /**
+ * Gets whether the color grading effect is enabled.
+ */
+ set cameraColorGradingEnabled(value) {
+ this.imageProcessingConfiguration.colorGradingEnabled = value;
+ }
+ /**
+ * Gets whether tonemapping is enabled or not.
+ */
+ get cameraToneMappingEnabled() {
+ return this._imageProcessingConfiguration.toneMappingEnabled;
+ }
+ /**
+ * Sets whether tonemapping is enabled or not
+ */
+ set cameraToneMappingEnabled(value) {
+ this._imageProcessingConfiguration.toneMappingEnabled = value;
+ }
+ /**
+ * The camera exposure used on this material.
+ * This property is here and not in the camera to allow controlling exposure without full screen post process.
+ * This corresponds to a photographic exposure.
+ */
+ get cameraExposure() {
+ return this._imageProcessingConfiguration.exposure;
+ }
+ /**
+ * The camera exposure used on this material.
+ * This property is here and not in the camera to allow controlling exposure without full screen post process.
+ * This corresponds to a photographic exposure.
+ */
+ set cameraExposure(value) {
+ this._imageProcessingConfiguration.exposure = value;
+ }
+ /**
+ * Gets The camera contrast used on this material.
+ */
+ get cameraContrast() {
+ return this._imageProcessingConfiguration.contrast;
+ }
+ /**
+ * Sets The camera contrast used on this material.
+ */
+ set cameraContrast(value) {
+ this._imageProcessingConfiguration.contrast = value;
+ }
+ /**
+ * Gets the Color Grading 2D Lookup Texture.
+ */
+ get cameraColorGradingTexture() {
+ return this._imageProcessingConfiguration.colorGradingTexture;
+ }
+ /**
+ * Sets the Color Grading 2D Lookup Texture.
+ */
+ set cameraColorGradingTexture(value) {
+ this._imageProcessingConfiguration.colorGradingTexture = value;
+ }
+ /**
+ * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
+ * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
+ * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
+ * corresponding to low luminance, medium luminance, and high luminance areas respectively.
+ */
+ get cameraColorCurves() {
+ return this._imageProcessingConfiguration.colorCurves;
+ }
+ /**
+ * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).
+ * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
+ * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
+ * corresponding to low luminance, medium luminance, and high luminance areas respectively.
+ */
+ set cameraColorCurves(value) {
+ this._imageProcessingConfiguration.colorCurves = value;
+ }
+ /**
+ * Can this material render to several textures at once
+ */
+ get canRenderToMRT() {
+ return true;
+ }
+ /**
+ * Instantiates a new standard material.
+ * This is the default material used in Babylon. It is the best trade off between quality
+ * and performances.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction
+ * @param name Define the name of the material in the scene
+ * @param scene Define the scene the material belong to
+ * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false
+ */
+ constructor(name, scene, forceGLSL = false) {
+ super(name, scene, undefined, forceGLSL || StandardMaterial.ForceGLSL);
+ this._diffuseTexture = null;
+ this._ambientTexture = null;
+ this._opacityTexture = null;
+ this._reflectionTexture = null;
+ this._emissiveTexture = null;
+ this._specularTexture = null;
+ this._bumpTexture = null;
+ this._lightmapTexture = null;
+ this._refractionTexture = null;
+ /**
+ * The color of the material lit by the environmental background lighting.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#ambient-color-example
+ */
+ this.ambientColor = new Color3(0, 0, 0);
+ /**
+ * The basic color of the material as viewed under a light.
+ */
+ this.diffuseColor = new Color3(1, 1, 1);
+ /**
+ * Define how the color and intensity of the highlight given by the light in the material.
+ */
+ this.specularColor = new Color3(1, 1, 1);
+ /**
+ * Define the color of the material as if self lit.
+ * This will be mixed in the final result even in the absence of light.
+ */
+ this.emissiveColor = new Color3(0, 0, 0);
+ /**
+ * Defines how sharp are the highlights in the material.
+ * The bigger the value the sharper giving a more glossy feeling to the result.
+ * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
+ */
+ this.specularPower = 64;
+ this._useAlphaFromDiffuseTexture = false;
+ this._useEmissiveAsIllumination = false;
+ this._linkEmissiveWithDiffuse = false;
+ this._useSpecularOverAlpha = false;
+ this._useReflectionOverAlpha = false;
+ this._disableLighting = false;
+ this._useObjectSpaceNormalMap = false;
+ this._useParallax = false;
+ this._useParallaxOcclusion = false;
+ /**
+ * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
+ */
+ this.parallaxScaleBias = 0.05;
+ this._roughness = 0;
+ /**
+ * In case of refraction, define the value of the index of refraction.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions
+ */
+ this.indexOfRefraction = 0.98;
+ /**
+ * Invert the refraction texture alongside the y axis.
+ * It can be useful with procedural textures or probe for instance.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions
+ */
+ this.invertRefractionY = true;
+ /**
+ * Defines the alpha limits in alpha test mode.
+ */
+ this.alphaCutOff = 0.4;
+ this._useLightmapAsShadowmap = false;
+ this._useReflectionFresnelFromSpecular = false;
+ this._useGlossinessFromSpecularMapAlpha = false;
+ this._maxSimultaneousLights = 4;
+ this._invertNormalMapX = false;
+ this._invertNormalMapY = false;
+ this._twoSidedLighting = false;
+ this._applyDecalMapAfterDetailMap = false;
+ this._shadersLoaded = false;
+ this._renderTargets = new SmartArray(16);
+ this._globalAmbientColor = new Color3(0, 0, 0);
+ this._cacheHasRenderTargetTextures = false;
+ this.detailMap = new DetailMapConfiguration(this);
+ // Setup the default processing configuration to the scene.
+ this._attachImageProcessingConfiguration(null);
+ this.prePassConfiguration = new PrePassConfiguration();
+ this.getRenderTargetTextures = () => {
+ this._renderTargets.reset();
+ if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
+ this._renderTargets.push(this._reflectionTexture);
+ }
+ if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
+ this._renderTargets.push(this._refractionTexture);
+ }
+ this._eventInfo.renderTargets = this._renderTargets;
+ this._callbackPluginEventFillRenderTargetTextures(this._eventInfo);
+ return this._renderTargets;
+ };
+ }
+ /**
+ * Gets a boolean indicating that current material needs to register RTT
+ */
+ get hasRenderTargetTextures() {
+ if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
+ return true;
+ }
+ if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
+ return true;
+ }
+ return this._cacheHasRenderTargetTextures;
+ }
+ /**
+ * Gets the current class name of the material e.g. "StandardMaterial"
+ * Mainly use in serialization.
+ * @returns the class name
+ */
+ getClassName() {
+ return "StandardMaterial";
+ }
+ /**
+ * Specifies if the material will require alpha blending
+ * @returns a boolean specifying if alpha blending is needed
+ */
+ needAlphaBlending() {
+ if (this._hasTransparencyMode) {
+ return this._transparencyModeIsBlend;
+ }
+ if (this._disableAlphaBlending) {
+ return false;
+ }
+ return (this.alpha < 1.0 ||
+ this._opacityTexture != null ||
+ this._shouldUseAlphaFromDiffuseTexture() ||
+ (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled));
+ }
+ /**
+ * Specifies if this material should be rendered in alpha test mode
+ * @returns a boolean specifying if an alpha test is needed.
+ */
+ needAlphaTesting() {
+ if (this._hasTransparencyMode) {
+ return this._transparencyModeIsTest;
+ }
+ return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === Material.MATERIAL_ALPHATEST);
+ }
+ /**
+ * @returns whether or not the alpha value of the diffuse texture should be used for alpha blending.
+ */
+ _shouldUseAlphaFromDiffuseTexture() {
+ return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture && this._transparencyMode !== Material.MATERIAL_OPAQUE;
+ }
+ /**
+ * @returns whether or not there is a usable alpha channel for transparency.
+ */
+ _hasAlphaChannel() {
+ return (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._opacityTexture != null;
+ }
+ /**
+ * Get the texture used for alpha test purpose.
+ * @returns the diffuse texture in case of the standard material.
+ */
+ getAlphaTestTexture() {
+ return this._diffuseTexture;
+ }
+ /**
+ * Get if the submesh is ready to be used and all its information available.
+ * Child classes can use it to update shaders
+ * @param mesh defines the mesh to check
+ * @param subMesh defines which submesh to check
+ * @param useInstances specifies that instances should be used
+ * @returns a boolean indicating that the submesh is ready or not
+ */
+ isReadyForSubMesh(mesh, subMesh, useInstances = false) {
+ if (!this._uniformBufferLayoutBuilt) {
+ this.buildUniformLayout();
+ }
+ const drawWrapper = subMesh._drawWrapper;
+ if (drawWrapper.effect && this.isFrozen) {
+ if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) {
+ return true;
+ }
+ }
+ if (!subMesh.materialDefines) {
+ this._callbackPluginEventGeneric(4 /* MaterialPluginEvent.GetDefineNames */, this._eventInfo);
+ subMesh.materialDefines = new StandardMaterialDefines(this._eventInfo.defineNames);
+ }
+ const scene = this.getScene();
+ const defines = subMesh.materialDefines;
+ if (this._isReadyForSubMesh(subMesh)) {
+ return true;
+ }
+ const engine = scene.getEngine();
+ // Lights
+ defines._needNormals = PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
+ // Multiview
+ PrepareDefinesForMultiview(scene, defines);
+ // PrePass
+ const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;
+ PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit);
+ // Order independant transparency
+ PrepareDefinesForOIT(scene, defines, oit);
+ MaterialHelperGeometryRendering.PrepareDefines(engine.currentRenderPassId, mesh, defines);
+ // Textures
+ if (defines._areTexturesDirty) {
+ this._eventInfo.hasRenderTargetTextures = false;
+ this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);
+ this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures;
+ defines._needUVs = false;
+ for (let i = 1; i <= 6; ++i) {
+ defines["MAINUV" + i] = false;
+ }
+ if (scene.texturesEnabled) {
+ defines.DIFFUSEDIRECTUV = 0;
+ defines.BUMPDIRECTUV = 0;
+ defines.AMBIENTDIRECTUV = 0;
+ defines.OPACITYDIRECTUV = 0;
+ defines.EMISSIVEDIRECTUV = 0;
+ defines.SPECULARDIRECTUV = 0;
+ defines.LIGHTMAPDIRECTUV = 0;
+ if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
+ if (!this._diffuseTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ else {
+ PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
+ }
+ }
+ else {
+ defines.DIFFUSE = false;
+ }
+ if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
+ if (!this._ambientTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ else {
+ PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
+ }
+ }
+ else {
+ defines.AMBIENT = false;
+ }
+ if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
+ if (!this._opacityTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ else {
+ PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
+ defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
+ }
+ }
+ else {
+ defines.OPACITY = false;
+ }
+ if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
+ if (!this._reflectionTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ else {
+ defines._needNormals = true;
+ defines.REFLECTION = true;
+ defines.ROUGHNESS = this._roughness > 0;
+ defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
+ defines.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE;
+ defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
+ defines.REFLECTIONMAP_OPPOSITEZ =
+ defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !this._reflectionTexture.invertZ : this._reflectionTexture.invertZ;
+ defines.RGBDREFLECTION = this._reflectionTexture.isRGBD;
+ switch (this._reflectionTexture.coordinatesMode) {
+ case Texture.EXPLICIT_MODE:
+ defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
+ break;
+ case Texture.PLANAR_MODE:
+ defines.setReflectionMode("REFLECTIONMAP_PLANAR");
+ break;
+ case Texture.PROJECTION_MODE:
+ defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
+ break;
+ case Texture.SKYBOX_MODE:
+ defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
+ break;
+ case Texture.SPHERICAL_MODE:
+ defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
+ break;
+ case Texture.EQUIRECTANGULAR_MODE:
+ defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
+ break;
+ case Texture.FIXED_EQUIRECTANGULAR_MODE:
+ defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
+ break;
+ case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
+ defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
+ break;
+ case Texture.CUBIC_MODE:
+ case Texture.INVCUBIC_MODE:
+ default:
+ defines.setReflectionMode("REFLECTIONMAP_CUBIC");
+ break;
+ }
+ defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
+ }
+ }
+ else {
+ defines.REFLECTION = false;
+ defines.REFLECTIONMAP_OPPOSITEZ = false;
+ }
+ if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
+ if (!this._emissiveTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ else {
+ PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
+ }
+ }
+ else {
+ defines.EMISSIVE = false;
+ }
+ if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
+ if (!this._lightmapTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ else {
+ PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
+ defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
+ defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;
+ }
+ }
+ else {
+ defines.LIGHTMAP = false;
+ }
+ if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
+ if (!this._specularTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ else {
+ PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
+ defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
+ }
+ }
+ else {
+ defines.SPECULAR = false;
+ }
+ if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
+ // Bump texture can not be not blocking.
+ if (!this._bumpTexture.isReady()) {
+ return false;
+ }
+ else {
+ PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
+ defines.PARALLAX = this._useParallax;
+ defines.PARALLAX_RHS = scene.useRightHandedSystem;
+ defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
+ }
+ defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
+ }
+ else {
+ defines.BUMP = false;
+ defines.PARALLAX = false;
+ defines.PARALLAX_RHS = false;
+ defines.PARALLAXOCCLUSION = false;
+ }
+ if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
+ if (!this._refractionTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ else {
+ defines._needUVs = true;
+ defines.REFRACTION = true;
+ defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
+ defines.RGBDREFRACTION = this._refractionTexture.isRGBD;
+ defines.USE_LOCAL_REFRACTIONMAP_CUBIC = this._refractionTexture.boundingBoxSize ? true : false;
+ }
+ }
+ else {
+ defines.REFRACTION = false;
+ }
+ defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
+ }
+ else {
+ defines.DIFFUSE = false;
+ defines.AMBIENT = false;
+ defines.OPACITY = false;
+ defines.REFLECTION = false;
+ defines.EMISSIVE = false;
+ defines.LIGHTMAP = false;
+ defines.BUMP = false;
+ defines.REFRACTION = false;
+ }
+ defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
+ defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
+ defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
+ defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
+ defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;
+ defines.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null;
+ defines.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(mesh); // check on null for backward compatibility
+ }
+ this._eventInfo.isReadyForSubMesh = true;
+ this._eventInfo.defines = defines;
+ this._eventInfo.subMesh = subMesh;
+ this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);
+ if (!this._eventInfo.isReadyForSubMesh) {
+ return false;
+ }
+ if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
+ if (!this._imageProcessingConfiguration.isReady()) {
+ return false;
+ }
+ this._imageProcessingConfiguration.prepareDefines(defines);
+ defines.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace;
+ defines.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace;
+ }
+ if (defines._areFresnelDirty) {
+ if (StandardMaterial.FresnelEnabled) {
+ // Fresnel
+ if (this._diffuseFresnelParameters ||
+ this._opacityFresnelParameters ||
+ this._emissiveFresnelParameters ||
+ this._refractionFresnelParameters ||
+ this._reflectionFresnelParameters) {
+ defines.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled;
+ defines.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
+ defines.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled;
+ defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
+ defines.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled;
+ defines.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled;
+ defines._needNormals = true;
+ defines.FRESNEL = true;
+ }
+ }
+ else {
+ defines.FRESNEL = false;
+ }
+ }
+ // Check if Area Lights have LTC texture.
+ if (defines["AREALIGHTUSED"]) {
+ for (let index = 0; index < mesh.lightSources.length; index++) {
+ if (!mesh.lightSources[index]._isReady()) {
+ return false;
+ }
+ }
+ }
+ // Misc.
+ PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines, this._applyDecalMapAfterDetailMap);
+ // Values that need to be evaluated on every frame
+ PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
+ // External config
+ this._eventInfo.defines = defines;
+ this._eventInfo.mesh = mesh;
+ this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo);
+ // Attribs
+ PrepareDefinesForAttributes(mesh, defines, true, true, true);
+ // External config
+ this._callbackPluginEventPrepareDefines(this._eventInfo);
+ // Get correct effect
+ let forceWasNotReadyPreviously = false;
+ if (defines.isDirty) {
+ const lightDisposed = defines._areLightsDisposed;
+ defines.markAsProcessed();
+ // Fallbacks
+ const fallbacks = new EffectFallbacks();
+ if (defines.REFLECTION) {
+ fallbacks.addFallback(0, "REFLECTION");
+ }
+ if (defines.SPECULAR) {
+ fallbacks.addFallback(0, "SPECULAR");
+ }
+ if (defines.BUMP) {
+ fallbacks.addFallback(0, "BUMP");
+ }
+ if (defines.PARALLAX) {
+ fallbacks.addFallback(1, "PARALLAX");
+ }
+ if (defines.PARALLAX_RHS) {
+ fallbacks.addFallback(1, "PARALLAX_RHS");
+ }
+ if (defines.PARALLAXOCCLUSION) {
+ fallbacks.addFallback(0, "PARALLAXOCCLUSION");
+ }
+ if (defines.SPECULAROVERALPHA) {
+ fallbacks.addFallback(0, "SPECULAROVERALPHA");
+ }
+ if (defines.FOG) {
+ fallbacks.addFallback(1, "FOG");
+ }
+ if (defines.POINTSIZE) {
+ fallbacks.addFallback(0, "POINTSIZE");
+ }
+ if (defines.LOGARITHMICDEPTH) {
+ fallbacks.addFallback(0, "LOGARITHMICDEPTH");
+ }
+ HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
+ if (defines.SPECULARTERM) {
+ fallbacks.addFallback(0, "SPECULARTERM");
+ }
+ if (defines.DIFFUSEFRESNEL) {
+ fallbacks.addFallback(1, "DIFFUSEFRESNEL");
+ }
+ if (defines.OPACITYFRESNEL) {
+ fallbacks.addFallback(2, "OPACITYFRESNEL");
+ }
+ if (defines.REFLECTIONFRESNEL) {
+ fallbacks.addFallback(3, "REFLECTIONFRESNEL");
+ }
+ if (defines.EMISSIVEFRESNEL) {
+ fallbacks.addFallback(4, "EMISSIVEFRESNEL");
+ }
+ if (defines.FRESNEL) {
+ fallbacks.addFallback(4, "FRESNEL");
+ }
+ if (defines.MULTIVIEW) {
+ fallbacks.addFallback(0, "MULTIVIEW");
+ }
+ //Attributes
+ const attribs = [VertexBuffer.PositionKind];
+ if (defines.NORMAL) {
+ attribs.push(VertexBuffer.NormalKind);
+ }
+ if (defines.TANGENT) {
+ attribs.push(VertexBuffer.TangentKind);
+ }
+ for (let i = 1; i <= 6; ++i) {
+ if (defines["UV" + i]) {
+ attribs.push(`uv${i === 1 ? "" : i}`);
+ }
+ }
+ if (defines.VERTEXCOLOR) {
+ attribs.push(VertexBuffer.ColorKind);
+ }
+ PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
+ PrepareAttributesForInstances(attribs, defines);
+ PrepareAttributesForMorphTargets(attribs, mesh, defines);
+ PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);
+ let shaderName = "default";
+ const uniforms = [
+ "world",
+ "view",
+ "viewProjection",
+ "vEyePosition",
+ "vLightsType",
+ "vAmbientColor",
+ "vDiffuseColor",
+ "vSpecularColor",
+ "vEmissiveColor",
+ "visibility",
+ "vFogInfos",
+ "vFogColor",
+ "pointSize",
+ "vDiffuseInfos",
+ "vAmbientInfos",
+ "vOpacityInfos",
+ "vReflectionInfos",
+ "vEmissiveInfos",
+ "vSpecularInfos",
+ "vBumpInfos",
+ "vLightmapInfos",
+ "vRefractionInfos",
+ "mBones",
+ "diffuseMatrix",
+ "ambientMatrix",
+ "opacityMatrix",
+ "reflectionMatrix",
+ "emissiveMatrix",
+ "specularMatrix",
+ "bumpMatrix",
+ "normalMatrix",
+ "lightmapMatrix",
+ "refractionMatrix",
+ "diffuseLeftColor",
+ "diffuseRightColor",
+ "opacityParts",
+ "reflectionLeftColor",
+ "reflectionRightColor",
+ "emissiveLeftColor",
+ "emissiveRightColor",
+ "refractionLeftColor",
+ "refractionRightColor",
+ "vReflectionPosition",
+ "vReflectionSize",
+ "vRefractionPosition",
+ "vRefractionSize",
+ "logarithmicDepthConstant",
+ "vTangentSpaceParams",
+ "alphaCutOff",
+ "boneTextureWidth",
+ "morphTargetTextureInfo",
+ "morphTargetTextureIndices",
+ ];
+ const samplers = [
+ "diffuseSampler",
+ "ambientSampler",
+ "opacitySampler",
+ "reflectionCubeSampler",
+ "reflection2DSampler",
+ "emissiveSampler",
+ "specularSampler",
+ "bumpSampler",
+ "lightmapSampler",
+ "refractionCubeSampler",
+ "refraction2DSampler",
+ "boneSampler",
+ "morphTargets",
+ "oitDepthSampler",
+ "oitFrontColorSampler",
+ "areaLightsLTC1Sampler",
+ "areaLightsLTC2Sampler",
+ ];
+ const uniformBuffers = ["Material", "Scene", "Mesh"];
+ const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS };
+ this._eventInfo.fallbacks = fallbacks;
+ this._eventInfo.fallbackRank = 0;
+ this._eventInfo.defines = defines;
+ this._eventInfo.uniforms = uniforms;
+ this._eventInfo.attributes = attribs;
+ this._eventInfo.samplers = samplers;
+ this._eventInfo.uniformBuffersNames = uniformBuffers;
+ this._eventInfo.customCode = undefined;
+ this._eventInfo.mesh = mesh;
+ this._eventInfo.indexParameters = indexParameters;
+ this._callbackPluginEventGeneric(128 /* MaterialPluginEvent.PrepareEffect */, this._eventInfo);
+ MaterialHelperGeometryRendering.AddUniformsAndSamplers(uniforms, samplers);
+ PrePassConfiguration.AddUniforms(uniforms);
+ if (ImageProcessingConfiguration) {
+ ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
+ ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
+ }
+ PrepareUniformsAndSamplersList({
+ uniformsNames: uniforms,
+ uniformBuffersNames: uniformBuffers,
+ samplers: samplers,
+ defines: defines,
+ maxSimultaneousLights: this._maxSimultaneousLights,
+ });
+ addClipPlaneUniforms(uniforms);
+ const csnrOptions = {};
+ if (this.customShaderNameResolve) {
+ shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);
+ }
+ const join = defines.toString();
+ const previousEffect = subMesh.effect;
+ let effect = scene.getEngine().createEffect(shaderName, {
+ attributes: attribs,
+ uniformsNames: uniforms,
+ uniformBuffersNames: uniformBuffers,
+ samplers: samplers,
+ defines: join,
+ fallbacks: fallbacks,
+ onCompiled: this.onCompiled,
+ onError: this.onError,
+ indexParameters,
+ processFinalCode: csnrOptions.processFinalCode,
+ processCodeAfterIncludes: this._eventInfo.customCode,
+ multiTarget: defines.PREPASS,
+ shaderLanguage: this._shaderLanguage,
+ extraInitializationsAsync: this._shadersLoaded
+ ? undefined
+ : async () => {
+ if (this._shaderLanguage === 1 /* ShaderLanguage.WGSL */) {
+ await Promise.all([Promise.resolve().then(() => default_vertex), Promise.resolve().then(() => default_fragment)]);
+ }
+ else {
+ await Promise.all([Promise.resolve().then(() => default_vertex$1), Promise.resolve().then(() => default_fragment$1)]);
+ }
+ this._shadersLoaded = true;
+ },
+ }, engine);
+ this._eventInfo.customCode = undefined;
+ if (effect) {
+ if (this._onEffectCreatedObservable) {
+ onCreatedEffectParameters$3.effect = effect;
+ onCreatedEffectParameters$3.subMesh = subMesh;
+ this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$3);
+ }
+ // Use previous effect while new one is compiling
+ if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
+ effect = previousEffect;
+ defines.markAsUnprocessed();
+ forceWasNotReadyPreviously = this.isFrozen;
+ if (lightDisposed) {
+ // re register in case it takes more than one frame.
+ defines._areLightsDisposed = true;
+ return false;
+ }
+ }
+ else {
+ scene.resetCachedMaterial();
+ subMesh.setEffect(effect, defines, this._materialContext);
+ }
+ }
+ }
+ if (!subMesh.effect || !subMesh.effect.isReady()) {
+ return false;
+ }
+ defines._renderId = scene.getRenderId();
+ drawWrapper._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true;
+ drawWrapper._wasPreviouslyUsingInstances = useInstances;
+ this._checkScenePerformancePriority();
+ return true;
+ }
+ /**
+ * Builds the material UBO layouts.
+ * Used internally during the effect preparation.
+ */
+ buildUniformLayout() {
+ // Order is important !
+ const ubo = this._uniformBuffer;
+ ubo.addUniform("diffuseLeftColor", 4);
+ ubo.addUniform("diffuseRightColor", 4);
+ ubo.addUniform("opacityParts", 4);
+ ubo.addUniform("reflectionLeftColor", 4);
+ ubo.addUniform("reflectionRightColor", 4);
+ ubo.addUniform("refractionLeftColor", 4);
+ ubo.addUniform("refractionRightColor", 4);
+ ubo.addUniform("emissiveLeftColor", 4);
+ ubo.addUniform("emissiveRightColor", 4);
+ ubo.addUniform("vDiffuseInfos", 2);
+ ubo.addUniform("vAmbientInfos", 2);
+ ubo.addUniform("vOpacityInfos", 2);
+ ubo.addUniform("vReflectionInfos", 2);
+ ubo.addUniform("vReflectionPosition", 3);
+ ubo.addUniform("vReflectionSize", 3);
+ ubo.addUniform("vEmissiveInfos", 2);
+ ubo.addUniform("vLightmapInfos", 2);
+ ubo.addUniform("vSpecularInfos", 2);
+ ubo.addUniform("vBumpInfos", 3);
+ ubo.addUniform("diffuseMatrix", 16);
+ ubo.addUniform("ambientMatrix", 16);
+ ubo.addUniform("opacityMatrix", 16);
+ ubo.addUniform("reflectionMatrix", 16);
+ ubo.addUniform("emissiveMatrix", 16);
+ ubo.addUniform("lightmapMatrix", 16);
+ ubo.addUniform("specularMatrix", 16);
+ ubo.addUniform("bumpMatrix", 16);
+ ubo.addUniform("vTangentSpaceParams", 2);
+ ubo.addUniform("pointSize", 1);
+ ubo.addUniform("alphaCutOff", 1);
+ ubo.addUniform("refractionMatrix", 16);
+ ubo.addUniform("vRefractionInfos", 4);
+ ubo.addUniform("vRefractionPosition", 3);
+ ubo.addUniform("vRefractionSize", 3);
+ ubo.addUniform("vSpecularColor", 4);
+ ubo.addUniform("vEmissiveColor", 3);
+ ubo.addUniform("vDiffuseColor", 4);
+ ubo.addUniform("vAmbientColor", 3);
+ super.buildUniformLayout();
+ }
+ /**
+ * Binds the submesh to this material by preparing the effect and shader to draw
+ * @param world defines the world transformation matrix
+ * @param mesh defines the mesh containing the submesh
+ * @param subMesh defines the submesh to bind the material to
+ */
+ bindForSubMesh(world, mesh, subMesh) {
+ const scene = this.getScene();
+ const defines = subMesh.materialDefines;
+ if (!defines) {
+ return;
+ }
+ const effect = subMesh.effect;
+ if (!effect) {
+ return;
+ }
+ this._activeEffect = effect;
+ // Matrices Mesh.
+ mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
+ mesh.transferToEffect(world);
+ // Binding unconditionally
+ this._uniformBuffer.bindToEffect(effect, "Material");
+ this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen);
+ MaterialHelperGeometryRendering.Bind(scene.getEngine().currentRenderPassId, this._activeEffect, mesh, world, this);
+ this._eventInfo.subMesh = subMesh;
+ this._callbackPluginEventHardBindForSubMesh(this._eventInfo);
+ // Normal Matrix
+ if (defines.OBJECTSPACE_NORMALMAP) {
+ world.toNormalMatrix(this._normalMatrix);
+ this.bindOnlyNormalMatrix(this._normalMatrix);
+ }
+ const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility);
+ // Bones
+ BindBonesParameters(mesh, effect);
+ const ubo = this._uniformBuffer;
+ if (mustRebind) {
+ this.bindViewProjection(effect);
+ if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || subMesh._drawWrapper._forceRebindOnNextCall) {
+ if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
+ // Fresnel
+ if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
+ ubo.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
+ ubo.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
+ }
+ if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
+ ubo.updateColor4("opacityParts", new Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
+ }
+ if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
+ ubo.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
+ ubo.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
+ }
+ if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
+ ubo.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
+ ubo.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
+ }
+ if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
+ ubo.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
+ ubo.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
+ }
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
+ ubo.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
+ BindTextureMatrix(this._diffuseTexture, ubo, "diffuse");
+ }
+ if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
+ ubo.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
+ BindTextureMatrix(this._ambientTexture, ubo, "ambient");
+ }
+ if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
+ ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
+ BindTextureMatrix(this._opacityTexture, ubo, "opacity");
+ }
+ if (this._hasAlphaChannel()) {
+ ubo.updateFloat("alphaCutOff", this.alphaCutOff);
+ }
+ if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
+ ubo.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
+ ubo.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
+ if (this._reflectionTexture.boundingBoxSize) {
+ const cubeTexture = this._reflectionTexture;
+ ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
+ ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
+ }
+ }
+ else {
+ ubo.updateFloat2("vReflectionInfos", 0.0, this.roughness);
+ }
+ if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
+ ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
+ BindTextureMatrix(this._emissiveTexture, ubo, "emissive");
+ }
+ if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
+ ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
+ BindTextureMatrix(this._lightmapTexture, ubo, "lightmap");
+ }
+ if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
+ ubo.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
+ BindTextureMatrix(this._specularTexture, ubo, "specular");
+ }
+ if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
+ ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
+ BindTextureMatrix(this._bumpTexture, ubo, "bump");
+ if (scene._mirroredCameraPosition) {
+ ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1, this._invertNormalMapY ? 1.0 : -1);
+ }
+ else {
+ ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1.0, this._invertNormalMapY ? -1 : 1.0);
+ }
+ }
+ if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
+ let depth = 1.0;
+ if (!this._refractionTexture.isCube) {
+ ubo.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
+ if (this._refractionTexture.depth) {
+ depth = this._refractionTexture.depth;
+ }
+ }
+ ubo.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
+ if (this._refractionTexture.boundingBoxSize) {
+ const cubeTexture = this._refractionTexture;
+ ubo.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition);
+ ubo.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize);
+ }
+ }
+ }
+ // Point size
+ if (this.pointsCloud) {
+ ubo.updateFloat("pointSize", this.pointSize);
+ }
+ ubo.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
+ ubo.updateColor3("vEmissiveColor", StandardMaterial.EmissiveTextureEnabled ? this.emissiveColor : Color3.BlackReadOnly);
+ ubo.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha);
+ scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
+ ubo.updateColor3("vAmbientColor", this._globalAmbientColor);
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
+ effect.setTexture("diffuseSampler", this._diffuseTexture);
+ }
+ if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
+ effect.setTexture("ambientSampler", this._ambientTexture);
+ }
+ if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
+ effect.setTexture("opacitySampler", this._opacityTexture);
+ }
+ if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
+ if (this._reflectionTexture.isCube) {
+ effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
+ }
+ else {
+ effect.setTexture("reflection2DSampler", this._reflectionTexture);
+ }
+ }
+ if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
+ effect.setTexture("emissiveSampler", this._emissiveTexture);
+ }
+ if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
+ effect.setTexture("lightmapSampler", this._lightmapTexture);
+ }
+ if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
+ effect.setTexture("specularSampler", this._specularTexture);
+ }
+ if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
+ effect.setTexture("bumpSampler", this._bumpTexture);
+ }
+ if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
+ if (this._refractionTexture.isCube) {
+ effect.setTexture("refractionCubeSampler", this._refractionTexture);
+ }
+ else {
+ effect.setTexture("refraction2DSampler", this._refractionTexture);
+ }
+ }
+ }
+ // OIT with depth peeling
+ if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) {
+ this.getScene().depthPeelingRenderer.bind(effect);
+ }
+ this._eventInfo.subMesh = subMesh;
+ this._callbackPluginEventBindForSubMesh(this._eventInfo);
+ // Clip plane
+ bindClipPlane(effect, this, scene);
+ // Colors
+ this.bindEyePosition(effect);
+ }
+ else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {
+ this._needToBindSceneUbo = true;
+ }
+ if (mustRebind || !this.isFrozen) {
+ // Lights
+ if (scene.lightsEnabled && !this._disableLighting) {
+ BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
+ }
+ // View
+ if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) ||
+ this._reflectionTexture ||
+ this._refractionTexture ||
+ mesh.receiveShadows ||
+ defines.PREPASS) {
+ this.bindView(effect);
+ }
+ // Fog
+ BindFogParameters(scene, mesh, effect);
+ // Morph targets
+ if (defines.NUM_MORPH_INFLUENCERS) {
+ BindMorphTargetParameters(mesh, effect);
+ }
+ if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) {
+ mesh.bakedVertexAnimationManager?.bind(effect, defines.INSTANCES);
+ }
+ // Log. depth
+ if (this.useLogarithmicDepth) {
+ BindLogDepth(defines, effect, scene);
+ }
+ // image processing
+ if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
+ this._imageProcessingConfiguration.bind(this._activeEffect);
+ }
+ }
+ this._afterBind(mesh, this._activeEffect, subMesh);
+ ubo.update();
+ }
+ /**
+ * Get the list of animatables in the material.
+ * @returns the list of animatables object used in the material
+ */
+ getAnimatables() {
+ const results = super.getAnimatables();
+ if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
+ results.push(this._diffuseTexture);
+ }
+ if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
+ results.push(this._ambientTexture);
+ }
+ if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
+ results.push(this._opacityTexture);
+ }
+ if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
+ results.push(this._reflectionTexture);
+ }
+ if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
+ results.push(this._emissiveTexture);
+ }
+ if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
+ results.push(this._specularTexture);
+ }
+ if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
+ results.push(this._bumpTexture);
+ }
+ if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
+ results.push(this._lightmapTexture);
+ }
+ if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
+ results.push(this._refractionTexture);
+ }
+ return results;
+ }
+ /**
+ * Gets the active textures from the material
+ * @returns an array of textures
+ */
+ getActiveTextures() {
+ const activeTextures = super.getActiveTextures();
+ if (this._diffuseTexture) {
+ activeTextures.push(this._diffuseTexture);
+ }
+ if (this._ambientTexture) {
+ activeTextures.push(this._ambientTexture);
+ }
+ if (this._opacityTexture) {
+ activeTextures.push(this._opacityTexture);
+ }
+ if (this._reflectionTexture) {
+ activeTextures.push(this._reflectionTexture);
+ }
+ if (this._emissiveTexture) {
+ activeTextures.push(this._emissiveTexture);
+ }
+ if (this._specularTexture) {
+ activeTextures.push(this._specularTexture);
+ }
+ if (this._bumpTexture) {
+ activeTextures.push(this._bumpTexture);
+ }
+ if (this._lightmapTexture) {
+ activeTextures.push(this._lightmapTexture);
+ }
+ if (this._refractionTexture) {
+ activeTextures.push(this._refractionTexture);
+ }
+ return activeTextures;
+ }
+ /**
+ * Specifies if the material uses a texture
+ * @param texture defines the texture to check against the material
+ * @returns a boolean specifying if the material uses the texture
+ */
+ hasTexture(texture) {
+ if (super.hasTexture(texture)) {
+ return true;
+ }
+ if (this._diffuseTexture === texture) {
+ return true;
+ }
+ if (this._ambientTexture === texture) {
+ return true;
+ }
+ if (this._opacityTexture === texture) {
+ return true;
+ }
+ if (this._reflectionTexture === texture) {
+ return true;
+ }
+ if (this._emissiveTexture === texture) {
+ return true;
+ }
+ if (this._specularTexture === texture) {
+ return true;
+ }
+ if (this._bumpTexture === texture) {
+ return true;
+ }
+ if (this._lightmapTexture === texture) {
+ return true;
+ }
+ if (this._refractionTexture === texture) {
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Disposes the material
+ * @param forceDisposeEffect specifies if effects should be forcefully disposed
+ * @param forceDisposeTextures specifies if textures should be forcefully disposed
+ */
+ dispose(forceDisposeEffect, forceDisposeTextures) {
+ if (forceDisposeTextures) {
+ this._diffuseTexture?.dispose();
+ this._ambientTexture?.dispose();
+ this._opacityTexture?.dispose();
+ this._reflectionTexture?.dispose();
+ this._emissiveTexture?.dispose();
+ this._specularTexture?.dispose();
+ this._bumpTexture?.dispose();
+ this._lightmapTexture?.dispose();
+ this._refractionTexture?.dispose();
+ }
+ if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
+ this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
+ }
+ super.dispose(forceDisposeEffect, forceDisposeTextures);
+ }
+ /**
+ * Makes a duplicate of the material, and gives it a new name
+ * @param name defines the new name for the duplicated material
+ * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false.
+ * @param rootUrl defines the root URL to use to load textures
+ * @returns the cloned material
+ */
+ clone(name, cloneTexturesOnlyOnce = true, rootUrl = "") {
+ const result = SerializationHelper.Clone(() => new StandardMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce });
+ result.name = name;
+ result.id = name;
+ this.stencil.copyTo(result.stencil);
+ this._clonePlugins(result, rootUrl);
+ return result;
+ }
+ /**
+ * Creates a standard material from parsed material data
+ * @param source defines the JSON representation of the material
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root URL to use to load textures and relative dependencies
+ * @returns a new standard material
+ */
+ static Parse(source, scene, rootUrl) {
+ const material = SerializationHelper.Parse(() => new StandardMaterial(source.name, scene), source, scene, rootUrl);
+ if (source.stencil) {
+ material.stencil.parse(source.stencil, scene, rootUrl);
+ }
+ Material._ParsePlugins(source, material, scene, rootUrl);
+ return material;
+ }
+ // Flags used to enable or disable a type of texture for all Standard Materials
+ /**
+ * Are diffuse textures enabled in the application.
+ */
+ static get DiffuseTextureEnabled() {
+ return MaterialFlags.DiffuseTextureEnabled;
+ }
+ static set DiffuseTextureEnabled(value) {
+ MaterialFlags.DiffuseTextureEnabled = value;
+ }
+ /**
+ * Are detail textures enabled in the application.
+ */
+ static get DetailTextureEnabled() {
+ return MaterialFlags.DetailTextureEnabled;
+ }
+ static set DetailTextureEnabled(value) {
+ MaterialFlags.DetailTextureEnabled = value;
+ }
+ /**
+ * Are ambient textures enabled in the application.
+ */
+ static get AmbientTextureEnabled() {
+ return MaterialFlags.AmbientTextureEnabled;
+ }
+ static set AmbientTextureEnabled(value) {
+ MaterialFlags.AmbientTextureEnabled = value;
+ }
+ /**
+ * Are opacity textures enabled in the application.
+ */
+ static get OpacityTextureEnabled() {
+ return MaterialFlags.OpacityTextureEnabled;
+ }
+ static set OpacityTextureEnabled(value) {
+ MaterialFlags.OpacityTextureEnabled = value;
+ }
+ /**
+ * Are reflection textures enabled in the application.
+ */
+ static get ReflectionTextureEnabled() {
+ return MaterialFlags.ReflectionTextureEnabled;
+ }
+ static set ReflectionTextureEnabled(value) {
+ MaterialFlags.ReflectionTextureEnabled = value;
+ }
+ /**
+ * Are emissive textures enabled in the application.
+ */
+ static get EmissiveTextureEnabled() {
+ return MaterialFlags.EmissiveTextureEnabled;
+ }
+ static set EmissiveTextureEnabled(value) {
+ MaterialFlags.EmissiveTextureEnabled = value;
+ }
+ /**
+ * Are specular textures enabled in the application.
+ */
+ static get SpecularTextureEnabled() {
+ return MaterialFlags.SpecularTextureEnabled;
+ }
+ static set SpecularTextureEnabled(value) {
+ MaterialFlags.SpecularTextureEnabled = value;
+ }
+ /**
+ * Are bump textures enabled in the application.
+ */
+ static get BumpTextureEnabled() {
+ return MaterialFlags.BumpTextureEnabled;
+ }
+ static set BumpTextureEnabled(value) {
+ MaterialFlags.BumpTextureEnabled = value;
+ }
+ /**
+ * Are lightmap textures enabled in the application.
+ */
+ static get LightmapTextureEnabled() {
+ return MaterialFlags.LightmapTextureEnabled;
+ }
+ static set LightmapTextureEnabled(value) {
+ MaterialFlags.LightmapTextureEnabled = value;
+ }
+ /**
+ * Are refraction textures enabled in the application.
+ */
+ static get RefractionTextureEnabled() {
+ return MaterialFlags.RefractionTextureEnabled;
+ }
+ static set RefractionTextureEnabled(value) {
+ MaterialFlags.RefractionTextureEnabled = value;
+ }
+ /**
+ * Are color grading textures enabled in the application.
+ */
+ static get ColorGradingTextureEnabled() {
+ return MaterialFlags.ColorGradingTextureEnabled;
+ }
+ static set ColorGradingTextureEnabled(value) {
+ MaterialFlags.ColorGradingTextureEnabled = value;
+ }
+ /**
+ * Are fresnels enabled in the application.
+ */
+ static get FresnelEnabled() {
+ return MaterialFlags.FresnelEnabled;
+ }
+ static set FresnelEnabled(value) {
+ MaterialFlags.FresnelEnabled = value;
+ }
+}
+/**
+ * Force all the standard materials to compile to glsl even on WebGPU engines.
+ * False by default. This is mostly meant for backward compatibility.
+ */
+StandardMaterial.ForceGLSL = false;
+__decorate([
+ serializeAsTexture("diffuseTexture")
+], StandardMaterial.prototype, "_diffuseTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
+], StandardMaterial.prototype, "diffuseTexture", void 0);
+__decorate([
+ serializeAsTexture("ambientTexture")
+], StandardMaterial.prototype, "_ambientTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "ambientTexture", void 0);
+__decorate([
+ serializeAsTexture("opacityTexture")
+], StandardMaterial.prototype, "_opacityTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
+], StandardMaterial.prototype, "opacityTexture", void 0);
+__decorate([
+ serializeAsTexture("reflectionTexture")
+], StandardMaterial.prototype, "_reflectionTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "reflectionTexture", void 0);
+__decorate([
+ serializeAsTexture("emissiveTexture")
+], StandardMaterial.prototype, "_emissiveTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "emissiveTexture", void 0);
+__decorate([
+ serializeAsTexture("specularTexture")
+], StandardMaterial.prototype, "_specularTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "specularTexture", void 0);
+__decorate([
+ serializeAsTexture("bumpTexture")
+], StandardMaterial.prototype, "_bumpTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "bumpTexture", void 0);
+__decorate([
+ serializeAsTexture("lightmapTexture")
+], StandardMaterial.prototype, "_lightmapTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "lightmapTexture", void 0);
+__decorate([
+ serializeAsTexture("refractionTexture")
+], StandardMaterial.prototype, "_refractionTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "refractionTexture", void 0);
+__decorate([
+ serializeAsColor3("ambient")
+], StandardMaterial.prototype, "ambientColor", void 0);
+__decorate([
+ serializeAsColor3("diffuse")
+], StandardMaterial.prototype, "diffuseColor", void 0);
+__decorate([
+ serializeAsColor3("specular")
+], StandardMaterial.prototype, "specularColor", void 0);
+__decorate([
+ serializeAsColor3("emissive")
+], StandardMaterial.prototype, "emissiveColor", void 0);
+__decorate([
+ serialize()
+], StandardMaterial.prototype, "specularPower", void 0);
+__decorate([
+ serialize("useAlphaFromDiffuseTexture")
+], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
+], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
+__decorate([
+ serialize("useEmissiveAsIllumination")
+], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
+__decorate([
+ serialize("linkEmissiveWithDiffuse")
+], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
+__decorate([
+ serialize("useSpecularOverAlpha")
+], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
+__decorate([
+ serialize("useReflectionOverAlpha")
+], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
+__decorate([
+ serialize("disableLighting")
+], StandardMaterial.prototype, "_disableLighting", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsLightsDirty")
+], StandardMaterial.prototype, "disableLighting", void 0);
+__decorate([
+ serialize("useObjectSpaceNormalMap")
+], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
+__decorate([
+ serialize("useParallax")
+], StandardMaterial.prototype, "_useParallax", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "useParallax", void 0);
+__decorate([
+ serialize("useParallaxOcclusion")
+], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
+__decorate([
+ serialize()
+], StandardMaterial.prototype, "parallaxScaleBias", void 0);
+__decorate([
+ serialize("roughness")
+], StandardMaterial.prototype, "_roughness", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "roughness", void 0);
+__decorate([
+ serialize()
+], StandardMaterial.prototype, "indexOfRefraction", void 0);
+__decorate([
+ serialize()
+], StandardMaterial.prototype, "invertRefractionY", void 0);
+__decorate([
+ serialize()
+], StandardMaterial.prototype, "alphaCutOff", void 0);
+__decorate([
+ serialize("useLightmapAsShadowmap")
+], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
+__decorate([
+ serializeAsFresnelParameters("diffuseFresnelParameters")
+], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsFresnelDirty")
+], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
+__decorate([
+ serializeAsFresnelParameters("opacityFresnelParameters")
+], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
+], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
+__decorate([
+ serializeAsFresnelParameters("reflectionFresnelParameters")
+], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsFresnelDirty")
+], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
+__decorate([
+ serializeAsFresnelParameters("refractionFresnelParameters")
+], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsFresnelDirty")
+], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
+__decorate([
+ serializeAsFresnelParameters("emissiveFresnelParameters")
+], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsFresnelDirty")
+], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
+__decorate([
+ serialize("useReflectionFresnelFromSpecular")
+], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsFresnelDirty")
+], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
+__decorate([
+ serialize("useGlossinessFromSpecularMapAlpha")
+], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
+__decorate([
+ serialize("maxSimultaneousLights")
+], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsLightsDirty")
+], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
+__decorate([
+ serialize("invertNormalMapX")
+], StandardMaterial.prototype, "_invertNormalMapX", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "invertNormalMapX", void 0);
+__decorate([
+ serialize("invertNormalMapY")
+], StandardMaterial.prototype, "_invertNormalMapY", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "invertNormalMapY", void 0);
+__decorate([
+ serialize("twoSidedLighting")
+], StandardMaterial.prototype, "_twoSidedLighting", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], StandardMaterial.prototype, "twoSidedLighting", void 0);
+__decorate([
+ serialize("applyDecalMapAfterDetailMap")
+], StandardMaterial.prototype, "_applyDecalMapAfterDetailMap", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], StandardMaterial.prototype, "applyDecalMapAfterDetailMap", void 0);
+RegisterClass("BABYLON.StandardMaterial", StandardMaterial);
+Scene.DefaultMaterialFactory = (scene) => {
+ return new StandardMaterial("default material", scene);
+};
+
+const onCreatedEffectParameters$2 = { effect: null, subMesh: null };
+/**
+ * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
+ *
+ * This returned material effects how the mesh will look based on the code in the shaders.
+ *
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial
+ */
+class ShaderMaterial extends PushMaterial {
+ /**
+ * Instantiate a new shader material.
+ * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
+ * This returned material effects how the mesh will look based on the code in the shaders.
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial
+ * @param name Define the name of the material in the scene
+ * @param scene Define the scene the material belongs to
+ * @param shaderPath Defines the route to the shader code.
+ * @param options Define the options used to create the shader
+ * @param storeEffectOnSubMeshes true to store effect on submeshes, false to store the effect directly in the material class.
+ */
+ constructor(name, scene, shaderPath, options = {}, storeEffectOnSubMeshes = true) {
+ super(name, scene, storeEffectOnSubMeshes);
+ this._textures = {};
+ this._textureArrays = {};
+ this._externalTextures = {};
+ this._floats = {};
+ this._ints = {};
+ this._uints = {};
+ this._floatsArrays = {};
+ this._colors3 = {};
+ this._colors3Arrays = {};
+ this._colors4 = {};
+ this._colors4Arrays = {};
+ this._vectors2 = {};
+ this._vectors3 = {};
+ this._vectors4 = {};
+ this._quaternions = {};
+ this._quaternionsArrays = {};
+ this._matrices = {};
+ this._matrixArrays = {};
+ this._matrices3x3 = {};
+ this._matrices2x2 = {};
+ this._vectors2Arrays = {};
+ this._vectors3Arrays = {};
+ this._vectors4Arrays = {};
+ this._uniformBuffers = {};
+ this._textureSamplers = {};
+ this._storageBuffers = {};
+ this._cachedWorldViewMatrix = new Matrix();
+ this._cachedWorldViewProjectionMatrix = new Matrix();
+ this._multiview = false;
+ /**
+ * @internal
+ */
+ this._materialHelperNeedsPreviousMatrices = false;
+ this._shaderPath = shaderPath;
+ this._options = {
+ needAlphaBlending: false,
+ needAlphaTesting: false,
+ attributes: ["position", "normal", "uv"],
+ uniforms: ["worldViewProjection"],
+ uniformBuffers: [],
+ samplers: [],
+ externalTextures: [],
+ samplerObjects: [],
+ storageBuffers: [],
+ defines: [],
+ useClipPlane: false,
+ ...options,
+ };
+ }
+ /**
+ * Gets the shader path used to define the shader code
+ * It can be modified to trigger a new compilation
+ */
+ get shaderPath() {
+ return this._shaderPath;
+ }
+ /**
+ * Sets the shader path used to define the shader code
+ * It can be modified to trigger a new compilation
+ */
+ set shaderPath(shaderPath) {
+ this._shaderPath = shaderPath;
+ }
+ /**
+ * Gets the options used to compile the shader.
+ * They can be modified to trigger a new compilation
+ */
+ get options() {
+ return this._options;
+ }
+ /**
+ * is multiview set to true?
+ */
+ get isMultiview() {
+ return this._multiview;
+ }
+ /**
+ * Gets the current class name of the material e.g. "ShaderMaterial"
+ * Mainly use in serialization.
+ * @returns the class name
+ */
+ getClassName() {
+ return "ShaderMaterial";
+ }
+ /**
+ * Specifies if the material will require alpha blending
+ * @returns a boolean specifying if alpha blending is needed
+ */
+ needAlphaBlending() {
+ return this.alpha < 1.0 || this._options.needAlphaBlending;
+ }
+ /**
+ * Specifies if this material should be rendered in alpha test mode
+ * @returns a boolean specifying if an alpha test is needed.
+ */
+ needAlphaTesting() {
+ return this._options.needAlphaTesting;
+ }
+ _checkUniform(uniformName) {
+ if (this._options.uniforms.indexOf(uniformName) === -1) {
+ this._options.uniforms.push(uniformName);
+ }
+ }
+ /**
+ * Set a texture in the shader.
+ * @param name Define the name of the uniform samplers as defined in the shader
+ * @param texture Define the texture to bind to this sampler
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setTexture(name, texture) {
+ if (this._options.samplers.indexOf(name) === -1) {
+ this._options.samplers.push(name);
+ }
+ this._textures[name] = texture;
+ return this;
+ }
+ /**
+ * Remove a texture from the material.
+ * @param name Define the name of the texture to remove
+ */
+ removeTexture(name) {
+ delete this._textures[name];
+ }
+ /**
+ * Set a texture array in the shader.
+ * @param name Define the name of the uniform sampler array as defined in the shader
+ * @param textures Define the list of textures to bind to this sampler
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setTextureArray(name, textures) {
+ if (this._options.samplers.indexOf(name) === -1) {
+ this._options.samplers.push(name);
+ }
+ this._checkUniform(name);
+ this._textureArrays[name] = textures;
+ return this;
+ }
+ /**
+ * Set an internal texture in the shader.
+ * @param name Define the name of the uniform samplers as defined in the shader
+ * @param texture Define the texture to bind to this sampler
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setExternalTexture(name, texture) {
+ if (this._options.externalTextures.indexOf(name) === -1) {
+ this._options.externalTextures.push(name);
+ }
+ this._externalTextures[name] = texture;
+ return this;
+ }
+ /**
+ * Set a float in the shader.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setFloat(name, value) {
+ this._checkUniform(name);
+ this._floats[name] = value;
+ return this;
+ }
+ /**
+ * Set a int in the shader.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setInt(name, value) {
+ this._checkUniform(name);
+ this._ints[name] = value;
+ return this;
+ }
+ /**
+ * Set a unsigned int in the shader.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setUInt(name, value) {
+ this._checkUniform(name);
+ this._uints[name] = value;
+ return this;
+ }
+ /**
+ * Set an array of floats in the shader.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setFloats(name, value) {
+ this._checkUniform(name);
+ this._floatsArrays[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec3 in the shader from a Color3.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setColor3(name, value) {
+ this._checkUniform(name);
+ this._colors3[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec3 array in the shader from a Color3 array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setColor3Array(name, value) {
+ this._checkUniform(name);
+ this._colors3Arrays[name] = value.reduce((arr, color) => {
+ color.toArray(arr, arr.length);
+ return arr;
+ }, []);
+ return this;
+ }
+ /**
+ * Set a vec4 in the shader from a Color4.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setColor4(name, value) {
+ this._checkUniform(name);
+ this._colors4[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec4 array in the shader from a Color4 array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setColor4Array(name, value) {
+ this._checkUniform(name);
+ this._colors4Arrays[name] = value.reduce((arr, color) => {
+ color.toArray(arr, arr.length);
+ return arr;
+ }, []);
+ return this;
+ }
+ /**
+ * Set a vec2 in the shader from a Vector2.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setVector2(name, value) {
+ this._checkUniform(name);
+ this._vectors2[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec3 in the shader from a Vector3.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setVector3(name, value) {
+ this._checkUniform(name);
+ this._vectors3[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec4 in the shader from a Vector4.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setVector4(name, value) {
+ this._checkUniform(name);
+ this._vectors4[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec4 in the shader from a Quaternion.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setQuaternion(name, value) {
+ this._checkUniform(name);
+ this._quaternions[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec4 array in the shader from a Quaternion array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setQuaternionArray(name, value) {
+ this._checkUniform(name);
+ this._quaternionsArrays[name] = value.reduce((arr, quaternion) => {
+ quaternion.toArray(arr, arr.length);
+ return arr;
+ }, []);
+ return this;
+ }
+ /**
+ * Set a mat4 in the shader from a Matrix.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setMatrix(name, value) {
+ this._checkUniform(name);
+ this._matrices[name] = value;
+ return this;
+ }
+ /**
+ * Set a float32Array in the shader from a matrix array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setMatrices(name, value) {
+ this._checkUniform(name);
+ const float32Array = new Float32Array(value.length * 16);
+ for (let index = 0; index < value.length; index++) {
+ const matrix = value[index];
+ matrix.copyToArray(float32Array, index * 16);
+ }
+ this._matrixArrays[name] = float32Array;
+ return this;
+ }
+ /**
+ * Set a mat3 in the shader from a Float32Array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setMatrix3x3(name, value) {
+ this._checkUniform(name);
+ this._matrices3x3[name] = value;
+ return this;
+ }
+ /**
+ * Set a mat2 in the shader from a Float32Array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setMatrix2x2(name, value) {
+ this._checkUniform(name);
+ this._matrices2x2[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec2 array in the shader from a number array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setArray2(name, value) {
+ this._checkUniform(name);
+ this._vectors2Arrays[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec3 array in the shader from a number array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setArray3(name, value) {
+ this._checkUniform(name);
+ this._vectors3Arrays[name] = value;
+ return this;
+ }
+ /**
+ * Set a vec4 array in the shader from a number array.
+ * @param name Define the name of the uniform as defined in the shader
+ * @param value Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setArray4(name, value) {
+ this._checkUniform(name);
+ this._vectors4Arrays[name] = value;
+ return this;
+ }
+ /**
+ * Set a uniform buffer in the shader
+ * @param name Define the name of the uniform as defined in the shader
+ * @param buffer Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setUniformBuffer(name, buffer) {
+ if (this._options.uniformBuffers.indexOf(name) === -1) {
+ this._options.uniformBuffers.push(name);
+ }
+ this._uniformBuffers[name] = buffer;
+ return this;
+ }
+ /**
+ * Set a texture sampler in the shader
+ * @param name Define the name of the uniform as defined in the shader
+ * @param sampler Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setTextureSampler(name, sampler) {
+ if (this._options.samplerObjects.indexOf(name) === -1) {
+ this._options.samplerObjects.push(name);
+ }
+ this._textureSamplers[name] = sampler;
+ return this;
+ }
+ /**
+ * Set a storage buffer in the shader
+ * @param name Define the name of the storage buffer as defined in the shader
+ * @param buffer Define the value to give to the uniform
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setStorageBuffer(name, buffer) {
+ if (this._options.storageBuffers.indexOf(name) === -1) {
+ this._options.storageBuffers.push(name);
+ }
+ this._storageBuffers[name] = buffer;
+ return this;
+ }
+ /**
+ * Adds, removes, or replaces the specified shader define and value.
+ * * setDefine("MY_DEFINE", true); // enables a boolean define
+ * * setDefine("MY_DEFINE", "0.5"); // adds "#define MY_DEFINE 0.5" to the shader (or sets and replaces the value of any existing define with that name)
+ * * setDefine("MY_DEFINE", false); // disables and removes the define
+ * Note if the active defines do change, the shader will be recompiled and this can be expensive.
+ * @param define the define name e.g., "OUTPUT_TO_SRGB" or "#define OUTPUT_TO_SRGB". If the define was passed into the constructor already, the version used should match that, and in either case, it should not include any appended value.
+ * @param value either the value of the define (e.g. a numerical value) or for booleans, true if the define should be enabled or false if it should be disabled
+ * @returns the material itself allowing "fluent" like uniform updates
+ */
+ setDefine(define, value) {
+ // First remove any existing define with this name.
+ const defineName = define.trimEnd() + " ";
+ const existingDefineIdx = this.options.defines.findIndex((x) => x === define || x.startsWith(defineName));
+ if (existingDefineIdx >= 0) {
+ this.options.defines.splice(existingDefineIdx, 1);
+ }
+ // Then add the new define value. (If it's a boolean value and false, don't add it.)
+ if (typeof value !== "boolean" || value) {
+ this.options.defines.push(defineName + value);
+ }
+ return this;
+ }
+ /**
+ * Specifies that the submesh is ready to be used
+ * @param mesh defines the mesh to check
+ * @param subMesh defines which submesh to check
+ * @param useInstances specifies that instances should be used
+ * @returns a boolean indicating that the submesh is ready or not
+ */
+ isReadyForSubMesh(mesh, subMesh, useInstances) {
+ return this.isReady(mesh, useInstances, subMesh);
+ }
+ /**
+ * Checks if the material is ready to render the requested mesh
+ * @param mesh Define the mesh to render
+ * @param useInstances Define whether or not the material is used with instances
+ * @param subMesh defines which submesh to render
+ * @returns true if ready, otherwise false
+ */
+ isReady(mesh, useInstances, subMesh) {
+ const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes;
+ if (this.isFrozen) {
+ const drawWrapper = storeEffectOnSubMeshes ? subMesh._drawWrapper : this._drawWrapper;
+ if (drawWrapper.effect && drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) {
+ return true;
+ }
+ }
+ const scene = this.getScene();
+ const engine = scene.getEngine();
+ // Instances
+ const defines = [];
+ const attribs = [];
+ let fallbacks = null;
+ let shaderName = this._shaderPath, uniforms = this._options.uniforms, uniformBuffers = this._options.uniformBuffers, samplers = this._options.samplers;
+ // global multiview
+ if (engine.getCaps().multiview && scene.activeCamera && scene.activeCamera.outputRenderTarget && scene.activeCamera.outputRenderTarget.getViewCount() > 1) {
+ this._multiview = true;
+ defines.push("#define MULTIVIEW");
+ if (uniforms.indexOf("viewProjection") !== -1 && uniforms.indexOf("viewProjectionR") === -1) {
+ uniforms.push("viewProjectionR");
+ }
+ }
+ for (let index = 0; index < this._options.defines.length; index++) {
+ const defineToAdd = this._options.defines[index].indexOf("#define") === 0 ? this._options.defines[index] : `#define ${this._options.defines[index]}`;
+ defines.push(defineToAdd);
+ }
+ for (let index = 0; index < this._options.attributes.length; index++) {
+ attribs.push(this._options.attributes[index]);
+ }
+ if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
+ if (attribs.indexOf(VertexBuffer.ColorKind) === -1) {
+ attribs.push(VertexBuffer.ColorKind);
+ }
+ defines.push("#define VERTEXCOLOR");
+ }
+ if (useInstances) {
+ defines.push("#define INSTANCES");
+ PushAttributesForInstances(attribs, this._materialHelperNeedsPreviousMatrices);
+ if (mesh?.hasThinInstances) {
+ defines.push("#define THIN_INSTANCES");
+ if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorInstanceKind)) {
+ attribs.push(VertexBuffer.ColorInstanceKind);
+ defines.push("#define INSTANCESCOLOR");
+ }
+ }
+ }
+ // Bones
+ if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
+ attribs.push(VertexBuffer.MatricesIndicesKind);
+ attribs.push(VertexBuffer.MatricesWeightsKind);
+ if (mesh.numBoneInfluencers > 4) {
+ attribs.push(VertexBuffer.MatricesIndicesExtraKind);
+ attribs.push(VertexBuffer.MatricesWeightsExtraKind);
+ }
+ const skeleton = mesh.skeleton;
+ defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
+ fallbacks = new EffectFallbacks();
+ fallbacks.addCPUSkinningFallback(0, mesh);
+ if (skeleton.isUsingTextureForMatrices) {
+ defines.push("#define BONETEXTURE");
+ if (uniforms.indexOf("boneTextureWidth") === -1) {
+ uniforms.push("boneTextureWidth");
+ }
+ if (this._options.samplers.indexOf("boneSampler") === -1) {
+ this._options.samplers.push("boneSampler");
+ }
+ }
+ else {
+ defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
+ if (uniforms.indexOf("mBones") === -1) {
+ uniforms.push("mBones");
+ }
+ }
+ }
+ else {
+ defines.push("#define NUM_BONE_INFLUENCERS 0");
+ }
+ // Morph
+ let numInfluencers = 0;
+ const manager = mesh ? mesh.morphTargetManager : null;
+ if (manager) {
+ const uv = defines.indexOf("#define UV1") !== -1;
+ const uv2 = defines.indexOf("#define UV2") !== -1;
+ const tangent = defines.indexOf("#define TANGENT") !== -1;
+ const normal = defines.indexOf("#define NORMAL") !== -1;
+ const color = defines.indexOf("#define VERTEXCOLOR") !== -1;
+ numInfluencers = PrepareDefinesAndAttributesForMorphTargets(manager, defines, attribs, mesh, true, // usePositionMorph
+ normal, // useNormalMorph
+ tangent, // useTangentMorph
+ uv, // useUVMorph
+ uv2, // useUV2Morph
+ color // useColorMorph
+ );
+ if (manager.isUsingTextureForTargets) {
+ if (uniforms.indexOf("morphTargetTextureIndices") === -1) {
+ uniforms.push("morphTargetTextureIndices");
+ }
+ if (this._options.samplers.indexOf("morphTargets") === -1) {
+ this._options.samplers.push("morphTargets");
+ }
+ }
+ if (numInfluencers > 0) {
+ uniforms = uniforms.slice();
+ uniforms.push("morphTargetInfluences");
+ uniforms.push("morphTargetCount");
+ uniforms.push("morphTargetTextureInfo");
+ uniforms.push("morphTargetTextureIndices");
+ }
+ }
+ else {
+ defines.push("#define NUM_MORPH_INFLUENCERS 0");
+ }
+ // Baked Vertex Animation
+ if (mesh) {
+ const bvaManager = mesh.bakedVertexAnimationManager;
+ if (bvaManager && bvaManager.isEnabled) {
+ defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
+ if (uniforms.indexOf("bakedVertexAnimationSettings") === -1) {
+ uniforms.push("bakedVertexAnimationSettings");
+ }
+ if (uniforms.indexOf("bakedVertexAnimationTextureSizeInverted") === -1) {
+ uniforms.push("bakedVertexAnimationTextureSizeInverted");
+ }
+ if (uniforms.indexOf("bakedVertexAnimationTime") === -1) {
+ uniforms.push("bakedVertexAnimationTime");
+ }
+ if (this._options.samplers.indexOf("bakedVertexAnimationTexture") === -1) {
+ this._options.samplers.push("bakedVertexAnimationTexture");
+ }
+ }
+ PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);
+ }
+ // Textures
+ for (const name in this._textures) {
+ if (!this._textures[name].isReady()) {
+ return false;
+ }
+ }
+ // Alpha test
+ if (mesh && this.needAlphaTestingForMesh(mesh)) {
+ defines.push("#define ALPHATEST");
+ }
+ // Clip planes
+ if (this._options.useClipPlane !== false) {
+ addClipPlaneUniforms(uniforms);
+ prepareStringDefinesForClipPlanes(this, scene, defines);
+ }
+ // Fog
+ if (scene.fogEnabled && mesh?.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
+ defines.push("#define FOG");
+ if (uniforms.indexOf("view") === -1) {
+ uniforms.push("view");
+ }
+ if (uniforms.indexOf("vFogInfos") === -1) {
+ uniforms.push("vFogInfos");
+ }
+ if (uniforms.indexOf("vFogColor") === -1) {
+ uniforms.push("vFogColor");
+ }
+ }
+ // Misc
+ if (this._useLogarithmicDepth) {
+ defines.push("#define LOGARITHMICDEPTH");
+ if (uniforms.indexOf("logarithmicDepthConstant") === -1) {
+ uniforms.push("logarithmicDepthConstant");
+ }
+ }
+ if (this.customShaderNameResolve) {
+ uniforms = uniforms.slice();
+ uniformBuffers = uniformBuffers.slice();
+ samplers = samplers.slice();
+ shaderName = this.customShaderNameResolve(this.name, uniforms, uniformBuffers, samplers, defines, attribs);
+ }
+ const drawWrapper = storeEffectOnSubMeshes ? subMesh._getDrawWrapper(undefined, true) : this._drawWrapper;
+ const previousEffect = drawWrapper?.effect ?? null;
+ const previousDefines = drawWrapper?.defines ?? null;
+ const join = defines.join("\n");
+ let effect = previousEffect;
+ if (previousDefines !== join) {
+ effect = engine.createEffect(shaderName, {
+ attributes: attribs,
+ uniformsNames: uniforms,
+ uniformBuffersNames: uniformBuffers,
+ samplers: samplers,
+ defines: join,
+ fallbacks: fallbacks,
+ onCompiled: this.onCompiled,
+ onError: this.onError,
+ indexParameters: { maxSimultaneousMorphTargets: numInfluencers },
+ shaderLanguage: this._options.shaderLanguage,
+ extraInitializationsAsync: this._options.extraInitializationsAsync,
+ }, engine);
+ if (storeEffectOnSubMeshes) {
+ subMesh.setEffect(effect, join, this._materialContext);
+ }
+ else if (drawWrapper) {
+ drawWrapper.setEffect(effect, join);
+ }
+ if (this._onEffectCreatedObservable) {
+ onCreatedEffectParameters$2.effect = effect;
+ onCreatedEffectParameters$2.subMesh = subMesh ?? mesh?.subMeshes[0] ?? null;
+ this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$2);
+ }
+ }
+ drawWrapper._wasPreviouslyUsingInstances = !!useInstances;
+ if (!effect?.isReady()) {
+ return false;
+ }
+ if (previousEffect !== effect) {
+ scene.resetCachedMaterial();
+ }
+ drawWrapper._wasPreviouslyReady = true;
+ return true;
+ }
+ /**
+ * Binds the world matrix to the material
+ * @param world defines the world transformation matrix
+ * @param effectOverride - If provided, use this effect instead of internal effect
+ */
+ bindOnlyWorldMatrix(world, effectOverride) {
+ const effect = effectOverride ?? this.getEffect();
+ if (!effect) {
+ return;
+ }
+ const uniforms = this._options.uniforms;
+ if (uniforms.indexOf("world") !== -1) {
+ effect.setMatrix("world", world);
+ }
+ const scene = this.getScene();
+ if (uniforms.indexOf("worldView") !== -1) {
+ world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
+ effect.setMatrix("worldView", this._cachedWorldViewMatrix);
+ }
+ if (uniforms.indexOf("worldViewProjection") !== -1) {
+ world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
+ effect.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix);
+ }
+ if (uniforms.indexOf("view") !== -1) {
+ effect.setMatrix("view", scene.getViewMatrix());
+ }
+ }
+ /**
+ * Binds the submesh to this material by preparing the effect and shader to draw
+ * @param world defines the world transformation matrix
+ * @param mesh defines the mesh containing the submesh
+ * @param subMesh defines the submesh to bind the material to
+ */
+ bindForSubMesh(world, mesh, subMesh) {
+ this.bind(world, mesh, subMesh._drawWrapperOverride?.effect, subMesh);
+ }
+ /**
+ * Binds the material to the mesh
+ * @param world defines the world transformation matrix
+ * @param mesh defines the mesh to bind the material to
+ * @param effectOverride - If provided, use this effect instead of internal effect
+ * @param subMesh defines the submesh to bind the material to
+ */
+ bind(world, mesh, effectOverride, subMesh) {
+ // Std values
+ const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes;
+ const effect = effectOverride ?? (storeEffectOnSubMeshes ? subMesh.effect : this.getEffect());
+ if (!effect) {
+ return;
+ }
+ const scene = this.getScene();
+ this._activeEffect = effect;
+ this.bindOnlyWorldMatrix(world, effectOverride);
+ const uniformBuffers = this._options.uniformBuffers;
+ let useSceneUBO = false;
+ if (effect && uniformBuffers && uniformBuffers.length > 0 && scene.getEngine().supportsUniformBuffers) {
+ for (let i = 0; i < uniformBuffers.length; ++i) {
+ const bufferName = uniformBuffers[i];
+ switch (bufferName) {
+ case "Mesh":
+ if (mesh) {
+ mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
+ mesh.transferToEffect(world);
+ }
+ break;
+ case "Scene":
+ BindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
+ scene.finalizeSceneUbo();
+ useSceneUBO = true;
+ break;
+ }
+ }
+ }
+ const mustRebind = mesh && storeEffectOnSubMeshes ? this._mustRebind(scene, effect, subMesh, mesh.visibility) : scene.getCachedMaterial() !== this;
+ if (effect && mustRebind) {
+ if (!useSceneUBO && this._options.uniforms.indexOf("view") !== -1) {
+ effect.setMatrix("view", scene.getViewMatrix());
+ }
+ if (!useSceneUBO && this._options.uniforms.indexOf("projection") !== -1) {
+ effect.setMatrix("projection", scene.getProjectionMatrix());
+ }
+ if (!useSceneUBO && this._options.uniforms.indexOf("viewProjection") !== -1) {
+ effect.setMatrix("viewProjection", scene.getTransformMatrix());
+ if (this._multiview) {
+ effect.setMatrix("viewProjectionR", scene._transformMatrixR);
+ }
+ }
+ if (scene.activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1) {
+ effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
+ }
+ // Bones
+ BindBonesParameters(mesh, effect);
+ // Clip plane
+ bindClipPlane(effect, this, scene);
+ // Misc
+ if (this._useLogarithmicDepth) {
+ BindLogDepth(storeEffectOnSubMeshes ? subMesh.materialDefines : effect.defines, effect, scene);
+ }
+ // Fog
+ if (mesh) {
+ BindFogParameters(scene, mesh, effect);
+ }
+ let name;
+ // Texture
+ for (name in this._textures) {
+ effect.setTexture(name, this._textures[name]);
+ }
+ // Texture arrays
+ for (name in this._textureArrays) {
+ effect.setTextureArray(name, this._textureArrays[name]);
+ }
+ // Int
+ for (name in this._ints) {
+ effect.setInt(name, this._ints[name]);
+ }
+ // UInt
+ for (name in this._uints) {
+ effect.setUInt(name, this._uints[name]);
+ }
+ // Float
+ for (name in this._floats) {
+ effect.setFloat(name, this._floats[name]);
+ }
+ // Floats
+ for (name in this._floatsArrays) {
+ effect.setArray(name, this._floatsArrays[name]);
+ }
+ // Color3
+ for (name in this._colors3) {
+ effect.setColor3(name, this._colors3[name]);
+ }
+ // Color3Array
+ for (name in this._colors3Arrays) {
+ effect.setArray3(name, this._colors3Arrays[name]);
+ }
+ // Color4
+ for (name in this._colors4) {
+ const color = this._colors4[name];
+ effect.setFloat4(name, color.r, color.g, color.b, color.a);
+ }
+ // Color4Array
+ for (name in this._colors4Arrays) {
+ effect.setArray4(name, this._colors4Arrays[name]);
+ }
+ // Vector2
+ for (name in this._vectors2) {
+ effect.setVector2(name, this._vectors2[name]);
+ }
+ // Vector3
+ for (name in this._vectors3) {
+ effect.setVector3(name, this._vectors3[name]);
+ }
+ // Vector4
+ for (name in this._vectors4) {
+ effect.setVector4(name, this._vectors4[name]);
+ }
+ // Quaternion
+ for (name in this._quaternions) {
+ effect.setQuaternion(name, this._quaternions[name]);
+ }
+ // Matrix
+ for (name in this._matrices) {
+ effect.setMatrix(name, this._matrices[name]);
+ }
+ // MatrixArray
+ for (name in this._matrixArrays) {
+ effect.setMatrices(name, this._matrixArrays[name]);
+ }
+ // Matrix 3x3
+ for (name in this._matrices3x3) {
+ effect.setMatrix3x3(name, this._matrices3x3[name]);
+ }
+ // Matrix 2x2
+ for (name in this._matrices2x2) {
+ effect.setMatrix2x2(name, this._matrices2x2[name]);
+ }
+ // Vector2Array
+ for (name in this._vectors2Arrays) {
+ effect.setArray2(name, this._vectors2Arrays[name]);
+ }
+ // Vector3Array
+ for (name in this._vectors3Arrays) {
+ effect.setArray3(name, this._vectors3Arrays[name]);
+ }
+ // Vector4Array
+ for (name in this._vectors4Arrays) {
+ effect.setArray4(name, this._vectors4Arrays[name]);
+ }
+ // QuaternionArray
+ for (name in this._quaternionsArrays) {
+ effect.setArray4(name, this._quaternionsArrays[name]);
+ }
+ // Uniform buffers
+ for (name in this._uniformBuffers) {
+ const buffer = this._uniformBuffers[name].getBuffer();
+ if (buffer) {
+ effect.bindUniformBuffer(buffer, name);
+ }
+ }
+ const engineWebGPU = scene.getEngine();
+ // External texture
+ const setExternalTexture = engineWebGPU.setExternalTexture;
+ if (setExternalTexture) {
+ for (name in this._externalTextures) {
+ setExternalTexture.call(engineWebGPU, name, this._externalTextures[name]);
+ }
+ }
+ // Samplers
+ const setTextureSampler = engineWebGPU.setTextureSampler;
+ if (setTextureSampler) {
+ for (name in this._textureSamplers) {
+ setTextureSampler.call(engineWebGPU, name, this._textureSamplers[name]);
+ }
+ }
+ // Storage buffers
+ const setStorageBuffer = engineWebGPU.setStorageBuffer;
+ if (setStorageBuffer) {
+ for (name in this._storageBuffers) {
+ setStorageBuffer.call(engineWebGPU, name, this._storageBuffers[name]);
+ }
+ }
+ }
+ if (effect && mesh && (mustRebind || !this.isFrozen)) {
+ // Morph targets
+ BindMorphTargetParameters(mesh, effect);
+ if (mesh.morphTargetManager && mesh.morphTargetManager.isUsingTextureForTargets) {
+ mesh.morphTargetManager._bind(effect);
+ }
+ const bvaManager = mesh.bakedVertexAnimationManager;
+ if (bvaManager && bvaManager.isEnabled) {
+ const drawWrapper = storeEffectOnSubMeshes ? subMesh._drawWrapper : this._drawWrapper;
+ mesh.bakedVertexAnimationManager?.bind(effect, !!drawWrapper._wasPreviouslyUsingInstances);
+ }
+ }
+ this._afterBind(mesh, effect, subMesh);
+ }
+ /**
+ * Gets the active textures from the material
+ * @returns an array of textures
+ */
+ getActiveTextures() {
+ const activeTextures = super.getActiveTextures();
+ for (const name in this._textures) {
+ activeTextures.push(this._textures[name]);
+ }
+ for (const name in this._textureArrays) {
+ const array = this._textureArrays[name];
+ for (let index = 0; index < array.length; index++) {
+ activeTextures.push(array[index]);
+ }
+ }
+ return activeTextures;
+ }
+ /**
+ * Specifies if the material uses a texture
+ * @param texture defines the texture to check against the material
+ * @returns a boolean specifying if the material uses the texture
+ */
+ hasTexture(texture) {
+ if (super.hasTexture(texture)) {
+ return true;
+ }
+ for (const name in this._textures) {
+ if (this._textures[name] === texture) {
+ return true;
+ }
+ }
+ for (const name in this._textureArrays) {
+ const array = this._textureArrays[name];
+ for (let index = 0; index < array.length; index++) {
+ if (array[index] === texture) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ /**
+ * Makes a duplicate of the material, and gives it a new name
+ * @param name defines the new name for the duplicated material
+ * @returns the cloned material
+ */
+ clone(name) {
+ const result = SerializationHelper.Clone(() => new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options, this._storeEffectOnSubMeshes), this);
+ result.name = name;
+ result.id = name;
+ // Shader code path
+ if (typeof result._shaderPath === "object") {
+ result._shaderPath = { ...result._shaderPath };
+ }
+ // Options
+ this._options = { ...this._options };
+ Object.keys(this._options).forEach((propName) => {
+ const propValue = this._options[propName];
+ if (Array.isArray(propValue)) {
+ this._options[propName] = propValue.slice(0);
+ }
+ });
+ // Stencil
+ this.stencil.copyTo(result.stencil);
+ // Texture
+ for (const key in this._textures) {
+ result.setTexture(key, this._textures[key]);
+ }
+ // TextureArray
+ for (const key in this._textureArrays) {
+ result.setTextureArray(key, this._textureArrays[key]);
+ }
+ // External texture
+ for (const key in this._externalTextures) {
+ result.setExternalTexture(key, this._externalTextures[key]);
+ }
+ // Int
+ for (const key in this._ints) {
+ result.setInt(key, this._ints[key]);
+ }
+ // UInt
+ for (const key in this._uints) {
+ result.setUInt(key, this._uints[key]);
+ }
+ // Float
+ for (const key in this._floats) {
+ result.setFloat(key, this._floats[key]);
+ }
+ // Floats
+ for (const key in this._floatsArrays) {
+ result.setFloats(key, this._floatsArrays[key]);
+ }
+ // Color3
+ for (const key in this._colors3) {
+ result.setColor3(key, this._colors3[key]);
+ }
+ // Color3Array
+ for (const key in this._colors3Arrays) {
+ result._colors3Arrays[key] = this._colors3Arrays[key];
+ }
+ // Color4
+ for (const key in this._colors4) {
+ result.setColor4(key, this._colors4[key]);
+ }
+ // Color4Array
+ for (const key in this._colors4Arrays) {
+ result._colors4Arrays[key] = this._colors4Arrays[key];
+ }
+ // Vector2
+ for (const key in this._vectors2) {
+ result.setVector2(key, this._vectors2[key]);
+ }
+ // Vector3
+ for (const key in this._vectors3) {
+ result.setVector3(key, this._vectors3[key]);
+ }
+ // Vector4
+ for (const key in this._vectors4) {
+ result.setVector4(key, this._vectors4[key]);
+ }
+ // Quaternion
+ for (const key in this._quaternions) {
+ result.setQuaternion(key, this._quaternions[key]);
+ }
+ // QuaternionArray
+ for (const key in this._quaternionsArrays) {
+ result._quaternionsArrays[key] = this._quaternionsArrays[key];
+ }
+ // Matrix
+ for (const key in this._matrices) {
+ result.setMatrix(key, this._matrices[key]);
+ }
+ // MatrixArray
+ for (const key in this._matrixArrays) {
+ result._matrixArrays[key] = this._matrixArrays[key].slice();
+ }
+ // Matrix 3x3
+ for (const key in this._matrices3x3) {
+ result.setMatrix3x3(key, this._matrices3x3[key]);
+ }
+ // Matrix 2x2
+ for (const key in this._matrices2x2) {
+ result.setMatrix2x2(key, this._matrices2x2[key]);
+ }
+ // Vector2Array
+ for (const key in this._vectors2Arrays) {
+ result.setArray2(key, this._vectors2Arrays[key]);
+ }
+ // Vector3Array
+ for (const key in this._vectors3Arrays) {
+ result.setArray3(key, this._vectors3Arrays[key]);
+ }
+ // Vector4Array
+ for (const key in this._vectors4Arrays) {
+ result.setArray4(key, this._vectors4Arrays[key]);
+ }
+ // Uniform buffers
+ for (const key in this._uniformBuffers) {
+ result.setUniformBuffer(key, this._uniformBuffers[key]);
+ }
+ // Samplers
+ for (const key in this._textureSamplers) {
+ result.setTextureSampler(key, this._textureSamplers[key]);
+ }
+ // Storag buffers
+ for (const key in this._storageBuffers) {
+ result.setStorageBuffer(key, this._storageBuffers[key]);
+ }
+ return result;
+ }
+ /**
+ * Disposes the material
+ * @param forceDisposeEffect specifies if effects should be forcefully disposed
+ * @param forceDisposeTextures specifies if textures should be forcefully disposed
+ * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
+ */
+ dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
+ if (forceDisposeTextures) {
+ let name;
+ for (name in this._textures) {
+ this._textures[name].dispose();
+ }
+ for (name in this._textureArrays) {
+ const array = this._textureArrays[name];
+ for (let index = 0; index < array.length; index++) {
+ array[index].dispose();
+ }
+ }
+ }
+ this._textures = {};
+ super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
+ }
+ /**
+ * Serializes this material in a JSON representation
+ * @returns the serialized material object
+ */
+ serialize() {
+ const serializationObject = SerializationHelper.Serialize(this);
+ serializationObject.customType = "BABYLON.ShaderMaterial";
+ serializationObject.uniqueId = this.uniqueId;
+ serializationObject.options = this._options;
+ serializationObject.shaderPath = this._shaderPath;
+ serializationObject.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes;
+ let name;
+ // Stencil
+ serializationObject.stencil = this.stencil.serialize();
+ // Texture
+ serializationObject.textures = {};
+ for (name in this._textures) {
+ serializationObject.textures[name] = this._textures[name].serialize();
+ }
+ // Texture arrays
+ serializationObject.textureArrays = {};
+ for (name in this._textureArrays) {
+ serializationObject.textureArrays[name] = [];
+ const array = this._textureArrays[name];
+ for (let index = 0; index < array.length; index++) {
+ serializationObject.textureArrays[name].push(array[index].serialize());
+ }
+ }
+ // Int
+ serializationObject.ints = {};
+ for (name in this._ints) {
+ serializationObject.ints[name] = this._ints[name];
+ }
+ // UInt
+ serializationObject.uints = {};
+ for (name in this._uints) {
+ serializationObject.uints[name] = this._uints[name];
+ }
+ // Float
+ serializationObject.floats = {};
+ for (name in this._floats) {
+ serializationObject.floats[name] = this._floats[name];
+ }
+ // Floats
+ serializationObject.floatsArrays = {};
+ for (name in this._floatsArrays) {
+ serializationObject.floatsArrays[name] = this._floatsArrays[name];
+ }
+ // Color3
+ serializationObject.colors3 = {};
+ for (name in this._colors3) {
+ serializationObject.colors3[name] = this._colors3[name].asArray();
+ }
+ // Color3 array
+ serializationObject.colors3Arrays = {};
+ for (name in this._colors3Arrays) {
+ serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
+ }
+ // Color4
+ serializationObject.colors4 = {};
+ for (name in this._colors4) {
+ serializationObject.colors4[name] = this._colors4[name].asArray();
+ }
+ // Color4 array
+ serializationObject.colors4Arrays = {};
+ for (name in this._colors4Arrays) {
+ serializationObject.colors4Arrays[name] = this._colors4Arrays[name];
+ }
+ // Vector2
+ serializationObject.vectors2 = {};
+ for (name in this._vectors2) {
+ const v2 = this._vectors2[name];
+ serializationObject.vectors2[name] = [v2.x, v2.y];
+ }
+ // Vector3
+ serializationObject.vectors3 = {};
+ for (name in this._vectors3) {
+ const v3 = this._vectors3[name];
+ serializationObject.vectors3[name] = [v3.x, v3.y, v3.z];
+ }
+ // Vector4
+ serializationObject.vectors4 = {};
+ for (name in this._vectors4) {
+ const v4 = this._vectors4[name];
+ serializationObject.vectors4[name] = [v4.x, v4.y, v4.z, v4.w];
+ }
+ // Quaternion
+ serializationObject.quaternions = {};
+ for (name in this._quaternions) {
+ serializationObject.quaternions[name] = this._quaternions[name].asArray();
+ }
+ // Matrix
+ serializationObject.matrices = {};
+ for (name in this._matrices) {
+ serializationObject.matrices[name] = this._matrices[name].asArray();
+ }
+ // MatrixArray
+ serializationObject.matrixArray = {};
+ for (name in this._matrixArrays) {
+ serializationObject.matrixArray[name] = this._matrixArrays[name];
+ }
+ // Matrix 3x3
+ serializationObject.matrices3x3 = {};
+ for (name in this._matrices3x3) {
+ serializationObject.matrices3x3[name] = this._matrices3x3[name];
+ }
+ // Matrix 2x2
+ serializationObject.matrices2x2 = {};
+ for (name in this._matrices2x2) {
+ serializationObject.matrices2x2[name] = this._matrices2x2[name];
+ }
+ // Vector2Array
+ serializationObject.vectors2Arrays = {};
+ for (name in this._vectors2Arrays) {
+ serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
+ }
+ // Vector3Array
+ serializationObject.vectors3Arrays = {};
+ for (name in this._vectors3Arrays) {
+ serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
+ }
+ // Vector4Array
+ serializationObject.vectors4Arrays = {};
+ for (name in this._vectors4Arrays) {
+ serializationObject.vectors4Arrays[name] = this._vectors4Arrays[name];
+ }
+ // QuaternionArray
+ serializationObject.quaternionsArrays = {};
+ for (name in this._quaternionsArrays) {
+ serializationObject.quaternionsArrays[name] = this._quaternionsArrays[name];
+ }
+ return serializationObject;
+ }
+ /**
+ * Creates a shader material from parsed shader material data
+ * @param source defines the JSON representation of the material
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root URL to use to load textures and relative dependencies
+ * @returns a new material
+ */
+ static Parse(source, scene, rootUrl) {
+ const material = SerializationHelper.Parse(() => new ShaderMaterial(source.name, scene, source.shaderPath, source.options, source.storeEffectOnSubMeshes), source, scene, rootUrl);
+ let name;
+ // Stencil
+ if (source.stencil) {
+ material.stencil.parse(source.stencil, scene, rootUrl);
+ }
+ // Texture
+ for (name in source.textures) {
+ material.setTexture(name, Texture.Parse(source.textures[name], scene, rootUrl));
+ }
+ // Texture arrays
+ for (name in source.textureArrays) {
+ const array = source.textureArrays[name];
+ const textureArray = [];
+ for (let index = 0; index < array.length; index++) {
+ textureArray.push(Texture.Parse(array[index], scene, rootUrl));
+ }
+ material.setTextureArray(name, textureArray);
+ }
+ // Int
+ for (name in source.ints) {
+ material.setInt(name, source.ints[name]);
+ }
+ // UInt
+ for (name in source.uints) {
+ material.setUInt(name, source.uints[name]);
+ }
+ // Float
+ for (name in source.floats) {
+ material.setFloat(name, source.floats[name]);
+ }
+ // Floats
+ for (name in source.floatsArrays) {
+ material.setFloats(name, source.floatsArrays[name]);
+ }
+ // Color3
+ for (name in source.colors3) {
+ material.setColor3(name, Color3.FromArray(source.colors3[name]));
+ }
+ // Color3 arrays
+ for (name in source.colors3Arrays) {
+ const colors = source.colors3Arrays[name]
+ .reduce((arr, num, i) => {
+ if (i % 3 === 0) {
+ arr.push([num]);
+ }
+ else {
+ arr[arr.length - 1].push(num);
+ }
+ return arr;
+ }, [])
+ .map((color) => Color3.FromArray(color));
+ material.setColor3Array(name, colors);
+ }
+ // Color4
+ for (name in source.colors4) {
+ material.setColor4(name, Color4.FromArray(source.colors4[name]));
+ }
+ // Color4 arrays
+ for (name in source.colors4Arrays) {
+ const colors = source.colors4Arrays[name]
+ .reduce((arr, num, i) => {
+ if (i % 4 === 0) {
+ arr.push([num]);
+ }
+ else {
+ arr[arr.length - 1].push(num);
+ }
+ return arr;
+ }, [])
+ .map((color) => Color4.FromArray(color));
+ material.setColor4Array(name, colors);
+ }
+ // Vector2
+ for (name in source.vectors2) {
+ material.setVector2(name, Vector2.FromArray(source.vectors2[name]));
+ }
+ // Vector3
+ for (name in source.vectors3) {
+ material.setVector3(name, Vector3.FromArray(source.vectors3[name]));
+ }
+ // Vector4
+ for (name in source.vectors4) {
+ material.setVector4(name, Vector4.FromArray(source.vectors4[name]));
+ }
+ // Quaternion
+ for (name in source.quaternions) {
+ material.setQuaternion(name, Quaternion.FromArray(source.quaternions[name]));
+ }
+ // Matrix
+ for (name in source.matrices) {
+ material.setMatrix(name, Matrix.FromArray(source.matrices[name]));
+ }
+ // MatrixArray
+ for (name in source.matrixArray) {
+ material._matrixArrays[name] = new Float32Array(source.matrixArray[name]);
+ }
+ // Matrix 3x3
+ for (name in source.matrices3x3) {
+ material.setMatrix3x3(name, source.matrices3x3[name]);
+ }
+ // Matrix 2x2
+ for (name in source.matrices2x2) {
+ material.setMatrix2x2(name, source.matrices2x2[name]);
+ }
+ // Vector2Array
+ for (name in source.vectors2Arrays) {
+ material.setArray2(name, source.vectors2Arrays[name]);
+ }
+ // Vector3Array
+ for (name in source.vectors3Arrays) {
+ material.setArray3(name, source.vectors3Arrays[name]);
+ }
+ // Vector4Array
+ for (name in source.vectors4Arrays) {
+ material.setArray4(name, source.vectors4Arrays[name]);
+ }
+ // QuaternionArray
+ for (name in source.quaternionsArrays) {
+ material.setArray4(name, source.quaternionsArrays[name]);
+ }
+ return material;
+ }
+ /**
+ * Creates a new ShaderMaterial from a snippet saved in a remote file
+ * @param name defines the name of the ShaderMaterial to create (can be null or empty to use the one from the json data)
+ * @param url defines the url to load from
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root URL to use to load textures and relative dependencies
+ * @returns a promise that will resolve to the new ShaderMaterial
+ */
+ static ParseFromFileAsync(name, url, scene, rootUrl = "") {
+ return new Promise((resolve, reject) => {
+ const request = new WebRequest();
+ request.addEventListener("readystatechange", () => {
+ if (request.readyState == 4) {
+ if (request.status == 200) {
+ const serializationObject = JSON.parse(request.responseText);
+ const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);
+ if (name) {
+ output.name = name;
+ }
+ resolve(output);
+ }
+ else {
+ reject("Unable to load the ShaderMaterial");
+ }
+ }
+ });
+ request.open("GET", url);
+ request.send();
+ });
+ }
+ /**
+ * Creates a ShaderMaterial from a snippet saved by the Inspector
+ * @param snippetId defines the snippet to load
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root URL to use to load textures and relative dependencies
+ * @returns a promise that will resolve to the new ShaderMaterial
+ */
+ static ParseFromSnippetAsync(snippetId, scene, rootUrl = "") {
+ return new Promise((resolve, reject) => {
+ const request = new WebRequest();
+ request.addEventListener("readystatechange", () => {
+ if (request.readyState == 4) {
+ if (request.status == 200) {
+ const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);
+ const serializationObject = JSON.parse(snippet.shaderMaterial);
+ const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);
+ output.snippetId = snippetId;
+ resolve(output);
+ }
+ else {
+ reject("Unable to load the snippet " + snippetId);
+ }
+ }
+ });
+ request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
+ request.send();
+ });
+ }
+}
+/** Define the Url to load snippets */
+ShaderMaterial.SnippetUrl = `https://snippet.babylonjs.com`;
+/**
+ * Creates a ShaderMaterial from a snippet saved by the Inspector
+ * @deprecated Please use ParseFromSnippetAsync instead
+ * @param snippetId defines the snippet to load
+ * @param scene defines the hosting scene
+ * @param rootUrl defines the root URL to use to load textures and relative dependencies
+ * @returns a promise that will resolve to the new ShaderMaterial
+ */
+ShaderMaterial.CreateFromSnippetAsync = ShaderMaterial.ParseFromSnippetAsync;
+RegisterClass("BABYLON.ShaderMaterial", ShaderMaterial);
+
+Node$2.AddNodeConstructor("Light_Type_3", (name, scene) => {
+ return () => new HemisphericLight(name, Vector3.Zero(), scene);
+});
+/**
+ * The HemisphericLight simulates the ambient environment light,
+ * so the passed direction is the light reflection direction, not the incoming direction.
+ */
+class HemisphericLight extends Light {
+ /**
+ * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
+ * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
+ * The HemisphericLight can't cast shadows.
+ * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ * @param name The friendly name of the light
+ * @param direction The direction of the light reflection
+ * @param scene The scene the light belongs to
+ */
+ constructor(name, direction, scene) {
+ super(name, scene);
+ /**
+ * The groundColor is the light in the opposite direction to the one specified during creation.
+ * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
+ */
+ this.groundColor = new Color3(0.0, 0.0, 0.0);
+ this.direction = direction || Vector3.Up();
+ }
+ _buildUniformLayout() {
+ this._uniformBuffer.addUniform("vLightData", 4);
+ this._uniformBuffer.addUniform("vLightDiffuse", 4);
+ this._uniformBuffer.addUniform("vLightSpecular", 4);
+ this._uniformBuffer.addUniform("vLightGround", 3);
+ this._uniformBuffer.addUniform("shadowsInfo", 3);
+ this._uniformBuffer.addUniform("depthValues", 2);
+ this._uniformBuffer.create();
+ }
+ /**
+ * Returns the string "HemisphericLight".
+ * @returns The class name
+ */
+ getClassName() {
+ return "HemisphericLight";
+ }
+ /**
+ * Sets the HemisphericLight direction towards the passed target (Vector3).
+ * Returns the updated direction.
+ * @param target The target the direction should point to
+ * @returns The computed direction
+ */
+ setDirectionToTarget(target) {
+ this.direction = Vector3.Normalize(target.subtract(Vector3.Zero()));
+ return this.direction;
+ }
+ /**
+ * Returns the shadow generator associated to the light.
+ * @returns Always null for hemispheric lights because it does not support shadows.
+ */
+ getShadowGenerator() {
+ return null;
+ }
+ /**
+ * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
+ * @param _effect The effect to update
+ * @param lightIndex The index of the light in the effect to update
+ * @returns The hemispheric light
+ */
+ transferToEffect(_effect, lightIndex) {
+ const normalizeDirection = Vector3.Normalize(this.direction);
+ this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
+ this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
+ return this;
+ }
+ transferToNodeMaterialEffect(effect, lightDataUniformName) {
+ const normalizeDirection = Vector3.Normalize(this.direction);
+ effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);
+ return this;
+ }
+ /**
+ * Computes the world matrix of the node
+ * @returns the world matrix
+ */
+ computeWorldMatrix() {
+ if (!this._worldMatrix) {
+ this._worldMatrix = Matrix.Identity();
+ }
+ return this._worldMatrix;
+ }
+ /**
+ * Returns the integer 3.
+ * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
+ */
+ getTypeID() {
+ return Light.LIGHTTYPEID_HEMISPHERICLIGHT;
+ }
+ /**
+ * Prepares the list of defines specific to the light type.
+ * @param defines the list of defines
+ * @param lightIndex defines the index of the light for the effect
+ */
+ prepareLightSpecificDefines(defines, lightIndex) {
+ defines["HEMILIGHT" + lightIndex] = true;
+ }
+}
+__decorate([
+ serializeAsColor3()
+], HemisphericLight.prototype, "groundColor", void 0);
+__decorate([
+ serializeAsVector3()
+], HemisphericLight.prototype, "direction", void 0);
+// Register Class Name
+RegisterClass("BABYLON.HemisphericLight", HemisphericLight);
+
+Node$2.AddNodeConstructor("Light_Type_0", (name, scene) => {
+ return () => new PointLight(name, Vector3.Zero(), scene);
+});
+/**
+ * A point light is a light defined by an unique point in world space.
+ * The light is emitted in every direction from this point.
+ * A good example of a point light is a standard light bulb.
+ * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ */
+class PointLight extends ShadowLight {
+ /**
+ * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
+ * This specifies what angle the shadow will use to be created.
+ *
+ * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
+ */
+ get shadowAngle() {
+ return this._shadowAngle;
+ }
+ /**
+ * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
+ * This specifies what angle the shadow will use to be created.
+ *
+ * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
+ */
+ set shadowAngle(value) {
+ this._shadowAngle = value;
+ this.forceProjectionMatrixCompute();
+ }
+ /**
+ * Gets the direction if it has been set.
+ * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
+ */
+ get direction() {
+ return this._direction;
+ }
+ /**
+ * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
+ */
+ set direction(value) {
+ const previousNeedCube = this.needCube();
+ this._direction = value;
+ if (this.needCube() !== previousNeedCube && this._shadowGenerators) {
+ const iterator = this._shadowGenerators.values();
+ for (let key = iterator.next(); key.done !== true; key = iterator.next()) {
+ const shadowGenerator = key.value;
+ shadowGenerator.recreateShadowMap();
+ }
+ }
+ }
+ /**
+ * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
+ * A PointLight emits the light in every direction.
+ * It can cast shadows.
+ * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
+ * ```javascript
+ * var pointLight = new PointLight("pl", camera.position, scene);
+ * ```
+ * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ * @param name The light friendly name
+ * @param position The position of the point light in the scene
+ * @param scene The scene the lights belongs to
+ */
+ constructor(name, position, scene) {
+ super(name, scene);
+ this._shadowAngle = Math.PI / 2;
+ this.position = position;
+ }
+ /**
+ * Returns the string "PointLight"
+ * @returns the class name
+ */
+ getClassName() {
+ return "PointLight";
+ }
+ /**
+ * Returns the integer 0.
+ * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
+ */
+ getTypeID() {
+ return Light.LIGHTTYPEID_POINTLIGHT;
+ }
+ /**
+ * Specifies whether or not the shadowmap should be a cube texture.
+ * @returns true if the shadowmap needs to be a cube texture.
+ */
+ needCube() {
+ return !this.direction;
+ }
+ /**
+ * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
+ * @param faceIndex The index of the face we are computed the direction to generate shadow
+ * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
+ */
+ getShadowDirection(faceIndex) {
+ if (this.direction) {
+ return super.getShadowDirection(faceIndex);
+ }
+ else {
+ switch (faceIndex) {
+ case 0:
+ return new Vector3(1.0, 0.0, 0.0);
+ case 1:
+ return new Vector3(-1, 0.0, 0.0);
+ case 2:
+ return new Vector3(0.0, -1, 0.0);
+ case 3:
+ return new Vector3(0.0, 1.0, 0.0);
+ case 4:
+ return new Vector3(0.0, 0.0, 1.0);
+ case 5:
+ return new Vector3(0.0, 0.0, -1);
+ }
+ }
+ return Vector3.Zero();
+ }
+ /**
+ * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
+ * - fov = PI / 2
+ * - aspect ratio : 1.0
+ * - z-near and far equal to the active camera minZ and maxZ.
+ * Returns the PointLight.
+ * @param matrix
+ * @param viewMatrix
+ * @param renderList
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {
+ const activeCamera = this.getScene().activeCamera;
+ if (!activeCamera) {
+ return;
+ }
+ const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
+ const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
+ const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;
+ Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer);
+ }
+ _buildUniformLayout() {
+ this._uniformBuffer.addUniform("vLightData", 4);
+ this._uniformBuffer.addUniform("vLightDiffuse", 4);
+ this._uniformBuffer.addUniform("vLightSpecular", 4);
+ this._uniformBuffer.addUniform("vLightFalloff", 4);
+ this._uniformBuffer.addUniform("shadowsInfo", 3);
+ this._uniformBuffer.addUniform("depthValues", 2);
+ this._uniformBuffer.create();
+ }
+ /**
+ * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
+ * @param effect The effect to update
+ * @param lightIndex The index of the light in the effect to update
+ * @returns The point light
+ */
+ transferToEffect(effect, lightIndex) {
+ if (this.computeTransformedInformation()) {
+ this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
+ }
+ else {
+ this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
+ }
+ this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
+ return this;
+ }
+ transferToNodeMaterialEffect(effect, lightDataUniformName) {
+ if (this.computeTransformedInformation()) {
+ effect.setFloat3(lightDataUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z);
+ }
+ else {
+ effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z);
+ }
+ return this;
+ }
+ /**
+ * Prepares the list of defines specific to the light type.
+ * @param defines the list of defines
+ * @param lightIndex defines the index of the light for the effect
+ */
+ prepareLightSpecificDefines(defines, lightIndex) {
+ defines["POINTLIGHT" + lightIndex] = true;
+ }
+}
+__decorate([
+ serialize()
+], PointLight.prototype, "shadowAngle", null);
+// Register Class Name
+RegisterClass("BABYLON.PointLight", PointLight);
+
+Node$2.AddNodeConstructor("Light_Type_2", (name, scene) => {
+ return () => new SpotLight(name, Vector3.Zero(), Vector3.Zero(), 0, 0, scene);
+});
+/**
+ * A spot light is defined by a position, a direction, an angle, and an exponent.
+ * These values define a cone of light starting from the position, emitting toward the direction.
+ * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
+ * and the exponent defines the speed of the decay of the light with distance (reach).
+ * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ */
+class SpotLight extends ShadowLight {
+ /**
+ * Gets or sets the IES profile texture used to create the spotlight
+ * @see https://playground.babylonjs.com/#UIAXAU#1
+ */
+ get iesProfileTexture() {
+ return this._iesProfileTexture;
+ }
+ set iesProfileTexture(value) {
+ if (this._iesProfileTexture === value) {
+ return;
+ }
+ this._iesProfileTexture = value;
+ if (this._iesProfileTexture && SpotLight._IsTexture(this._iesProfileTexture)) {
+ this._iesProfileTexture.onLoadObservable.addOnce(() => {
+ this._markMeshesAsLightDirty();
+ });
+ }
+ }
+ /**
+ * Gets the cone angle of the spot light in Radians.
+ */
+ get angle() {
+ return this._angle;
+ }
+ /**
+ * Sets the cone angle of the spot light in Radians.
+ */
+ set angle(value) {
+ this._angle = value;
+ this._cosHalfAngle = Math.cos(value * 0.5);
+ this._projectionTextureProjectionLightDirty = true;
+ this.forceProjectionMatrixCompute();
+ this._computeAngleValues();
+ }
+ /**
+ * Only used in gltf falloff mode, this defines the angle where
+ * the directional falloff will start before cutting at angle which could be seen
+ * as outer angle.
+ */
+ get innerAngle() {
+ return this._innerAngle;
+ }
+ /**
+ * Only used in gltf falloff mode, this defines the angle where
+ * the directional falloff will start before cutting at angle which could be seen
+ * as outer angle.
+ */
+ set innerAngle(value) {
+ this._innerAngle = value;
+ this._computeAngleValues();
+ }
+ /**
+ * Allows scaling the angle of the light for shadow generation only.
+ */
+ get shadowAngleScale() {
+ return this._shadowAngleScale;
+ }
+ /**
+ * Allows scaling the angle of the light for shadow generation only.
+ */
+ set shadowAngleScale(value) {
+ this._shadowAngleScale = value;
+ this.forceProjectionMatrixCompute();
+ }
+ /**
+ * Allows reading the projection texture
+ */
+ get projectionTextureMatrix() {
+ return this._projectionTextureMatrix;
+ }
+ /**
+ * Gets the near clip of the Spotlight for texture projection.
+ */
+ get projectionTextureLightNear() {
+ return this._projectionTextureLightNear;
+ }
+ /**
+ * Sets the near clip of the Spotlight for texture projection.
+ */
+ set projectionTextureLightNear(value) {
+ this._projectionTextureLightNear = value;
+ this._projectionTextureProjectionLightDirty = true;
+ }
+ /**
+ * Gets the far clip of the Spotlight for texture projection.
+ */
+ get projectionTextureLightFar() {
+ return this._projectionTextureLightFar;
+ }
+ /**
+ * Sets the far clip of the Spotlight for texture projection.
+ */
+ set projectionTextureLightFar(value) {
+ this._projectionTextureLightFar = value;
+ this._projectionTextureProjectionLightDirty = true;
+ }
+ /**
+ * Gets the Up vector of the Spotlight for texture projection.
+ */
+ get projectionTextureUpDirection() {
+ return this._projectionTextureUpDirection;
+ }
+ /**
+ * Sets the Up vector of the Spotlight for texture projection.
+ */
+ set projectionTextureUpDirection(value) {
+ this._projectionTextureUpDirection = value;
+ this._projectionTextureProjectionLightDirty = true;
+ }
+ /**
+ * Gets the projection texture of the light.
+ */
+ get projectionTexture() {
+ return this._projectionTexture;
+ }
+ /**
+ * Sets the projection texture of the light.
+ */
+ set projectionTexture(value) {
+ if (this._projectionTexture === value) {
+ return;
+ }
+ this._projectionTexture = value;
+ this._projectionTextureDirty = true;
+ if (this._projectionTexture && !this._projectionTexture.isReady()) {
+ if (SpotLight._IsProceduralTexture(this._projectionTexture)) {
+ this._projectionTexture.getEffect().executeWhenCompiled(() => {
+ this._markMeshesAsLightDirty();
+ });
+ }
+ else if (SpotLight._IsTexture(this._projectionTexture)) {
+ this._projectionTexture.onLoadObservable.addOnce(() => {
+ this._markMeshesAsLightDirty();
+ });
+ }
+ }
+ }
+ static _IsProceduralTexture(texture) {
+ return texture.onGeneratedObservable !== undefined;
+ }
+ static _IsTexture(texture) {
+ return texture.onLoadObservable !== undefined;
+ }
+ /**
+ * Gets or sets the light projection matrix as used by the projection texture
+ */
+ get projectionTextureProjectionLightMatrix() {
+ return this._projectionTextureProjectionLightMatrix;
+ }
+ set projectionTextureProjectionLightMatrix(projection) {
+ this._projectionTextureProjectionLightMatrix = projection;
+ this._projectionTextureProjectionLightDirty = false;
+ this._projectionTextureDirty = true;
+ }
+ /**
+ * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
+ * It can cast shadows.
+ * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction
+ * @param name The light friendly name
+ * @param position The position of the spot light in the scene
+ * @param direction The direction of the light in the scene
+ * @param angle The cone angle of the light in Radians
+ * @param exponent The light decay speed with the distance from the emission spot
+ * @param scene The scene the lights belongs to
+ */
+ constructor(name, position, direction, angle, exponent, scene) {
+ super(name, scene);
+ this._innerAngle = 0;
+ this._iesProfileTexture = null;
+ this._projectionTextureMatrix = Matrix.Zero();
+ this._projectionTextureLightNear = 1e-6;
+ this._projectionTextureLightFar = 1000.0;
+ this._projectionTextureUpDirection = Vector3.Up();
+ this._projectionTextureViewLightDirty = true;
+ this._projectionTextureProjectionLightDirty = true;
+ this._projectionTextureDirty = true;
+ this._projectionTextureViewTargetVector = Vector3.Zero();
+ this._projectionTextureViewLightMatrix = Matrix.Zero();
+ this._projectionTextureProjectionLightMatrix = Matrix.Zero();
+ this._projectionTextureScalingMatrix = Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
+ this.position = position;
+ this.direction = direction;
+ this.angle = angle;
+ this.exponent = exponent;
+ }
+ /**
+ * Returns the string "SpotLight".
+ * @returns the class name
+ */
+ getClassName() {
+ return "SpotLight";
+ }
+ /**
+ * Returns the integer 2.
+ * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
+ */
+ getTypeID() {
+ return Light.LIGHTTYPEID_SPOTLIGHT;
+ }
+ /**
+ * Overrides the direction setter to recompute the projection texture view light Matrix.
+ * @param value
+ */
+ _setDirection(value) {
+ super._setDirection(value);
+ this._projectionTextureViewLightDirty = true;
+ }
+ /**
+ * Overrides the position setter to recompute the projection texture view light Matrix.
+ * @param value
+ */
+ _setPosition(value) {
+ super._setPosition(value);
+ this._projectionTextureViewLightDirty = true;
+ }
+ /**
+ * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
+ * Returns the SpotLight.
+ * @param matrix
+ * @param viewMatrix
+ * @param renderList
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {
+ const activeCamera = this.getScene().activeCamera;
+ if (!activeCamera) {
+ return;
+ }
+ this._shadowAngleScale = this._shadowAngleScale || 1;
+ const angle = this._shadowAngleScale * this._angle;
+ const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
+ const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
+ const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;
+ Matrix.PerspectiveFovLHToRef(angle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer);
+ }
+ _computeProjectionTextureViewLightMatrix() {
+ this._projectionTextureViewLightDirty = false;
+ this._projectionTextureDirty = true;
+ this.getAbsolutePosition().addToRef(this.getShadowDirection(), this._projectionTextureViewTargetVector);
+ Matrix.LookAtLHToRef(this.getAbsolutePosition(), this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
+ }
+ _computeProjectionTextureProjectionLightMatrix() {
+ this._projectionTextureProjectionLightDirty = false;
+ this._projectionTextureDirty = true;
+ const lightFar = this.projectionTextureLightFar;
+ const lightNear = this.projectionTextureLightNear;
+ const P = lightFar / (lightFar - lightNear);
+ const Q = -P * lightNear;
+ const S = 1.0 / Math.tan(this._angle / 2.0);
+ const A = 1.0;
+ Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
+ }
+ /**
+ * Main function for light texture projection matrix computing.
+ */
+ _computeProjectionTextureMatrix() {
+ this._projectionTextureDirty = false;
+ this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
+ if (this._projectionTexture instanceof Texture) {
+ const u = this._projectionTexture.uScale / 2.0;
+ const v = this._projectionTexture.vScale / 2.0;
+ Matrix.FromValuesToRef(u, 0.0, 0.0, 0.0, 0.0, v, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0, this._projectionTextureScalingMatrix);
+ }
+ this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
+ }
+ _buildUniformLayout() {
+ this._uniformBuffer.addUniform("vLightData", 4);
+ this._uniformBuffer.addUniform("vLightDiffuse", 4);
+ this._uniformBuffer.addUniform("vLightSpecular", 4);
+ this._uniformBuffer.addUniform("vLightDirection", 3);
+ this._uniformBuffer.addUniform("vLightFalloff", 4);
+ this._uniformBuffer.addUniform("shadowsInfo", 3);
+ this._uniformBuffer.addUniform("depthValues", 2);
+ this._uniformBuffer.create();
+ }
+ _computeAngleValues() {
+ this._lightAngleScale = 1.0 / Math.max(0.001, Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle);
+ this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
+ }
+ /**
+ * Sets the passed Effect "effect" with the Light textures.
+ * @param effect The effect to update
+ * @param lightIndex The index of the light in the effect to update
+ * @returns The light
+ */
+ transferTexturesToEffect(effect, lightIndex) {
+ if (this.projectionTexture && this.projectionTexture.isReady()) {
+ if (this._projectionTextureViewLightDirty) {
+ this._computeProjectionTextureViewLightMatrix();
+ }
+ if (this._projectionTextureProjectionLightDirty) {
+ this._computeProjectionTextureProjectionLightMatrix();
+ }
+ if (this._projectionTextureDirty) {
+ this._computeProjectionTextureMatrix();
+ }
+ effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
+ effect.setTexture("projectionLightTexture" + lightIndex, this.projectionTexture);
+ }
+ if (this._iesProfileTexture && this._iesProfileTexture.isReady()) {
+ effect.setTexture("iesLightTexture" + lightIndex, this._iesProfileTexture);
+ }
+ return this;
+ }
+ /**
+ * Sets the passed Effect object with the SpotLight transformed position (or position if not parented) and normalized direction.
+ * @param effect The effect to update
+ * @param lightIndex The index of the light in the effect to update
+ * @returns The spot light
+ */
+ transferToEffect(effect, lightIndex) {
+ let normalizeDirection;
+ if (this.computeTransformedInformation()) {
+ this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
+ normalizeDirection = Vector3.Normalize(this.transformedDirection);
+ }
+ else {
+ this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
+ normalizeDirection = Vector3.Normalize(this.direction);
+ }
+ this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
+ this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
+ return this;
+ }
+ transferToNodeMaterialEffect(effect, lightDataUniformName) {
+ let normalizeDirection;
+ if (this.computeTransformedInformation()) {
+ normalizeDirection = Vector3.Normalize(this.transformedDirection);
+ }
+ else {
+ normalizeDirection = Vector3.Normalize(this.direction);
+ }
+ if (this.getScene().useRightHandedSystem) {
+ effect.setFloat3(lightDataUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z);
+ }
+ else {
+ effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);
+ }
+ return this;
+ }
+ /**
+ * Disposes the light and the associated resources.
+ */
+ dispose() {
+ super.dispose();
+ if (this._projectionTexture) {
+ this._projectionTexture.dispose();
+ }
+ if (this._iesProfileTexture) {
+ this._iesProfileTexture.dispose();
+ this._iesProfileTexture = null;
+ }
+ }
+ /**
+ * Gets the minZ used for shadow according to both the scene and the light.
+ * @param activeCamera The camera we are returning the min for
+ * @returns the depth min z
+ */
+ getDepthMinZ(activeCamera) {
+ const engine = this._scene.getEngine();
+ const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : (activeCamera?.minZ ?? 0);
+ return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? minZ : this._scene.getEngine().isNDCHalfZRange ? 0 : minZ;
+ }
+ /**
+ * Gets the maxZ used for shadow according to both the scene and the light.
+ * @param activeCamera The camera we are returning the max for
+ * @returns the depth max z
+ */
+ getDepthMaxZ(activeCamera) {
+ const engine = this._scene.getEngine();
+ const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : (activeCamera?.maxZ ?? 10000);
+ return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : maxZ;
+ }
+ /**
+ * Prepares the list of defines specific to the light type.
+ * @param defines the list of defines
+ * @param lightIndex defines the index of the light for the effect
+ */
+ prepareLightSpecificDefines(defines, lightIndex) {
+ defines["SPOTLIGHT" + lightIndex] = true;
+ defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture && this.projectionTexture.isReady() ? true : false;
+ defines["IESLIGHTTEXTURE" + lightIndex] = this._iesProfileTexture && this._iesProfileTexture.isReady() ? true : false;
+ }
+}
+__decorate([
+ serialize()
+], SpotLight.prototype, "angle", null);
+__decorate([
+ serialize()
+], SpotLight.prototype, "innerAngle", null);
+__decorate([
+ serialize()
+], SpotLight.prototype, "shadowAngleScale", null);
+__decorate([
+ serialize()
+], SpotLight.prototype, "exponent", void 0);
+__decorate([
+ serialize()
+], SpotLight.prototype, "projectionTextureLightNear", null);
+__decorate([
+ serialize()
+], SpotLight.prototype, "projectionTextureLightFar", null);
+__decorate([
+ serialize()
+], SpotLight.prototype, "projectionTextureUpDirection", null);
+__decorate([
+ serializeAsTexture("projectedLightTexture")
+], SpotLight.prototype, "_projectionTexture", void 0);
+// Register Class Name
+RegisterClass("BABYLON.SpotLight", SpotLight);
+
+/**
+ * Utils functions for GLTF
+ * @internal
+ * @deprecated
+ */
+class GLTFUtils {
+ /**
+ * Sets the given "parameter" matrix
+ * @param scene the Scene object
+ * @param source the source node where to pick the matrix
+ * @param parameter the GLTF technique parameter
+ * @param uniformName the name of the shader's uniform
+ * @param shaderMaterial the shader material
+ */
+ static SetMatrix(scene, source, parameter, uniformName, shaderMaterial) {
+ let mat = null;
+ if (parameter.semantic === "MODEL") {
+ mat = source.getWorldMatrix();
+ }
+ else if (parameter.semantic === "PROJECTION") {
+ mat = scene.getProjectionMatrix();
+ }
+ else if (parameter.semantic === "VIEW") {
+ mat = scene.getViewMatrix();
+ }
+ else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
+ mat = Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
+ }
+ else if (parameter.semantic === "MODELVIEW") {
+ mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
+ }
+ else if (parameter.semantic === "MODELVIEWPROJECTION") {
+ mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
+ }
+ else if (parameter.semantic === "MODELINVERSE") {
+ mat = source.getWorldMatrix().invert();
+ }
+ else if (parameter.semantic === "VIEWINVERSE") {
+ mat = scene.getViewMatrix().invert();
+ }
+ else if (parameter.semantic === "PROJECTIONINVERSE") {
+ mat = scene.getProjectionMatrix().invert();
+ }
+ else if (parameter.semantic === "MODELVIEWINVERSE") {
+ mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
+ }
+ else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
+ mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
+ }
+ else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
+ mat = Matrix.Transpose(source.getWorldMatrix().invert());
+ }
+ if (mat) {
+ switch (parameter.type) {
+ case EParameterType.FLOAT_MAT2:
+ shaderMaterial.setMatrix2x2(uniformName, Matrix.GetAsMatrix2x2(mat));
+ break;
+ case EParameterType.FLOAT_MAT3:
+ shaderMaterial.setMatrix3x3(uniformName, Matrix.GetAsMatrix3x3(mat));
+ break;
+ case EParameterType.FLOAT_MAT4:
+ shaderMaterial.setMatrix(uniformName, mat);
+ break;
+ }
+ }
+ }
+ /**
+ * Sets the given "parameter" matrix
+ * @param shaderMaterial the shader material
+ * @param uniform the name of the shader's uniform
+ * @param value the value of the uniform
+ * @param type the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
+ * @returns true if set, else false
+ */
+ static SetUniform(shaderMaterial, uniform, value, type) {
+ switch (type) {
+ case EParameterType.FLOAT:
+ shaderMaterial.setFloat(uniform, value);
+ return true;
+ case EParameterType.FLOAT_VEC2:
+ shaderMaterial.setVector2(uniform, Vector2.FromArray(value));
+ return true;
+ case EParameterType.FLOAT_VEC3:
+ shaderMaterial.setVector3(uniform, Vector3.FromArray(value));
+ return true;
+ case EParameterType.FLOAT_VEC4:
+ shaderMaterial.setVector4(uniform, Vector4.FromArray(value));
+ return true;
+ default:
+ return false;
+ }
+ }
+ /**
+ * Returns the wrap mode of the texture
+ * @param mode the mode value
+ * @returns the wrap mode (TEXTURE_WRAP_ADDRESSMODE, MIRROR_ADDRESSMODE or CLAMP_ADDRESSMODE)
+ */
+ static GetWrapMode(mode) {
+ switch (mode) {
+ case ETextureWrapMode.CLAMP_TO_EDGE:
+ return Texture.CLAMP_ADDRESSMODE;
+ case ETextureWrapMode.MIRRORED_REPEAT:
+ return Texture.MIRROR_ADDRESSMODE;
+ case ETextureWrapMode.REPEAT:
+ return Texture.WRAP_ADDRESSMODE;
+ default:
+ return Texture.WRAP_ADDRESSMODE;
+ }
+ }
+ /**
+ * Returns the byte stride giving an accessor
+ * @param accessor the GLTF accessor objet
+ * @returns the byte stride
+ */
+ static GetByteStrideFromType(accessor) {
+ // Needs this function since "byteStride" isn't requiered in glTF format
+ const type = accessor.type;
+ switch (type) {
+ case "VEC2":
+ return 2;
+ case "VEC3":
+ return 3;
+ case "VEC4":
+ return 4;
+ case "MAT2":
+ return 4;
+ case "MAT3":
+ return 9;
+ case "MAT4":
+ return 16;
+ default:
+ return 1;
+ }
+ }
+ /**
+ * Returns the texture filter mode giving a mode value
+ * @param mode the filter mode value
+ * @returns the filter mode (TODO - needs to be a type?)
+ */
+ static GetTextureFilterMode(mode) {
+ switch (mode) {
+ case ETextureFilterType.LINEAR:
+ case ETextureFilterType.LINEAR_MIPMAP_NEAREST:
+ case ETextureFilterType.LINEAR_MIPMAP_LINEAR:
+ return Texture.TRILINEAR_SAMPLINGMODE;
+ case ETextureFilterType.NEAREST:
+ case ETextureFilterType.NEAREST_MIPMAP_NEAREST:
+ return Texture.NEAREST_SAMPLINGMODE;
+ default:
+ return Texture.BILINEAR_SAMPLINGMODE;
+ }
+ }
+ static GetBufferFromBufferView(gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
+ byteOffset = bufferView.byteOffset + byteOffset;
+ const loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
+ if (byteOffset + byteLength > loadedBufferView.byteLength) {
+ throw new Error("Buffer access is out of range");
+ }
+ const buffer = loadedBufferView.buffer;
+ byteOffset += loadedBufferView.byteOffset;
+ switch (componentType) {
+ case EComponentType.BYTE:
+ return new Int8Array(buffer, byteOffset, byteLength);
+ case EComponentType.UNSIGNED_BYTE:
+ return new Uint8Array(buffer, byteOffset, byteLength);
+ case EComponentType.SHORT:
+ return new Int16Array(buffer, byteOffset, byteLength);
+ case EComponentType.UNSIGNED_SHORT:
+ return new Uint16Array(buffer, byteOffset, byteLength);
+ default:
+ return new Float32Array(buffer, byteOffset, byteLength);
+ }
+ }
+ /**
+ * Returns a buffer from its accessor
+ * @param gltfRuntime the GLTF runtime
+ * @param accessor the GLTF accessor
+ * @returns an array buffer view
+ */
+ static GetBufferFromAccessor(gltfRuntime, accessor) {
+ const bufferView = gltfRuntime.bufferViews[accessor.bufferView];
+ const byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
+ return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
+ }
+ /**
+ * Decodes a buffer view into a string
+ * @param view the buffer view
+ * @returns a string
+ */
+ static DecodeBufferToText(view) {
+ let result = "";
+ const length = view.byteLength;
+ for (let i = 0; i < length; ++i) {
+ result += String.fromCharCode(view[i]);
+ }
+ return result;
+ }
+ /**
+ * Returns the default material of gltf. Related to
+ * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
+ * @param scene the Babylon.js scene
+ * @returns the default Babylon material
+ */
+ static GetDefaultMaterial(scene) {
+ if (!GLTFUtils._DefaultMaterial) {
+ Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
+ "precision highp float;",
+ "",
+ "uniform mat4 worldView;",
+ "uniform mat4 projection;",
+ "",
+ "attribute vec3 position;",
+ "",
+ "void main(void)",
+ "{",
+ " gl_Position = projection * worldView * vec4(position, 1.0);",
+ "}",
+ ].join("\n");
+ Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
+ "precision highp float;",
+ "",
+ "uniform vec4 u_emission;",
+ "",
+ "void main(void)",
+ "{",
+ " gl_FragColor = u_emission;",
+ "}",
+ ].join("\n");
+ const shaderPath = {
+ vertex: "GLTFDefaultMaterial",
+ fragment: "GLTFDefaultMaterial",
+ };
+ const options = {
+ attributes: ["position"],
+ uniforms: ["worldView", "projection", "u_emission"],
+ samplers: new Array(),
+ needAlphaBlending: false,
+ };
+ GLTFUtils._DefaultMaterial = new ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
+ GLTFUtils._DefaultMaterial.setColor4("u_emission", new Color4(0.5, 0.5, 0.5, 1.0));
+ }
+ return GLTFUtils._DefaultMaterial;
+ }
+}
+// The GLTF default material
+GLTFUtils._DefaultMaterial = null;
+
+/* eslint-disable @typescript-eslint/naming-convention */
+/** Defines the cross module used constants to avoid circular dependencies */
+class Constants {
+}
+/** Sampler suffix when associated with a texture name */
+Constants.AUTOSAMPLERSUFFIX = "Sampler";
+/** Flag used to disable diagnostics for WebGPU */
+Constants.DISABLEUA = "#define DISABLE_UNIFORMITY_ANALYSIS";
+/** Defines that alpha blending is disabled */
+Constants.ALPHA_DISABLE = 0;
+/** Defines that alpha blending is SRC ALPHA * SRC + DEST */
+Constants.ALPHA_ADD = 1;
+/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
+Constants.ALPHA_COMBINE = 2;
+/** Defines that alpha blending is DEST - SRC * DEST */
+Constants.ALPHA_SUBTRACT = 3;
+/** Defines that alpha blending is SRC * DEST */
+Constants.ALPHA_MULTIPLY = 4;
+/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC) * DEST */
+Constants.ALPHA_MAXIMIZED = 5;
+/** Defines that alpha blending is SRC + DEST */
+Constants.ALPHA_ONEONE = 6;
+/** Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST */
+Constants.ALPHA_PREMULTIPLIED = 7;
+/**
+ * Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST
+ * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
+ */
+Constants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
+/** Defines that alpha blending is CST * SRC + (1 - CST) * DEST */
+Constants.ALPHA_INTERPOLATE = 9;
+/**
+ * Defines that alpha blending is SRC + (1 - SRC) * DEST
+ * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
+ */
+Constants.ALPHA_SCREENMODE = 10;
+/**
+ * Defines that alpha blending is SRC + DST
+ * Alpha will be set to SRC ALPHA + DST ALPHA
+ */
+Constants.ALPHA_ONEONE_ONEONE = 11;
+/**
+ * Defines that alpha blending is SRC * DST ALPHA + DST
+ * Alpha will be set to 0
+ */
+Constants.ALPHA_ALPHATOCOLOR = 12;
+/**
+ * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC)
+ */
+Constants.ALPHA_REVERSEONEMINUS = 13;
+/**
+ * Defines that alpha blending is SRC + DST * (1 - SRC ALPHA)
+ * Alpha will be set to SRC ALPHA + DST ALPHA * (1 - SRC ALPHA)
+ */
+Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14;
+/**
+ * Defines that alpha blending is SRC + DST
+ * Alpha will be set to SRC ALPHA
+ */
+Constants.ALPHA_ONEONE_ONEZERO = 15;
+/**
+ * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC)
+ * Alpha will be set to DST ALPHA
+ */
+Constants.ALPHA_EXCLUSION = 16;
+/**
+ * Defines that alpha blending is SRC * SRC ALPHA + DST * (1 - SRC ALPHA)
+ * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DST ALPHA
+ */
+Constants.ALPHA_LAYER_ACCUMULATE = 17;
+/** Defines that alpha blending equation a SUM */
+Constants.ALPHA_EQUATION_ADD = 0;
+/** Defines that alpha blending equation a SUBSTRACTION */
+Constants.ALPHA_EQUATION_SUBSTRACT = 1;
+/** Defines that alpha blending equation a REVERSE SUBSTRACTION */
+Constants.ALPHA_EQUATION_REVERSE_SUBTRACT = 2;
+/** Defines that alpha blending equation a MAX operation */
+Constants.ALPHA_EQUATION_MAX = 3;
+/** Defines that alpha blending equation a MIN operation */
+Constants.ALPHA_EQUATION_MIN = 4;
+/**
+ * Defines that alpha blending equation a DARKEN operation:
+ * It takes the min of the src and sums the alpha channels.
+ */
+Constants.ALPHA_EQUATION_DARKEN = 5;
+/** Defines that the resource is not delayed*/
+Constants.DELAYLOADSTATE_NONE = 0;
+/** Defines that the resource was successfully delay loaded */
+Constants.DELAYLOADSTATE_LOADED = 1;
+/** Defines that the resource is currently delay loading */
+Constants.DELAYLOADSTATE_LOADING = 2;
+/** Defines that the resource is delayed and has not started loading */
+Constants.DELAYLOADSTATE_NOTLOADED = 4;
+// Depth or Stencil test Constants.
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
+Constants.NEVER = 0x0200;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
+Constants.ALWAYS = 0x0207;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
+Constants.LESS = 0x0201;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
+Constants.EQUAL = 0x0202;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
+Constants.LEQUAL = 0x0203;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
+Constants.GREATER = 0x0204;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
+Constants.GEQUAL = 0x0206;
+/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
+Constants.NOTEQUAL = 0x0205;
+// Stencil Actions Constants.
+/** Passed to stencilOperation to specify that stencil value must be kept */
+Constants.KEEP = 0x1e00;
+/** Passed to stencilOperation to specify that stencil value must be zero */
+Constants.ZERO = 0x0000;
+/** Passed to stencilOperation to specify that stencil value must be replaced */
+Constants.REPLACE = 0x1e01;
+/** Passed to stencilOperation to specify that stencil value must be incremented */
+Constants.INCR = 0x1e02;
+/** Passed to stencilOperation to specify that stencil value must be decremented */
+Constants.DECR = 0x1e03;
+/** Passed to stencilOperation to specify that stencil value must be inverted */
+Constants.INVERT = 0x150a;
+/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
+Constants.INCR_WRAP = 0x8507;
+/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
+Constants.DECR_WRAP = 0x8508;
+/** Texture is not repeating outside of 0..1 UVs */
+Constants.TEXTURE_CLAMP_ADDRESSMODE = 0;
+/** Texture is repeating outside of 0..1 UVs */
+Constants.TEXTURE_WRAP_ADDRESSMODE = 1;
+/** Texture is repeating and mirrored */
+Constants.TEXTURE_MIRROR_ADDRESSMODE = 2;
+/** Flag to create a storage texture */
+Constants.TEXTURE_CREATIONFLAG_STORAGE = 1;
+/** ALPHA */
+Constants.TEXTUREFORMAT_ALPHA = 0;
+/** LUMINANCE */
+Constants.TEXTUREFORMAT_LUMINANCE = 1;
+/** LUMINANCE_ALPHA */
+Constants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
+/** RGB */
+Constants.TEXTUREFORMAT_RGB = 4;
+/** RGBA */
+Constants.TEXTUREFORMAT_RGBA = 5;
+/** RED */
+Constants.TEXTUREFORMAT_RED = 6;
+/** RED (2nd reference) */
+Constants.TEXTUREFORMAT_R = 6;
+/** RED unsigned short normed to [0, 1] **/
+Constants.TEXTUREFORMAT_R16_UNORM = 0x822a;
+/** RG unsigned short normed to [0, 1] **/
+Constants.TEXTUREFORMAT_RG16_UNORM = 0x822c;
+/** RGB unsigned short normed to [0, 1] **/
+Constants.TEXTUREFORMAT_RGB16_UNORM = 0x8054;
+/** RGBA unsigned short normed to [0, 1] **/
+Constants.TEXTUREFORMAT_RGBA16_UNORM = 0x805b;
+/** RED signed short normed to [-1, 1] **/
+Constants.TEXTUREFORMAT_R16_SNORM = 0x8f98;
+/** RG signed short normed to [-1, 1] **/
+Constants.TEXTUREFORMAT_RG16_SNORM = 0x8f99;
+/** RGB signed short normed to [-1, 1] **/
+Constants.TEXTUREFORMAT_RGB16_SNORM = 0x8f9a;
+/** RGBA signed short normed to [-1, 1] **/
+Constants.TEXTUREFORMAT_RGBA16_SNORM = 0x8f9b;
+/** RG */
+Constants.TEXTUREFORMAT_RG = 7;
+/** RED_INTEGER */
+Constants.TEXTUREFORMAT_RED_INTEGER = 8;
+/** RED_INTEGER (2nd reference) */
+Constants.TEXTUREFORMAT_R_INTEGER = 8;
+/** RG_INTEGER */
+Constants.TEXTUREFORMAT_RG_INTEGER = 9;
+/** RGB_INTEGER */
+Constants.TEXTUREFORMAT_RGB_INTEGER = 10;
+/** RGBA_INTEGER */
+Constants.TEXTUREFORMAT_RGBA_INTEGER = 11;
+/** BGRA */
+Constants.TEXTUREFORMAT_BGRA = 12;
+/** Depth 24 bits + Stencil 8 bits */
+Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13;
+/** Depth 32 bits float */
+Constants.TEXTUREFORMAT_DEPTH32_FLOAT = 14;
+/** Depth 16 bits */
+Constants.TEXTUREFORMAT_DEPTH16 = 15;
+/** Depth 24 bits */
+Constants.TEXTUREFORMAT_DEPTH24 = 16;
+/** Depth 24 bits unorm + Stencil 8 bits */
+Constants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8 = 17;
+/** Depth 32 bits float + Stencil 8 bits */
+Constants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8 = 18;
+/** Stencil 8 bits */
+Constants.TEXTUREFORMAT_STENCIL8 = 19;
+/** UNDEFINED */
+Constants.TEXTUREFORMAT_UNDEFINED = 0xffffffff;
+/** Compressed BC7 */
+Constants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492;
+/** Compressed BC7 (SRGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 36493;
+/** Compressed BC6 unsigned float */
+Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495;
+/** Compressed BC6 signed float */
+Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494;
+/** Compressed BC3 */
+Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779;
+/** Compressed BC3 (SRGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 35919;
+/** Compressed BC2 */
+Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778;
+/** Compressed BC2 (SRGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 35918;
+/** Compressed BC1 (RGBA) */
+Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777;
+/** Compressed BC1 (RGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776;
+/** Compressed BC1 (SRGB+A) */
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 35917;
+/** Compressed BC1 (SRGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT = 35916;
+/** Compressed ASTC 4x4 */
+Constants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808;
+/** Compressed ASTC 4x4 (SRGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 37840;
+/** Compressed ETC1 (RGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196;
+/** Compressed ETC2 (RGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2 = 37492;
+/** Compressed ETC2 (SRGB) */
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2 = 37493;
+/** Compressed ETC2 (RGB+A1) */
+Constants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494;
+/** Compressed ETC2 (SRGB+A1)*/
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495;
+/** Compressed ETC2 (RGB+A) */
+Constants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC = 37496;
+/** Compressed ETC2 (SRGB+1) */
+Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497;
+/** UNSIGNED_BYTE */
+Constants.TEXTURETYPE_UNSIGNED_BYTE = 0;
+/** @deprecated use more explicit TEXTURETYPE_UNSIGNED_BYTE instead. Use TEXTURETYPE_UNSIGNED_INTEGER for 32bits values.*/
+Constants.TEXTURETYPE_UNSIGNED_INT = 0;
+/** FLOAT */
+Constants.TEXTURETYPE_FLOAT = 1;
+/** HALF_FLOAT */
+Constants.TEXTURETYPE_HALF_FLOAT = 2;
+/** BYTE */
+Constants.TEXTURETYPE_BYTE = 3;
+/** SHORT */
+Constants.TEXTURETYPE_SHORT = 4;
+/** UNSIGNED_SHORT */
+Constants.TEXTURETYPE_UNSIGNED_SHORT = 5;
+/** INT */
+Constants.TEXTURETYPE_INT = 6;
+/** UNSIGNED_INT */
+Constants.TEXTURETYPE_UNSIGNED_INTEGER = 7;
+/** UNSIGNED_SHORT_4_4_4_4 */
+Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
+/** UNSIGNED_SHORT_5_5_5_1 */
+Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
+/** UNSIGNED_SHORT_5_6_5 */
+Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
+/** UNSIGNED_INT_2_10_10_10_REV */
+Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
+/** UNSIGNED_INT_24_8 */
+Constants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
+/** UNSIGNED_INT_10F_11F_11F_REV */
+Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
+/** UNSIGNED_INT_5_9_9_9_REV */
+Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
+/** FLOAT_32_UNSIGNED_INT_24_8_REV */
+Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
+/** UNDEFINED */
+Constants.TEXTURETYPE_UNDEFINED = 16;
+/** 2D Texture target*/
+Constants.TEXTURE_2D = 3553;
+/** 2D Array Texture target */
+Constants.TEXTURE_2D_ARRAY = 35866;
+/** Cube Map Texture target */
+Constants.TEXTURE_CUBE_MAP = 34067;
+/** Cube Map Array Texture target */
+Constants.TEXTURE_CUBE_MAP_ARRAY = 0xdeadbeef;
+/** 3D Texture target */
+Constants.TEXTURE_3D = 32879;
+/** nearest is mag = nearest and min = nearest and no mip */
+Constants.TEXTURE_NEAREST_SAMPLINGMODE = 1;
+/** mag = nearest and min = nearest and mip = none */
+Constants.TEXTURE_NEAREST_NEAREST = 1;
+/** Bilinear is mag = linear and min = linear and no mip */
+Constants.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
+/** mag = linear and min = linear and mip = none */
+Constants.TEXTURE_LINEAR_LINEAR = 2;
+/** Trilinear is mag = linear and min = linear and mip = linear */
+Constants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
+/** Trilinear is mag = linear and min = linear and mip = linear */
+Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
+/** mag = nearest and min = nearest and mip = nearest */
+Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
+/** mag = nearest and min = linear and mip = nearest */
+Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
+/** mag = nearest and min = linear and mip = linear */
+Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
+/** mag = nearest and min = linear and mip = none */
+Constants.TEXTURE_NEAREST_LINEAR = 7;
+/** nearest is mag = nearest and min = nearest and mip = linear */
+Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;
+/** mag = linear and min = nearest and mip = nearest */
+Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
+/** mag = linear and min = nearest and mip = linear */
+Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
+/** Bilinear is mag = linear and min = linear and mip = nearest */
+Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;
+/** mag = linear and min = nearest and mip = none */
+Constants.TEXTURE_LINEAR_NEAREST = 12;
+/** Explicit coordinates mode */
+Constants.TEXTURE_EXPLICIT_MODE = 0;
+/** Spherical coordinates mode */
+Constants.TEXTURE_SPHERICAL_MODE = 1;
+/** Planar coordinates mode */
+Constants.TEXTURE_PLANAR_MODE = 2;
+/** Cubic coordinates mode */
+Constants.TEXTURE_CUBIC_MODE = 3;
+/** Projection coordinates mode */
+Constants.TEXTURE_PROJECTION_MODE = 4;
+/** Skybox coordinates mode */
+Constants.TEXTURE_SKYBOX_MODE = 5;
+/** Inverse Cubic coordinates mode */
+Constants.TEXTURE_INVCUBIC_MODE = 6;
+/** Equirectangular coordinates mode */
+Constants.TEXTURE_EQUIRECTANGULAR_MODE = 7;
+/** Equirectangular Fixed coordinates mode */
+Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
+/** Equirectangular Fixed Mirrored coordinates mode */
+Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
+/** Offline (baking) quality for texture filtering */
+Constants.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096;
+/** High quality for texture filtering */
+Constants.TEXTURE_FILTERING_QUALITY_HIGH = 64;
+/** Medium quality for texture filtering */
+Constants.TEXTURE_FILTERING_QUALITY_MEDIUM = 16;
+/** Low quality for texture filtering */
+Constants.TEXTURE_FILTERING_QUALITY_LOW = 8;
+// Texture rescaling mode
+/** Defines that texture rescaling will use a floor to find the closer power of 2 size */
+Constants.SCALEMODE_FLOOR = 1;
+/** Defines that texture rescaling will look for the nearest power of 2 size */
+Constants.SCALEMODE_NEAREST = 2;
+/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
+Constants.SCALEMODE_CEILING = 3;
+/**
+ * The dirty texture flag value
+ */
+Constants.MATERIAL_TextureDirtyFlag = 1;
+/**
+ * The dirty light flag value
+ */
+Constants.MATERIAL_LightDirtyFlag = 2;
+/**
+ * The dirty fresnel flag value
+ */
+Constants.MATERIAL_FresnelDirtyFlag = 4;
+/**
+ * The dirty attribute flag value
+ */
+Constants.MATERIAL_AttributesDirtyFlag = 8;
+/**
+ * The dirty misc flag value
+ */
+Constants.MATERIAL_MiscDirtyFlag = 16;
+/**
+ * The dirty prepass flag value
+ */
+Constants.MATERIAL_PrePassDirtyFlag = 32;
+/**
+ * The dirty image processing flag value
+ */
+Constants.MATERIAL_ImageProcessingDirtyFlag = 64;
+/**
+ * The all dirty flag value
+ */
+Constants.MATERIAL_AllDirtyFlag = 127;
+/**
+ * Returns the triangle fill mode
+ */
+Constants.MATERIAL_TriangleFillMode = 0;
+/**
+ * Returns the wireframe mode
+ */
+Constants.MATERIAL_WireFrameFillMode = 1;
+/**
+ * Returns the point fill mode
+ */
+Constants.MATERIAL_PointFillMode = 2;
+/**
+ * Returns the point list draw mode
+ */
+Constants.MATERIAL_PointListDrawMode = 3;
+/**
+ * Returns the line list draw mode
+ */
+Constants.MATERIAL_LineListDrawMode = 4;
+/**
+ * Returns the line loop draw mode
+ */
+Constants.MATERIAL_LineLoopDrawMode = 5;
+/**
+ * Returns the line strip draw mode
+ */
+Constants.MATERIAL_LineStripDrawMode = 6;
+/**
+ * Returns the triangle strip draw mode
+ */
+Constants.MATERIAL_TriangleStripDrawMode = 7;
+/**
+ * Returns the triangle fan draw mode
+ */
+Constants.MATERIAL_TriangleFanDrawMode = 8;
+/**
+ * Stores the clock-wise side orientation
+ */
+Constants.MATERIAL_ClockWiseSideOrientation = 0;
+/**
+ * Stores the counter clock-wise side orientation
+ */
+Constants.MATERIAL_CounterClockWiseSideOrientation = 1;
+/**
+ * Nothing
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_NothingTrigger = 0;
+/**
+ * On pick
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnPickTrigger = 1;
+/**
+ * On left pick
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnLeftPickTrigger = 2;
+/**
+ * On right pick
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnRightPickTrigger = 3;
+/**
+ * On center pick
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnCenterPickTrigger = 4;
+/**
+ * On pick down
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnPickDownTrigger = 5;
+/**
+ * On double pick
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnDoublePickTrigger = 6;
+/**
+ * On pick up
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnPickUpTrigger = 7;
+/**
+ * On pick out.
+ * This trigger will only be raised if you also declared a OnPickDown
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnPickOutTrigger = 16;
+/**
+ * On long press
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnLongPressTrigger = 8;
+/**
+ * On pointer over
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnPointerOverTrigger = 9;
+/**
+ * On pointer out
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnPointerOutTrigger = 10;
+/**
+ * On every frame
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnEveryFrameTrigger = 11;
+/**
+ * On intersection enter
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnIntersectionEnterTrigger = 12;
+/**
+ * On intersection exit
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnIntersectionExitTrigger = 13;
+/**
+ * On key down
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnKeyDownTrigger = 14;
+/**
+ * On key up
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers
+ */
+Constants.ACTION_OnKeyUpTrigger = 15;
+/**
+ * Billboard mode will only apply to Y axis
+ */
+Constants.PARTICLES_BILLBOARDMODE_Y = 2;
+/**
+ * Billboard mode will apply to all axes
+ */
+Constants.PARTICLES_BILLBOARDMODE_ALL = 7;
+/**
+ * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
+ */
+Constants.PARTICLES_BILLBOARDMODE_STRETCHED = 8;
+/**
+ * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission
+ */
+Constants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL = 9;
+/** Default culling strategy : this is an exclusion test and it's the more accurate.
+ * Test order :
+ * Is the bounding sphere outside the frustum ?
+ * If not, are the bounding box vertices outside the frustum ?
+ * It not, then the cullable object is in the frustum.
+ */
+Constants.MESHES_CULLINGSTRATEGY_STANDARD = 0;
+/** Culling strategy : Bounding Sphere Only.
+ * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested.
+ * It's also less accurate than the standard because some not visible objects can still be selected.
+ * Test : is the bounding sphere outside the frustum ?
+ * If not, then the cullable object is in the frustum.
+ */
+Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
+/** Culling strategy : Optimistic Inclusion.
+ * This in an inclusion test first, then the standard exclusion test.
+ * This can be faster when a cullable object is expected to be almost always in the camera frustum.
+ * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside.
+ * Anyway, it's as accurate as the standard strategy.
+ * Test :
+ * Is the cullable object bounding sphere center in the frustum ?
+ * If not, apply the default culling strategy.
+ */
+Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;
+/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only.
+ * This in an inclusion test first, then the bounding sphere only exclusion test.
+ * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum.
+ * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it.
+ * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy.
+ * Test :
+ * Is the cullable object bounding sphere center in the frustum ?
+ * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here.
+ */
+Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;
+/**
+ * No logging while loading
+ */
+Constants.SCENELOADER_NO_LOGGING = 0;
+/**
+ * Minimal logging while loading
+ */
+Constants.SCENELOADER_MINIMAL_LOGGING = 1;
+/**
+ * Summary logging while loading
+ */
+Constants.SCENELOADER_SUMMARY_LOGGING = 2;
+/**
+ * Detailed logging while loading
+ */
+Constants.SCENELOADER_DETAILED_LOGGING = 3;
+/**
+ * Constant used to retrieve the irradiance texture index in the textures array in the prepass
+ * using getIndex(Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE)
+ */
+Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0;
+/**
+ * Constant used to retrieve the position texture index in the textures array in the prepass
+ * using getIndex(Constants.PREPASS_POSITION_TEXTURE_INDEX)
+ */
+Constants.PREPASS_POSITION_TEXTURE_TYPE = 1;
+/**
+ * Constant used to retrieve the velocity texture index in the textures array in the prepass
+ * using getIndex(Constants.PREPASS_VELOCITY_TEXTURE_TYPE)
+ */
+Constants.PREPASS_VELOCITY_TEXTURE_TYPE = 2;
+/**
+ * Constant used to retrieve the reflectivity texture index in the textures array in the prepass
+ * using the getIndex(Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE)
+ */
+Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3;
+/**
+ * Constant used to retrieve the lit color texture index in the textures array in the prepass
+ * using the getIndex(Constants.PREPASS_COLOR_TEXTURE_TYPE)
+ */
+Constants.PREPASS_COLOR_TEXTURE_TYPE = 4;
+/**
+ * Constant used to retrieve depth index in the textures array in the prepass
+ * using the getIndex(Constants.PREPASS_DEPTH_TEXTURE_TYPE)
+ */
+Constants.PREPASS_DEPTH_TEXTURE_TYPE = 5;
+/**
+ * Constant used to retrieve normal index in the textures array in the prepass
+ * using the getIndex(Constants.PREPASS_NORMAL_TEXTURE_TYPE)
+ */
+Constants.PREPASS_NORMAL_TEXTURE_TYPE = 6;
+/**
+ * Constant used to retrieve (sqrt) albedo index in the textures array in the prepass
+ * using the getIndex(Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE)
+ */
+Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7;
+/**
+ * Constant used to retrieve world normal index in the textures array in the prepass
+ * using the getIndex(Constants.PREPASS_WORLD_NORMAL_TEXTURE_TYPE)
+ */
+Constants.PREPASS_WORLD_NORMAL_TEXTURE_TYPE = 8;
+/**
+ * Constant used to retrieve the local position texture index in the textures array in the prepass
+ * using getIndex(Constants.PREPASS_LOCAL_POSITION_TEXTURE_TYPE)
+ */
+Constants.PREPASS_LOCAL_POSITION_TEXTURE_TYPE = 9;
+/**
+ * Constant used to retrieve screen-space (non-linear) depth index in the textures array in the prepass
+ * using the getIndex(Constants.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE)
+ */
+Constants.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE = 10;
+/**
+ * Constant used to retrieve the velocity texture index in the textures array in the prepass
+ * using getIndex(Constants.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE)
+ */
+Constants.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE = 11;
+/**
+ * Constant used to retrieve albedo index in the textures array in the prepass
+ * using the getIndex(Constants.PREPASS_ALBEDO_TEXTURE_TYPE)
+ */
+Constants.PREPASS_ALBEDO_TEXTURE_TYPE = 12;
+/** Flag to create a readable buffer (the buffer can be the source of a copy) */
+Constants.BUFFER_CREATIONFLAG_READ = 1;
+/** Flag to create a writable buffer (the buffer can be the destination of a copy) */
+Constants.BUFFER_CREATIONFLAG_WRITE = 2;
+/** Flag to create a readable and writable buffer */
+Constants.BUFFER_CREATIONFLAG_READWRITE = 3;
+/** Flag to create a buffer suitable to be used as a uniform buffer */
+Constants.BUFFER_CREATIONFLAG_UNIFORM = 4;
+/** Flag to create a buffer suitable to be used as a vertex buffer */
+Constants.BUFFER_CREATIONFLAG_VERTEX = 8;
+/** Flag to create a buffer suitable to be used as an index buffer */
+Constants.BUFFER_CREATIONFLAG_INDEX = 16;
+/** Flag to create a buffer suitable to be used as a storage buffer */
+Constants.BUFFER_CREATIONFLAG_STORAGE = 32;
+/** Flag to create a buffer suitable to be used for indirect calls, such as `dispatchIndirect` */
+Constants.BUFFER_CREATIONFLAG_INDIRECT = 64;
+/**
+ * Prefixes used by the engine for sub mesh draw wrappers
+ */
+/** @internal */
+Constants.RENDERPASS_MAIN = 0;
+/**
+ * Constant used as key code for Alt key
+ */
+Constants.INPUT_ALT_KEY = 18;
+/**
+ * Constant used as key code for Ctrl key
+ */
+Constants.INPUT_CTRL_KEY = 17;
+/**
+ * Constant used as key code for Meta key (Left Win, Left Cmd)
+ */
+Constants.INPUT_META_KEY1 = 91;
+/**
+ * Constant used as key code for Meta key (Right Win)
+ */
+Constants.INPUT_META_KEY2 = 92;
+/**
+ * Constant used as key code for Meta key (Right Win, Right Cmd)
+ */
+Constants.INPUT_META_KEY3 = 93;
+/**
+ * Constant used as key code for Shift key
+ */
+Constants.INPUT_SHIFT_KEY = 16;
+/** Standard snapshot rendering. In this mode, some form of dynamic behavior is possible (for eg, uniform buffers are still updated) */
+Constants.SNAPSHOTRENDERING_STANDARD = 0;
+/** Fast snapshot rendering. In this mode, everything is static and only some limited form of dynamic behaviour is possible */
+Constants.SNAPSHOTRENDERING_FAST = 1;
+/**
+ * This is the default projection mode used by the cameras.
+ * It helps recreating a feeling of perspective and better appreciate depth.
+ * This is the best way to simulate real life cameras.
+ */
+Constants.PERSPECTIVE_CAMERA = 0;
+/**
+ * This helps creating camera with an orthographic mode.
+ * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
+ */
+Constants.ORTHOGRAPHIC_CAMERA = 1;
+/**
+ * This is the default FOV mode for perspective cameras.
+ * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
+ */
+Constants.FOVMODE_VERTICAL_FIXED = 0;
+/**
+ * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
+ */
+Constants.FOVMODE_HORIZONTAL_FIXED = 1;
+/**
+ * This specifies there is no need for a camera rig.
+ * Basically only one eye is rendered corresponding to the camera.
+ */
+Constants.RIG_MODE_NONE = 0;
+/**
+ * Simulates a camera Rig with one blue eye and one red eye.
+ * This can be use with 3d blue and red glasses.
+ */
+Constants.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
+/**
+ * Defines that both eyes of the camera will be rendered side by side with a parallel target.
+ */
+Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
+/**
+ * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
+ */
+Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
+/**
+ * Defines that both eyes of the camera will be rendered over under each other.
+ */
+Constants.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
+/**
+ * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors.
+ */
+Constants.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;
+/**
+ * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
+ */
+Constants.RIG_MODE_VR = 20;
+/**
+ * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
+ */
+Constants.RIG_MODE_CUSTOM = 22;
+/**
+ * Maximum number of uv sets supported
+ */
+Constants.MAX_SUPPORTED_UV_SETS = 6;
+/**
+ * GL constants
+ */
+/** Alpha blend equation: ADD */
+Constants.GL_ALPHA_EQUATION_ADD = 0x8006;
+/** Alpha equation: MIN */
+Constants.GL_ALPHA_EQUATION_MIN = 0x8007;
+/** Alpha equation: MAX */
+Constants.GL_ALPHA_EQUATION_MAX = 0x8008;
+/** Alpha equation: SUBTRACT */
+Constants.GL_ALPHA_EQUATION_SUBTRACT = 0x800a;
+/** Alpha equation: REVERSE_SUBTRACT */
+Constants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 0x800b;
+/** Alpha blend function: SRC */
+Constants.GL_ALPHA_FUNCTION_SRC = 0x0300;
+/** Alpha blend function: ONE_MINUS_SRC */
+Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 0x0301;
+/** Alpha blend function: SRC_ALPHA */
+Constants.GL_ALPHA_FUNCTION_SRC_ALPHA = 0x0302;
+/** Alpha blend function: ONE_MINUS_SRC_ALPHA */
+Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 0x0303;
+/** Alpha blend function: DST_ALPHA */
+Constants.GL_ALPHA_FUNCTION_DST_ALPHA = 0x0304;
+/** Alpha blend function: ONE_MINUS_DST_ALPHA */
+Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 0x0305;
+/** Alpha blend function: ONE_MINUS_DST */
+Constants.GL_ALPHA_FUNCTION_DST_COLOR = 0x0306;
+/** Alpha blend function: ONE_MINUS_DST */
+Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 0x0307;
+/** Alpha blend function: SRC_ALPHA_SATURATED */
+Constants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 0x0308;
+/** Alpha blend function: CONSTANT */
+Constants.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 0x8001;
+/** Alpha blend function: ONE_MINUS_CONSTANT */
+Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 0x8002;
+/** Alpha blend function: CONSTANT_ALPHA */
+Constants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 0x8003;
+/** Alpha blend function: ONE_MINUS_CONSTANT_ALPHA */
+Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 0x8004;
+/** Alpha blend function: SRC1 */
+Constants.GL_ALPHA_FUNCTION_SRC1_COLOR = 0x88f9;
+/** Alpha blend function: SRC1 */
+Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR = 0x88fa;
+/** Alpha blend function: SRC1 */
+Constants.GL_ALPHA_FUNCTION_SRC1_ALPHA = 0x8589;
+/** Alpha blend function: SRC1 */
+Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA = 0x88fb;
+/** URL to the snippet server. Points to the public snippet server by default */
+Constants.SnippetUrl = "https://snippet.babylonjs.com";
+/** The fog is deactivated */
+Constants.FOGMODE_NONE = 0;
+/** The fog density is following an exponential function */
+Constants.FOGMODE_EXP = 1;
+/** The fog density is following an exponential function faster than FOGMODE_EXP */
+Constants.FOGMODE_EXP2 = 2;
+/** The fog density is following a linear function. */
+Constants.FOGMODE_LINEAR = 3;
+/**
+ * The byte type.
+ */
+Constants.BYTE = 5120;
+/**
+ * The unsigned byte type.
+ */
+Constants.UNSIGNED_BYTE = 5121;
+/**
+ * The short type.
+ */
+Constants.SHORT = 5122;
+/**
+ * The unsigned short type.
+ */
+Constants.UNSIGNED_SHORT = 5123;
+/**
+ * The integer type.
+ */
+Constants.INT = 5124;
+/**
+ * The unsigned integer type.
+ */
+Constants.UNSIGNED_INT = 5125;
+/**
+ * The float type.
+ */
+Constants.FLOAT = 5126;
+/**
+ * Positions
+ */
+Constants.PositionKind = "position";
+/**
+ * Normals
+ */
+Constants.NormalKind = "normal";
+/**
+ * Tangents
+ */
+Constants.TangentKind = "tangent";
+/**
+ * Texture coordinates
+ */
+Constants.UVKind = "uv";
+/**
+ * Texture coordinates 2
+ */
+Constants.UV2Kind = "uv2";
+/**
+ * Texture coordinates 3
+ */
+Constants.UV3Kind = "uv3";
+/**
+ * Texture coordinates 4
+ */
+Constants.UV4Kind = "uv4";
+/**
+ * Texture coordinates 5
+ */
+Constants.UV5Kind = "uv5";
+/**
+ * Texture coordinates 6
+ */
+Constants.UV6Kind = "uv6";
+/**
+ * Colors
+ */
+Constants.ColorKind = "color";
+/**
+ * Instance Colors
+ */
+Constants.ColorInstanceKind = "instanceColor";
+/**
+ * Matrix indices (for bones)
+ */
+Constants.MatricesIndicesKind = "matricesIndices";
+/**
+ * Matrix weights (for bones)
+ */
+Constants.MatricesWeightsKind = "matricesWeights";
+/**
+ * Additional matrix indices (for bones)
+ */
+Constants.MatricesIndicesExtraKind = "matricesIndicesExtra";
+/**
+ * Additional matrix weights (for bones)
+ */
+Constants.MatricesWeightsExtraKind = "matricesWeightsExtra";
+// Animation type
+/**
+ * Float animation type
+ */
+Constants.ANIMATIONTYPE_FLOAT = 0;
+/**
+ * Vector3 animation type
+ */
+Constants.ANIMATIONTYPE_VECTOR3 = 1;
+/**
+ * Quaternion animation type
+ */
+Constants.ANIMATIONTYPE_QUATERNION = 2;
+/**
+ * Matrix animation type
+ */
+Constants.ANIMATIONTYPE_MATRIX = 3;
+/**
+ * Color3 animation type
+ */
+Constants.ANIMATIONTYPE_COLOR3 = 4;
+/**
+ * Color3 animation type
+ */
+Constants.ANIMATIONTYPE_COLOR4 = 7;
+/**
+ * Vector2 animation type
+ */
+Constants.ANIMATIONTYPE_VECTOR2 = 5;
+/**
+ * Size animation type
+ */
+Constants.ANIMATIONTYPE_SIZE = 6;
+/**
+ * The default minZ value for the near plane of a frustum light
+ */
+Constants.ShadowMinZ = 0;
+/**
+ * The default maxZ value for the far plane of a frustum light
+ */
+Constants.ShadowMaxZ = 10000;
+
+/**
+ * Tokenizer. Used for shaders compatibility
+ * Automatically map world, view, projection, worldViewProjection, attributes and so on
+ */
+var ETokenType;
+(function (ETokenType) {
+ ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
+ ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
+ ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
+})(ETokenType || (ETokenType = {}));
+class Tokenizer {
+ constructor(toParse) {
+ this._pos = 0;
+ this.currentToken = ETokenType.UNKNOWN;
+ this.currentIdentifier = "";
+ this.currentString = "";
+ this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
+ this._toParse = toParse;
+ this._maxPos = toParse.length;
+ }
+ getNextToken() {
+ if (this.isEnd()) {
+ return ETokenType.END_OF_INPUT;
+ }
+ this.currentString = this.read();
+ this.currentToken = ETokenType.UNKNOWN;
+ if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
+ this.currentToken = ETokenType.IDENTIFIER;
+ this.currentIdentifier = this.currentString;
+ while (!this.isEnd() && (this.isLetterOrDigitPattern.test((this.currentString = this.peek())) || this.currentString === "_")) {
+ this.currentIdentifier += this.currentString;
+ this.forward();
+ }
+ }
+ return this.currentToken;
+ }
+ peek() {
+ return this._toParse[this._pos];
+ }
+ read() {
+ return this._toParse[this._pos++];
+ }
+ forward() {
+ this._pos++;
+ }
+ isEnd() {
+ return this._pos >= this._maxPos;
+ }
+}
+/**
+ * Values
+ */
+const glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
+const babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
+const glTFAnimationPaths = ["translation", "rotation", "scale"];
+const babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
+/**
+ * Parse
+ * @param parsedBuffers
+ * @param gltfRuntime
+ */
+const parseBuffers = (parsedBuffers, gltfRuntime) => {
+ for (const buf in parsedBuffers) {
+ const parsedBuffer = parsedBuffers[buf];
+ gltfRuntime.buffers[buf] = parsedBuffer;
+ gltfRuntime.buffersCount++;
+ }
+};
+const parseShaders = (parsedShaders, gltfRuntime) => {
+ for (const sha in parsedShaders) {
+ const parsedShader = parsedShaders[sha];
+ gltfRuntime.shaders[sha] = parsedShader;
+ gltfRuntime.shaderscount++;
+ }
+};
+const parseObject = (parsedObjects, runtimeProperty, gltfRuntime) => {
+ for (const object in parsedObjects) {
+ const parsedObject = parsedObjects[object];
+ gltfRuntime[runtimeProperty][object] = parsedObject;
+ }
+};
+/**
+ * Utils
+ * @param buffer
+ */
+const normalizeUVs = (buffer) => {
+ if (!buffer) {
+ return;
+ }
+ for (let i = 0; i < buffer.length / 2; i++) {
+ buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
+ }
+};
+const getAttribute = (attributeParameter) => {
+ if (attributeParameter.semantic === "NORMAL") {
+ return "normal";
+ }
+ else if (attributeParameter.semantic === "POSITION") {
+ return "position";
+ }
+ else if (attributeParameter.semantic === "JOINT") {
+ return "matricesIndices";
+ }
+ else if (attributeParameter.semantic === "WEIGHT") {
+ return "matricesWeights";
+ }
+ else if (attributeParameter.semantic === "COLOR") {
+ return "color";
+ }
+ else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
+ const channel = Number(attributeParameter.semantic.split("_")[1]);
+ return "uv" + (channel === 0 ? "" : channel + 1);
+ }
+ return null;
+};
+/**
+ * Loads and creates animations
+ * @param gltfRuntime
+ */
+const loadAnimations = (gltfRuntime) => {
+ for (const anim in gltfRuntime.animations) {
+ const animation = gltfRuntime.animations[anim];
+ if (!animation.channels || !animation.samplers) {
+ continue;
+ }
+ let lastAnimation = null;
+ for (let i = 0; i < animation.channels.length; i++) {
+ // Get parameters and load buffers
+ const channel = animation.channels[i];
+ const sampler = animation.samplers[channel.sampler];
+ if (!sampler) {
+ continue;
+ }
+ let inputData = null;
+ let outputData = null;
+ if (animation.parameters) {
+ inputData = animation.parameters[sampler.input];
+ outputData = animation.parameters[sampler.output];
+ }
+ else {
+ inputData = sampler.input;
+ outputData = sampler.output;
+ }
+ const bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
+ const bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
+ const targetId = channel.target.id;
+ let targetNode = gltfRuntime.scene.getNodeById(targetId);
+ if (targetNode === null) {
+ targetNode = gltfRuntime.scene.getNodeByName(targetId);
+ }
+ if (targetNode === null) {
+ Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetId + " to attach to");
+ continue;
+ }
+ const isBone = targetNode instanceof Bone;
+ // Get target path (position, rotation or scaling)
+ let targetPath = channel.target.path;
+ const targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
+ if (targetPathIndex !== -1) {
+ targetPath = babylonAnimationPaths[targetPathIndex];
+ }
+ // Determine animation type
+ let animationType = Animation.ANIMATIONTYPE_MATRIX;
+ if (!isBone) {
+ if (targetPath === "rotationQuaternion") {
+ animationType = Animation.ANIMATIONTYPE_QUATERNION;
+ targetNode.rotationQuaternion = new Quaternion();
+ }
+ else {
+ animationType = Animation.ANIMATIONTYPE_VECTOR3;
+ }
+ }
+ // Create animation and key frames
+ let babylonAnimation = null;
+ const keys = [];
+ let arrayOffset = 0;
+ let modifyKey = false;
+ if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
+ babylonAnimation = lastAnimation;
+ modifyKey = true;
+ }
+ if (!modifyKey) {
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
+ babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
+ gltfRuntime.scene._blockEntityCollection = false;
+ }
+ // For each frame
+ for (let j = 0; j < bufferInput.length; j++) {
+ let value = null;
+ if (targetPath === "rotationQuaternion") {
+ // VEC4
+ value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
+ arrayOffset += 4;
+ }
+ else {
+ // Position and scaling are VEC3
+ value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
+ arrayOffset += 3;
+ }
+ if (isBone) {
+ const bone = targetNode;
+ let translation = Vector3.Zero();
+ let rotationQuaternion = new Quaternion();
+ let scaling = Vector3.Zero();
+ // Warning on decompose
+ let mat = bone.getBaseMatrix();
+ if (modifyKey && lastAnimation) {
+ mat = lastAnimation.getKeys()[j].value;
+ }
+ mat.decompose(scaling, rotationQuaternion, translation);
+ if (targetPath === "position") {
+ translation = value;
+ }
+ else if (targetPath === "rotationQuaternion") {
+ rotationQuaternion = value;
+ }
+ else {
+ scaling = value;
+ }
+ value = Matrix.Compose(scaling, rotationQuaternion, translation);
+ }
+ if (!modifyKey) {
+ keys.push({
+ frame: bufferInput[j],
+ value: value,
+ });
+ }
+ else if (lastAnimation) {
+ lastAnimation.getKeys()[j].value = value;
+ }
+ }
+ // Finish
+ if (!modifyKey && babylonAnimation) {
+ babylonAnimation.setKeys(keys);
+ targetNode.animations.push(babylonAnimation);
+ }
+ lastAnimation = babylonAnimation;
+ gltfRuntime.scene.stopAnimation(targetNode);
+ gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
+ }
+ }
+};
+/**
+ * @returns the bones transformation matrix
+ * @param node
+ */
+const configureBoneTransformation = (node) => {
+ let mat = null;
+ if (node.translation || node.rotation || node.scale) {
+ const scale = Vector3.FromArray(node.scale || [1, 1, 1]);
+ const rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
+ const position = Vector3.FromArray(node.translation || [0, 0, 0]);
+ mat = Matrix.Compose(scale, rotation, position);
+ }
+ else {
+ mat = Matrix.FromArray(node.matrix);
+ }
+ return mat;
+};
+/**
+ * Returns the parent bone
+ * @param gltfRuntime
+ * @param skins
+ * @param jointName
+ * @param newSkeleton
+ * @returns the parent bone
+ */
+const getParentBone = (gltfRuntime, skins, jointName, newSkeleton) => {
+ // Try to find
+ for (let i = 0; i < newSkeleton.bones.length; i++) {
+ if (newSkeleton.bones[i].name === jointName) {
+ return newSkeleton.bones[i];
+ }
+ }
+ // Not found, search in gltf nodes
+ const nodes = gltfRuntime.nodes;
+ for (const nde in nodes) {
+ const node = nodes[nde];
+ if (!node.jointName) {
+ continue;
+ }
+ const children = node.children;
+ for (let i = 0; i < children.length; i++) {
+ const child = gltfRuntime.nodes[children[i]];
+ if (!child.jointName) {
+ continue;
+ }
+ if (child.jointName === jointName) {
+ const mat = configureBoneTransformation(node);
+ const bone = new Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
+ bone.id = nde;
+ return bone;
+ }
+ }
+ }
+ return null;
+};
+/**
+ * Returns the appropriate root node
+ * @param nodesToRoot
+ * @param id
+ * @returns the root node
+ */
+const getNodeToRoot = (nodesToRoot, id) => {
+ for (let i = 0; i < nodesToRoot.length; i++) {
+ const nodeToRoot = nodesToRoot[i];
+ for (let j = 0; j < nodeToRoot.node.children.length; j++) {
+ const child = nodeToRoot.node.children[j];
+ if (child === id) {
+ return nodeToRoot.bone;
+ }
+ }
+ }
+ return null;
+};
+/**
+ * Returns the node with the joint name
+ * @param gltfRuntime
+ * @param jointName
+ * @returns the node with the joint name
+ */
+const getJointNode = (gltfRuntime, jointName) => {
+ const nodes = gltfRuntime.nodes;
+ let node = nodes[jointName];
+ if (node) {
+ return {
+ node: node,
+ id: jointName,
+ };
+ }
+ for (const nde in nodes) {
+ node = nodes[nde];
+ if (node.jointName === jointName) {
+ return {
+ node: node,
+ id: nde,
+ };
+ }
+ }
+ return null;
+};
+/**
+ * Checks if a nodes is in joints
+ * @param skins
+ * @param id
+ * @returns true if the node is in joints, else false
+ */
+const nodeIsInJoints = (skins, id) => {
+ for (let i = 0; i < skins.jointNames.length; i++) {
+ if (skins.jointNames[i] === id) {
+ return true;
+ }
+ }
+ return false;
+};
+/**
+ * Fills the nodes to root for bones and builds hierarchy
+ * @param gltfRuntime
+ * @param newSkeleton
+ * @param skins
+ * @param nodesToRoot
+ */
+const getNodesToRoot = (gltfRuntime, newSkeleton, skins, nodesToRoot) => {
+ // Creates nodes for root
+ for (const nde in gltfRuntime.nodes) {
+ const node = gltfRuntime.nodes[nde];
+ const id = nde;
+ if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
+ continue;
+ }
+ // Create node to root bone
+ const mat = configureBoneTransformation(node);
+ const bone = new Bone(node.name || "", newSkeleton, null, mat);
+ bone.id = id;
+ nodesToRoot.push({ bone: bone, node: node, id: id });
+ }
+ // Parenting
+ for (let i = 0; i < nodesToRoot.length; i++) {
+ const nodeToRoot = nodesToRoot[i];
+ const children = nodeToRoot.node.children;
+ for (let j = 0; j < children.length; j++) {
+ let child = null;
+ for (let k = 0; k < nodesToRoot.length; k++) {
+ if (nodesToRoot[k].id === children[j]) {
+ child = nodesToRoot[k];
+ break;
+ }
+ }
+ if (child) {
+ child.bone._parent = nodeToRoot.bone;
+ nodeToRoot.bone.children.push(child.bone);
+ }
+ }
+ }
+};
+/**
+ * Imports a skeleton
+ * @param gltfRuntime
+ * @param skins
+ * @param mesh
+ * @param newSkeleton
+ * @returns the bone name
+ */
+const importSkeleton = (gltfRuntime, skins, mesh, newSkeleton) => {
+ if (!newSkeleton) {
+ newSkeleton = new Skeleton(skins.name || "", "", gltfRuntime.scene);
+ }
+ if (!skins.babylonSkeleton) {
+ return newSkeleton;
+ }
+ // Find the root bones
+ const nodesToRoot = [];
+ const nodesToRootToAdd = [];
+ getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
+ newSkeleton.bones = [];
+ // Joints
+ for (let i = 0; i < skins.jointNames.length; i++) {
+ const jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
+ if (!jointNode) {
+ continue;
+ }
+ const node = jointNode.node;
+ if (!node) {
+ Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
+ continue;
+ }
+ const id = jointNode.id;
+ // Optimize, if the bone already exists...
+ const existingBone = gltfRuntime.scene.getBoneById(id);
+ if (existingBone) {
+ newSkeleton.bones.push(existingBone);
+ continue;
+ }
+ // Search for parent bone
+ let foundBone = false;
+ let parentBone = null;
+ for (let j = 0; j < i; j++) {
+ const jointNode = getJointNode(gltfRuntime, skins.jointNames[j]);
+ if (!jointNode) {
+ continue;
+ }
+ const joint = jointNode.node;
+ if (!joint) {
+ Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
+ continue;
+ }
+ const children = joint.children;
+ if (!children) {
+ continue;
+ }
+ foundBone = false;
+ for (let k = 0; k < children.length; k++) {
+ if (children[k] === id) {
+ parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
+ foundBone = true;
+ break;
+ }
+ }
+ if (foundBone) {
+ break;
+ }
+ }
+ // Create bone
+ const mat = configureBoneTransformation(node);
+ if (!parentBone && nodesToRoot.length > 0) {
+ parentBone = getNodeToRoot(nodesToRoot, id);
+ if (parentBone) {
+ if (nodesToRootToAdd.indexOf(parentBone) === -1) {
+ nodesToRootToAdd.push(parentBone);
+ }
+ }
+ }
+ const bone = new Bone(node.jointName || "", newSkeleton, parentBone, mat);
+ bone.id = id;
+ }
+ // Polish
+ const bones = newSkeleton.bones;
+ newSkeleton.bones = [];
+ for (let i = 0; i < skins.jointNames.length; i++) {
+ const jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
+ if (!jointNode) {
+ continue;
+ }
+ for (let j = 0; j < bones.length; j++) {
+ if (bones[j].id === jointNode.id) {
+ newSkeleton.bones.push(bones[j]);
+ break;
+ }
+ }
+ }
+ newSkeleton.prepare();
+ // Finish
+ for (let i = 0; i < nodesToRootToAdd.length; i++) {
+ newSkeleton.bones.push(nodesToRootToAdd[i]);
+ }
+ return newSkeleton;
+};
+/**
+ * Imports a mesh and its geometries
+ * @param gltfRuntime
+ * @param node
+ * @param meshes
+ * @param id
+ * @param newMesh
+ * @returns the new mesh
+ */
+const importMesh = (gltfRuntime, node, meshes, id, newMesh) => {
+ if (!newMesh) {
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
+ newMesh = new Mesh(node.name || "", gltfRuntime.scene);
+ newMesh._parentContainer = gltfRuntime.assetContainer;
+ gltfRuntime.scene._blockEntityCollection = false;
+ newMesh.id = id;
+ }
+ if (!node.babylonNode) {
+ return newMesh;
+ }
+ const subMaterials = [];
+ let vertexData = null;
+ const verticesStarts = [];
+ const verticesCounts = [];
+ const indexStarts = [];
+ const indexCounts = [];
+ for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
+ const meshId = meshes[meshIndex];
+ const mesh = gltfRuntime.meshes[meshId];
+ if (!mesh) {
+ continue;
+ }
+ // Positions, normals and UVs
+ for (let i = 0; i < mesh.primitives.length; i++) {
+ // Temporary vertex data
+ const tempVertexData = new VertexData();
+ const primitive = mesh.primitives[i];
+ if (primitive.mode !== 4) ;
+ const attributes = primitive.attributes;
+ let accessor = null;
+ let buffer = null;
+ // Set positions, normal and uvs
+ for (const semantic in attributes) {
+ // Link accessor and buffer view
+ accessor = gltfRuntime.accessors[attributes[semantic]];
+ buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
+ if (semantic === "NORMAL") {
+ tempVertexData.normals = new Float32Array(buffer.length);
+ tempVertexData.normals.set(buffer);
+ }
+ else if (semantic === "POSITION") {
+ if (GLTFFileLoader.HomogeneousCoordinates) {
+ tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
+ for (let j = 0; j < buffer.length; j += 4) {
+ tempVertexData.positions[j] = buffer[j];
+ tempVertexData.positions[j + 1] = buffer[j + 1];
+ tempVertexData.positions[j + 2] = buffer[j + 2];
+ }
+ }
+ else {
+ tempVertexData.positions = new Float32Array(buffer.length);
+ tempVertexData.positions.set(buffer);
+ }
+ verticesCounts.push(tempVertexData.positions.length);
+ }
+ else if (semantic.indexOf("TEXCOORD_") !== -1) {
+ const channel = Number(semantic.split("_")[1]);
+ const uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : channel + 1);
+ const uvs = new Float32Array(buffer.length);
+ uvs.set(buffer);
+ normalizeUVs(uvs);
+ tempVertexData.set(uvs, uvKind);
+ }
+ else if (semantic === "JOINT") {
+ tempVertexData.matricesIndices = new Float32Array(buffer.length);
+ tempVertexData.matricesIndices.set(buffer);
+ }
+ else if (semantic === "WEIGHT") {
+ tempVertexData.matricesWeights = new Float32Array(buffer.length);
+ tempVertexData.matricesWeights.set(buffer);
+ }
+ else if (semantic === "COLOR") {
+ tempVertexData.colors = new Float32Array(buffer.length);
+ tempVertexData.colors.set(buffer);
+ }
+ }
+ // Indices
+ accessor = gltfRuntime.accessors[primitive.indices];
+ if (accessor) {
+ buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
+ tempVertexData.indices = new Int32Array(buffer.length);
+ tempVertexData.indices.set(buffer);
+ indexCounts.push(tempVertexData.indices.length);
+ }
+ else {
+ // Set indices on the fly
+ const indices = [];
+ for (let j = 0; j < tempVertexData.positions.length / 3; j++) {
+ indices.push(j);
+ }
+ tempVertexData.indices = new Int32Array(indices);
+ indexCounts.push(tempVertexData.indices.length);
+ }
+ if (!vertexData) {
+ vertexData = tempVertexData;
+ }
+ else {
+ vertexData.merge(tempVertexData);
+ }
+ // Sub material
+ const material = gltfRuntime.scene.getMaterialById(primitive.material);
+ subMaterials.push(material === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
+ // Update vertices start and index start
+ verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
+ indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
+ }
+ }
+ let material;
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
+ if (subMaterials.length > 1) {
+ material = new MultiMaterial("multimat" + id, gltfRuntime.scene);
+ material.subMaterials = subMaterials;
+ }
+ else {
+ material = new StandardMaterial("multimat" + id, gltfRuntime.scene);
+ }
+ if (subMaterials.length === 1) {
+ material = subMaterials[0];
+ }
+ material._parentContainer = gltfRuntime.assetContainer;
+ if (!newMesh.material) {
+ newMesh.material = material;
+ }
+ // Apply geometry
+ new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
+ newMesh.computeWorldMatrix(true);
+ gltfRuntime.scene._blockEntityCollection = false;
+ // Apply submeshes
+ newMesh.subMeshes = [];
+ let index = 0;
+ for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
+ const meshId = meshes[meshIndex];
+ const mesh = gltfRuntime.meshes[meshId];
+ if (!mesh) {
+ continue;
+ }
+ for (let i = 0; i < mesh.primitives.length; i++) {
+ if (mesh.primitives[i].mode !== 4) ;
+ SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
+ index++;
+ }
+ }
+ // Finish
+ return newMesh;
+};
+/**
+ * Configure node transformation from position, rotation and scaling
+ * @param newNode
+ * @param position
+ * @param rotation
+ * @param scaling
+ */
+const configureNode = (newNode, position, rotation, scaling) => {
+ if (newNode.position) {
+ newNode.position = position;
+ }
+ if (newNode.rotationQuaternion || newNode.rotation) {
+ newNode.rotationQuaternion = rotation;
+ }
+ if (newNode.scaling) {
+ newNode.scaling = scaling;
+ }
+};
+/**
+ * Configures node from transformation matrix
+ * @param newNode
+ * @param node
+ */
+const configureNodeFromMatrix = (newNode, node) => {
+ if (node.matrix) {
+ const position = new Vector3(0, 0, 0);
+ const rotation = new Quaternion();
+ const scaling = new Vector3(0, 0, 0);
+ const mat = Matrix.FromArray(node.matrix);
+ mat.decompose(scaling, rotation, position);
+ configureNode(newNode, position, rotation, scaling);
+ }
+ else if (node.translation && node.rotation && node.scale) {
+ configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
+ }
+ newNode.computeWorldMatrix(true);
+};
+/**
+ * Imports a node
+ * @param gltfRuntime
+ * @param node
+ * @param id
+ * @returns the newly imported node
+ */
+const importNode = (gltfRuntime, node, id) => {
+ let lastNode = null;
+ if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
+ if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
+ return null;
+ }
+ }
+ // Meshes
+ if (node.skin) {
+ if (node.meshes) {
+ const skin = gltfRuntime.skins[node.skin];
+ const newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
+ newMesh.skeleton = gltfRuntime.scene.getLastSkeletonById(node.skin);
+ if (newMesh.skeleton === null) {
+ newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton);
+ if (!skin.babylonSkeleton) {
+ skin.babylonSkeleton = newMesh.skeleton;
+ }
+ }
+ lastNode = newMesh;
+ }
+ }
+ else if (node.meshes) {
+ /**
+ * Improve meshes property
+ */
+ const newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
+ lastNode = newMesh;
+ }
+ // Lights
+ else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
+ const light = gltfRuntime.lights[node.light];
+ if (light) {
+ if (light.type === "ambient") {
+ const ambienLight = light[light.type];
+ const hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
+ hemiLight.name = node.name || "";
+ if (ambienLight.color) {
+ hemiLight.diffuse = Color3.FromArray(ambienLight.color);
+ }
+ lastNode = hemiLight;
+ }
+ else if (light.type === "directional") {
+ const directionalLight = light[light.type];
+ const dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
+ dirLight.name = node.name || "";
+ if (directionalLight.color) {
+ dirLight.diffuse = Color3.FromArray(directionalLight.color);
+ }
+ lastNode = dirLight;
+ }
+ else if (light.type === "point") {
+ const pointLight = light[light.type];
+ const ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
+ ptLight.name = node.name || "";
+ if (pointLight.color) {
+ ptLight.diffuse = Color3.FromArray(pointLight.color);
+ }
+ lastNode = ptLight;
+ }
+ else if (light.type === "spot") {
+ const spotLight = light[light.type];
+ const spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
+ spLight.name = node.name || "";
+ if (spotLight.color) {
+ spLight.diffuse = Color3.FromArray(spotLight.color);
+ }
+ if (spotLight.fallOfAngle) {
+ spLight.angle = spotLight.fallOfAngle;
+ }
+ if (spotLight.fallOffExponent) {
+ spLight.exponent = spotLight.fallOffExponent;
+ }
+ lastNode = spLight;
+ }
+ }
+ }
+ // Cameras
+ else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
+ const camera = gltfRuntime.cameras[node.camera];
+ if (camera) {
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
+ if (camera.type === "orthographic") {
+ const orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
+ orthoCamera.name = node.name || "";
+ orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
+ orthoCamera.attachControl();
+ lastNode = orthoCamera;
+ orthoCamera._parentContainer = gltfRuntime.assetContainer;
+ }
+ else if (camera.type === "perspective") {
+ const perspectiveCamera = camera[camera.type];
+ const persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
+ persCamera.name = node.name || "";
+ persCamera.attachControl();
+ if (!perspectiveCamera.aspectRatio) {
+ perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
+ }
+ if (perspectiveCamera.znear && perspectiveCamera.zfar) {
+ persCamera.maxZ = perspectiveCamera.zfar;
+ persCamera.minZ = perspectiveCamera.znear;
+ }
+ lastNode = persCamera;
+ persCamera._parentContainer = gltfRuntime.assetContainer;
+ }
+ gltfRuntime.scene._blockEntityCollection = false;
+ }
+ }
+ // Empty node
+ if (!node.jointName) {
+ if (node.babylonNode) {
+ return node.babylonNode;
+ }
+ else if (lastNode === null) {
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
+ const dummy = new Mesh(node.name || "", gltfRuntime.scene);
+ dummy._parentContainer = gltfRuntime.assetContainer;
+ gltfRuntime.scene._blockEntityCollection = false;
+ node.babylonNode = dummy;
+ lastNode = dummy;
+ }
+ }
+ if (lastNode !== null) {
+ if (node.matrix && lastNode instanceof Mesh) {
+ configureNodeFromMatrix(lastNode, node);
+ }
+ else {
+ const translation = node.translation || [0, 0, 0];
+ const rotation = node.rotation || [0, 0, 0, 1];
+ const scale = node.scale || [1, 1, 1];
+ configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));
+ }
+ lastNode.updateCache(true);
+ node.babylonNode = lastNode;
+ }
+ return lastNode;
+};
+/**
+ * Traverses nodes and creates them
+ * @param gltfRuntime
+ * @param id
+ * @param parent
+ * @param meshIncluded
+ */
+const traverseNodes = (gltfRuntime, id, parent, meshIncluded = false) => {
+ const node = gltfRuntime.nodes[id];
+ let newNode = null;
+ if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
+ if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
+ meshIncluded = true;
+ }
+ else {
+ meshIncluded = false;
+ }
+ }
+ else {
+ meshIncluded = true;
+ }
+ if (!node.jointName && meshIncluded) {
+ newNode = importNode(gltfRuntime, node, id);
+ if (newNode !== null) {
+ newNode.id = id;
+ newNode.parent = parent;
+ }
+ }
+ if (node.children) {
+ for (let i = 0; i < node.children.length; i++) {
+ traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
+ }
+ }
+};
+/**
+ * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
+ * @param gltfRuntime
+ */
+const postLoad = (gltfRuntime) => {
+ // Nodes
+ let currentScene = gltfRuntime.currentScene;
+ if (currentScene) {
+ for (let i = 0; i < currentScene.nodes.length; i++) {
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
+ }
+ }
+ else {
+ for (const thing in gltfRuntime.scenes) {
+ currentScene = gltfRuntime.scenes[thing];
+ for (let i = 0; i < currentScene.nodes.length; i++) {
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
+ }
+ }
+ }
+ // Set animations
+ loadAnimations(gltfRuntime);
+ for (let i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
+ const skeleton = gltfRuntime.scene.skeletons[i];
+ gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
+ }
+};
+/**
+ * onBind shaderrs callback to set uniforms and matrices
+ * @param mesh
+ * @param gltfRuntime
+ * @param unTreatedUniforms
+ * @param shaderMaterial
+ * @param technique
+ * @param material
+ * @param onSuccess
+ */
+const onBindShaderMaterial = (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) => {
+ const materialValues = material.values || technique.parameters;
+ for (const unif in unTreatedUniforms) {
+ const uniform = unTreatedUniforms[unif];
+ const type = uniform.type;
+ if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
+ if (uniform.semantic && !uniform.source && !uniform.node) {
+ GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
+ }
+ else if (uniform.semantic && (uniform.source || uniform.node)) {
+ let source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
+ if (source === null) {
+ source = gltfRuntime.scene.getNodeById(uniform.source || uniform.node || "");
+ }
+ if (source === null) {
+ continue;
+ }
+ GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
+ }
+ }
+ else {
+ const value = materialValues[technique.uniforms[unif]];
+ if (!value) {
+ continue;
+ }
+ if (type === EParameterType.SAMPLER_2D) {
+ const texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
+ if (texture === null || texture === undefined) {
+ continue;
+ }
+ shaderMaterial.getEffect().setTexture(unif, texture);
+ }
+ else {
+ GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
+ }
+ }
+ }
+ onSuccess(shaderMaterial);
+};
+/**
+ * Prepare uniforms to send the only one time
+ * Loads the appropriate textures
+ * @param gltfRuntime
+ * @param shaderMaterial
+ * @param technique
+ * @param material
+ */
+const prepareShaderMaterialUniforms = (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) => {
+ const materialValues = material.values || technique.parameters;
+ const techniqueUniforms = technique.uniforms;
+ /**
+ * Prepare values here (not matrices)
+ */
+ for (const unif in unTreatedUniforms) {
+ const uniform = unTreatedUniforms[unif];
+ const type = uniform.type;
+ let value = materialValues[techniqueUniforms[unif]];
+ if (value === undefined) {
+ // In case the value is the same for all materials
+ value = uniform.value;
+ }
+ if (!value) {
+ continue;
+ }
+ const onLoadTexture = (uniformName) => {
+ return (texture) => {
+ if (uniform.value && uniformName) {
+ // Static uniform
+ shaderMaterial.setTexture(uniformName, texture);
+ delete unTreatedUniforms[uniformName];
+ }
+ };
+ };
+ // Texture (sampler2D)
+ if (type === EParameterType.SAMPLER_2D) {
+ GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), () => onLoadTexture(null));
+ }
+ // Others
+ else {
+ if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
+ // Static uniform
+ delete unTreatedUniforms[unif];
+ }
+ }
+ }
+};
+/**
+ * Shader compilation failed
+ * @param program
+ * @param shaderMaterial
+ * @param onError
+ * @returns callback when shader is compiled
+ */
+const onShaderCompileError = (program, shaderMaterial, onError) => {
+ return (effect, error) => {
+ shaderMaterial.dispose(true);
+ onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
+ };
+};
+/**
+ * Shader compilation success
+ * @param gltfRuntime
+ * @param shaderMaterial
+ * @param technique
+ * @param material
+ * @param unTreatedUniforms
+ * @param onSuccess
+ * @returns callback when shader is compiled
+ */
+const onShaderCompileSuccess = (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) => {
+ return (_) => {
+ prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
+ shaderMaterial.onBind = (mesh) => {
+ onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
+ };
+ };
+};
+/**
+ * Returns the appropriate uniform if already handled by babylon
+ * @param tokenizer
+ * @param technique
+ * @param unTreatedUniforms
+ * @returns the name of the uniform handled by babylon
+ */
+const parseShaderUniforms = (tokenizer, technique, unTreatedUniforms) => {
+ for (const unif in technique.uniforms) {
+ const uniform = technique.uniforms[unif];
+ const uniformParameter = technique.parameters[uniform];
+ if (tokenizer.currentIdentifier === unif) {
+ if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
+ const transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
+ if (transformIndex !== -1) {
+ delete unTreatedUniforms[unif];
+ return babylonTransforms[transformIndex];
+ }
+ }
+ }
+ }
+ return tokenizer.currentIdentifier;
+};
+/**
+ * All shaders loaded. Create materials one by one
+ * @param gltfRuntime
+ */
+const importMaterials = (gltfRuntime) => {
+ // Create materials
+ for (const mat in gltfRuntime.materials) {
+ GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, () => { }, () => { });
+ }
+};
+/**
+ * Implementation of the base glTF spec
+ * @internal
+ */
+class GLTFLoaderBase {
+ static CreateRuntime(parsedData, scene, rootUrl) {
+ const gltfRuntime = {
+ extensions: {},
+ accessors: {},
+ buffers: {},
+ bufferViews: {},
+ meshes: {},
+ lights: {},
+ cameras: {},
+ nodes: {},
+ images: {},
+ textures: {},
+ shaders: {},
+ programs: {},
+ samplers: {},
+ techniques: {},
+ materials: {},
+ animations: {},
+ skins: {},
+ extensionsUsed: [],
+ scenes: {},
+ buffersCount: 0,
+ shaderscount: 0,
+ scene: scene,
+ rootUrl: rootUrl,
+ loadedBufferCount: 0,
+ loadedBufferViews: {},
+ loadedShaderCount: 0,
+ importOnlyMeshes: false,
+ dummyNodes: [],
+ assetContainer: null,
+ };
+ // Parse
+ if (parsedData.extensions) {
+ parseObject(parsedData.extensions, "extensions", gltfRuntime);
+ }
+ if (parsedData.extensionsUsed) {
+ parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
+ }
+ if (parsedData.buffers) {
+ parseBuffers(parsedData.buffers, gltfRuntime);
+ }
+ if (parsedData.bufferViews) {
+ parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
+ }
+ if (parsedData.accessors) {
+ parseObject(parsedData.accessors, "accessors", gltfRuntime);
+ }
+ if (parsedData.meshes) {
+ parseObject(parsedData.meshes, "meshes", gltfRuntime);
+ }
+ if (parsedData.lights) {
+ parseObject(parsedData.lights, "lights", gltfRuntime);
+ }
+ if (parsedData.cameras) {
+ parseObject(parsedData.cameras, "cameras", gltfRuntime);
+ }
+ if (parsedData.nodes) {
+ parseObject(parsedData.nodes, "nodes", gltfRuntime);
+ }
+ if (parsedData.images) {
+ parseObject(parsedData.images, "images", gltfRuntime);
+ }
+ if (parsedData.textures) {
+ parseObject(parsedData.textures, "textures", gltfRuntime);
+ }
+ if (parsedData.shaders) {
+ parseShaders(parsedData.shaders, gltfRuntime);
+ }
+ if (parsedData.programs) {
+ parseObject(parsedData.programs, "programs", gltfRuntime);
+ }
+ if (parsedData.samplers) {
+ parseObject(parsedData.samplers, "samplers", gltfRuntime);
+ }
+ if (parsedData.techniques) {
+ parseObject(parsedData.techniques, "techniques", gltfRuntime);
+ }
+ if (parsedData.materials) {
+ parseObject(parsedData.materials, "materials", gltfRuntime);
+ }
+ if (parsedData.animations) {
+ parseObject(parsedData.animations, "animations", gltfRuntime);
+ }
+ if (parsedData.skins) {
+ parseObject(parsedData.skins, "skins", gltfRuntime);
+ }
+ if (parsedData.scenes) {
+ gltfRuntime.scenes = parsedData.scenes;
+ }
+ if (parsedData.scene && parsedData.scenes) {
+ gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
+ }
+ return gltfRuntime;
+ }
+ static LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {
+ const buffer = gltfRuntime.buffers[id];
+ if (Tools.IsBase64(buffer.uri)) {
+ setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri))));
+ }
+ else {
+ Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, (data) => onSuccess(new Uint8Array(data)), onProgress, undefined, true, (request) => {
+ if (request) {
+ onError(request.status + " " + request.statusText);
+ }
+ });
+ }
+ }
+ static LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {
+ const texture = gltfRuntime.textures[id];
+ if (!texture || !texture.source) {
+ onError("");
+ return;
+ }
+ if (texture.babylonTexture) {
+ onSuccess(null);
+ return;
+ }
+ const source = gltfRuntime.images[texture.source];
+ if (Tools.IsBase64(source.uri)) {
+ setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri))));
+ }
+ else {
+ Tools.LoadFile(gltfRuntime.rootUrl + source.uri, (data) => onSuccess(new Uint8Array(data)), undefined, undefined, true, (request) => {
+ if (request) {
+ onError(request.status + " " + request.statusText);
+ }
+ });
+ }
+ }
+ static CreateTextureAsync(gltfRuntime, id, buffer, onSuccess) {
+ const texture = gltfRuntime.textures[id];
+ if (texture.babylonTexture) {
+ onSuccess(texture.babylonTexture);
+ return;
+ }
+ const sampler = gltfRuntime.samplers[texture.sampler];
+ const createMipMaps = sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST ||
+ sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR ||
+ sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST ||
+ sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR;
+ const samplingMode = Texture.BILINEAR_SAMPLINGMODE;
+ const blob = buffer == null ? new Blob() : new Blob([buffer]);
+ const blobURL = URL.createObjectURL(blob);
+ const revokeBlobURL = () => URL.revokeObjectURL(blobURL);
+ const newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
+ if (sampler.wrapS !== undefined) {
+ newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
+ }
+ if (sampler.wrapT !== undefined) {
+ newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
+ }
+ newTexture.name = id;
+ texture.babylonTexture = newTexture;
+ onSuccess(newTexture);
+ }
+ static LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {
+ const shader = gltfRuntime.shaders[id];
+ if (Tools.IsBase64(shader.uri)) {
+ const shaderString = atob(shader.uri.split(",")[1]);
+ if (onSuccess) {
+ onSuccess(shaderString);
+ }
+ }
+ else {
+ Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, (request) => {
+ if (request && onError) {
+ onError(request.status + " " + request.statusText);
+ }
+ });
+ }
+ }
+ static LoadMaterialAsync(gltfRuntime, id, onSuccess, onError) {
+ const material = gltfRuntime.materials[id];
+ if (!material.technique) {
+ if (onError) {
+ onError("No technique found.");
+ }
+ return;
+ }
+ const technique = gltfRuntime.techniques[material.technique];
+ if (!technique) {
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
+ const defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);
+ defaultMaterial._parentContainer = gltfRuntime.assetContainer;
+ gltfRuntime.scene._blockEntityCollection = false;
+ defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);
+ defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
+ onSuccess(defaultMaterial);
+ return;
+ }
+ const program = gltfRuntime.programs[technique.program];
+ const states = technique.states;
+ const vertexShader = Effect.ShadersStore[program.vertexShader + "VertexShader"];
+ const pixelShader = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
+ let newVertexShader = "";
+ let newPixelShader = "";
+ const vertexTokenizer = new Tokenizer(vertexShader);
+ const pixelTokenizer = new Tokenizer(pixelShader);
+ const unTreatedUniforms = {};
+ const uniforms = [];
+ const attributes = [];
+ const samplers = [];
+ // Fill uniform, sampler2D and attributes
+ for (const unif in technique.uniforms) {
+ const uniform = technique.uniforms[unif];
+ const uniformParameter = technique.parameters[uniform];
+ unTreatedUniforms[unif] = uniformParameter;
+ if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
+ const transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
+ if (transformIndex !== -1) {
+ uniforms.push(babylonTransforms[transformIndex]);
+ delete unTreatedUniforms[unif];
+ }
+ else {
+ uniforms.push(unif);
+ }
+ }
+ else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
+ samplers.push(unif);
+ }
+ else {
+ uniforms.push(unif);
+ }
+ }
+ for (const attr in technique.attributes) {
+ const attribute = technique.attributes[attr];
+ const attributeParameter = technique.parameters[attribute];
+ if (attributeParameter.semantic) {
+ const name = getAttribute(attributeParameter);
+ if (name) {
+ attributes.push(name);
+ }
+ }
+ }
+ // Configure vertex shader
+ while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
+ const tokenType = vertexTokenizer.currentToken;
+ if (tokenType !== ETokenType.IDENTIFIER) {
+ newVertexShader += vertexTokenizer.currentString;
+ continue;
+ }
+ let foundAttribute = false;
+ for (const attr in technique.attributes) {
+ const attribute = technique.attributes[attr];
+ const attributeParameter = technique.parameters[attribute];
+ if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
+ newVertexShader += getAttribute(attributeParameter);
+ foundAttribute = true;
+ break;
+ }
+ }
+ if (foundAttribute) {
+ continue;
+ }
+ newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
+ }
+ // Configure pixel shader
+ while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
+ const tokenType = pixelTokenizer.currentToken;
+ if (tokenType !== ETokenType.IDENTIFIER) {
+ newPixelShader += pixelTokenizer.currentString;
+ continue;
+ }
+ newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
+ }
+ // Create shader material
+ const shaderPath = {
+ vertex: program.vertexShader + id,
+ fragment: program.fragmentShader + id,
+ };
+ const options = {
+ attributes: attributes,
+ uniforms: uniforms,
+ samplers: samplers,
+ needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1,
+ };
+ Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
+ Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
+ const shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
+ shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
+ shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
+ shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
+ if (states && states.functions) {
+ const functions = states.functions;
+ if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
+ shaderMaterial.backFaceCulling = false;
+ }
+ const blendFunc = functions.blendFuncSeparate;
+ if (blendFunc) {
+ if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA &&
+ blendFunc[2] === EBlendingFunction.ONE &&
+ blendFunc[3] === EBlendingFunction.ONE) {
+ shaderMaterial.alphaMode = Constants.ALPHA_COMBINE;
+ }
+ else if (blendFunc[0] === EBlendingFunction.ONE &&
+ blendFunc[1] === EBlendingFunction.ONE &&
+ blendFunc[2] === EBlendingFunction.ZERO &&
+ blendFunc[3] === EBlendingFunction.ONE) {
+ shaderMaterial.alphaMode = Constants.ALPHA_ONEONE;
+ }
+ else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
+ blendFunc[1] === EBlendingFunction.ONE &&
+ blendFunc[2] === EBlendingFunction.ZERO &&
+ blendFunc[3] === EBlendingFunction.ONE) {
+ shaderMaterial.alphaMode = Constants.ALPHA_ADD;
+ }
+ else if (blendFunc[0] === EBlendingFunction.ZERO &&
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&
+ blendFunc[2] === EBlendingFunction.ONE &&
+ blendFunc[3] === EBlendingFunction.ONE) {
+ shaderMaterial.alphaMode = Constants.ALPHA_SUBTRACT;
+ }
+ else if (blendFunc[0] === EBlendingFunction.DST_COLOR &&
+ blendFunc[1] === EBlendingFunction.ZERO &&
+ blendFunc[2] === EBlendingFunction.ONE &&
+ blendFunc[3] === EBlendingFunction.ONE) {
+ shaderMaterial.alphaMode = Constants.ALPHA_MULTIPLY;
+ }
+ else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&
+ blendFunc[2] === EBlendingFunction.ONE &&
+ blendFunc[3] === EBlendingFunction.ONE) {
+ shaderMaterial.alphaMode = Constants.ALPHA_MAXIMIZED;
+ }
+ }
+ }
+ }
+}
+/**
+ * glTF V1 Loader
+ * @internal
+ * @deprecated
+ */
+let GLTFLoader$1 = class GLTFLoader {
+ static RegisterExtension(extension) {
+ if (GLTFLoader.Extensions[extension.name]) {
+ Tools.Error('Tool with the same name "' + extension.name + '" already exists');
+ return;
+ }
+ GLTFLoader.Extensions[extension.name] = extension;
+ }
+ dispose() {
+ // do nothing
+ }
+ _importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, onSuccess, onProgress, onError) {
+ scene.useRightHandedSystem = true;
+ GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, (gltfRuntime) => {
+ gltfRuntime.assetContainer = assetContainer;
+ gltfRuntime.importOnlyMeshes = true;
+ if (meshesNames === "") {
+ gltfRuntime.importMeshesNames = [];
+ }
+ else if (typeof meshesNames === "string") {
+ gltfRuntime.importMeshesNames = [meshesNames];
+ }
+ else if (meshesNames && !(meshesNames instanceof Array)) {
+ gltfRuntime.importMeshesNames = [meshesNames];
+ }
+ else {
+ gltfRuntime.importMeshesNames = [];
+ Tools.Warn("Argument meshesNames must be of type string or string[]");
+ }
+ // Create nodes
+ this._createNodes(gltfRuntime);
+ const meshes = [];
+ const skeletons = [];
+ // Fill arrays of meshes and skeletons
+ for (const nde in gltfRuntime.nodes) {
+ const node = gltfRuntime.nodes[nde];
+ if (node.babylonNode instanceof AbstractMesh) {
+ meshes.push(node.babylonNode);
+ }
+ }
+ for (const skl in gltfRuntime.skins) {
+ const skin = gltfRuntime.skins[skl];
+ if (skin.babylonSkeleton instanceof Skeleton) {
+ skeletons.push(skin.babylonSkeleton);
+ }
+ }
+ // Load buffers, shaders, materials, etc.
+ this._loadBuffersAsync(gltfRuntime, () => {
+ this._loadShadersAsync(gltfRuntime, () => {
+ importMaterials(gltfRuntime);
+ postLoad(gltfRuntime);
+ if (!GLTFFileLoader.IncrementalLoading && onSuccess) {
+ onSuccess(meshes, skeletons);
+ }
+ });
+ });
+ if (GLTFFileLoader.IncrementalLoading && onSuccess) {
+ onSuccess(meshes, skeletons);
+ }
+ }, onError);
+ return true;
+ }
+ /**
+ * Imports one or more meshes from a loaded gltf file 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 assetContainer defines the asset container to use (can be null)
+ * @param data gltf data containing information of the meshes in a loaded file
+ * @param rootUrl root url to load from
+ * @param onProgress event that fires when loading progress has occured
+ * @returns a promise containg the loaded meshes, particles, skeletons and animations
+ */
+ importMeshAsync(meshesNames, scene, assetContainer, data, rootUrl, onProgress) {
+ return new Promise((resolve, reject) => {
+ this._importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, (meshes, skeletons) => {
+ resolve({
+ meshes: meshes,
+ particleSystems: [],
+ skeletons: skeletons,
+ animationGroups: [],
+ lights: [],
+ transformNodes: [],
+ geometries: [],
+ spriteManagers: [],
+ });
+ }, onProgress, (message) => {
+ reject(new Error(message));
+ });
+ });
+ }
+ _loadAsync(scene, data, rootUrl, onSuccess, onProgress, onError) {
+ scene.useRightHandedSystem = true;
+ GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, (gltfRuntime) => {
+ // Load runtime extensios
+ GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, () => {
+ // Create nodes
+ this._createNodes(gltfRuntime);
+ // Load buffers, shaders, materials, etc.
+ this._loadBuffersAsync(gltfRuntime, () => {
+ this._loadShadersAsync(gltfRuntime, () => {
+ importMaterials(gltfRuntime);
+ postLoad(gltfRuntime);
+ if (!GLTFFileLoader.IncrementalLoading) {
+ onSuccess();
+ }
+ });
+ });
+ if (GLTFFileLoader.IncrementalLoading) {
+ onSuccess();
+ }
+ }, onError);
+ }, onError);
+ }
+ /**
+ * Imports all objects from a loaded gltf file and adds them to the scene
+ * @param scene the scene the objects should be added to
+ * @param data gltf data containing information of the meshes in a loaded file
+ * @param rootUrl root url to load from
+ * @param onProgress event that fires when loading progress has occured
+ * @returns a promise which completes when objects have been loaded to the scene
+ */
+ loadAsync(scene, data, rootUrl, onProgress) {
+ return new Promise((resolve, reject) => {
+ this._loadAsync(scene, data, rootUrl, () => {
+ resolve();
+ }, onProgress, (message) => {
+ reject(new Error(message));
+ });
+ });
+ }
+ _loadShadersAsync(gltfRuntime, onload) {
+ let hasShaders = false;
+ const processShader = (sha, shader) => {
+ GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, (shaderString) => {
+ if (shaderString instanceof ArrayBuffer) {
+ return;
+ }
+ gltfRuntime.loadedShaderCount++;
+ if (shaderString) {
+ Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
+ }
+ if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
+ onload();
+ }
+ }, () => {
+ Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
+ });
+ };
+ for (const sha in gltfRuntime.shaders) {
+ hasShaders = true;
+ const shader = gltfRuntime.shaders[sha];
+ if (shader) {
+ processShader.bind(this, sha, shader)();
+ }
+ else {
+ Tools.Error("No shader named: " + sha);
+ }
+ }
+ if (!hasShaders) {
+ onload();
+ }
+ }
+ _loadBuffersAsync(gltfRuntime, onLoad) {
+ let hasBuffers = false;
+ const processBuffer = (buf, buffer) => {
+ GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, (bufferView) => {
+ gltfRuntime.loadedBufferCount++;
+ if (bufferView) {
+ if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
+ Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
+ }
+ gltfRuntime.loadedBufferViews[buf] = bufferView;
+ }
+ if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
+ onLoad();
+ }
+ }, () => {
+ Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
+ });
+ };
+ for (const buf in gltfRuntime.buffers) {
+ hasBuffers = true;
+ const buffer = gltfRuntime.buffers[buf];
+ if (buffer) {
+ processBuffer.bind(this, buf, buffer)();
+ }
+ else {
+ Tools.Error("No buffer named: " + buf);
+ }
+ }
+ if (!hasBuffers) {
+ onLoad();
+ }
+ }
+ _createNodes(gltfRuntime) {
+ let currentScene = gltfRuntime.currentScene;
+ if (currentScene) {
+ // Only one scene even if multiple scenes are defined
+ for (let i = 0; i < currentScene.nodes.length; i++) {
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
+ }
+ }
+ else {
+ // Load all scenes
+ for (const thing in gltfRuntime.scenes) {
+ currentScene = gltfRuntime.scenes[thing];
+ for (let i = 0; i < currentScene.nodes.length; i++) {
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
+ }
+ }
+ }
+ }
+};
+GLTFLoader$1.Extensions = {};
+/** @internal */
+class GLTFLoaderExtension {
+ constructor(name) {
+ this._name = name;
+ }
+ get name() {
+ return this._name;
+ }
+ /**
+ * Defines an override for loading the runtime
+ * Return true to stop further extensions from loading the runtime
+ * @param scene
+ * @param data
+ * @param rootUrl
+ * @param onSuccess
+ * @param onError
+ * @returns true to stop further extensions from loading the runtime
+ */
+ loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError) {
+ return false;
+ }
+ /**
+ * Defines an onverride for creating gltf runtime
+ * Return true to stop further extensions from creating the runtime
+ * @param gltfRuntime
+ * @param onSuccess
+ * @param onError
+ * @returns true to stop further extensions from creating the runtime
+ */
+ loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError) {
+ return false;
+ }
+ /**
+ * Defines an override for loading buffers
+ * Return true to stop further extensions from loading this buffer
+ * @param gltfRuntime
+ * @param id
+ * @param onSuccess
+ * @param onError
+ * @param onProgress
+ * @returns true to stop further extensions from loading this buffer
+ */
+ loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {
+ return false;
+ }
+ /**
+ * Defines an override for loading texture buffers
+ * Return true to stop further extensions from loading this texture data
+ * @param gltfRuntime
+ * @param id
+ * @param onSuccess
+ * @param onError
+ * @returns true to stop further extensions from loading this texture data
+ */
+ loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {
+ return false;
+ }
+ /**
+ * Defines an override for creating textures
+ * Return true to stop further extensions from loading this texture
+ * @param gltfRuntime
+ * @param id
+ * @param buffer
+ * @param onSuccess
+ * @param onError
+ * @returns true to stop further extensions from loading this texture
+ */
+ createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError) {
+ return false;
+ }
+ /**
+ * Defines an override for loading shader strings
+ * Return true to stop further extensions from loading this shader data
+ * @param gltfRuntime
+ * @param id
+ * @param onSuccess
+ * @param onError
+ * @returns true to stop further extensions from loading this shader data
+ */
+ loadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {
+ return false;
+ }
+ /**
+ * Defines an override for loading materials
+ * Return true to stop further extensions from loading this material
+ * @param gltfRuntime
+ * @param id
+ * @param onSuccess
+ * @param onError
+ * @returns true to stop further extensions from loading this material
+ */
+ loadMaterialAsync(gltfRuntime, id, onSuccess, onError) {
+ return false;
+ }
+ // ---------
+ // Utilities
+ // ---------
+ static LoadRuntimeAsync(scene, data, rootUrl, onSuccess, onError) {
+ GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {
+ return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
+ }, () => {
+ setTimeout(() => {
+ if (!onSuccess) {
+ return;
+ }
+ onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
+ });
+ });
+ }
+ static LoadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError) {
+ GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {
+ return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
+ }, () => {
+ setTimeout(() => {
+ onSuccess();
+ });
+ });
+ }
+ static LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {
+ GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {
+ return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
+ }, () => {
+ GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
+ });
+ }
+ static LoadTextureAsync(gltfRuntime, id, onSuccess, onError) {
+ GLTFLoaderExtension._LoadTextureBufferAsync(gltfRuntime, id, (buffer) => {
+ if (buffer) {
+ GLTFLoaderExtension._CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
+ }
+ }, onError);
+ }
+ static LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {
+ GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {
+ return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
+ }, () => {
+ GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
+ });
+ }
+ static LoadMaterialAsync(gltfRuntime, id, onSuccess, onError) {
+ GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {
+ return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
+ }, () => {
+ GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
+ });
+ }
+ static _LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {
+ GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {
+ return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
+ }, () => {
+ GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
+ });
+ }
+ static _CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError) {
+ GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {
+ return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
+ }, () => {
+ GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess);
+ });
+ }
+ static _ApplyExtensions(func, defaultFunc) {
+ for (const extensionName in GLTFLoader$1.Extensions) {
+ const loaderExtension = GLTFLoader$1.Extensions[extensionName];
+ if (func(loaderExtension)) {
+ return;
+ }
+ }
+ defaultFunc();
+ }
+}
+GLTFFileLoader._CreateGLTF1Loader = () => new GLTFLoader$1();
+
+const BinaryExtensionBufferName = "binary_glTF";
+/**
+ * @internal
+ * @deprecated
+ */
+class GLTFBinaryExtension extends GLTFLoaderExtension {
+ constructor() {
+ super("KHR_binary_glTF");
+ }
+ loadRuntimeAsync(scene, data, rootUrl, onSuccess) {
+ const extensionsUsed = data.json.extensionsUsed;
+ if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
+ return false;
+ }
+ this._bin = data.bin;
+ onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
+ return true;
+ }
+ loadBufferAsync(gltfRuntime, id, onSuccess, onError) {
+ if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
+ return false;
+ }
+ if (id !== BinaryExtensionBufferName) {
+ return false;
+ }
+ this._bin.readAsync(0, this._bin.byteLength).then(onSuccess, (error) => onError(error.message));
+ return true;
+ }
+ loadTextureBufferAsync(gltfRuntime, id, onSuccess) {
+ const texture = gltfRuntime.textures[id];
+ const source = gltfRuntime.images[texture.source];
+ if (!source.extensions || !(this.name in source.extensions)) {
+ return false;
+ }
+ const sourceExt = source.extensions[this.name];
+ const bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
+ const buffer = GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE);
+ onSuccess(buffer);
+ return true;
+ }
+ loadShaderStringAsync(gltfRuntime, id, onSuccess) {
+ const shader = gltfRuntime.shaders[id];
+ if (!shader.extensions || !(this.name in shader.extensions)) {
+ return false;
+ }
+ const binaryExtensionShader = shader.extensions[this.name];
+ const bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
+ const shaderBytes = GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE);
+ setTimeout(() => {
+ const shaderString = GLTFUtils.DecodeBufferToText(shaderBytes);
+ onSuccess(shaderString);
+ });
+ return true;
+ }
+}
+GLTFLoader$1.RegisterExtension(new GLTFBinaryExtension());
+
+/**
+ * @internal
+ * @deprecated
+ */
+class GLTFMaterialsCommonExtension extends GLTFLoaderExtension {
+ constructor() {
+ super("KHR_materials_common");
+ }
+ loadRuntimeExtensionsAsync(gltfRuntime) {
+ if (!gltfRuntime.extensions) {
+ return false;
+ }
+ const extension = gltfRuntime.extensions[this.name];
+ if (!extension) {
+ return false;
+ }
+ // Create lights
+ const lights = extension.lights;
+ if (lights) {
+ for (const thing in lights) {
+ const light = lights[thing];
+ switch (light.type) {
+ case "ambient": {
+ const ambientLight = new HemisphericLight(light.name, new Vector3(0, 1, 0), gltfRuntime.scene);
+ const ambient = light.ambient;
+ if (ambient) {
+ ambientLight.diffuse = Color3.FromArray(ambient.color || [1, 1, 1]);
+ }
+ break;
+ }
+ case "point": {
+ const pointLight = new PointLight(light.name, new Vector3(10, 10, 10), gltfRuntime.scene);
+ const point = light.point;
+ if (point) {
+ pointLight.diffuse = Color3.FromArray(point.color || [1, 1, 1]);
+ }
+ break;
+ }
+ case "directional": {
+ const dirLight = new DirectionalLight(light.name, new Vector3(0, -1, 0), gltfRuntime.scene);
+ const directional = light.directional;
+ if (directional) {
+ dirLight.diffuse = Color3.FromArray(directional.color || [1, 1, 1]);
+ }
+ break;
+ }
+ case "spot": {
+ const spot = light.spot;
+ if (spot) {
+ const spotLight = new SpotLight(light.name, new Vector3(0, 10, 0), new Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
+ spotLight.diffuse = Color3.FromArray(spot.color || [1, 1, 1]);
+ }
+ break;
+ }
+ default:
+ Tools.Warn('GLTF Material Common extension: light type "' + light.type + "” not supported");
+ break;
+ }
+ }
+ }
+ return false;
+ }
+ loadMaterialAsync(gltfRuntime, id, onSuccess, onError) {
+ const material = gltfRuntime.materials[id];
+ if (!material || !material.extensions) {
+ return false;
+ }
+ const extension = material.extensions[this.name];
+ if (!extension) {
+ return false;
+ }
+ const standardMaterial = new StandardMaterial(id, gltfRuntime.scene);
+ standardMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
+ if (extension.technique === "CONSTANT") {
+ standardMaterial.disableLighting = true;
+ }
+ standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
+ standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
+ standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
+ // Ambient
+ if (typeof extension.values.ambient === "string") {
+ this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
+ }
+ else {
+ standardMaterial.ambientColor = Color3.FromArray(extension.values.ambient || [0, 0, 0]);
+ }
+ // Diffuse
+ if (typeof extension.values.diffuse === "string") {
+ this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
+ }
+ else {
+ standardMaterial.diffuseColor = Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
+ }
+ // Emission
+ if (typeof extension.values.emission === "string") {
+ this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
+ }
+ else {
+ standardMaterial.emissiveColor = Color3.FromArray(extension.values.emission || [0, 0, 0]);
+ }
+ // Specular
+ if (typeof extension.values.specular === "string") {
+ this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
+ }
+ else {
+ standardMaterial.specularColor = Color3.FromArray(extension.values.specular || [0, 0, 0]);
+ }
+ return true;
+ }
+ _loadTexture(gltfRuntime, id, material, propertyPath, onError) {
+ // Create buffer from texture url
+ GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, (buffer) => {
+ // Create texture from buffer
+ GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, (texture) => (material[propertyPath] = texture));
+ }, onError);
+ }
+}
+GLTFLoader$1.RegisterExtension(new GLTFMaterialsCommonExtension());
+
+/**
+ * Wrapper class for promise with external resolve and reject.
+ */
+class Deferred {
+ /**
+ * The resolve method of the promise associated with this deferred object.
+ */
+ get resolve() {
+ return this._resolve;
+ }
+ /**
+ * The reject method of the promise associated with this deferred object.
+ */
+ get reject() {
+ return this._reject;
+ }
+ /**
+ * Constructor for this deferred object.
+ */
+ constructor() {
+ this.promise = new Promise((resolve, reject) => {
+ this._resolve = resolve;
+ this._reject = reject;
+ });
+ }
+}
+
+/**
+ * PassPostProcess which produces an output the same as it's input
+ */
+class ThinPassPostProcess extends EffectWrapper {
+ _gatherImports(useWebGPU, list) {
+ if (useWebGPU) {
+ this._webGPUReady = true;
+ list.push(Promise.all([Promise.resolve().then(() => pass_fragment)]));
+ }
+ else {
+ list.push(Promise.all([Promise.resolve().then(() => pass_fragment$1)]));
+ }
+ super._gatherImports(useWebGPU, list);
+ }
+ /**
+ * Constructs a new pass post process
+ * @param name Name of the effect
+ * @param engine Engine to use to render the effect. If not provided, the last created engine will be used
+ * @param options Options to configure the effect
+ */
+ constructor(name, engine = null, options) {
+ super({
+ ...options,
+ name,
+ engine: engine || Engine.LastCreatedEngine,
+ useShaderStore: true,
+ useAsPostProcess: true,
+ fragmentShader: ThinPassPostProcess.FragmentUrl,
+ });
+ }
+}
+/**
+ * The fragment shader url
+ */
+ThinPassPostProcess.FragmentUrl = "pass";
+/**
+ * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture)
+ */
+class ThinPassCubePostProcess extends EffectWrapper {
+ _gatherImports(useWebGPU, list) {
+ if (useWebGPU) {
+ this._webGPUReady = true;
+ list.push(Promise.all([Promise.resolve().then(() => passCube_fragment)]));
+ }
+ else {
+ list.push(Promise.all([Promise.resolve().then(() => passCube_fragment$1)]));
+ }
+ super._gatherImports(useWebGPU, list);
+ }
+ /**
+ * Creates the PassCubePostProcess
+ * @param name Name of the effect
+ * @param engine Engine to use to render the effect. If not provided, the last created engine will be used
+ * @param options Options to configure the effect
+ */
+ constructor(name, engine = null, options) {
+ super({
+ ...options,
+ name,
+ engine: engine || Engine.LastCreatedEngine,
+ useShaderStore: true,
+ useAsPostProcess: true,
+ fragmentShader: ThinPassCubePostProcess.FragmentUrl,
+ defines: "#define POSITIVEX",
+ });
+ this._face = 0;
+ }
+ /**
+ * Gets or sets the cube face to display.
+ * * 0 is +X
+ * * 1 is -X
+ * * 2 is +Y
+ * * 3 is -Y
+ * * 4 is +Z
+ * * 5 is -Z
+ */
+ get face() {
+ return this._face;
+ }
+ set face(value) {
+ if (value < 0 || value > 5) {
+ return;
+ }
+ this._face = value;
+ switch (this._face) {
+ case 0:
+ this.updateEffect("#define POSITIVEX");
+ break;
+ case 1:
+ this.updateEffect("#define NEGATIVEX");
+ break;
+ case 2:
+ this.updateEffect("#define POSITIVEY");
+ break;
+ case 3:
+ this.updateEffect("#define NEGATIVEY");
+ break;
+ case 4:
+ this.updateEffect("#define POSITIVEZ");
+ break;
+ case 5:
+ this.updateEffect("#define NEGATIVEZ");
+ break;
+ }
+ }
+}
+/**
+ * The fragment shader url
+ */
+ThinPassCubePostProcess.FragmentUrl = "passCube";
+
+/**
+ * PassPostProcess which produces an output the same as it's input
+ */
+class PassPostProcess extends PostProcess {
+ /**
+ * Gets a string identifying the name of the class
+ * @returns "PassPostProcess" string
+ */
+ getClassName() {
+ return "PassPostProcess";
+ }
+ /**
+ * Creates the PassPostProcess
+ * @param name The name of the effect.
+ * @param options The required width/height ratio to downsize to before computing the render pass.
+ * @param camera The camera to apply the render pass to.
+ * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
+ * @param engine The engine which the post process will be applied. (default: current engine)
+ * @param reusable If the post process can be reused on the same frame. (default: false)
+ * @param textureType The type of texture to be used when performing the post processing.
+ * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
+ */
+ constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {
+ const localOptions = {
+ size: typeof options === "number" ? options : undefined,
+ camera,
+ samplingMode,
+ engine,
+ reusable,
+ textureType,
+ blockCompilation,
+ ...options,
+ };
+ super(name, ThinPassPostProcess.FragmentUrl, {
+ effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassPostProcess(name, engine, localOptions) : undefined,
+ ...localOptions,
+ });
+ }
+ /**
+ * @internal
+ */
+ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {
+ return SerializationHelper.Parse(() => {
+ return new PassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable);
+ }, parsedPostProcess, scene, rootUrl);
+ }
+}
+RegisterClass("BABYLON.PassPostProcess", PassPostProcess);
+/**
+ * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture)
+ */
+class PassCubePostProcess extends PostProcess {
+ /**
+ * Gets or sets the cube face to display.
+ * * 0 is +X
+ * * 1 is -X
+ * * 2 is +Y
+ * * 3 is -Y
+ * * 4 is +Z
+ * * 5 is -Z
+ */
+ get face() {
+ return this._effectWrapper.face;
+ }
+ set face(value) {
+ this._effectWrapper.face = value;
+ }
+ /**
+ * Gets a string identifying the name of the class
+ * @returns "PassCubePostProcess" string
+ */
+ getClassName() {
+ return "PassCubePostProcess";
+ }
+ /**
+ * Creates the PassCubePostProcess
+ * @param name The name of the effect.
+ * @param options The required width/height ratio to downsize to before computing the render pass.
+ * @param camera The camera to apply the render pass to.
+ * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
+ * @param engine The engine which the post process will be applied. (default: current engine)
+ * @param reusable If the post process can be reused on the same frame. (default: false)
+ * @param textureType The type of texture to be used when performing the post processing.
+ * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
+ */
+ constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {
+ const localOptions = {
+ size: typeof options === "number" ? options : undefined,
+ camera,
+ samplingMode,
+ engine,
+ reusable,
+ textureType,
+ blockCompilation,
+ ...options,
+ };
+ super(name, ThinPassPostProcess.FragmentUrl, {
+ effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassCubePostProcess(name, engine, localOptions) : undefined,
+ ...localOptions,
+ });
+ }
+ /**
+ * @internal
+ */
+ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {
+ return SerializationHelper.Parse(() => {
+ return new PassCubePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable);
+ }, parsedPostProcess, scene, rootUrl);
+ }
+}
+__decorate([
+ serialize()
+], PassCubePostProcess.prototype, "face", null);
+AbstractEngine._RescalePostProcessFactory = (engine) => {
+ return new PassPostProcess("rescale", 1, null, 2, engine, false, 0);
+};
+
+/**
+ * Uses the GPU to create a copy texture rescaled at a given size
+ * @param texture Texture to copy from
+ * @param width defines the desired width
+ * @param height defines the desired height
+ * @param useBilinearMode defines if bilinear mode has to be used
+ * @returns the generated texture
+ */
+function CreateResizedCopy(texture, width, height, useBilinearMode = true) {
+ const scene = texture.getScene();
+ const engine = scene.getEngine();
+ const rtt = new RenderTargetTexture("resized" + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture.samplingMode, false);
+ rtt.wrapU = texture.wrapU;
+ rtt.wrapV = texture.wrapV;
+ rtt.uOffset = texture.uOffset;
+ rtt.vOffset = texture.vOffset;
+ rtt.uScale = texture.uScale;
+ rtt.vScale = texture.vScale;
+ rtt.uAng = texture.uAng;
+ rtt.vAng = texture.vAng;
+ rtt.wAng = texture.wAng;
+ rtt.coordinatesIndex = texture.coordinatesIndex;
+ rtt.level = texture.level;
+ rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
+ rtt._texture.isReady = false;
+ texture.wrapU = Texture.CLAMP_ADDRESSMODE;
+ texture.wrapV = Texture.CLAMP_ADDRESSMODE;
+ const passPostProcess = new PassPostProcess("pass", 1, null, useBilinearMode ? Texture.BILINEAR_SAMPLINGMODE : Texture.NEAREST_SAMPLINGMODE, engine, false, 0);
+ passPostProcess.externalTextureSamplerBinding = true;
+ passPostProcess.onEffectCreatedObservable.addOnce((e) => {
+ e.executeWhenCompiled(() => {
+ passPostProcess.onApply = function (effect) {
+ effect.setTexture("textureSampler", texture);
+ };
+ const internalTexture = rtt.renderTarget;
+ if (internalTexture) {
+ scene.postProcessManager.directRender([passPostProcess], internalTexture);
+ engine.unBindFramebuffer(internalTexture);
+ rtt.disposeFramebufferObjects();
+ passPostProcess.dispose();
+ rtt.getInternalTexture().isReady = true;
+ }
+ });
+ });
+ return rtt;
+}
+/**
+ * Apply a post process to a texture
+ * @param postProcessName name of the fragment post process
+ * @param internalTexture the texture to encode
+ * @param scene the scene hosting the texture
+ * @param type type of the output texture. If not provided, use the one from internalTexture
+ * @param samplingMode sampling mode to use to sample the source texture. If not provided, use the one from internalTexture
+ * @param format format of the output texture. If not provided, use the one from internalTexture
+ * @param width width of the output texture. If not provided, use the one from internalTexture
+ * @param height height of the output texture. If not provided, use the one from internalTexture
+ * @returns a promise with the internalTexture having its texture replaced by the result of the processing
+ */
+function ApplyPostProcess(postProcessName, internalTexture, scene, type, samplingMode, format, width, height) {
+ // Gets everything ready.
+ const engine = internalTexture.getEngine();
+ internalTexture.isReady = false;
+ samplingMode = samplingMode ?? internalTexture.samplingMode;
+ type = type ?? internalTexture.type;
+ format = format ?? internalTexture.format;
+ width = width ?? internalTexture.width;
+ height = height ?? internalTexture.height;
+ if (type === -1) {
+ type = 0;
+ }
+ return new Promise((resolve) => {
+ // Create the post process
+ const postProcess = new PostProcess("postprocess", postProcessName, null, null, 1, null, samplingMode, engine, false, undefined, type, undefined, null, false, format);
+ postProcess.externalTextureSamplerBinding = true;
+ // Hold the output of the decoding.
+ const encodedTexture = engine.createRenderTargetTexture({ width: width, height: height }, {
+ generateDepthBuffer: false,
+ generateMipMaps: false,
+ generateStencilBuffer: false,
+ samplingMode,
+ type,
+ format,
+ });
+ postProcess.onEffectCreatedObservable.addOnce((e) => {
+ e.executeWhenCompiled(() => {
+ // PP Render Pass
+ postProcess.onApply = (effect) => {
+ effect._bindTexture("textureSampler", internalTexture);
+ effect.setFloat2("scale", 1, 1);
+ };
+ scene.postProcessManager.directRender([postProcess], encodedTexture, true);
+ // Cleanup
+ engine.restoreDefaultFramebuffer();
+ engine._releaseTexture(internalTexture);
+ if (postProcess) {
+ postProcess.dispose();
+ }
+ // Internal Swap
+ encodedTexture._swapAndDie(internalTexture);
+ // Ready to get rolling again.
+ internalTexture.type = type;
+ internalTexture.format = 5;
+ internalTexture.isReady = true;
+ resolve(internalTexture);
+ });
+ });
+ });
+}
+// ref: http://stackoverflow.com/questions/32633585/how-do-you-convert-to-half-floats-in-javascript
+let floatView;
+let int32View;
+/**
+ * Converts a number to half float
+ * @param value number to convert
+ * @returns converted number
+ */
+function ToHalfFloat$1(value) {
+ if (!floatView) {
+ floatView = new Float32Array(1);
+ int32View = new Int32Array(floatView.buffer);
+ }
+ floatView[0] = value;
+ const x = int32View[0];
+ let bits = (x >> 16) & 0x8000; /* Get the sign */
+ let m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
+ const e = (x >> 23) & 0xff; /* Using int is faster here */
+ /* If zero, or denormal, or exponent underflows too much for a denormal
+ * half, return signed zero. */
+ if (e < 103) {
+ return bits;
+ }
+ /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
+ if (e > 142) {
+ bits |= 0x7c00;
+ /* If exponent was 0xff and one mantissa bit was set, it means NaN,
+ * not Inf, so make sure we set one mantissa bit too. */
+ bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
+ return bits;
+ }
+ /* If exponent underflows but not too much, return a denormal */
+ if (e < 113) {
+ m |= 0x0800;
+ /* Extra rounding may overflow and set mantissa to 0 and exponent
+ * to 1, which is OK. */
+ bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
+ return bits;
+ }
+ bits |= ((e - 112) << 10) | (m >> 1);
+ bits += m & 1;
+ return bits;
+}
+/**
+ * Converts a half float to a number
+ * @param value half float to convert
+ * @returns converted half float
+ */
+function FromHalfFloat(value) {
+ const s = (value & 0x8000) >> 15;
+ const e = (value & 0x7c00) >> 10;
+ const f = value & 0x03ff;
+ if (e === 0) {
+ return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
+ }
+ else if (e == 0x1f) {
+ return f ? NaN : (s ? -1 : 1) * Infinity;
+ }
+ return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + f / Math.pow(2, 10));
+}
+const ProcessAsync = async (texture, width, height, face, lod) => {
+ const scene = texture.getScene();
+ const engine = scene.getEngine();
+ if (!engine.isWebGPU) {
+ if (texture.isCube) {
+ await Promise.resolve().then(() => lodCube_fragment$1);
+ }
+ else {
+ await Promise.resolve().then(() => lod_fragment$1);
+ }
+ }
+ else {
+ if (texture.isCube) {
+ await Promise.resolve().then(() => lodCube_fragment);
+ }
+ else {
+ await Promise.resolve().then(() => lod_fragment);
+ }
+ }
+ let lodPostProcess;
+ if (!texture.isCube) {
+ lodPostProcess = new PostProcess("lod", "lod", {
+ uniforms: ["lod", "gamma"],
+ samplingMode: Texture.NEAREST_NEAREST_MIPNEAREST,
+ engine,
+ shaderLanguage: engine.isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */,
+ });
+ }
+ else {
+ const faceDefines = ["#define POSITIVEX", "#define NEGATIVEX", "#define POSITIVEY", "#define NEGATIVEY", "#define POSITIVEZ", "#define NEGATIVEZ"];
+ lodPostProcess = new PostProcess("lodCube", "lodCube", {
+ uniforms: ["lod", "gamma"],
+ samplingMode: Texture.NEAREST_NEAREST_MIPNEAREST,
+ engine,
+ defines: faceDefines[face],
+ shaderLanguage: engine.isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */,
+ });
+ }
+ await new Promise((resolve) => {
+ lodPostProcess.onEffectCreatedObservable.addOnce((e) => {
+ e.executeWhenCompiled(() => {
+ resolve(0);
+ });
+ });
+ });
+ const rtt = new RenderTargetTexture("temp", { width: width, height: height }, scene, false);
+ lodPostProcess.onApply = function (effect) {
+ effect.setTexture("textureSampler", texture);
+ effect.setFloat("lod", lod);
+ effect.setInt("gamma", texture.gammaSpace ? 1 : 0);
+ };
+ const internalTexture = texture.getInternalTexture();
+ try {
+ if (rtt.renderTarget && internalTexture) {
+ const samplingMode = internalTexture.samplingMode;
+ if (lod !== 0) {
+ texture.updateSamplingMode(Texture.NEAREST_NEAREST_MIPNEAREST);
+ }
+ else {
+ texture.updateSamplingMode(Texture.NEAREST_NEAREST);
+ }
+ scene.postProcessManager.directRender([lodPostProcess], rtt.renderTarget, true);
+ texture.updateSamplingMode(samplingMode);
+ //Reading datas from WebGL
+ const bufferView = await engine.readPixels(0, 0, width, height);
+ const data = new Uint8Array(bufferView.buffer, 0, bufferView.byteLength);
+ // Unbind
+ engine.unBindFramebuffer(rtt.renderTarget);
+ return data;
+ }
+ else {
+ throw Error("Render to texture failed.");
+ }
+ }
+ finally {
+ rtt.dispose();
+ lodPostProcess.dispose();
+ }
+};
+/**
+ * Gets the data of the specified texture by rendering it to an intermediate RGBA texture and retrieving the bytes from it.
+ * This is convienent to get 8-bit RGBA values for a texture in a GPU compressed format.
+ * @param texture the source texture
+ * @param width the width of the result, which does not have to match the source texture width
+ * @param height the height of the result, which does not have to match the source texture height
+ * @param face if the texture has multiple faces, the face index to use for the source
+ * @param lod if the texture has multiple LODs, the lod index to use for the source
+ * @returns the 8-bit texture data
+ */
+async function GetTextureDataAsync(texture, width, height, face = 0, lod = 0) {
+ if (!texture.isReady() && texture._texture) {
+ await new Promise((resolve, reject) => {
+ if (texture._texture === null) {
+ reject(0);
+ return;
+ }
+ texture._texture.onLoadedObservable.addOnce(() => {
+ resolve(0);
+ });
+ });
+ }
+ return await ProcessAsync(texture, width, height, face, lod);
+}
+/**
+ * Class used to host texture specific utilities
+ */
+const TextureTools = {
+ /**
+ * Uses the GPU to create a copy texture rescaled at a given size
+ * @param texture Texture to copy from
+ * @param width defines the desired width
+ * @param height defines the desired height
+ * @param useBilinearMode defines if bilinear mode has to be used
+ * @returns the generated texture
+ */
+ CreateResizedCopy,
+ /**
+ * Apply a post process to a texture
+ * @param postProcessName name of the fragment post process
+ * @param internalTexture the texture to encode
+ * @param scene the scene hosting the texture
+ * @param type type of the output texture. If not provided, use the one from internalTexture
+ * @param samplingMode sampling mode to use to sample the source texture. If not provided, use the one from internalTexture
+ * @param format format of the output texture. If not provided, use the one from internalTexture
+ * @returns a promise with the internalTexture having its texture replaced by the result of the processing
+ */
+ ApplyPostProcess,
+ /**
+ * Converts a number to half float
+ * @param value number to convert
+ * @returns converted number
+ */
+ ToHalfFloat: ToHalfFloat$1,
+ /**
+ * Converts a half float to a number
+ * @param value half float to convert
+ * @returns converted half float
+ */
+ FromHalfFloat,
+ /**
+ * Gets the data of the specified texture by rendering it to an intermediate RGBA texture and retrieving the bytes from it.
+ * This is convienent to get 8-bit RGBA values for a texture in a GPU compressed format.
+ * @param texture the source texture
+ * @param width the width of the result, which does not have to match the source texture width
+ * @param height the height of the result, which does not have to match the source texture height
+ * @param face if the texture has multiple faces, the face index to use for the source
+ * @param channels a filter for which of the RGBA channels to return in the result
+ * @param lod if the texture has multiple LODs, the lod index to use for the source
+ * @returns the 8-bit texture data
+ */
+ GetTextureDataAsync,
+};
+
+/**
+ * Class used to host RGBD texture specific utilities
+ */
+class RGBDTextureTools {
+ /**
+ * Expand the RGBD Texture from RGBD to Half Float if possible.
+ * @param texture the texture to expand.
+ */
+ static ExpandRGBDTexture(texture) {
+ const internalTexture = texture._texture;
+ if (!internalTexture || !texture.isRGBD) {
+ return;
+ }
+ // Gets everything ready.
+ const engine = internalTexture.getEngine();
+ const caps = engine.getCaps();
+ const isReady = internalTexture.isReady;
+ let expandTexture = false;
+ // If half float available we can uncompress the texture
+ if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
+ expandTexture = true;
+ internalTexture.type = 2;
+ }
+ // If full float available we can uncompress the texture
+ else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
+ expandTexture = true;
+ internalTexture.type = 1;
+ }
+ if (expandTexture) {
+ // Do not use during decode.
+ internalTexture.isReady = false;
+ internalTexture._isRGBD = false;
+ internalTexture.invertY = false;
+ }
+ const expandRGBDTexture = async () => {
+ const isWebGPU = engine.isWebGPU;
+ const shaderLanguage = isWebGPU ? 1 /* ShaderLanguage.WGSL */ : 0 /* ShaderLanguage.GLSL */;
+ internalTexture.isReady = false;
+ if (isWebGPU) {
+ await Promise.resolve().then(() => rgbdDecode_fragment);
+ }
+ else {
+ await Promise.resolve().then(() => rgbdDecode_fragment$1);
+ }
+ // Expand the texture if possible
+ // Simply run through the decode PP.
+ const rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, undefined, internalTexture.type, undefined, null, false, undefined, shaderLanguage);
+ rgbdPostProcess.externalTextureSamplerBinding = true;
+ // Hold the output of the decoding.
+ const expandedTexture = engine.createRenderTargetTexture(internalTexture.width, {
+ generateDepthBuffer: false,
+ generateMipMaps: false,
+ generateStencilBuffer: false,
+ samplingMode: internalTexture.samplingMode,
+ type: internalTexture.type,
+ format: 5,
+ });
+ rgbdPostProcess.onEffectCreatedObservable.addOnce((e) => {
+ e.executeWhenCompiled(() => {
+ // PP Render Pass
+ rgbdPostProcess.onApply = (effect) => {
+ effect._bindTexture("textureSampler", internalTexture);
+ effect.setFloat2("scale", 1, 1);
+ };
+ texture.getScene().postProcessManager.directRender([rgbdPostProcess], expandedTexture, true);
+ // Cleanup
+ engine.restoreDefaultFramebuffer();
+ engine._releaseTexture(internalTexture);
+ if (rgbdPostProcess) {
+ rgbdPostProcess.dispose();
+ }
+ // Internal Swap
+ expandedTexture._swapAndDie(internalTexture);
+ // Ready to get rolling again.
+ internalTexture.isReady = true;
+ });
+ });
+ };
+ if (expandTexture) {
+ if (isReady) {
+ expandRGBDTexture();
+ }
+ else {
+ texture.onLoadObservable.addOnce(expandRGBDTexture);
+ }
+ }
+ }
+ /**
+ * Encode the texture to RGBD if possible.
+ * @param internalTexture the texture to encode
+ * @param scene the scene hosting the texture
+ * @param outputTextureType type of the texture in which the encoding is performed
+ * @returns a promise with the internalTexture having its texture replaced by the result of the processing
+ */
+ static async EncodeTextureToRGBD(internalTexture, scene, outputTextureType = 0) {
+ if (!scene.getEngine().isWebGPU) {
+ await Promise.resolve().then(() => rgbdEncode_fragment$1);
+ }
+ else {
+ await Promise.resolve().then(() => rgbdEncode_fragment);
+ }
+ return ApplyPostProcess("rgbdEncode", internalTexture, scene, outputTextureType, 1, 5);
+ }
+}
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const _environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==";
+let _instanceNumber = 0;
+/**
+ * Gets a default environment BRDF for MS-BRDF Height Correlated BRDF
+ * @param scene defines the hosting scene
+ * @returns the environment BRDF texture
+ */
+const GetEnvironmentBRDFTexture = (scene) => {
+ if (!scene.environmentBRDFTexture) {
+ // Forces Delayed Texture Loading to prevent undefined error whilst setting RGBD values.
+ const useDelayedTextureLoading = scene.useDelayedTextureLoading;
+ scene.useDelayedTextureLoading = false;
+ const previousState = scene._blockEntityCollection;
+ scene._blockEntityCollection = false;
+ const texture = Texture.CreateFromBase64String(_environmentBRDFBase64Texture, "EnvironmentBRDFTexture" + _instanceNumber++, scene, true, false, Texture.BILINEAR_SAMPLINGMODE);
+ scene._blockEntityCollection = previousState;
+ // BRDF Texture should not be cached here due to pre processing and redundant scene caches.
+ const texturesCache = scene.getEngine().getLoadedTexturesCache();
+ const index = texturesCache.indexOf(texture.getInternalTexture());
+ if (index !== -1) {
+ texturesCache.splice(index, 1);
+ }
+ texture.isRGBD = true;
+ texture.wrapU = Texture.CLAMP_ADDRESSMODE;
+ texture.wrapV = Texture.CLAMP_ADDRESSMODE;
+ scene.environmentBRDFTexture = texture;
+ scene.useDelayedTextureLoading = useDelayedTextureLoading;
+ RGBDTextureTools.ExpandRGBDTexture(texture);
+ const observer = scene.getEngine().onContextRestoredObservable.add(() => {
+ texture.isRGBD = true;
+ /**
+ * Using scene.onBeforeRenderObservable instead of Tools.SetImmediate to check the texture's state of readiness allows us to check before any rendering occurs.
+ * When a context restore occurs, it gives ExpandRGBDTexture the ability to reset the state to false, preventing the texture from being used in any rendering.
+ * In WebGPU, not doing so would generate an error because ExpandRGBDTexture performs a _swapAndDie on the texture, which causes WebGPU caches to fail if the texture has already been used for rendering.
+ * Only when ExpandRGBDTexture has finished its work, the texture is ready to be used again.
+ */
+ const oo = scene.onBeforeRenderObservable.add(() => {
+ if (texture.isReady()) {
+ scene.onBeforeRenderObservable.remove(oo);
+ RGBDTextureTools.ExpandRGBDTexture(texture);
+ }
+ });
+ });
+ scene.onDisposeObservable.add(() => {
+ scene.getEngine().onContextRestoredObservable.remove(observer);
+ });
+ }
+ return scene.environmentBRDFTexture;
+};
+
+/**
+ * @internal
+ */
+class MaterialBRDFDefines extends MaterialDefines {
+ constructor() {
+ super(...arguments);
+ this.BRDF_V_HEIGHT_CORRELATED = false;
+ this.MS_BRDF_ENERGY_CONSERVATION = false;
+ this.SPHERICAL_HARMONICS = false;
+ this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = false;
+ this.MIX_IBL_RADIANCE_WITH_IRRADIANCE = true;
+ }
+}
+/**
+ * Plugin that implements the BRDF component of the PBR material
+ */
+class PBRBRDFConfiguration extends MaterialPluginBase {
+ /** @internal */
+ _markAllSubMeshesAsMiscDirty() {
+ this._internalMarkAllSubMeshesAsMiscDirty();
+ }
+ /**
+ * Gets a boolean indicating that the plugin is compatible with a given shader language.
+ * @returns true if the plugin is compatible with the shader language
+ */
+ isCompatible() {
+ return true;
+ }
+ constructor(material, addToPluginList = true) {
+ super(material, "PBRBRDF", 90, new MaterialBRDFDefines(), addToPluginList);
+ this._useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;
+ /**
+ * Defines if the material uses energy conservation.
+ */
+ this.useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;
+ this._useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;
+ /**
+ * LEGACY Mode set to false
+ * Defines if the material uses height smith correlated visibility term.
+ * If you intent to not use our default BRDF, you need to load a separate BRDF Texture for the PBR
+ * You can either load https://assets.babylonjs.com/environments/uncorrelatedBRDF.png
+ * or https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds to have more precision
+ * Not relying on height correlated will also disable energy conservation.
+ */
+ this.useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;
+ this._useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;
+ /**
+ * LEGACY Mode set to false
+ * Defines if the material uses spherical harmonics vs spherical polynomials for the
+ * diffuse part of the IBL.
+ * The harmonics despite a tiny bigger cost has been proven to provide closer results
+ * to the ground truth.
+ */
+ this.useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;
+ this._useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;
+ /**
+ * Defines if the material uses energy conservation, when the specular workflow is active.
+ * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)).
+ * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1.
+ * In the deactivated case, the material author has to ensure energy conservation, for a physically plausible rendering.
+ */
+ this.useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;
+ this._mixIblRadianceWithIrradiance = PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE;
+ /**
+ * Defines if IBL irradiance is used to augment rough radiance.
+ * If activated, irradiance is blended into the radiance contribution when the material is rough.
+ * This better approximates raytracing results for rough surfaces.
+ */
+ this.mixIblRadianceWithIrradiance = PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE;
+ this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16];
+ this._enable(true);
+ }
+ prepareDefines(defines) {
+ defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated;
+ defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated;
+ defines.SPHERICAL_HARMONICS = this._useSphericalHarmonics;
+ defines.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = this._useSpecularGlossinessInputEnergyConservation;
+ defines.MIX_IBL_RADIANCE_WITH_IRRADIANCE = this._mixIblRadianceWithIrradiance;
+ }
+ getClassName() {
+ return "PBRBRDFConfiguration";
+ }
+}
+/**
+ * Default value used for the energy conservation.
+ * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture.
+ */
+PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true;
+/**
+ * Default value used for the Smith Visibility Height Correlated mode.
+ * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture.
+ */
+PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true;
+/**
+ * Default value used for the IBL diffuse part.
+ * This can help switching back to the polynomials mode globally which is a tiny bit
+ * less GPU intensive at the drawback of a lower quality.
+ */
+PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS = true;
+/**
+ * Default value used for activating energy conservation for the specular workflow.
+ * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)).
+ * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1.
+ */
+PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = true;
+/**
+ * Default value for whether IBL irradiance is used to augment rough radiance.
+ * If activated, irradiance is blended into the radiance contribution when the material is rough.
+ * This better approximates raytracing results for rough surfaces.
+ */
+PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE = true;
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRBRDFConfiguration.prototype, "useEnergyConservation", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRBRDFConfiguration.prototype, "useSmithVisibilityHeightCorrelated", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRBRDFConfiguration.prototype, "useSphericalHarmonics", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRBRDFConfiguration.prototype, "useSpecularGlossinessInputEnergyConservation", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRBRDFConfiguration.prototype, "mixIblRadianceWithIrradiance", void 0);
+
+class FileFaceOrientation {
+ constructor(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
+ this.name = name;
+ this.worldAxisForNormal = worldAxisForNormal;
+ this.worldAxisForFileX = worldAxisForFileX;
+ this.worldAxisForFileY = worldAxisForFileY;
+ }
+}
+/**
+ * Helper class dealing with the extraction of spherical polynomial dataArray
+ * from a cube map.
+ */
+class CubeMapToSphericalPolynomialTools {
+ /**
+ * Converts a texture to the according Spherical Polynomial data.
+ * This extracts the first 3 orders only as they are the only one used in the lighting.
+ *
+ * @param texture The texture to extract the information from.
+ * @returns The Spherical Polynomial data.
+ */
+ static ConvertCubeMapTextureToSphericalPolynomial(texture) {
+ if (!texture.isCube) {
+ // Only supports cube Textures currently.
+ return null;
+ }
+ texture.getScene()?.getEngine().flushFramebuffer();
+ const size = texture.getSize().width;
+ const rightPromise = texture.readPixels(0, undefined, undefined, false);
+ const leftPromise = texture.readPixels(1, undefined, undefined, false);
+ let upPromise;
+ let downPromise;
+ if (texture.isRenderTarget) {
+ upPromise = texture.readPixels(3, undefined, undefined, false);
+ downPromise = texture.readPixels(2, undefined, undefined, false);
+ }
+ else {
+ upPromise = texture.readPixels(2, undefined, undefined, false);
+ downPromise = texture.readPixels(3, undefined, undefined, false);
+ }
+ const frontPromise = texture.readPixels(4, undefined, undefined, false);
+ const backPromise = texture.readPixels(5, undefined, undefined, false);
+ const gammaSpace = texture.gammaSpace;
+ // Always read as RGBA.
+ const format = 5;
+ let type = 0;
+ if (texture.textureType == 1 || texture.textureType == 2) {
+ type = 1;
+ }
+ return new Promise((resolve) => {
+ Promise.all([leftPromise, rightPromise, upPromise, downPromise, frontPromise, backPromise]).then(([left, right, up, down, front, back]) => {
+ const cubeInfo = {
+ size,
+ right,
+ left,
+ up,
+ down,
+ front,
+ back,
+ format,
+ type,
+ gammaSpace,
+ };
+ resolve(this.ConvertCubeMapToSphericalPolynomial(cubeInfo));
+ });
+ });
+ }
+ /**
+ * Compute the area on the unit sphere of the rectangle defined by (x,y) and the origin
+ * See https://www.rorydriscoll.com/2012/01/15/cubemap-texel-solid-angle/
+ * @param x
+ * @param y
+ * @returns the area
+ */
+ static _AreaElement(x, y) {
+ return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
+ }
+ /**
+ * Converts a cubemap to the according Spherical Polynomial data.
+ * This extracts the first 3 orders only as they are the only one used in the lighting.
+ *
+ * @param cubeInfo The Cube map to extract the information from.
+ * @returns The Spherical Polynomial data.
+ */
+ static ConvertCubeMapToSphericalPolynomial(cubeInfo) {
+ const sphericalHarmonics = new SphericalHarmonics();
+ let totalSolidAngle = 0.0;
+ // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
+ const du = 2.0 / cubeInfo.size;
+ const dv = du;
+ const halfTexel = 0.5 * du;
+ // The (u,v) of the first texel is half a texel from the corner (-1,-1).
+ const minUV = halfTexel - 1.0;
+ for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
+ const fileFace = this._FileFaces[faceIndex];
+ const dataArray = cubeInfo[fileFace.name];
+ let v = minUV;
+ // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
+ // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
+ // Because SP is still linear, so summation is fine in that basis.
+ const stride = cubeInfo.format === 5 ? 4 : 3;
+ for (let y = 0; y < cubeInfo.size; y++) {
+ let u = minUV;
+ for (let x = 0; x < cubeInfo.size; x++) {
+ // World direction (not normalised)
+ const worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
+ worldDirection.normalize();
+ const deltaSolidAngle = this._AreaElement(u - halfTexel, v - halfTexel) -
+ this._AreaElement(u - halfTexel, v + halfTexel) -
+ this._AreaElement(u + halfTexel, v - halfTexel) +
+ this._AreaElement(u + halfTexel, v + halfTexel);
+ let r = dataArray[y * cubeInfo.size * stride + x * stride + 0];
+ let g = dataArray[y * cubeInfo.size * stride + x * stride + 1];
+ let b = dataArray[y * cubeInfo.size * stride + x * stride + 2];
+ // Prevent NaN harmonics with extreme HDRI data.
+ if (isNaN(r)) {
+ r = 0;
+ }
+ if (isNaN(g)) {
+ g = 0;
+ }
+ if (isNaN(b)) {
+ b = 0;
+ }
+ // Handle Integer types.
+ if (cubeInfo.type === 0) {
+ r /= 255;
+ g /= 255;
+ b /= 255;
+ }
+ // Handle Gamma space textures.
+ if (cubeInfo.gammaSpace) {
+ r = Math.pow(Clamp(r), ToLinearSpace);
+ g = Math.pow(Clamp(g), ToLinearSpace);
+ b = Math.pow(Clamp(b), ToLinearSpace);
+ }
+ // Prevent to explode in case of really high dynamic ranges.
+ // sh 3 would not be enough to accurately represent it.
+ const max = this.MAX_HDRI_VALUE;
+ if (this.PRESERVE_CLAMPED_COLORS) {
+ const currentMax = Math.max(r, g, b);
+ if (currentMax > max) {
+ const factor = max / currentMax;
+ r *= factor;
+ g *= factor;
+ b *= factor;
+ }
+ }
+ else {
+ r = Clamp(r, 0, max);
+ g = Clamp(g, 0, max);
+ b = Clamp(b, 0, max);
+ }
+ const color = new Color3(r, g, b);
+ sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
+ totalSolidAngle += deltaSolidAngle;
+ u += du;
+ }
+ v += dv;
+ }
+ }
+ // Solid angle for entire sphere is 4*pi
+ const sphereSolidAngle = 4.0 * Math.PI;
+ // Adjust the solid angle to allow for how many faces we processed.
+ const facesProcessed = 6.0;
+ const expectedSolidAngle = (sphereSolidAngle * facesProcessed) / 6.0;
+ // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
+ // This is needed because the numerical integration over the cube uses a
+ // small angle approximation of solid angle for each texel (see deltaSolidAngle),
+ // and also to compensate for accumulative error due to float precision in the summation.
+ const correctionFactor = expectedSolidAngle / totalSolidAngle;
+ sphericalHarmonics.scaleInPlace(correctionFactor);
+ sphericalHarmonics.convertIncidentRadianceToIrradiance();
+ sphericalHarmonics.convertIrradianceToLambertianRadiance();
+ return SphericalPolynomial.FromHarmonics(sphericalHarmonics);
+ }
+}
+CubeMapToSphericalPolynomialTools._FileFaces = [
+ new FileFaceOrientation("right", new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)), // +X east
+ new FileFaceOrientation("left", new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, -1, 0)), // -X west
+ new FileFaceOrientation("up", new Vector3(0, 1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, 1)), // +Y north
+ new FileFaceOrientation("down", new Vector3(0, -1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, -1)), // -Y south
+ new FileFaceOrientation("front", new Vector3(0, 0, 1), new Vector3(1, 0, 0), new Vector3(0, -1, 0)), // +Z top
+ new FileFaceOrientation("back", new Vector3(0, 0, -1), new Vector3(-1, 0, 0), new Vector3(0, -1, 0)), // -Z bottom
+];
+/** @internal */
+CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE = 4096;
+/** @internal */
+CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS = false;
+
+BaseTexture.prototype.forceSphericalPolynomialsRecompute = function () {
+ if (this._texture) {
+ this._texture._sphericalPolynomial = null;
+ this._texture._sphericalPolynomialPromise = null;
+ this._texture._sphericalPolynomialComputed = false;
+ }
+};
+Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
+ get: function () {
+ if (this._texture) {
+ if (this._texture._sphericalPolynomial || this._texture._sphericalPolynomialComputed) {
+ return this._texture._sphericalPolynomial;
+ }
+ if (this._texture.isReady) {
+ if (!this._texture._sphericalPolynomialPromise) {
+ this._texture._sphericalPolynomialPromise = CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
+ if (this._texture._sphericalPolynomialPromise === null) {
+ this._texture._sphericalPolynomialComputed = true;
+ }
+ else {
+ this._texture._sphericalPolynomialPromise.then((sphericalPolynomial) => {
+ this._texture._sphericalPolynomial = sphericalPolynomial;
+ this._texture._sphericalPolynomialComputed = true;
+ });
+ }
+ }
+ return null;
+ }
+ }
+ return null;
+ },
+ set: function (value) {
+ if (this._texture) {
+ this._texture._sphericalPolynomial = value;
+ }
+ },
+ enumerable: true,
+ configurable: true,
+});
+
+/**
+ * @internal
+ */
+class MaterialClearCoatDefines extends MaterialDefines {
+ constructor() {
+ super(...arguments);
+ this.CLEARCOAT = false;
+ this.CLEARCOAT_DEFAULTIOR = false;
+ this.CLEARCOAT_TEXTURE = false;
+ this.CLEARCOAT_TEXTURE_ROUGHNESS = false;
+ this.CLEARCOAT_TEXTUREDIRECTUV = 0;
+ this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0;
+ this.CLEARCOAT_BUMP = false;
+ this.CLEARCOAT_BUMPDIRECTUV = 0;
+ this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false;
+ this.CLEARCOAT_REMAP_F0 = false;
+ this.CLEARCOAT_TINT = false;
+ this.CLEARCOAT_TINT_TEXTURE = false;
+ this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;
+ this.CLEARCOAT_TINT_GAMMATEXTURE = false;
+ }
+}
+/**
+ * Plugin that implements the clear coat component of the PBR material
+ */
+class PBRClearCoatConfiguration extends MaterialPluginBase {
+ /** @internal */
+ _markAllSubMeshesAsTexturesDirty() {
+ this._enable(this._isEnabled);
+ this._internalMarkAllSubMeshesAsTexturesDirty();
+ }
+ /**
+ * Gets a boolean indicating that the plugin is compatible with a given shader language.
+ * @returns true if the plugin is compatible with the shader language
+ */
+ isCompatible() {
+ return true;
+ }
+ constructor(material, addToPluginList = true) {
+ super(material, "PBRClearCoat", 100, new MaterialClearCoatDefines(), addToPluginList);
+ this._isEnabled = false;
+ /**
+ * Defines if the clear coat is enabled in the material.
+ */
+ this.isEnabled = false;
+ /**
+ * Defines the clear coat layer strength (between 0 and 1) it defaults to 1.
+ */
+ this.intensity = 1;
+ /**
+ * Defines the clear coat layer roughness.
+ */
+ this.roughness = 0;
+ this._indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;
+ /**
+ * Defines the index of refraction of the clear coat.
+ * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence
+ * The default fits with a polyurethane material.
+ * Changing the default value is more performance intensive.
+ */
+ this.indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;
+ this._texture = null;
+ /**
+ * Stores the clear coat values in a texture (red channel is intensity and green channel is roughness)
+ * If useRoughnessFromMainTexture is false, the green channel of texture is not used and the green channel of textureRoughness is used instead
+ * if textureRoughness is not empty, else no texture roughness is used
+ */
+ this.texture = null;
+ this._useRoughnessFromMainTexture = true;
+ /**
+ * Indicates that the green channel of the texture property will be used for roughness (default: true)
+ * If false, the green channel from textureRoughness is used for roughness
+ */
+ this.useRoughnessFromMainTexture = true;
+ this._textureRoughness = null;
+ /**
+ * Stores the clear coat roughness in a texture (green channel)
+ * Not used if useRoughnessFromMainTexture is true
+ */
+ this.textureRoughness = null;
+ this._remapF0OnInterfaceChange = true;
+ /**
+ * Defines if the F0 value should be remapped to account for the interface change in the material.
+ */
+ this.remapF0OnInterfaceChange = true;
+ this._bumpTexture = null;
+ /**
+ * Define the clear coat specific bump texture.
+ */
+ this.bumpTexture = null;
+ this._isTintEnabled = false;
+ /**
+ * Defines if the clear coat tint is enabled in the material.
+ */
+ this.isTintEnabled = false;
+ /**
+ * Defines the clear coat tint of the material.
+ * This is only use if tint is enabled
+ */
+ this.tintColor = Color3.White();
+ /**
+ * Defines the distance at which the tint color should be found in the
+ * clear coat media.
+ * This is only use if tint is enabled
+ */
+ this.tintColorAtDistance = 1;
+ /**
+ * Defines the clear coat layer thickness.
+ * This is only use if tint is enabled
+ */
+ this.tintThickness = 1;
+ this._tintTexture = null;
+ /**
+ * Stores the clear tint values in a texture.
+ * rgb is tint
+ * a is a thickness factor
+ */
+ this.tintTexture = null;
+ this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
+ }
+ isReadyForSubMesh(defines, scene, engine) {
+ if (!this._isEnabled) {
+ return true;
+ }
+ const disableBumpMap = this._material._disableBumpMap;
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {
+ if (!this._texture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) {
+ if (!this._textureRoughness.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) {
+ // Bump texture cannot be not blocking.
+ if (!this._bumpTexture.isReady()) {
+ return false;
+ }
+ }
+ if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {
+ if (!this._tintTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+ prepareDefinesBeforeAttributes(defines, scene) {
+ if (this._isEnabled) {
+ defines.CLEARCOAT = true;
+ defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture;
+ defines.CLEARCOAT_REMAP_F0 = this._remapF0OnInterfaceChange;
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {
+ PrepareDefinesForMergedUV(this._texture, defines, "CLEARCOAT_TEXTURE");
+ }
+ else {
+ defines.CLEARCOAT_TEXTURE = false;
+ }
+ if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) {
+ PrepareDefinesForMergedUV(this._textureRoughness, defines, "CLEARCOAT_TEXTURE_ROUGHNESS");
+ }
+ else {
+ defines.CLEARCOAT_TEXTURE_ROUGHNESS = false;
+ }
+ if (this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled) {
+ PrepareDefinesForMergedUV(this._bumpTexture, defines, "CLEARCOAT_BUMP");
+ }
+ else {
+ defines.CLEARCOAT_BUMP = false;
+ }
+ defines.CLEARCOAT_DEFAULTIOR = this._indexOfRefraction === PBRClearCoatConfiguration._DefaultIndexOfRefraction;
+ if (this._isTintEnabled) {
+ defines.CLEARCOAT_TINT = true;
+ if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {
+ PrepareDefinesForMergedUV(this._tintTexture, defines, "CLEARCOAT_TINT_TEXTURE");
+ defines.CLEARCOAT_TINT_GAMMATEXTURE = this._tintTexture.gammaSpace;
+ }
+ else {
+ defines.CLEARCOAT_TINT_TEXTURE = false;
+ }
+ }
+ else {
+ defines.CLEARCOAT_TINT = false;
+ defines.CLEARCOAT_TINT_TEXTURE = false;
+ }
+ }
+ }
+ }
+ else {
+ defines.CLEARCOAT = false;
+ defines.CLEARCOAT_TEXTURE = false;
+ defines.CLEARCOAT_TEXTURE_ROUGHNESS = false;
+ defines.CLEARCOAT_BUMP = false;
+ defines.CLEARCOAT_TINT = false;
+ defines.CLEARCOAT_TINT_TEXTURE = false;
+ defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false;
+ defines.CLEARCOAT_DEFAULTIOR = false;
+ defines.CLEARCOAT_TEXTUREDIRECTUV = 0;
+ defines.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0;
+ defines.CLEARCOAT_BUMPDIRECTUV = 0;
+ defines.CLEARCOAT_REMAP_F0 = false;
+ defines.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;
+ defines.CLEARCOAT_TINT_GAMMATEXTURE = false;
+ }
+ }
+ bindForSubMesh(uniformBuffer, scene, engine, subMesh) {
+ if (!this._isEnabled) {
+ return;
+ }
+ const defines = subMesh.materialDefines;
+ const isFrozen = this._material.isFrozen;
+ const disableBumpMap = this._material._disableBumpMap;
+ const invertNormalMapX = this._material._invertNormalMapX;
+ const invertNormalMapY = this._material._invertNormalMapY;
+ if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
+ if ((this._texture || this._textureRoughness) && MaterialFlags.ClearCoatTextureEnabled) {
+ uniformBuffer.updateFloat4("vClearCoatInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._textureRoughness?.coordinatesIndex ?? 0, this._textureRoughness?.level ?? 0);
+ if (this._texture) {
+ BindTextureMatrix(this._texture, uniformBuffer, "clearCoat");
+ }
+ if (this._textureRoughness && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) {
+ BindTextureMatrix(this._textureRoughness, uniformBuffer, "clearCoatRoughness");
+ }
+ }
+ if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatTextureEnabled && !disableBumpMap) {
+ uniformBuffer.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level);
+ BindTextureMatrix(this._bumpTexture, uniformBuffer, "clearCoatBump");
+ if (scene._mirroredCameraPosition) {
+ uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? 1.0 : -1, invertNormalMapY ? 1.0 : -1);
+ }
+ else {
+ uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? -1 : 1.0, invertNormalMapY ? -1 : 1.0);
+ }
+ }
+ if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {
+ uniformBuffer.updateFloat2("vClearCoatTintInfos", this._tintTexture.coordinatesIndex, this._tintTexture.level);
+ BindTextureMatrix(this._tintTexture, uniformBuffer, "clearCoatTint");
+ }
+ // Clear Coat General params
+ uniformBuffer.updateFloat2("vClearCoatParams", this.intensity, this.roughness);
+ // Clear Coat Refraction params
+ const a = 1 - this._indexOfRefraction;
+ const b = 1 + this._indexOfRefraction;
+ const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1.
+ const eta = 1 / this._indexOfRefraction;
+ uniformBuffer.updateFloat4("vClearCoatRefractionParams", f0, eta, a, b);
+ if (this._isTintEnabled) {
+ uniformBuffer.updateFloat4("vClearCoatTintParams", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness));
+ uniformBuffer.updateFloat("clearCoatColorAtDistance", Math.max(0.00001, this.tintColorAtDistance));
+ }
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {
+ uniformBuffer.setTexture("clearCoatSampler", this._texture);
+ }
+ if (this._textureRoughness && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.ClearCoatTextureEnabled) {
+ uniformBuffer.setTexture("clearCoatRoughnessSampler", this._textureRoughness);
+ }
+ if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) {
+ uniformBuffer.setTexture("clearCoatBumpSampler", this._bumpTexture);
+ }
+ if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {
+ uniformBuffer.setTexture("clearCoatTintSampler", this._tintTexture);
+ }
+ }
+ }
+ hasTexture(texture) {
+ if (this._texture === texture) {
+ return true;
+ }
+ if (this._textureRoughness === texture) {
+ return true;
+ }
+ if (this._bumpTexture === texture) {
+ return true;
+ }
+ if (this._tintTexture === texture) {
+ return true;
+ }
+ return false;
+ }
+ getActiveTextures(activeTextures) {
+ if (this._texture) {
+ activeTextures.push(this._texture);
+ }
+ if (this._textureRoughness) {
+ activeTextures.push(this._textureRoughness);
+ }
+ if (this._bumpTexture) {
+ activeTextures.push(this._bumpTexture);
+ }
+ if (this._tintTexture) {
+ activeTextures.push(this._tintTexture);
+ }
+ }
+ getAnimatables(animatables) {
+ if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
+ animatables.push(this._texture);
+ }
+ if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) {
+ animatables.push(this._textureRoughness);
+ }
+ if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
+ animatables.push(this._bumpTexture);
+ }
+ if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) {
+ animatables.push(this._tintTexture);
+ }
+ }
+ dispose(forceDisposeTextures) {
+ if (forceDisposeTextures) {
+ this._texture?.dispose();
+ this._textureRoughness?.dispose();
+ this._bumpTexture?.dispose();
+ this._tintTexture?.dispose();
+ }
+ }
+ getClassName() {
+ return "PBRClearCoatConfiguration";
+ }
+ addFallbacks(defines, fallbacks, currentRank) {
+ if (defines.CLEARCOAT_BUMP) {
+ fallbacks.addFallback(currentRank++, "CLEARCOAT_BUMP");
+ }
+ if (defines.CLEARCOAT_TINT) {
+ fallbacks.addFallback(currentRank++, "CLEARCOAT_TINT");
+ }
+ if (defines.CLEARCOAT) {
+ fallbacks.addFallback(currentRank++, "CLEARCOAT");
+ }
+ return currentRank;
+ }
+ getSamplers(samplers) {
+ samplers.push("clearCoatSampler", "clearCoatRoughnessSampler", "clearCoatBumpSampler", "clearCoatTintSampler");
+ }
+ getUniforms() {
+ return {
+ ubo: [
+ { name: "vClearCoatParams", size: 2, type: "vec2" },
+ { name: "vClearCoatRefractionParams", size: 4, type: "vec4" },
+ { name: "vClearCoatInfos", size: 4, type: "vec4" },
+ { name: "clearCoatMatrix", size: 16, type: "mat4" },
+ { name: "clearCoatRoughnessMatrix", size: 16, type: "mat4" },
+ { name: "vClearCoatBumpInfos", size: 2, type: "vec2" },
+ { name: "vClearCoatTangentSpaceParams", size: 2, type: "vec2" },
+ { name: "clearCoatBumpMatrix", size: 16, type: "mat4" },
+ { name: "vClearCoatTintParams", size: 4, type: "vec4" },
+ { name: "clearCoatColorAtDistance", size: 1, type: "float" },
+ { name: "vClearCoatTintInfos", size: 2, type: "vec2" },
+ { name: "clearCoatTintMatrix", size: 16, type: "mat4" },
+ ],
+ };
+ }
+}
+/**
+ * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence
+ * The default fits with a polyurethane material.
+ * @internal
+ */
+PBRClearCoatConfiguration._DefaultIndexOfRefraction = 1.5;
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "isEnabled", void 0);
+__decorate([
+ serialize()
+], PBRClearCoatConfiguration.prototype, "intensity", void 0);
+__decorate([
+ serialize()
+], PBRClearCoatConfiguration.prototype, "roughness", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "indexOfRefraction", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "texture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "useRoughnessFromMainTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "textureRoughness", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "remapF0OnInterfaceChange", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "bumpTexture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "isTintEnabled", void 0);
+__decorate([
+ serializeAsColor3()
+], PBRClearCoatConfiguration.prototype, "tintColor", void 0);
+__decorate([
+ serialize()
+], PBRClearCoatConfiguration.prototype, "tintColorAtDistance", void 0);
+__decorate([
+ serialize()
+], PBRClearCoatConfiguration.prototype, "tintThickness", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRClearCoatConfiguration.prototype, "tintTexture", void 0);
+
+/**
+ * @internal
+ */
+class MaterialIridescenceDefines extends MaterialDefines {
+ constructor() {
+ super(...arguments);
+ this.IRIDESCENCE = false;
+ this.IRIDESCENCE_TEXTURE = false;
+ this.IRIDESCENCE_TEXTUREDIRECTUV = 0;
+ this.IRIDESCENCE_THICKNESS_TEXTURE = false;
+ this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0;
+ }
+}
+/**
+ * Plugin that implements the iridescence (thin film) component of the PBR material
+ */
+class PBRIridescenceConfiguration extends MaterialPluginBase {
+ /** @internal */
+ _markAllSubMeshesAsTexturesDirty() {
+ this._enable(this._isEnabled);
+ this._internalMarkAllSubMeshesAsTexturesDirty();
+ }
+ /**
+ * Gets a boolean indicating that the plugin is compatible with a given shader language.
+ * @returns true if the plugin is compatible with the shader language
+ */
+ isCompatible() {
+ return true;
+ }
+ constructor(material, addToPluginList = true) {
+ super(material, "PBRIridescence", 110, new MaterialIridescenceDefines(), addToPluginList);
+ this._isEnabled = false;
+ /**
+ * Defines if the iridescence is enabled in the material.
+ */
+ this.isEnabled = false;
+ /**
+ * Defines the iridescence layer strength (between 0 and 1) it defaults to 1.
+ */
+ this.intensity = 1;
+ /**
+ * Defines the minimum thickness of the thin-film layer given in nanometers (nm).
+ */
+ this.minimumThickness = PBRIridescenceConfiguration._DefaultMinimumThickness;
+ /**
+ * Defines the maximum thickness of the thin-film layer given in nanometers (nm). This will be the thickness used if not thickness texture has been set.
+ */
+ this.maximumThickness = PBRIridescenceConfiguration._DefaultMaximumThickness;
+ /**
+ * Defines the maximum thickness of the thin-film layer given in nanometers (nm).
+ */
+ this.indexOfRefraction = PBRIridescenceConfiguration._DefaultIndexOfRefraction;
+ this._texture = null;
+ /**
+ * Stores the iridescence intensity in a texture (red channel)
+ */
+ this.texture = null;
+ this._thicknessTexture = null;
+ /**
+ * Stores the iridescence thickness in a texture (green channel)
+ */
+ this.thicknessTexture = null;
+ this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
+ }
+ isReadyForSubMesh(defines, scene) {
+ if (!this._isEnabled) {
+ return true;
+ }
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.IridescenceTextureEnabled) {
+ if (!this._texture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {
+ if (!this._thicknessTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+ prepareDefinesBeforeAttributes(defines, scene) {
+ if (this._isEnabled) {
+ defines.IRIDESCENCE = true;
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.IridescenceTextureEnabled) {
+ PrepareDefinesForMergedUV(this._texture, defines, "IRIDESCENCE_TEXTURE");
+ }
+ else {
+ defines.IRIDESCENCE_TEXTURE = false;
+ }
+ if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {
+ PrepareDefinesForMergedUV(this._thicknessTexture, defines, "IRIDESCENCE_THICKNESS_TEXTURE");
+ }
+ else {
+ defines.IRIDESCENCE_THICKNESS_TEXTURE = false;
+ }
+ }
+ }
+ }
+ else {
+ defines.IRIDESCENCE = false;
+ defines.IRIDESCENCE_TEXTURE = false;
+ defines.IRIDESCENCE_THICKNESS_TEXTURE = false;
+ defines.IRIDESCENCE_TEXTUREDIRECTUV = 0;
+ defines.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0;
+ }
+ }
+ bindForSubMesh(uniformBuffer, scene) {
+ if (!this._isEnabled) {
+ return;
+ }
+ const isFrozen = this._material.isFrozen;
+ if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
+ if ((this._texture || this._thicknessTexture) && MaterialFlags.IridescenceTextureEnabled) {
+ uniformBuffer.updateFloat4("vIridescenceInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._thicknessTexture?.coordinatesIndex ?? 0, this._thicknessTexture?.level ?? 0);
+ if (this._texture) {
+ BindTextureMatrix(this._texture, uniformBuffer, "iridescence");
+ }
+ if (this._thicknessTexture) {
+ BindTextureMatrix(this._thicknessTexture, uniformBuffer, "iridescenceThickness");
+ }
+ }
+ // Clear Coat General params
+ uniformBuffer.updateFloat4("vIridescenceParams", this.intensity, this.indexOfRefraction, this.minimumThickness, this.maximumThickness);
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.IridescenceTextureEnabled) {
+ uniformBuffer.setTexture("iridescenceSampler", this._texture);
+ }
+ if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {
+ uniformBuffer.setTexture("iridescenceThicknessSampler", this._thicknessTexture);
+ }
+ }
+ }
+ hasTexture(texture) {
+ if (this._texture === texture) {
+ return true;
+ }
+ if (this._thicknessTexture === texture) {
+ return true;
+ }
+ return false;
+ }
+ getActiveTextures(activeTextures) {
+ if (this._texture) {
+ activeTextures.push(this._texture);
+ }
+ if (this._thicknessTexture) {
+ activeTextures.push(this._thicknessTexture);
+ }
+ }
+ getAnimatables(animatables) {
+ if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
+ animatables.push(this._texture);
+ }
+ if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {
+ animatables.push(this._thicknessTexture);
+ }
+ }
+ dispose(forceDisposeTextures) {
+ if (forceDisposeTextures) {
+ this._texture?.dispose();
+ this._thicknessTexture?.dispose();
+ }
+ }
+ getClassName() {
+ return "PBRIridescenceConfiguration";
+ }
+ addFallbacks(defines, fallbacks, currentRank) {
+ if (defines.IRIDESCENCE) {
+ fallbacks.addFallback(currentRank++, "IRIDESCENCE");
+ }
+ return currentRank;
+ }
+ getSamplers(samplers) {
+ samplers.push("iridescenceSampler", "iridescenceThicknessSampler");
+ }
+ getUniforms() {
+ return {
+ ubo: [
+ { name: "vIridescenceParams", size: 4, type: "vec4" },
+ { name: "vIridescenceInfos", size: 4, type: "vec4" },
+ { name: "iridescenceMatrix", size: 16, type: "mat4" },
+ { name: "iridescenceThicknessMatrix", size: 16, type: "mat4" },
+ ],
+ };
+ }
+}
+/**
+ * The default minimum thickness of the thin-film layer given in nanometers (nm).
+ * Defaults to 100 nm.
+ * @internal
+ */
+PBRIridescenceConfiguration._DefaultMinimumThickness = 100;
+/**
+ * The default maximum thickness of the thin-film layer given in nanometers (nm).
+ * Defaults to 400 nm.
+ * @internal
+ */
+PBRIridescenceConfiguration._DefaultMaximumThickness = 400;
+/**
+ * The default index of refraction of the thin-film layer.
+ * Defaults to 1.3
+ * @internal
+ */
+PBRIridescenceConfiguration._DefaultIndexOfRefraction = 1.3;
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRIridescenceConfiguration.prototype, "isEnabled", void 0);
+__decorate([
+ serialize()
+], PBRIridescenceConfiguration.prototype, "intensity", void 0);
+__decorate([
+ serialize()
+], PBRIridescenceConfiguration.prototype, "minimumThickness", void 0);
+__decorate([
+ serialize()
+], PBRIridescenceConfiguration.prototype, "maximumThickness", void 0);
+__decorate([
+ serialize()
+], PBRIridescenceConfiguration.prototype, "indexOfRefraction", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRIridescenceConfiguration.prototype, "texture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRIridescenceConfiguration.prototype, "thicknessTexture", void 0);
+
+/**
+ * @internal
+ */
+class MaterialAnisotropicDefines extends MaterialDefines {
+ constructor() {
+ super(...arguments);
+ this.ANISOTROPIC = false;
+ this.ANISOTROPIC_TEXTURE = false;
+ this.ANISOTROPIC_TEXTUREDIRECTUV = 0;
+ this.ANISOTROPIC_LEGACY = false;
+ this.MAINUV1 = false;
+ }
+}
+/**
+ * Plugin that implements the anisotropic component of the PBR material
+ */
+class PBRAnisotropicConfiguration extends MaterialPluginBase {
+ /**
+ * Sets the anisotropy direction as an angle.
+ */
+ set angle(value) {
+ this.direction.x = Math.cos(value);
+ this.direction.y = Math.sin(value);
+ }
+ /**
+ * Gets the anisotropy angle value in radians.
+ * @returns the anisotropy angle value in radians.
+ */
+ get angle() {
+ return Math.atan2(this.direction.y, this.direction.x);
+ }
+ /** @internal */
+ _markAllSubMeshesAsTexturesDirty() {
+ this._enable(this._isEnabled);
+ this._internalMarkAllSubMeshesAsTexturesDirty();
+ }
+ /** @internal */
+ _markAllSubMeshesAsMiscDirty() {
+ this._enable(this._isEnabled);
+ this._internalMarkAllSubMeshesAsMiscDirty();
+ }
+ /**
+ * Gets a boolean indicating that the plugin is compatible with a given shader language.
+ * @returns true if the plugin is compatible with the shader language
+ */
+ isCompatible() {
+ return true;
+ }
+ constructor(material, addToPluginList = true) {
+ super(material, "PBRAnisotropic", 110, new MaterialAnisotropicDefines(), addToPluginList);
+ this._isEnabled = false;
+ /**
+ * Defines if the anisotropy is enabled in the material.
+ */
+ this.isEnabled = false;
+ /**
+ * Defines the anisotropy strength (between 0 and 1) it defaults to 1.
+ */
+ this.intensity = 1;
+ /**
+ * Defines if the effect is along the tangents, bitangents or in between.
+ * By default, the effect is "stretching" the highlights along the tangents.
+ */
+ this.direction = new Vector2(1, 0);
+ this._texture = null;
+ /**
+ * Stores the anisotropy values in a texture.
+ * rg is direction (like normal from -1 to 1)
+ * b is a intensity
+ */
+ this.texture = null;
+ this._legacy = false;
+ /**
+ * Defines if the anisotropy is in legacy mode for backwards compatibility before 6.4.0.
+ */
+ this.legacy = false;
+ this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
+ this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16];
+ }
+ isReadyForSubMesh(defines, scene) {
+ if (!this._isEnabled) {
+ return true;
+ }
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {
+ if (!this._texture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+ prepareDefinesBeforeAttributes(defines, scene, mesh) {
+ if (this._isEnabled) {
+ defines.ANISOTROPIC = this._isEnabled;
+ if (this._isEnabled && !mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {
+ defines._needUVs = true;
+ defines.MAINUV1 = true;
+ }
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {
+ PrepareDefinesForMergedUV(this._texture, defines, "ANISOTROPIC_TEXTURE");
+ }
+ else {
+ defines.ANISOTROPIC_TEXTURE = false;
+ }
+ }
+ }
+ if (defines._areMiscDirty) {
+ defines.ANISOTROPIC_LEGACY = this._legacy;
+ }
+ }
+ else {
+ defines.ANISOTROPIC = false;
+ defines.ANISOTROPIC_TEXTURE = false;
+ defines.ANISOTROPIC_TEXTUREDIRECTUV = 0;
+ defines.ANISOTROPIC_LEGACY = false;
+ }
+ }
+ bindForSubMesh(uniformBuffer, scene) {
+ if (!this._isEnabled) {
+ return;
+ }
+ const isFrozen = this._material.isFrozen;
+ if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
+ if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {
+ uniformBuffer.updateFloat2("vAnisotropyInfos", this._texture.coordinatesIndex, this._texture.level);
+ BindTextureMatrix(this._texture, uniformBuffer, "anisotropy");
+ }
+ // Anisotropy
+ uniformBuffer.updateFloat3("vAnisotropy", this.direction.x, this.direction.y, this.intensity);
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {
+ uniformBuffer.setTexture("anisotropySampler", this._texture);
+ }
+ }
+ }
+ hasTexture(texture) {
+ if (this._texture === texture) {
+ return true;
+ }
+ return false;
+ }
+ getActiveTextures(activeTextures) {
+ if (this._texture) {
+ activeTextures.push(this._texture);
+ }
+ }
+ getAnimatables(animatables) {
+ if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
+ animatables.push(this._texture);
+ }
+ }
+ dispose(forceDisposeTextures) {
+ if (forceDisposeTextures) {
+ if (this._texture) {
+ this._texture.dispose();
+ }
+ }
+ }
+ getClassName() {
+ return "PBRAnisotropicConfiguration";
+ }
+ addFallbacks(defines, fallbacks, currentRank) {
+ if (defines.ANISOTROPIC) {
+ fallbacks.addFallback(currentRank++, "ANISOTROPIC");
+ }
+ return currentRank;
+ }
+ getSamplers(samplers) {
+ samplers.push("anisotropySampler");
+ }
+ getUniforms() {
+ return {
+ ubo: [
+ { name: "vAnisotropy", size: 3, type: "vec3" },
+ { name: "vAnisotropyInfos", size: 2, type: "vec2" },
+ { name: "anisotropyMatrix", size: 16, type: "mat4" },
+ ],
+ };
+ }
+ /**
+ * Parses a anisotropy Configuration from a serialized object.
+ * @param source - Serialized object.
+ * @param scene Defines the scene we are parsing for
+ * @param rootUrl Defines the rootUrl to load from
+ */
+ parse(source, scene, rootUrl) {
+ super.parse(source, scene, rootUrl);
+ // Backward compatibility
+ if (source.legacy === undefined) {
+ this.legacy = true;
+ }
+ }
+}
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRAnisotropicConfiguration.prototype, "isEnabled", void 0);
+__decorate([
+ serialize()
+], PBRAnisotropicConfiguration.prototype, "intensity", void 0);
+__decorate([
+ serializeAsVector2()
+], PBRAnisotropicConfiguration.prototype, "direction", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRAnisotropicConfiguration.prototype, "texture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRAnisotropicConfiguration.prototype, "legacy", void 0);
+
+/**
+ * @internal
+ */
+class MaterialSheenDefines extends MaterialDefines {
+ constructor() {
+ super(...arguments);
+ this.SHEEN = false;
+ this.SHEEN_TEXTURE = false;
+ this.SHEEN_GAMMATEXTURE = false;
+ this.SHEEN_TEXTURE_ROUGHNESS = false;
+ this.SHEEN_TEXTUREDIRECTUV = 0;
+ this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0;
+ this.SHEEN_LINKWITHALBEDO = false;
+ this.SHEEN_ROUGHNESS = false;
+ this.SHEEN_ALBEDOSCALING = false;
+ this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false;
+ }
+}
+/**
+ * Plugin that implements the sheen component of the PBR material.
+ */
+class PBRSheenConfiguration extends MaterialPluginBase {
+ /** @internal */
+ _markAllSubMeshesAsTexturesDirty() {
+ this._enable(this._isEnabled);
+ this._internalMarkAllSubMeshesAsTexturesDirty();
+ }
+ /**
+ * Gets a boolean indicating that the plugin is compatible with a given shader language.
+ * @returns true if the plugin is compatible with the shader language
+ */
+ isCompatible() {
+ return true;
+ }
+ constructor(material, addToPluginList = true) {
+ super(material, "Sheen", 120, new MaterialSheenDefines(), addToPluginList);
+ this._isEnabled = false;
+ /**
+ * Defines if the material uses sheen.
+ */
+ this.isEnabled = false;
+ this._linkSheenWithAlbedo = false;
+ /**
+ * Defines if the sheen is linked to the sheen color.
+ */
+ this.linkSheenWithAlbedo = false;
+ /**
+ * Defines the sheen intensity.
+ */
+ this.intensity = 1;
+ /**
+ * Defines the sheen color.
+ */
+ this.color = Color3.White();
+ this._texture = null;
+ /**
+ * Stores the sheen tint values in a texture.
+ * rgb is tint
+ * a is a intensity or roughness if the roughness property has been defined and useRoughnessFromTexture is true (in that case, textureRoughness won't be used)
+ * If the roughness property has been defined and useRoughnessFromTexture is false then the alpha channel is not used to modulate roughness
+ */
+ this.texture = null;
+ this._useRoughnessFromMainTexture = true;
+ /**
+ * Indicates that the alpha channel of the texture property will be used for roughness.
+ * Has no effect if the roughness (and texture!) property is not defined
+ */
+ this.useRoughnessFromMainTexture = true;
+ this._roughness = null;
+ /**
+ * Defines the sheen roughness.
+ * It is not taken into account if linkSheenWithAlbedo is true.
+ * To stay backward compatible, material roughness is used instead if sheen roughness = null
+ */
+ this.roughness = null;
+ this._textureRoughness = null;
+ /**
+ * Stores the sheen roughness in a texture.
+ * alpha channel is the roughness. This texture won't be used if the texture property is not empty and useRoughnessFromTexture is true
+ */
+ this.textureRoughness = null;
+ this._albedoScaling = false;
+ /**
+ * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique.
+ * It allows the strength of the sheen effect to not depend on the base color of the material,
+ * making it easier to setup and tweak the effect
+ */
+ this.albedoScaling = false;
+ this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
+ }
+ isReadyForSubMesh(defines, scene) {
+ if (!this._isEnabled) {
+ return true;
+ }
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.SheenTextureEnabled) {
+ if (!this._texture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) {
+ if (!this._textureRoughness.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+ prepareDefinesBeforeAttributes(defines, scene) {
+ if (this._isEnabled) {
+ defines.SHEEN = true;
+ defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo;
+ defines.SHEEN_ROUGHNESS = this._roughness !== null;
+ defines.SHEEN_ALBEDOSCALING = this._albedoScaling;
+ defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture;
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.SheenTextureEnabled) {
+ PrepareDefinesForMergedUV(this._texture, defines, "SHEEN_TEXTURE");
+ defines.SHEEN_GAMMATEXTURE = this._texture.gammaSpace;
+ }
+ else {
+ defines.SHEEN_TEXTURE = false;
+ }
+ if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) {
+ PrepareDefinesForMergedUV(this._textureRoughness, defines, "SHEEN_TEXTURE_ROUGHNESS");
+ }
+ else {
+ defines.SHEEN_TEXTURE_ROUGHNESS = false;
+ }
+ }
+ }
+ }
+ else {
+ defines.SHEEN = false;
+ defines.SHEEN_TEXTURE = false;
+ defines.SHEEN_TEXTURE_ROUGHNESS = false;
+ defines.SHEEN_LINKWITHALBEDO = false;
+ defines.SHEEN_ROUGHNESS = false;
+ defines.SHEEN_ALBEDOSCALING = false;
+ defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false;
+ defines.SHEEN_GAMMATEXTURE = false;
+ defines.SHEEN_TEXTUREDIRECTUV = 0;
+ defines.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0;
+ }
+ }
+ bindForSubMesh(uniformBuffer, scene, engine, subMesh) {
+ if (!this._isEnabled) {
+ return;
+ }
+ const defines = subMesh.materialDefines;
+ const isFrozen = this._material.isFrozen;
+ if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
+ if ((this._texture || this._textureRoughness) && MaterialFlags.SheenTextureEnabled) {
+ uniformBuffer.updateFloat4("vSheenInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._textureRoughness?.coordinatesIndex ?? 0, this._textureRoughness?.level ?? 0);
+ if (this._texture) {
+ BindTextureMatrix(this._texture, uniformBuffer, "sheen");
+ }
+ if (this._textureRoughness && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) {
+ BindTextureMatrix(this._textureRoughness, uniformBuffer, "sheenRoughness");
+ }
+ }
+ // Sheen
+ uniformBuffer.updateFloat4("vSheenColor", this.color.r, this.color.g, this.color.b, this.intensity);
+ if (this._roughness !== null) {
+ uniformBuffer.updateFloat("vSheenRoughness", this._roughness);
+ }
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._texture && MaterialFlags.SheenTextureEnabled) {
+ uniformBuffer.setTexture("sheenSampler", this._texture);
+ }
+ if (this._textureRoughness && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.SheenTextureEnabled) {
+ uniformBuffer.setTexture("sheenRoughnessSampler", this._textureRoughness);
+ }
+ }
+ }
+ hasTexture(texture) {
+ if (this._texture === texture) {
+ return true;
+ }
+ if (this._textureRoughness === texture) {
+ return true;
+ }
+ return false;
+ }
+ getActiveTextures(activeTextures) {
+ if (this._texture) {
+ activeTextures.push(this._texture);
+ }
+ if (this._textureRoughness) {
+ activeTextures.push(this._textureRoughness);
+ }
+ }
+ getAnimatables(animatables) {
+ if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
+ animatables.push(this._texture);
+ }
+ if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) {
+ animatables.push(this._textureRoughness);
+ }
+ }
+ dispose(forceDisposeTextures) {
+ if (forceDisposeTextures) {
+ this._texture?.dispose();
+ this._textureRoughness?.dispose();
+ }
+ }
+ getClassName() {
+ return "PBRSheenConfiguration";
+ }
+ addFallbacks(defines, fallbacks, currentRank) {
+ if (defines.SHEEN) {
+ fallbacks.addFallback(currentRank++, "SHEEN");
+ }
+ return currentRank;
+ }
+ getSamplers(samplers) {
+ samplers.push("sheenSampler", "sheenRoughnessSampler");
+ }
+ getUniforms() {
+ return {
+ ubo: [
+ { name: "vSheenColor", size: 4, type: "vec4" },
+ { name: "vSheenRoughness", size: 1, type: "float" },
+ { name: "vSheenInfos", size: 4, type: "vec4" },
+ { name: "sheenMatrix", size: 16, type: "mat4" },
+ { name: "sheenRoughnessMatrix", size: 16, type: "mat4" },
+ ],
+ };
+ }
+}
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSheenConfiguration.prototype, "isEnabled", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSheenConfiguration.prototype, "linkSheenWithAlbedo", void 0);
+__decorate([
+ serialize()
+], PBRSheenConfiguration.prototype, "intensity", void 0);
+__decorate([
+ serializeAsColor3()
+], PBRSheenConfiguration.prototype, "color", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSheenConfiguration.prototype, "texture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSheenConfiguration.prototype, "useRoughnessFromMainTexture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSheenConfiguration.prototype, "roughness", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSheenConfiguration.prototype, "textureRoughness", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSheenConfiguration.prototype, "albedoScaling", void 0);
+
+/**
+ * @internal
+ */
+class MaterialSubSurfaceDefines extends MaterialDefines {
+ constructor() {
+ super(...arguments);
+ this.SUBSURFACE = false;
+ this.SS_REFRACTION = false;
+ this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false;
+ this.SS_TRANSLUCENCY = false;
+ this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false;
+ this.SS_SCATTERING = false;
+ this.SS_DISPERSION = false;
+ this.SS_THICKNESSANDMASK_TEXTURE = false;
+ this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;
+ this.SS_HAS_THICKNESS = false;
+ this.SS_REFRACTIONINTENSITY_TEXTURE = false;
+ this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0;
+ this.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;
+ this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0;
+ this.SS_TRANSLUCENCYCOLOR_TEXTURE = false;
+ this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV = 0;
+ this.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = false;
+ this.SS_REFRACTIONMAP_3D = false;
+ this.SS_REFRACTIONMAP_OPPOSITEZ = false;
+ this.SS_LODINREFRACTIONALPHA = false;
+ this.SS_GAMMAREFRACTION = false;
+ this.SS_RGBDREFRACTION = false;
+ this.SS_LINEARSPECULARREFRACTION = false;
+ this.SS_LINKREFRACTIONTOTRANSPARENCY = false;
+ this.SS_ALBEDOFORREFRACTIONTINT = false;
+ this.SS_ALBEDOFORTRANSLUCENCYTINT = false;
+ this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;
+ this.SS_USE_THICKNESS_AS_DEPTH = false;
+ this.SS_USE_GLTF_TEXTURES = false;
+ }
+}
+/**
+ * Plugin that implements the sub surface component of the PBR material
+ */
+class PBRSubSurfaceConfiguration extends MaterialPluginBase {
+ /**
+ * Diffusion profile for subsurface scattering.
+ * Useful for better scattering in the skins or foliages.
+ */
+ get scatteringDiffusionProfile() {
+ if (!this._scene.subSurfaceConfiguration) {
+ return null;
+ }
+ return this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex];
+ }
+ set scatteringDiffusionProfile(c) {
+ if (!this._scene.enableSubSurfaceForPrePass()) {
+ // Not supported
+ return;
+ }
+ // addDiffusionProfile automatically checks for doubles
+ if (c) {
+ this._scatteringDiffusionProfileIndex = this._scene.subSurfaceConfiguration.addDiffusionProfile(c);
+ }
+ }
+ /**
+ * Index of refraction of the material's volume.
+ * https://en.wikipedia.org/wiki/List_of_refractive_indices
+ *
+ * This ONLY impacts refraction. If not provided or given a non-valid value,
+ * the volume will use the same IOR as the surface.
+ */
+ get volumeIndexOfRefraction() {
+ if (this._volumeIndexOfRefraction >= 1.0) {
+ return this._volumeIndexOfRefraction;
+ }
+ return this._indexOfRefraction;
+ }
+ set volumeIndexOfRefraction(value) {
+ if (value >= 1.0) {
+ this._volumeIndexOfRefraction = value;
+ }
+ else {
+ this._volumeIndexOfRefraction = -1;
+ }
+ }
+ /** @internal */
+ _markAllSubMeshesAsTexturesDirty() {
+ this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled);
+ this._internalMarkAllSubMeshesAsTexturesDirty();
+ }
+ /** @internal */
+ _markScenePrePassDirty() {
+ this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled);
+ this._internalMarkAllSubMeshesAsTexturesDirty();
+ this._internalMarkScenePrePassDirty();
+ }
+ /**
+ * Gets a boolean indicating that the plugin is compatible with a given shader language.
+ * @returns true if the plugin is compatible with the shader language
+ */
+ isCompatible() {
+ return true;
+ }
+ constructor(material, addToPluginList = true) {
+ super(material, "PBRSubSurface", 130, new MaterialSubSurfaceDefines(), addToPluginList);
+ this._isRefractionEnabled = false;
+ /**
+ * Defines if the refraction is enabled in the material.
+ */
+ this.isRefractionEnabled = false;
+ this._isTranslucencyEnabled = false;
+ /**
+ * Defines if the translucency is enabled in the material.
+ */
+ this.isTranslucencyEnabled = false;
+ this._isDispersionEnabled = false;
+ /**
+ * Defines if dispersion is enabled in the material.
+ */
+ this.isDispersionEnabled = false;
+ this._isScatteringEnabled = false;
+ /**
+ * Defines if the sub surface scattering is enabled in the material.
+ */
+ this.isScatteringEnabled = false;
+ this._scatteringDiffusionProfileIndex = 0;
+ /**
+ * Defines the refraction intensity of the material.
+ * The refraction when enabled replaces the Diffuse part of the material.
+ * The intensity helps transitioning between diffuse and refraction.
+ */
+ this.refractionIntensity = 1;
+ /**
+ * Defines the translucency intensity of the material.
+ * When translucency has been enabled, this defines how much of the "translucency"
+ * is added to the diffuse part of the material.
+ */
+ this.translucencyIntensity = 1;
+ /**
+ * When enabled, transparent surfaces will be tinted with the albedo colour (independent of thickness)
+ */
+ this.useAlbedoToTintRefraction = false;
+ /**
+ * When enabled, translucent surfaces will be tinted with the albedo colour (independent of thickness)
+ */
+ this.useAlbedoToTintTranslucency = false;
+ this._thicknessTexture = null;
+ /**
+ * Stores the average thickness of a mesh in a texture (The texture is holding the values linearly).
+ * The red (or green if useGltfStyleTextures=true) channel of the texture should contain the thickness remapped between 0 and 1.
+ * 0 would mean minimumThickness
+ * 1 would mean maximumThickness
+ * The other channels might be use as a mask to vary the different effects intensity.
+ */
+ this.thicknessTexture = null;
+ this._refractionTexture = null;
+ /**
+ * Defines the texture to use for refraction.
+ */
+ this.refractionTexture = null;
+ /** @internal */
+ this._indexOfRefraction = 1.5;
+ /**
+ * Index of refraction of the material base layer.
+ * https://en.wikipedia.org/wiki/List_of_refractive_indices
+ *
+ * This does not only impact refraction but also the Base F0 of Dielectric Materials.
+ *
+ * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI))
+ */
+ this.indexOfRefraction = 1.5;
+ this._volumeIndexOfRefraction = -1;
+ this._invertRefractionY = false;
+ /**
+ * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
+ */
+ this.invertRefractionY = false;
+ /** @internal */
+ this._linkRefractionWithTransparency = false;
+ /**
+ * This parameters will make the material used its opacity to control how much it is refracting against not.
+ * Materials half opaque for instance using refraction could benefit from this control.
+ */
+ this.linkRefractionWithTransparency = false;
+ /**
+ * Defines the minimum thickness stored in the thickness map.
+ * If no thickness map is defined, this value will be used to simulate thickness.
+ */
+ this.minimumThickness = 0;
+ /**
+ * Defines the maximum thickness stored in the thickness map.
+ */
+ this.maximumThickness = 1;
+ /**
+ * Defines that the thickness should be used as a measure of the depth volume.
+ */
+ this.useThicknessAsDepth = false;
+ /**
+ * Defines the volume tint of the material.
+ * This is used for both translucency and scattering.
+ */
+ this.tintColor = Color3.White();
+ /**
+ * Defines the distance at which the tint color should be found in the media.
+ * This is used for refraction only.
+ */
+ this.tintColorAtDistance = 1;
+ /**
+ * Defines the Abbe number for the volume.
+ */
+ this.dispersion = 0;
+ /**
+ * Defines how far each channel transmit through the media.
+ * It is defined as a color to simplify it selection.
+ */
+ this.diffusionDistance = Color3.White();
+ this._useMaskFromThicknessTexture = false;
+ /**
+ * Stores the intensity of the different subsurface effects in the thickness texture.
+ * Note that if refractionIntensityTexture and/or translucencyIntensityTexture is provided it takes precedence over thicknessTexture + useMaskFromThicknessTexture
+ * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity.
+ * * the blue (alpha if useGltfStyleTextures = true) channel is the translucency intensity.
+ */
+ this.useMaskFromThicknessTexture = false;
+ this._refractionIntensityTexture = null;
+ /**
+ * Stores the intensity of the refraction. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture
+ * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity.
+ */
+ this.refractionIntensityTexture = null;
+ this._translucencyIntensityTexture = null;
+ /**
+ * Stores the intensity of the translucency. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture
+ * * the blue (alpha if useGltfStyleTextures = true) channel is the translucency intensity.
+ */
+ this.translucencyIntensityTexture = null;
+ /**
+ * Defines the translucency tint of the material.
+ * If not set, the tint color will be used instead.
+ */
+ this.translucencyColor = null;
+ this._translucencyColorTexture = null;
+ /**
+ * Defines the translucency tint color of the material as a texture.
+ * This is multiplied against the translucency color to add variety and realism to the material.
+ * If translucencyColor is not set, the tint color will be used instead.
+ */
+ this.translucencyColorTexture = null;
+ this._useGltfStyleTextures = true;
+ /**
+ * Use channels layout used by glTF:
+ * * thicknessTexture: the green (instead of red) channel is the thickness
+ * * thicknessTexture/refractionIntensityTexture: the red (instead of green) channel is the refraction intensity
+ * * thicknessTexture/translucencyIntensityTexture: the alpha (instead of blue) channel is the translucency intensity
+ */
+ this.useGltfStyleTextures = true;
+ this._scene = material.getScene();
+ this.registerForExtraEvents = true;
+ this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
+ this._internalMarkScenePrePassDirty = material._dirtyCallbacks[32];
+ }
+ isReadyForSubMesh(defines, scene) {
+ if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
+ return true;
+ }
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
+ if (!this._thicknessTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled) {
+ if (!this._translucencyColorTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled) {
+ if (!this._translucencyIntensityTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ const refractionTexture = this._getRefractionTexture(scene);
+ if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
+ if (!refractionTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+ prepareDefinesBeforeAttributes(defines, scene) {
+ if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
+ defines.SUBSURFACE = false;
+ defines.SS_DISPERSION = false;
+ defines.SS_TRANSLUCENCY = false;
+ defines.SS_SCATTERING = false;
+ defines.SS_REFRACTION = false;
+ defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false;
+ defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false;
+ defines.SS_THICKNESSANDMASK_TEXTURE = false;
+ defines.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;
+ defines.SS_HAS_THICKNESS = false;
+ defines.SS_REFRACTIONINTENSITY_TEXTURE = false;
+ defines.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0;
+ defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;
+ defines.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0;
+ defines.SS_REFRACTIONMAP_3D = false;
+ defines.SS_REFRACTIONMAP_OPPOSITEZ = false;
+ defines.SS_LODINREFRACTIONALPHA = false;
+ defines.SS_GAMMAREFRACTION = false;
+ defines.SS_RGBDREFRACTION = false;
+ defines.SS_LINEARSPECULARREFRACTION = false;
+ defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;
+ defines.SS_ALBEDOFORREFRACTIONTINT = false;
+ defines.SS_ALBEDOFORTRANSLUCENCYTINT = false;
+ defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;
+ defines.SS_USE_THICKNESS_AS_DEPTH = false;
+ defines.SS_USE_GLTF_TEXTURES = false;
+ defines.SS_TRANSLUCENCYCOLOR_TEXTURE = false;
+ defines.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV = 0;
+ defines.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = false;
+ return;
+ }
+ if (defines._areTexturesDirty) {
+ defines.SUBSURFACE = true;
+ defines.SS_DISPERSION = this._isDispersionEnabled;
+ defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled;
+ defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false;
+ defines.SS_SCATTERING = this._isScatteringEnabled;
+ defines.SS_THICKNESSANDMASK_TEXTURE = false;
+ defines.SS_REFRACTIONINTENSITY_TEXTURE = false;
+ defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;
+ defines.SS_HAS_THICKNESS = false;
+ defines.SS_USE_GLTF_TEXTURES = false;
+ defines.SS_REFRACTION = false;
+ defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false;
+ defines.SS_REFRACTIONMAP_3D = false;
+ defines.SS_GAMMAREFRACTION = false;
+ defines.SS_RGBDREFRACTION = false;
+ defines.SS_LINEARSPECULARREFRACTION = false;
+ defines.SS_REFRACTIONMAP_OPPOSITEZ = false;
+ defines.SS_LODINREFRACTIONALPHA = false;
+ defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;
+ defines.SS_ALBEDOFORREFRACTIONTINT = false;
+ defines.SS_ALBEDOFORTRANSLUCENCYTINT = false;
+ defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;
+ defines.SS_USE_THICKNESS_AS_DEPTH = false;
+ defines.SS_TRANSLUCENCYCOLOR_TEXTURE = false;
+ if (defines._areTexturesDirty) {
+ if (scene.texturesEnabled) {
+ if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
+ PrepareDefinesForMergedUV(this._thicknessTexture, defines, "SS_THICKNESSANDMASK_TEXTURE");
+ }
+ if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled) {
+ PrepareDefinesForMergedUV(this._refractionIntensityTexture, defines, "SS_REFRACTIONINTENSITY_TEXTURE");
+ }
+ if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled) {
+ PrepareDefinesForMergedUV(this._translucencyIntensityTexture, defines, "SS_TRANSLUCENCYINTENSITY_TEXTURE");
+ }
+ if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled) {
+ PrepareDefinesForMergedUV(this._translucencyColorTexture, defines, "SS_TRANSLUCENCYCOLOR_TEXTURE");
+ defines.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = this._translucencyColorTexture.gammaSpace;
+ }
+ }
+ }
+ defines.SS_HAS_THICKNESS = this.maximumThickness - this.minimumThickness !== 0.0;
+ defines.SS_USE_GLTF_TEXTURES = this._useGltfStyleTextures;
+ defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = this._useMaskFromThicknessTexture && !this._refractionIntensityTexture;
+ defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = this._useMaskFromThicknessTexture && !this._translucencyIntensityTexture;
+ if (this._isRefractionEnabled) {
+ if (scene.texturesEnabled) {
+ const refractionTexture = this._getRefractionTexture(scene);
+ if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
+ defines.SS_REFRACTION = true;
+ defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube;
+ defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace;
+ defines.SS_RGBDREFRACTION = refractionTexture.isRGBD;
+ defines.SS_LINEARSPECULARREFRACTION = refractionTexture.linearSpecularLOD;
+ defines.SS_REFRACTIONMAP_OPPOSITEZ = this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ;
+ defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
+ defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency;
+ defines.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction;
+ defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = refractionTexture.isCube && refractionTexture.boundingBoxSize;
+ defines.SS_USE_THICKNESS_AS_DEPTH = this.useThicknessAsDepth;
+ }
+ }
+ }
+ if (this._isTranslucencyEnabled) {
+ defines.SS_ALBEDOFORTRANSLUCENCYTINT = this.useAlbedoToTintTranslucency;
+ }
+ }
+ }
+ /**
+ * Binds the material data (this function is called even if mustRebind() returns false)
+ * @param uniformBuffer defines the Uniform buffer to fill in.
+ * @param scene defines the scene the material belongs to.
+ * @param engine defines the engine the material belongs to.
+ * @param subMesh the submesh to bind data for
+ */
+ hardBindForSubMesh(uniformBuffer, scene, engine, subMesh) {
+ if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
+ return;
+ }
+ // If min/max thickness is 0, avoid decompising to determine the scaled thickness (it's always zero).
+ if (this.maximumThickness === 0.0 && this.minimumThickness === 0.0) {
+ uniformBuffer.updateFloat2("vThicknessParam", 0, 0);
+ }
+ else {
+ subMesh.getRenderingMesh().getWorldMatrix().decompose(TmpVectors.Vector3[0]);
+ const thicknessScale = Math.max(Math.abs(TmpVectors.Vector3[0].x), Math.abs(TmpVectors.Vector3[0].y), Math.abs(TmpVectors.Vector3[0].z));
+ uniformBuffer.updateFloat2("vThicknessParam", this.minimumThickness * thicknessScale, (this.maximumThickness - this.minimumThickness) * thicknessScale);
+ }
+ }
+ bindForSubMesh(uniformBuffer, scene, engine, subMesh) {
+ if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
+ return;
+ }
+ const defines = subMesh.materialDefines;
+ const isFrozen = this._material.isFrozen;
+ const realTimeFiltering = this._material.realTimeFiltering;
+ const lodBasedMicrosurface = defines.LODBASEDMICROSFURACE;
+ const refractionTexture = this._getRefractionTexture(scene);
+ if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
+ if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
+ uniformBuffer.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level);
+ BindTextureMatrix(this._thicknessTexture, uniformBuffer, "thickness");
+ }
+ if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) {
+ uniformBuffer.updateFloat2("vRefractionIntensityInfos", this._refractionIntensityTexture.coordinatesIndex, this._refractionIntensityTexture.level);
+ BindTextureMatrix(this._refractionIntensityTexture, uniformBuffer, "refractionIntensity");
+ }
+ if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled && defines.SS_TRANSLUCENCYCOLOR_TEXTURE) {
+ uniformBuffer.updateFloat2("vTranslucencyColorInfos", this._translucencyColorTexture.coordinatesIndex, this._translucencyColorTexture.level);
+ BindTextureMatrix(this._translucencyColorTexture, uniformBuffer, "translucencyColor");
+ }
+ if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) {
+ uniformBuffer.updateFloat2("vTranslucencyIntensityInfos", this._translucencyIntensityTexture.coordinatesIndex, this._translucencyIntensityTexture.level);
+ BindTextureMatrix(this._translucencyIntensityTexture, uniformBuffer, "translucencyIntensity");
+ }
+ if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
+ uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getRefractionTextureMatrix());
+ let depth = 1.0;
+ if (!refractionTexture.isCube) {
+ if (refractionTexture.depth) {
+ depth = refractionTexture.depth;
+ }
+ }
+ const width = refractionTexture.getSize().width;
+ const refractionIor = this.volumeIndexOfRefraction;
+ uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, 1 / refractionIor, depth, this._invertRefractionY ? -1 : 1);
+ uniformBuffer.updateFloat4("vRefractionMicrosurfaceInfos", width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1.0 / this.indexOfRefraction);
+ if (realTimeFiltering) {
+ uniformBuffer.updateFloat2("vRefractionFilteringInfo", width, Math.log2(width));
+ }
+ if (refractionTexture.boundingBoxSize) {
+ const cubeTexture = refractionTexture;
+ uniformBuffer.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition);
+ uniformBuffer.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize);
+ }
+ }
+ if (this._isScatteringEnabled) {
+ uniformBuffer.updateFloat("scatteringDiffusionProfile", this._scatteringDiffusionProfileIndex);
+ }
+ uniformBuffer.updateColor3("vDiffusionDistance", this.diffusionDistance);
+ uniformBuffer.updateFloat4("vTintColor", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintColorAtDistance));
+ uniformBuffer.updateColor4("vTranslucencyColor", this.translucencyColor ?? this.tintColor, 0);
+ uniformBuffer.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, 0);
+ uniformBuffer.updateFloat("dispersion", this.dispersion);
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
+ uniformBuffer.setTexture("thicknessSampler", this._thicknessTexture);
+ }
+ if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) {
+ uniformBuffer.setTexture("refractionIntensitySampler", this._refractionIntensityTexture);
+ }
+ if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) {
+ uniformBuffer.setTexture("translucencyIntensitySampler", this._translucencyIntensityTexture);
+ }
+ if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled && defines.SS_TRANSLUCENCYCOLOR_TEXTURE) {
+ uniformBuffer.setTexture("translucencyColorSampler", this._translucencyColorTexture);
+ }
+ if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
+ if (lodBasedMicrosurface) {
+ uniformBuffer.setTexture("refractionSampler", refractionTexture);
+ }
+ else {
+ uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
+ uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
+ uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
+ }
+ }
+ }
+ }
+ /**
+ * Returns the texture used for refraction or null if none is used.
+ * @param scene defines the scene the material belongs to.
+ * @returns - Refraction texture if present. If no refraction texture and refraction
+ * is linked with transparency, returns environment texture. Otherwise, returns null.
+ */
+ _getRefractionTexture(scene) {
+ if (this._refractionTexture) {
+ return this._refractionTexture;
+ }
+ if (this._isRefractionEnabled) {
+ return scene.environmentTexture;
+ }
+ return null;
+ }
+ /**
+ * Returns true if alpha blending should be disabled.
+ */
+ get disableAlphaBlending() {
+ return this._isRefractionEnabled && this._linkRefractionWithTransparency;
+ }
+ /**
+ * Fills the list of render target textures.
+ * @param renderTargets the list of render targets to update
+ */
+ fillRenderTargetTextures(renderTargets) {
+ if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
+ renderTargets.push(this._refractionTexture);
+ }
+ }
+ hasTexture(texture) {
+ if (this._thicknessTexture === texture) {
+ return true;
+ }
+ if (this._refractionTexture === texture) {
+ return true;
+ }
+ if (this._refractionIntensityTexture === texture) {
+ return true;
+ }
+ if (this._translucencyIntensityTexture === texture) {
+ return true;
+ }
+ if (this._translucencyColorTexture === texture) {
+ return true;
+ }
+ return false;
+ }
+ hasRenderTargetTextures() {
+ if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
+ return true;
+ }
+ return false;
+ }
+ getActiveTextures(activeTextures) {
+ if (this._thicknessTexture) {
+ activeTextures.push(this._thicknessTexture);
+ }
+ if (this._refractionTexture) {
+ activeTextures.push(this._refractionTexture);
+ }
+ if (this._translucencyColorTexture) {
+ activeTextures.push(this._translucencyColorTexture);
+ }
+ if (this._translucencyIntensityTexture) {
+ activeTextures.push(this._translucencyIntensityTexture);
+ }
+ }
+ getAnimatables(animatables) {
+ if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {
+ animatables.push(this._thicknessTexture);
+ }
+ if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
+ animatables.push(this._refractionTexture);
+ }
+ if (this._translucencyColorTexture && this._translucencyColorTexture.animations && this._translucencyColorTexture.animations.length > 0) {
+ animatables.push(this._translucencyColorTexture);
+ }
+ if (this._translucencyIntensityTexture && this._translucencyIntensityTexture.animations && this._translucencyIntensityTexture.animations.length > 0) {
+ animatables.push(this._translucencyIntensityTexture);
+ }
+ }
+ dispose(forceDisposeTextures) {
+ if (forceDisposeTextures) {
+ if (this._thicknessTexture) {
+ this._thicknessTexture.dispose();
+ }
+ if (this._refractionTexture) {
+ this._refractionTexture.dispose();
+ }
+ if (this._translucencyColorTexture) {
+ this._translucencyColorTexture.dispose();
+ }
+ if (this._translucencyIntensityTexture) {
+ this._translucencyIntensityTexture.dispose();
+ }
+ }
+ }
+ getClassName() {
+ return "PBRSubSurfaceConfiguration";
+ }
+ addFallbacks(defines, fallbacks, currentRank) {
+ if (defines.SS_SCATTERING) {
+ fallbacks.addFallback(currentRank++, "SS_SCATTERING");
+ }
+ if (defines.SS_TRANSLUCENCY) {
+ fallbacks.addFallback(currentRank++, "SS_TRANSLUCENCY");
+ }
+ return currentRank;
+ }
+ getSamplers(samplers) {
+ samplers.push("thicknessSampler", "refractionIntensitySampler", "translucencyIntensitySampler", "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh", "translucencyColorSampler");
+ }
+ getUniforms() {
+ return {
+ ubo: [
+ { name: "vRefractionMicrosurfaceInfos", size: 4, type: "vec4" },
+ { name: "vRefractionFilteringInfo", size: 2, type: "vec2" },
+ { name: "vTranslucencyIntensityInfos", size: 2, type: "vec2" },
+ { name: "vRefractionInfos", size: 4, type: "vec4" },
+ { name: "refractionMatrix", size: 16, type: "mat4" },
+ { name: "vThicknessInfos", size: 2, type: "vec2" },
+ { name: "vRefractionIntensityInfos", size: 2, type: "vec2" },
+ { name: "thicknessMatrix", size: 16, type: "mat4" },
+ { name: "refractionIntensityMatrix", size: 16, type: "mat4" },
+ { name: "translucencyIntensityMatrix", size: 16, type: "mat4" },
+ { name: "vThicknessParam", size: 2, type: "vec2" },
+ { name: "vDiffusionDistance", size: 3, type: "vec3" },
+ { name: "vTintColor", size: 4, type: "vec4" },
+ { name: "vSubSurfaceIntensity", size: 3, type: "vec3" },
+ { name: "vRefractionPosition", size: 3, type: "vec3" },
+ { name: "vRefractionSize", size: 3, type: "vec3" },
+ { name: "scatteringDiffusionProfile", size: 1, type: "float" },
+ { name: "dispersion", size: 1, type: "float" },
+ { name: "vTranslucencyColor", size: 4, type: "vec4" },
+ { name: "vTranslucencyColorInfos", size: 2, type: "vec2" },
+ { name: "translucencyColorMatrix", size: 16, type: "mat4" },
+ ],
+ };
+ }
+}
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "isRefractionEnabled", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "isTranslucencyEnabled", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "isDispersionEnabled", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markScenePrePassDirty")
+], PBRSubSurfaceConfiguration.prototype, "isScatteringEnabled", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "_scatteringDiffusionProfileIndex", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "refractionIntensity", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "translucencyIntensity", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintRefraction", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintTranslucency", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "thicknessTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "refractionTexture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "indexOfRefraction", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "_volumeIndexOfRefraction", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "volumeIndexOfRefraction", null);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "invertRefractionY", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "linkRefractionWithTransparency", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "minimumThickness", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "maximumThickness", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "useThicknessAsDepth", void 0);
+__decorate([
+ serializeAsColor3()
+], PBRSubSurfaceConfiguration.prototype, "tintColor", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "tintColorAtDistance", void 0);
+__decorate([
+ serialize()
+], PBRSubSurfaceConfiguration.prototype, "dispersion", void 0);
+__decorate([
+ serializeAsColor3()
+], PBRSubSurfaceConfiguration.prototype, "diffusionDistance", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "useMaskFromThicknessTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "refractionIntensityTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "translucencyIntensityTexture", void 0);
+__decorate([
+ serializeAsColor3()
+], PBRSubSurfaceConfiguration.prototype, "translucencyColor", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "translucencyColorTexture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRSubSurfaceConfiguration.prototype, "useGltfStyleTextures", void 0);
+
+const onCreatedEffectParameters$1 = { effect: null, subMesh: null };
+/**
+ * Manages the defines for the PBR Material.
+ * @internal
+ */
+class PBRMaterialDefines extends MaterialDefines {
+ /**
+ * Initializes the PBR Material defines.
+ * @param externalProperties The external properties
+ */
+ constructor(externalProperties) {
+ super(externalProperties);
+ this.PBR = true;
+ this.NUM_SAMPLES = "0";
+ this.REALTIME_FILTERING = false;
+ this.IBL_CDF_FILTERING = false;
+ this.MAINUV1 = false;
+ this.MAINUV2 = false;
+ this.MAINUV3 = false;
+ this.MAINUV4 = false;
+ this.MAINUV5 = false;
+ this.MAINUV6 = false;
+ this.UV1 = false;
+ this.UV2 = false;
+ this.UV3 = false;
+ this.UV4 = false;
+ this.UV5 = false;
+ this.UV6 = false;
+ this.ALBEDO = false;
+ this.GAMMAALBEDO = false;
+ this.ALBEDODIRECTUV = 0;
+ this.VERTEXCOLOR = false;
+ this.BASEWEIGHT = false;
+ this.BASEWEIGHTDIRECTUV = 0;
+ this.BAKED_VERTEX_ANIMATION_TEXTURE = false;
+ this.AMBIENT = false;
+ this.AMBIENTDIRECTUV = 0;
+ this.AMBIENTINGRAYSCALE = false;
+ this.OPACITY = false;
+ this.VERTEXALPHA = false;
+ this.OPACITYDIRECTUV = 0;
+ this.OPACITYRGB = false;
+ this.ALPHATEST = false;
+ this.DEPTHPREPASS = false;
+ this.ALPHABLEND = false;
+ this.ALPHAFROMALBEDO = false;
+ this.ALPHATESTVALUE = "0.5";
+ this.SPECULAROVERALPHA = false;
+ this.RADIANCEOVERALPHA = false;
+ this.ALPHAFRESNEL = false;
+ this.LINEARALPHAFRESNEL = false;
+ this.PREMULTIPLYALPHA = false;
+ this.EMISSIVE = false;
+ this.EMISSIVEDIRECTUV = 0;
+ this.GAMMAEMISSIVE = false;
+ this.REFLECTIVITY = false;
+ this.REFLECTIVITY_GAMMA = false;
+ this.REFLECTIVITYDIRECTUV = 0;
+ this.SPECULARTERM = false;
+ this.MICROSURFACEFROMREFLECTIVITYMAP = false;
+ this.MICROSURFACEAUTOMATIC = false;
+ this.LODBASEDMICROSFURACE = false;
+ this.MICROSURFACEMAP = false;
+ this.MICROSURFACEMAPDIRECTUV = 0;
+ this.METALLICWORKFLOW = false;
+ this.ROUGHNESSSTOREINMETALMAPALPHA = false;
+ this.ROUGHNESSSTOREINMETALMAPGREEN = false;
+ this.METALLNESSSTOREINMETALMAPBLUE = false;
+ this.AOSTOREINMETALMAPRED = false;
+ this.METALLIC_REFLECTANCE = false;
+ this.METALLIC_REFLECTANCE_GAMMA = false;
+ this.METALLIC_REFLECTANCEDIRECTUV = 0;
+ this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = false;
+ this.REFLECTANCE = false;
+ this.REFLECTANCE_GAMMA = false;
+ this.REFLECTANCEDIRECTUV = 0;
+ this.ENVIRONMENTBRDF = false;
+ this.ENVIRONMENTBRDF_RGBD = false;
+ this.NORMAL = false;
+ this.TANGENT = false;
+ this.BUMP = false;
+ this.BUMPDIRECTUV = 0;
+ this.OBJECTSPACE_NORMALMAP = false;
+ this.PARALLAX = false;
+ this.PARALLAX_RHS = false;
+ this.PARALLAXOCCLUSION = false;
+ this.NORMALXYSCALE = true;
+ this.LIGHTMAP = false;
+ this.LIGHTMAPDIRECTUV = 0;
+ this.USELIGHTMAPASSHADOWMAP = false;
+ this.GAMMALIGHTMAP = false;
+ this.RGBDLIGHTMAP = false;
+ this.REFLECTION = false;
+ this.REFLECTIONMAP_3D = false;
+ this.REFLECTIONMAP_SPHERICAL = false;
+ this.REFLECTIONMAP_PLANAR = false;
+ this.REFLECTIONMAP_CUBIC = false;
+ this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
+ this.REFLECTIONMAP_PROJECTION = false;
+ this.REFLECTIONMAP_SKYBOX = false;
+ this.REFLECTIONMAP_EXPLICIT = false;
+ this.REFLECTIONMAP_EQUIRECTANGULAR = false;
+ this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
+ this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
+ this.INVERTCUBICMAP = false;
+ this.USESPHERICALFROMREFLECTIONMAP = false;
+ this.USEIRRADIANCEMAP = false;
+ this.USESPHERICALINVERTEX = false;
+ this.REFLECTIONMAP_OPPOSITEZ = false;
+ this.LODINREFLECTIONALPHA = false;
+ this.GAMMAREFLECTION = false;
+ this.RGBDREFLECTION = false;
+ this.LINEARSPECULARREFLECTION = false;
+ this.RADIANCEOCCLUSION = false;
+ this.HORIZONOCCLUSION = false;
+ this.INSTANCES = false;
+ this.THIN_INSTANCES = false;
+ this.INSTANCESCOLOR = false;
+ this.PREPASS = false;
+ this.PREPASS_COLOR = false;
+ this.PREPASS_COLOR_INDEX = -1;
+ this.PREPASS_IRRADIANCE = false;
+ this.PREPASS_IRRADIANCE_INDEX = -1;
+ this.PREPASS_ALBEDO = false;
+ this.PREPASS_ALBEDO_INDEX = -1;
+ this.PREPASS_ALBEDO_SQRT = false;
+ this.PREPASS_ALBEDO_SQRT_INDEX = -1;
+ this.PREPASS_DEPTH = false;
+ this.PREPASS_DEPTH_INDEX = -1;
+ this.PREPASS_SCREENSPACE_DEPTH = false;
+ this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1;
+ this.PREPASS_NORMAL = false;
+ this.PREPASS_NORMAL_INDEX = -1;
+ this.PREPASS_NORMAL_WORLDSPACE = false;
+ this.PREPASS_WORLD_NORMAL = false;
+ this.PREPASS_WORLD_NORMAL_INDEX = -1;
+ this.PREPASS_POSITION = false;
+ this.PREPASS_POSITION_INDEX = -1;
+ this.PREPASS_LOCAL_POSITION = false;
+ this.PREPASS_LOCAL_POSITION_INDEX = -1;
+ this.PREPASS_VELOCITY = false;
+ this.PREPASS_VELOCITY_INDEX = -1;
+ this.PREPASS_VELOCITY_LINEAR = false;
+ this.PREPASS_VELOCITY_LINEAR_INDEX = -1;
+ this.PREPASS_REFLECTIVITY = false;
+ this.PREPASS_REFLECTIVITY_INDEX = -1;
+ this.SCENE_MRT_COUNT = 0;
+ this.NUM_BONE_INFLUENCERS = 0;
+ this.BonesPerMesh = 0;
+ this.BONETEXTURE = false;
+ this.BONES_VELOCITY_ENABLED = false;
+ this.NONUNIFORMSCALING = false;
+ this.MORPHTARGETS = false;
+ this.MORPHTARGETS_POSITION = false;
+ this.MORPHTARGETS_NORMAL = false;
+ this.MORPHTARGETS_TANGENT = false;
+ this.MORPHTARGETS_UV = false;
+ this.MORPHTARGETS_UV2 = false;
+ this.MORPHTARGETS_COLOR = false;
+ this.MORPHTARGETTEXTURE_HASPOSITIONS = false;
+ this.MORPHTARGETTEXTURE_HASNORMALS = false;
+ this.MORPHTARGETTEXTURE_HASTANGENTS = false;
+ this.MORPHTARGETTEXTURE_HASUVS = false;
+ this.MORPHTARGETTEXTURE_HASUV2S = false;
+ this.MORPHTARGETTEXTURE_HASCOLORS = false;
+ this.NUM_MORPH_INFLUENCERS = 0;
+ this.MORPHTARGETS_TEXTURE = false;
+ this.IMAGEPROCESSING = false;
+ this.VIGNETTE = false;
+ this.VIGNETTEBLENDMODEMULTIPLY = false;
+ this.VIGNETTEBLENDMODEOPAQUE = false;
+ this.TONEMAPPING = 0;
+ this.CONTRAST = false;
+ this.COLORCURVES = false;
+ this.COLORGRADING = false;
+ this.COLORGRADING3D = false;
+ this.SAMPLER3DGREENDEPTH = false;
+ this.SAMPLER3DBGRMAP = false;
+ this.DITHER = false;
+ this.IMAGEPROCESSINGPOSTPROCESS = false;
+ this.SKIPFINALCOLORCLAMP = false;
+ this.EXPOSURE = false;
+ this.MULTIVIEW = false;
+ this.ORDER_INDEPENDENT_TRANSPARENCY = false;
+ this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false;
+ this.USEPHYSICALLIGHTFALLOFF = false;
+ this.USEGLTFLIGHTFALLOFF = false;
+ this.TWOSIDEDLIGHTING = false;
+ this.SHADOWFLOAT = false;
+ this.CLIPPLANE = false;
+ this.CLIPPLANE2 = false;
+ this.CLIPPLANE3 = false;
+ this.CLIPPLANE4 = false;
+ this.CLIPPLANE5 = false;
+ this.CLIPPLANE6 = false;
+ this.POINTSIZE = false;
+ this.FOG = false;
+ this.LOGARITHMICDEPTH = false;
+ this.CAMERA_ORTHOGRAPHIC = false;
+ this.CAMERA_PERSPECTIVE = false;
+ this.AREALIGHTSUPPORTED = true;
+ this.FORCENORMALFORWARD = false;
+ this.SPECULARAA = false;
+ this.UNLIT = false;
+ this.DECAL_AFTER_DETAIL = false;
+ this.DEBUGMODE = 0;
+ this.rebuild();
+ }
+ /**
+ * Resets the PBR Material defines.
+ */
+ reset() {
+ super.reset();
+ this.ALPHATESTVALUE = "0.5";
+ this.PBR = true;
+ this.NORMALXYSCALE = true;
+ }
+}
+/**
+ * The Physically based material base class of BJS.
+ *
+ * This offers the main features of a standard PBR material.
+ * For more information, please refer to the documentation :
+ * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR
+ * @see [WebGL](https://playground.babylonjs.com/#CGHTSM#1)
+ * @see [WebGPU](https://playground.babylonjs.com/#CGHTSM#2)
+ */
+class PBRBaseMaterial extends PushMaterial {
+ /**
+ * Enables realtime filtering on the texture.
+ */
+ get realTimeFiltering() {
+ return this._realTimeFiltering;
+ }
+ set realTimeFiltering(b) {
+ this._realTimeFiltering = b;
+ this.markAsDirty(1);
+ }
+ /**
+ * Quality switch for realtime filtering
+ */
+ get realTimeFilteringQuality() {
+ return this._realTimeFilteringQuality;
+ }
+ set realTimeFilteringQuality(n) {
+ this._realTimeFilteringQuality = n;
+ this.markAsDirty(1);
+ }
+ /**
+ * Can this material render to several textures at once
+ */
+ get canRenderToMRT() {
+ return true;
+ }
+ /**
+ * Attaches a new image processing configuration to the PBR Material.
+ * @param configuration
+ */
+ _attachImageProcessingConfiguration(configuration) {
+ if (configuration === this._imageProcessingConfiguration) {
+ return;
+ }
+ // Detaches observer.
+ if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
+ this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
+ }
+ // Pick the scene configuration if needed.
+ if (!configuration) {
+ this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
+ }
+ else {
+ this._imageProcessingConfiguration = configuration;
+ }
+ // Attaches observer.
+ if (this._imageProcessingConfiguration) {
+ this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
+ this._markAllSubMeshesAsImageProcessingDirty();
+ });
+ }
+ }
+ /**
+ * Instantiates a new PBRMaterial instance.
+ *
+ * @param name The material name
+ * @param scene The scene the material will be use in.
+ * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false
+ */
+ constructor(name, scene, forceGLSL = false) {
+ super(name, scene, undefined, forceGLSL || PBRBaseMaterial.ForceGLSL);
+ /**
+ * Intensity of the direct lights e.g. the four lights available in your scene.
+ * This impacts both the direct diffuse and specular highlights.
+ * @internal
+ */
+ this._directIntensity = 1.0;
+ /**
+ * Intensity of the emissive part of the material.
+ * This helps controlling the emissive effect without modifying the emissive color.
+ * @internal
+ */
+ this._emissiveIntensity = 1.0;
+ /**
+ * Intensity of the environment e.g. how much the environment will light the object
+ * either through harmonics for rough material or through the reflection for shiny ones.
+ * @internal
+ */
+ this._environmentIntensity = 1.0;
+ /**
+ * This is a special control allowing the reduction of the specular highlights coming from the
+ * four lights of the scene. Those highlights may not be needed in full environment lighting.
+ * @internal
+ */
+ this._specularIntensity = 1.0;
+ /**
+ * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
+ */
+ this._lightingInfos = new Vector4(this._directIntensity, this._emissiveIntensity, this._environmentIntensity, this._specularIntensity);
+ /**
+ * Debug Control allowing disabling the bump map on this material.
+ * @internal
+ */
+ this._disableBumpMap = false;
+ /**
+ * AKA Diffuse Texture in standard nomenclature.
+ * @internal
+ */
+ this._albedoTexture = null;
+ /**
+ * OpenPBR Base Weight (multiplier to the diffuse and metal lobes).
+ * @internal
+ */
+ this._baseWeightTexture = null;
+ /**
+ * AKA Occlusion Texture in other nomenclature.
+ * @internal
+ */
+ this._ambientTexture = null;
+ /**
+ * AKA Occlusion Texture Intensity in other nomenclature.
+ * @internal
+ */
+ this._ambientTextureStrength = 1.0;
+ /**
+ * Defines how much the AO map is occluding the analytical lights (point spot...).
+ * 1 means it completely occludes it
+ * 0 mean it has no impact
+ * @internal
+ */
+ this._ambientTextureImpactOnAnalyticalLights = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
+ /**
+ * Stores the alpha values in a texture.
+ * @internal
+ */
+ this._opacityTexture = null;
+ /**
+ * Stores the reflection values in a texture.
+ * @internal
+ */
+ this._reflectionTexture = null;
+ /**
+ * Stores the emissive values in a texture.
+ * @internal
+ */
+ this._emissiveTexture = null;
+ /**
+ * AKA Specular texture in other nomenclature.
+ * @internal
+ */
+ this._reflectivityTexture = null;
+ /**
+ * Used to switch from specular/glossiness to metallic/roughness workflow.
+ * @internal
+ */
+ this._metallicTexture = null;
+ /**
+ * Specifies the metallic scalar of the metallic/roughness workflow.
+ * Can also be used to scale the metalness values of the metallic texture.
+ * @internal
+ */
+ this._metallic = null;
+ /**
+ * Specifies the roughness scalar of the metallic/roughness workflow.
+ * Can also be used to scale the roughness values of the metallic texture.
+ * @internal
+ */
+ this._roughness = null;
+ /**
+ * In metallic workflow, specifies an F0 factor to help configuring the material F0.
+ * By default the indexOfrefraction is used to compute F0;
+ *
+ * This is used as a factor against the default reflectance at normal incidence to tweak it.
+ *
+ * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;
+ * F90 = metallicReflectanceColor;
+ * @internal
+ */
+ this._metallicF0Factor = 1;
+ /**
+ * In metallic workflow, specifies an F0 color.
+ * By default the F90 is always 1;
+ *
+ * Please note that this factor is also used as a factor against the default reflectance at normal incidence.
+ *
+ * F0 = defaultF0_from_IOR * metallicF0Factor * metallicReflectanceColor
+ * F90 = metallicF0Factor;
+ * @internal
+ */
+ this._metallicReflectanceColor = Color3.White();
+ /**
+ * Specifies that only the A channel from _metallicReflectanceTexture should be used.
+ * If false, both RGB and A channels will be used
+ * @internal
+ */
+ this._useOnlyMetallicFromMetallicReflectanceTexture = false;
+ /**
+ * Defines to store metallicReflectanceColor in RGB and metallicF0Factor in A
+ * This is multiply against the scalar values defined in the material.
+ * @internal
+ */
+ this._metallicReflectanceTexture = null;
+ /**
+ * Defines to store reflectanceColor in RGB
+ * This is multiplied against the scalar values defined in the material.
+ * If both _reflectanceTexture and _metallicReflectanceTexture textures are provided and _useOnlyMetallicFromMetallicReflectanceTexture
+ * is false, _metallicReflectanceTexture takes precedence and _reflectanceTexture is not used
+ * @internal
+ */
+ this._reflectanceTexture = null;
+ /**
+ * Used to enable roughness/glossiness fetch from a separate channel depending on the current mode.
+ * Gray Scale represents roughness in metallic mode and glossiness in specular mode.
+ * @internal
+ */
+ this._microSurfaceTexture = null;
+ /**
+ * Stores surface normal data used to displace a mesh in a texture.
+ * @internal
+ */
+ this._bumpTexture = null;
+ /**
+ * Stores the pre-calculated light information of a mesh in a texture.
+ * @internal
+ */
+ this._lightmapTexture = null;
+ /**
+ * The color of a material in ambient lighting.
+ * @internal
+ */
+ this._ambientColor = new Color3(0, 0, 0);
+ /**
+ * AKA Diffuse Color in other nomenclature.
+ * @internal
+ */
+ this._albedoColor = new Color3(1, 1, 1);
+ /**
+ * OpenPBR Base Weight (multiplier to the diffuse and metal lobes).
+ * @internal
+ */
+ this._baseWeight = 1;
+ /**
+ * AKA Specular Color in other nomenclature.
+ * @internal
+ */
+ this._reflectivityColor = new Color3(1, 1, 1);
+ /**
+ * The color applied when light is reflected from a material.
+ * @internal
+ */
+ this._reflectionColor = new Color3(1, 1, 1);
+ /**
+ * The color applied when light is emitted from a material.
+ * @internal
+ */
+ this._emissiveColor = new Color3(0, 0, 0);
+ /**
+ * AKA Glossiness in other nomenclature.
+ * @internal
+ */
+ this._microSurface = 0.9;
+ /**
+ * Specifies that the material will use the light map as a show map.
+ * @internal
+ */
+ this._useLightmapAsShadowmap = false;
+ /**
+ * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
+ * makes the reflect vector face the model (under horizon).
+ * @internal
+ */
+ this._useHorizonOcclusion = true;
+ /**
+ * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
+ * too much the area relying on ambient texture to define their ambient occlusion.
+ * @internal
+ */
+ this._useRadianceOcclusion = true;
+ /**
+ * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
+ * @internal
+ */
+ this._useAlphaFromAlbedoTexture = false;
+ /**
+ * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones).
+ * A car glass is a good example of that. When sun reflects on it you can not see what is behind.
+ * @internal
+ */
+ this._useSpecularOverAlpha = true;
+ /**
+ * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
+ * @internal
+ */
+ this._useMicroSurfaceFromReflectivityMapAlpha = false;
+ /**
+ * Specifies if the metallic texture contains the roughness information in its alpha channel.
+ * @internal
+ */
+ this._useRoughnessFromMetallicTextureAlpha = true;
+ /**
+ * Specifies if the metallic texture contains the roughness information in its green channel.
+ * @internal
+ */
+ this._useRoughnessFromMetallicTextureGreen = false;
+ /**
+ * Specifies if the metallic texture contains the metallness information in its blue channel.
+ * @internal
+ */
+ this._useMetallnessFromMetallicTextureBlue = false;
+ /**
+ * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
+ * @internal
+ */
+ this._useAmbientOcclusionFromMetallicTextureRed = false;
+ /**
+ * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
+ * @internal
+ */
+ this._useAmbientInGrayScale = false;
+ /**
+ * In case the reflectivity map does not contain the microsurface information in its alpha channel,
+ * The material will try to infer what glossiness each pixel should be.
+ * @internal
+ */
+ this._useAutoMicroSurfaceFromReflectivityMap = false;
+ /**
+ * Defines the falloff type used in this material.
+ * It by default is Physical.
+ * @internal
+ */
+ this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
+ /**
+ * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).
+ * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind.
+ * @internal
+ */
+ this._useRadianceOverAlpha = true;
+ /**
+ * Allows using an object space normal map (instead of tangent space).
+ * @internal
+ */
+ this._useObjectSpaceNormalMap = false;
+ /**
+ * Allows using the bump map in parallax mode.
+ * @internal
+ */
+ this._useParallax = false;
+ /**
+ * Allows using the bump map in parallax occlusion mode.
+ * @internal
+ */
+ this._useParallaxOcclusion = false;
+ /**
+ * Controls the scale bias of the parallax mode.
+ * @internal
+ */
+ this._parallaxScaleBias = 0.05;
+ /**
+ * If sets to true, disables all the lights affecting the material.
+ * @internal
+ */
+ this._disableLighting = false;
+ /**
+ * Number of Simultaneous lights allowed on the material.
+ * @internal
+ */
+ this._maxSimultaneousLights = 4;
+ /**
+ * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
+ * @internal
+ */
+ this._invertNormalMapX = false;
+ /**
+ * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
+ * @internal
+ */
+ this._invertNormalMapY = false;
+ /**
+ * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
+ * @internal
+ */
+ this._twoSidedLighting = false;
+ /**
+ * Defines the alpha limits in alpha test mode.
+ * @internal
+ */
+ this._alphaCutOff = 0.4;
+ /**
+ * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
+ * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
+ * @internal
+ */
+ this._useAlphaFresnel = false;
+ /**
+ * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
+ * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
+ * @internal
+ */
+ this._useLinearAlphaFresnel = false;
+ /**
+ * Specifies the environment BRDF texture used to compute the scale and offset roughness values
+ * from cos theta and roughness:
+ * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
+ * @internal
+ */
+ this._environmentBRDFTexture = null;
+ /**
+ * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
+ * @internal
+ */
+ this._forceIrradianceInFragment = false;
+ this._realTimeFiltering = false;
+ this._realTimeFilteringQuality = 8;
+ /**
+ * Force normal to face away from face.
+ * @internal
+ */
+ this._forceNormalForward = false;
+ /**
+ * Enables specular anti aliasing in the PBR shader.
+ * It will both interacts on the Geometry for analytical and IBL lighting.
+ * It also prefilter the roughness map based on the bump values.
+ * @internal
+ */
+ this._enableSpecularAntiAliasing = false;
+ /**
+ * Keep track of the image processing observer to allow dispose and replace.
+ */
+ this._imageProcessingObserver = null;
+ /**
+ * Stores the available render targets.
+ */
+ this._renderTargets = new SmartArray(16);
+ /**
+ * Sets the global ambient color for the material used in lighting calculations.
+ */
+ this._globalAmbientColor = new Color3(0, 0, 0);
+ /**
+ * If set to true, no lighting calculations will be applied.
+ */
+ this._unlit = false;
+ /**
+ * If sets to true, the decal map will be applied after the detail map. Else, it is applied before (default: false)
+ */
+ this._applyDecalMapAfterDetailMap = false;
+ this._debugMode = 0;
+ this._shadersLoaded = false;
+ this._breakShaderLoadedCheck = false;
+ /**
+ * @internal
+ * This is reserved for the inspector.
+ * Defines the material debug mode.
+ * It helps seeing only some components of the material while troubleshooting.
+ */
+ this.debugMode = 0;
+ /**
+ * @internal
+ * This is reserved for the inspector.
+ * Specify from where on screen the debug mode should start.
+ * The value goes from -1 (full screen) to 1 (not visible)
+ * It helps with side by side comparison against the final render
+ * This defaults to -1
+ */
+ this.debugLimit = -1;
+ /**
+ * @internal
+ * This is reserved for the inspector.
+ * As the default viewing range might not be enough (if the ambient is really small for instance)
+ * You can use the factor to better multiply the final value.
+ */
+ this.debugFactor = 1;
+ this._cacheHasRenderTargetTextures = false;
+ this.brdf = new PBRBRDFConfiguration(this);
+ this.clearCoat = new PBRClearCoatConfiguration(this);
+ this.iridescence = new PBRIridescenceConfiguration(this);
+ this.anisotropy = new PBRAnisotropicConfiguration(this);
+ this.sheen = new PBRSheenConfiguration(this);
+ this.subSurface = new PBRSubSurfaceConfiguration(this);
+ this.detailMap = new DetailMapConfiguration(this);
+ // Setup the default processing configuration to the scene.
+ this._attachImageProcessingConfiguration(null);
+ this.getRenderTargetTextures = () => {
+ this._renderTargets.reset();
+ if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
+ this._renderTargets.push(this._reflectionTexture);
+ }
+ this._eventInfo.renderTargets = this._renderTargets;
+ this._callbackPluginEventFillRenderTargetTextures(this._eventInfo);
+ return this._renderTargets;
+ };
+ this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene());
+ this.prePassConfiguration = new PrePassConfiguration();
+ }
+ /**
+ * Gets a boolean indicating that current material needs to register RTT
+ */
+ get hasRenderTargetTextures() {
+ if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
+ return true;
+ }
+ return this._cacheHasRenderTargetTextures;
+ }
+ /**
+ * Can this material render to prepass
+ */
+ get isPrePassCapable() {
+ return !this.disableDepthWrite;
+ }
+ /**
+ * @returns the name of the material class.
+ */
+ getClassName() {
+ return "PBRBaseMaterial";
+ }
+ /**
+ * Returns true if alpha blending should be disabled.
+ */
+ get _disableAlphaBlending() {
+ return (this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE ||
+ this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST ||
+ this.subSurface?.disableAlphaBlending);
+ }
+ /**
+ * @returns whether or not this material should be rendered in alpha blend mode.
+ */
+ needAlphaBlending() {
+ if (this._hasTransparencyMode) {
+ return this._transparencyModeIsBlend;
+ }
+ if (this._disableAlphaBlending) {
+ return false;
+ }
+ return this.alpha < 1.0 || this._opacityTexture != null || this._shouldUseAlphaFromAlbedoTexture();
+ }
+ /**
+ * @returns whether or not this material should be rendered in alpha test mode.
+ */
+ needAlphaTesting() {
+ if (this._hasTransparencyMode) {
+ return this._transparencyModeIsTest;
+ }
+ if (this.subSurface?.disableAlphaBlending) {
+ return false;
+ }
+ return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST);
+ }
+ /**
+ * @returns whether or not the alpha value of the albedo texture should be used for alpha blending.
+ */
+ _shouldUseAlphaFromAlbedoTexture() {
+ return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE;
+ }
+ /**
+ * @returns whether or not there is a usable alpha channel for transparency.
+ */
+ _hasAlphaChannel() {
+ return (this._albedoTexture != null && this._albedoTexture.hasAlpha) || this._opacityTexture != null;
+ }
+ /**
+ * @returns the texture used for the alpha test.
+ */
+ getAlphaTestTexture() {
+ return this._albedoTexture;
+ }
+ /**
+ * Specifies that the submesh is ready to be used.
+ * @param mesh - BJS mesh.
+ * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
+ * @param useInstances - Specifies that instances should be used.
+ * @returns - boolean indicating that the submesh is ready or not.
+ */
+ isReadyForSubMesh(mesh, subMesh, useInstances) {
+ if (!this._uniformBufferLayoutBuilt) {
+ this.buildUniformLayout();
+ }
+ const drawWrapper = subMesh._drawWrapper;
+ if (drawWrapper.effect && this.isFrozen) {
+ if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) {
+ return true;
+ }
+ }
+ if (!subMesh.materialDefines) {
+ this._callbackPluginEventGeneric(4 /* MaterialPluginEvent.GetDefineNames */, this._eventInfo);
+ subMesh.materialDefines = new PBRMaterialDefines(this._eventInfo.defineNames);
+ }
+ const defines = subMesh.materialDefines;
+ if (this._isReadyForSubMesh(subMesh)) {
+ return true;
+ }
+ const scene = this.getScene();
+ const engine = scene.getEngine();
+ if (defines._areTexturesDirty) {
+ this._eventInfo.hasRenderTargetTextures = false;
+ this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);
+ this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures;
+ if (scene.texturesEnabled) {
+ if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
+ if (!this._albedoTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) {
+ if (!this._baseWeightTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
+ if (!this._ambientTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
+ if (!this._opacityTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ const reflectionTexture = this._getReflectionTexture();
+ if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
+ if (!reflectionTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ if (reflectionTexture.irradianceTexture) {
+ if (!reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ else {
+ // Not ready until spherical are ready too.
+ if (!reflectionTexture.sphericalPolynomial && reflectionTexture.getInternalTexture()?._sphericalPolynomialPromise) {
+ return false;
+ }
+ }
+ }
+ if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
+ if (!this._lightmapTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
+ if (!this._emissiveTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (MaterialFlags.SpecularTextureEnabled) {
+ if (this._metallicTexture) {
+ if (!this._metallicTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ else if (this._reflectivityTexture) {
+ if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._metallicReflectanceTexture) {
+ if (!this._metallicReflectanceTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._reflectanceTexture) {
+ if (!this._reflectanceTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ if (this._microSurfaceTexture) {
+ if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
+ return false;
+ }
+ }
+ }
+ if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
+ // Bump texture cannot be not blocking.
+ if (!this._bumpTexture.isReady()) {
+ return false;
+ }
+ }
+ if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {
+ // This is blocking.
+ if (!this._environmentBRDFTexture.isReady()) {
+ return false;
+ }
+ }
+ }
+ }
+ this._eventInfo.isReadyForSubMesh = true;
+ this._eventInfo.defines = defines;
+ this._eventInfo.subMesh = subMesh;
+ this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);
+ if (!this._eventInfo.isReadyForSubMesh) {
+ return false;
+ }
+ if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
+ if (!this._imageProcessingConfiguration.isReady()) {
+ return false;
+ }
+ }
+ // Check if Area Lights have LTC texture.
+ if (defines["AREALIGHTUSED"]) {
+ for (let index = 0; index < mesh.lightSources.length; index++) {
+ if (!mesh.lightSources[index]._isReady()) {
+ return false;
+ }
+ }
+ }
+ if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+ mesh.createNormals(true);
+ Logger.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
+ }
+ const previousEffect = subMesh.effect;
+ const lightDisposed = defines._areLightsDisposed;
+ let effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
+ let forceWasNotReadyPreviously = false;
+ if (effect) {
+ if (this._onEffectCreatedObservable) {
+ onCreatedEffectParameters$1.effect = effect;
+ onCreatedEffectParameters$1.subMesh = subMesh;
+ this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$1);
+ }
+ // Use previous effect while new one is compiling
+ if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
+ effect = previousEffect;
+ defines.markAsUnprocessed();
+ forceWasNotReadyPreviously = this.isFrozen;
+ if (lightDisposed) {
+ // re register in case it takes more than one frame.
+ defines._areLightsDisposed = true;
+ return false;
+ }
+ }
+ else {
+ scene.resetCachedMaterial();
+ subMesh.setEffect(effect, defines, this._materialContext);
+ }
+ }
+ if (!subMesh.effect || !subMesh.effect.isReady()) {
+ return false;
+ }
+ defines._renderId = scene.getRenderId();
+ drawWrapper._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true;
+ drawWrapper._wasPreviouslyUsingInstances = !!useInstances;
+ this._checkScenePerformancePriority();
+ return true;
+ }
+ /**
+ * Specifies if the material uses metallic roughness workflow.
+ * @returns boolean specifying if the material uses metallic roughness workflow.
+ */
+ isMetallicWorkflow() {
+ if (this._metallic != null || this._roughness != null || this._metallicTexture) {
+ return true;
+ }
+ return false;
+ }
+ _prepareEffect(mesh, defines, onCompiled = null, onError = null, useInstances = null, useClipPlane = null, useThinInstances) {
+ this._prepareDefines(mesh, defines, useInstances, useClipPlane, useThinInstances);
+ if (!defines.isDirty) {
+ return null;
+ }
+ defines.markAsProcessed();
+ const scene = this.getScene();
+ const engine = scene.getEngine();
+ // Fallbacks
+ const fallbacks = new EffectFallbacks();
+ let fallbackRank = 0;
+ if (defines.USESPHERICALINVERTEX) {
+ fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
+ }
+ if (defines.FOG) {
+ fallbacks.addFallback(fallbackRank, "FOG");
+ }
+ if (defines.SPECULARAA) {
+ fallbacks.addFallback(fallbackRank, "SPECULARAA");
+ }
+ if (defines.POINTSIZE) {
+ fallbacks.addFallback(fallbackRank, "POINTSIZE");
+ }
+ if (defines.LOGARITHMICDEPTH) {
+ fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
+ }
+ if (defines.PARALLAX) {
+ fallbacks.addFallback(fallbackRank, "PARALLAX");
+ }
+ if (defines.PARALLAX_RHS) {
+ fallbacks.addFallback(fallbackRank, "PARALLAX_RHS");
+ }
+ if (defines.PARALLAXOCCLUSION) {
+ fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
+ }
+ if (defines.ENVIRONMENTBRDF) {
+ fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
+ }
+ if (defines.TANGENT) {
+ fallbacks.addFallback(fallbackRank++, "TANGENT");
+ }
+ if (defines.BUMP) {
+ fallbacks.addFallback(fallbackRank++, "BUMP");
+ }
+ fallbackRank = HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
+ if (defines.SPECULARTERM) {
+ fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
+ }
+ if (defines.USESPHERICALFROMREFLECTIONMAP) {
+ fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
+ }
+ if (defines.USEIRRADIANCEMAP) {
+ fallbacks.addFallback(fallbackRank++, "USEIRRADIANCEMAP");
+ }
+ if (defines.LIGHTMAP) {
+ fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
+ }
+ if (defines.NORMAL) {
+ fallbacks.addFallback(fallbackRank++, "NORMAL");
+ }
+ if (defines.AMBIENT) {
+ fallbacks.addFallback(fallbackRank++, "AMBIENT");
+ }
+ if (defines.EMISSIVE) {
+ fallbacks.addFallback(fallbackRank++, "EMISSIVE");
+ }
+ if (defines.VERTEXCOLOR) {
+ fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
+ }
+ if (defines.MORPHTARGETS) {
+ fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
+ }
+ if (defines.MULTIVIEW) {
+ fallbacks.addFallback(0, "MULTIVIEW");
+ }
+ //Attributes
+ const attribs = [VertexBuffer.PositionKind];
+ if (defines.NORMAL) {
+ attribs.push(VertexBuffer.NormalKind);
+ }
+ if (defines.TANGENT) {
+ attribs.push(VertexBuffer.TangentKind);
+ }
+ for (let i = 1; i <= 6; ++i) {
+ if (defines["UV" + i]) {
+ attribs.push(`uv${i === 1 ? "" : i}`);
+ }
+ }
+ if (defines.VERTEXCOLOR) {
+ attribs.push(VertexBuffer.ColorKind);
+ }
+ PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
+ PrepareAttributesForInstances(attribs, defines);
+ PrepareAttributesForMorphTargets(attribs, mesh, defines);
+ PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);
+ let shaderName = "pbr";
+ const uniforms = [
+ "world",
+ "view",
+ "viewProjection",
+ "vEyePosition",
+ "vLightsType",
+ "vAmbientColor",
+ "vAlbedoColor",
+ "baseWeight",
+ "vReflectivityColor",
+ "vMetallicReflectanceFactors",
+ "vEmissiveColor",
+ "visibility",
+ "vReflectionColor",
+ "vFogInfos",
+ "vFogColor",
+ "pointSize",
+ "vAlbedoInfos",
+ "vBaseWeightInfos",
+ "vAmbientInfos",
+ "vOpacityInfos",
+ "vReflectionInfos",
+ "vReflectionPosition",
+ "vReflectionSize",
+ "vEmissiveInfos",
+ "vReflectivityInfos",
+ "vReflectionFilteringInfo",
+ "vMetallicReflectanceInfos",
+ "vReflectanceInfos",
+ "vMicroSurfaceSamplerInfos",
+ "vBumpInfos",
+ "vLightmapInfos",
+ "mBones",
+ "albedoMatrix",
+ "baseWeightMatrix",
+ "ambientMatrix",
+ "opacityMatrix",
+ "reflectionMatrix",
+ "emissiveMatrix",
+ "reflectivityMatrix",
+ "normalMatrix",
+ "microSurfaceSamplerMatrix",
+ "bumpMatrix",
+ "lightmapMatrix",
+ "metallicReflectanceMatrix",
+ "reflectanceMatrix",
+ "vLightingIntensity",
+ "logarithmicDepthConstant",
+ "vSphericalX",
+ "vSphericalY",
+ "vSphericalZ",
+ "vSphericalXX_ZZ",
+ "vSphericalYY_ZZ",
+ "vSphericalZZ",
+ "vSphericalXY",
+ "vSphericalYZ",
+ "vSphericalZX",
+ "vSphericalL00",
+ "vSphericalL1_1",
+ "vSphericalL10",
+ "vSphericalL11",
+ "vSphericalL2_2",
+ "vSphericalL2_1",
+ "vSphericalL20",
+ "vSphericalL21",
+ "vSphericalL22",
+ "vReflectionMicrosurfaceInfos",
+ "vTangentSpaceParams",
+ "boneTextureWidth",
+ "vDebugMode",
+ "morphTargetTextureInfo",
+ "morphTargetTextureIndices",
+ ];
+ const samplers = [
+ "albedoSampler",
+ "baseWeightSampler",
+ "reflectivitySampler",
+ "ambientSampler",
+ "emissiveSampler",
+ "bumpSampler",
+ "lightmapSampler",
+ "opacitySampler",
+ "reflectionSampler",
+ "reflectionSamplerLow",
+ "reflectionSamplerHigh",
+ "irradianceSampler",
+ "microSurfaceSampler",
+ "environmentBrdfSampler",
+ "boneSampler",
+ "metallicReflectanceSampler",
+ "reflectanceSampler",
+ "morphTargets",
+ "oitDepthSampler",
+ "oitFrontColorSampler",
+ "icdfSampler",
+ "areaLightsLTC1Sampler",
+ "areaLightsLTC2Sampler",
+ ];
+ const uniformBuffers = ["Material", "Scene", "Mesh"];
+ const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS };
+ this._eventInfo.fallbacks = fallbacks;
+ this._eventInfo.fallbackRank = fallbackRank;
+ this._eventInfo.defines = defines;
+ this._eventInfo.uniforms = uniforms;
+ this._eventInfo.attributes = attribs;
+ this._eventInfo.samplers = samplers;
+ this._eventInfo.uniformBuffersNames = uniformBuffers;
+ this._eventInfo.customCode = undefined;
+ this._eventInfo.mesh = mesh;
+ this._eventInfo.indexParameters = indexParameters;
+ this._callbackPluginEventGeneric(128 /* MaterialPluginEvent.PrepareEffect */, this._eventInfo);
+ MaterialHelperGeometryRendering.AddUniformsAndSamplers(uniforms, samplers);
+ PrePassConfiguration.AddUniforms(uniforms);
+ addClipPlaneUniforms(uniforms);
+ if (ImageProcessingConfiguration) {
+ ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
+ ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
+ }
+ PrepareUniformsAndSamplersList({
+ uniformsNames: uniforms,
+ uniformBuffersNames: uniformBuffers,
+ samplers: samplers,
+ defines: defines,
+ maxSimultaneousLights: this._maxSimultaneousLights,
+ });
+ const csnrOptions = {};
+ if (this.customShaderNameResolve) {
+ shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);
+ }
+ const join = defines.toString();
+ const effect = engine.createEffect(shaderName, {
+ attributes: attribs,
+ uniformsNames: uniforms,
+ uniformBuffersNames: uniformBuffers,
+ samplers: samplers,
+ defines: join,
+ fallbacks: fallbacks,
+ onCompiled: onCompiled,
+ onError: onError,
+ indexParameters,
+ processFinalCode: csnrOptions.processFinalCode,
+ processCodeAfterIncludes: this._eventInfo.customCode,
+ multiTarget: defines.PREPASS,
+ shaderLanguage: this._shaderLanguage,
+ extraInitializationsAsync: this._shadersLoaded
+ ? undefined
+ : async () => {
+ if (this.shaderLanguage === 1 /* ShaderLanguage.WGSL */) {
+ await Promise.all([Promise.resolve().then(() => pbr_vertex$1), Promise.resolve().then(() => pbr_fragment$1)]);
+ }
+ else {
+ await Promise.all([Promise.resolve().then(() => pbr_vertex), Promise.resolve().then(() => pbr_fragment)]);
+ }
+ this._shadersLoaded = true;
+ },
+ }, engine);
+ this._eventInfo.customCode = undefined;
+ return effect;
+ }
+ _prepareDefines(mesh, defines, useInstances = null, useClipPlane = null, useThinInstances = false) {
+ const scene = this.getScene();
+ const engine = scene.getEngine();
+ // Lights
+ PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
+ defines._needNormals = true;
+ // Multiview
+ PrepareDefinesForMultiview(scene, defines);
+ // PrePass
+ const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;
+ PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit);
+ // Order independant transparency
+ PrepareDefinesForOIT(scene, defines, oit);
+ MaterialHelperGeometryRendering.PrepareDefines(engine.currentRenderPassId, mesh, defines);
+ // Textures
+ defines.METALLICWORKFLOW = this.isMetallicWorkflow();
+ if (defines._areTexturesDirty) {
+ defines._needUVs = false;
+ for (let i = 1; i <= 6; ++i) {
+ defines["MAINUV" + i] = false;
+ }
+ if (scene.texturesEnabled) {
+ defines.ALBEDODIRECTUV = 0;
+ defines.BASEWEIGHTDIRECTUV = 0;
+ defines.AMBIENTDIRECTUV = 0;
+ defines.OPACITYDIRECTUV = 0;
+ defines.EMISSIVEDIRECTUV = 0;
+ defines.REFLECTIVITYDIRECTUV = 0;
+ defines.MICROSURFACEMAPDIRECTUV = 0;
+ defines.METALLIC_REFLECTANCEDIRECTUV = 0;
+ defines.REFLECTANCEDIRECTUV = 0;
+ defines.BUMPDIRECTUV = 0;
+ defines.LIGHTMAPDIRECTUV = 0;
+ if (engine.getCaps().textureLOD) {
+ defines.LODBASEDMICROSFURACE = true;
+ }
+ if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
+ PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
+ defines.GAMMAALBEDO = this._albedoTexture.gammaSpace;
+ }
+ else {
+ defines.ALBEDO = false;
+ }
+ if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) {
+ PrepareDefinesForMergedUV(this._baseWeightTexture, defines, "BASEWEIGHT");
+ }
+ else {
+ defines.BASEWEIGHT = false;
+ }
+ if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
+ PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
+ defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
+ }
+ else {
+ defines.AMBIENT = false;
+ }
+ if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
+ PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
+ defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
+ }
+ else {
+ defines.OPACITY = false;
+ }
+ const reflectionTexture = this._getReflectionTexture();
+ if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
+ defines.REFLECTION = true;
+ defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
+ defines.RGBDREFLECTION = reflectionTexture.isRGBD;
+ defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
+ defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD;
+ if (this.realTimeFiltering && this.realTimeFilteringQuality > 0) {
+ defines.NUM_SAMPLES = "" + this.realTimeFilteringQuality;
+ if (engine._features.needTypeSuffixInShaderConstants) {
+ defines.NUM_SAMPLES = defines.NUM_SAMPLES + "u";
+ }
+ defines.REALTIME_FILTERING = true;
+ if (this.getScene().iblCdfGenerator) {
+ defines.IBL_CDF_FILTERING = true;
+ }
+ }
+ else {
+ defines.REALTIME_FILTERING = false;
+ }
+ defines.INVERTCUBICMAP = reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE;
+ defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
+ defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
+ defines.REFLECTIONMAP_CUBIC = false;
+ defines.REFLECTIONMAP_EXPLICIT = false;
+ defines.REFLECTIONMAP_PLANAR = false;
+ defines.REFLECTIONMAP_PROJECTION = false;
+ defines.REFLECTIONMAP_SKYBOX = false;
+ defines.REFLECTIONMAP_SPHERICAL = false;
+ defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
+ defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
+ defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
+ switch (reflectionTexture.coordinatesMode) {
+ case Texture.EXPLICIT_MODE:
+ defines.REFLECTIONMAP_EXPLICIT = true;
+ break;
+ case Texture.PLANAR_MODE:
+ defines.REFLECTIONMAP_PLANAR = true;
+ break;
+ case Texture.PROJECTION_MODE:
+ defines.REFLECTIONMAP_PROJECTION = true;
+ break;
+ case Texture.SKYBOX_MODE:
+ defines.REFLECTIONMAP_SKYBOX = true;
+ break;
+ case Texture.SPHERICAL_MODE:
+ defines.REFLECTIONMAP_SPHERICAL = true;
+ break;
+ case Texture.EQUIRECTANGULAR_MODE:
+ defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
+ break;
+ case Texture.FIXED_EQUIRECTANGULAR_MODE:
+ defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
+ break;
+ case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
+ defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
+ break;
+ case Texture.CUBIC_MODE:
+ case Texture.INVCUBIC_MODE:
+ default:
+ defines.REFLECTIONMAP_CUBIC = true;
+ defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
+ break;
+ }
+ if (reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {
+ if (reflectionTexture.irradianceTexture) {
+ defines.USEIRRADIANCEMAP = true;
+ defines.USESPHERICALFROMREFLECTIONMAP = false;
+ defines.USESPHERICALINVERTEX = false;
+ }
+ // Assume using spherical polynomial if the reflection texture is a cube map
+ else if (reflectionTexture.isCube) {
+ defines.USESPHERICALFROMREFLECTIONMAP = true;
+ defines.USEIRRADIANCEMAP = false;
+ if (this._forceIrradianceInFragment || this.realTimeFiltering || this._twoSidedLighting || engine.getCaps().maxVaryingVectors <= 8) {
+ defines.USESPHERICALINVERTEX = false;
+ }
+ else {
+ defines.USESPHERICALINVERTEX = true;
+ }
+ }
+ }
+ }
+ else {
+ defines.REFLECTION = false;
+ defines.REFLECTIONMAP_3D = false;
+ defines.REFLECTIONMAP_SPHERICAL = false;
+ defines.REFLECTIONMAP_PLANAR = false;
+ defines.REFLECTIONMAP_CUBIC = false;
+ defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
+ defines.REFLECTIONMAP_PROJECTION = false;
+ defines.REFLECTIONMAP_SKYBOX = false;
+ defines.REFLECTIONMAP_EXPLICIT = false;
+ defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
+ defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
+ defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
+ defines.INVERTCUBICMAP = false;
+ defines.USESPHERICALFROMREFLECTIONMAP = false;
+ defines.USEIRRADIANCEMAP = false;
+ defines.USESPHERICALINVERTEX = false;
+ defines.REFLECTIONMAP_OPPOSITEZ = false;
+ defines.LODINREFLECTIONALPHA = false;
+ defines.GAMMAREFLECTION = false;
+ defines.RGBDREFLECTION = false;
+ defines.LINEARSPECULARREFLECTION = false;
+ }
+ if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
+ PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
+ defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
+ defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
+ defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;
+ }
+ else {
+ defines.LIGHTMAP = false;
+ }
+ if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
+ PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
+ defines.GAMMAEMISSIVE = this._emissiveTexture.gammaSpace;
+ }
+ else {
+ defines.EMISSIVE = false;
+ }
+ if (MaterialFlags.SpecularTextureEnabled) {
+ if (this._metallicTexture) {
+ PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
+ defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
+ defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
+ defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
+ defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
+ defines.REFLECTIVITY_GAMMA = false;
+ }
+ else if (this._reflectivityTexture) {
+ PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
+ defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
+ defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
+ defines.REFLECTIVITY_GAMMA = this._reflectivityTexture.gammaSpace;
+ }
+ else {
+ defines.REFLECTIVITY = false;
+ }
+ if (this._metallicReflectanceTexture || this._reflectanceTexture) {
+ defines.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = this._useOnlyMetallicFromMetallicReflectanceTexture;
+ if (this._metallicReflectanceTexture) {
+ PrepareDefinesForMergedUV(this._metallicReflectanceTexture, defines, "METALLIC_REFLECTANCE");
+ defines.METALLIC_REFLECTANCE_GAMMA = this._metallicReflectanceTexture.gammaSpace;
+ }
+ else {
+ defines.METALLIC_REFLECTANCE = false;
+ }
+ if (this._reflectanceTexture &&
+ (!this._metallicReflectanceTexture || (this._metallicReflectanceTexture && this._useOnlyMetallicFromMetallicReflectanceTexture))) {
+ PrepareDefinesForMergedUV(this._reflectanceTexture, defines, "REFLECTANCE");
+ defines.REFLECTANCE_GAMMA = this._reflectanceTexture.gammaSpace;
+ }
+ else {
+ defines.REFLECTANCE = false;
+ }
+ }
+ else {
+ defines.METALLIC_REFLECTANCE = false;
+ defines.REFLECTANCE = false;
+ }
+ if (this._microSurfaceTexture) {
+ PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
+ }
+ else {
+ defines.MICROSURFACEMAP = false;
+ }
+ }
+ else {
+ defines.REFLECTIVITY = false;
+ defines.MICROSURFACEMAP = false;
+ }
+ if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
+ PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
+ if (this._useParallax && this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
+ defines.PARALLAX = true;
+ defines.PARALLAX_RHS = scene.useRightHandedSystem;
+ defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
+ }
+ else {
+ defines.PARALLAX = false;
+ }
+ defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
+ }
+ else {
+ defines.BUMP = false;
+ defines.PARALLAX = false;
+ defines.PARALLAX_RHS = false;
+ defines.PARALLAXOCCLUSION = false;
+ defines.OBJECTSPACE_NORMALMAP = false;
+ }
+ if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {
+ defines.ENVIRONMENTBRDF = true;
+ defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD;
+ }
+ else {
+ defines.ENVIRONMENTBRDF = false;
+ defines.ENVIRONMENTBRDF_RGBD = false;
+ }
+ if (this._shouldUseAlphaFromAlbedoTexture()) {
+ defines.ALPHAFROMALBEDO = true;
+ }
+ else {
+ defines.ALPHAFROMALBEDO = false;
+ }
+ }
+ defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
+ if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
+ defines.USEPHYSICALLIGHTFALLOFF = false;
+ defines.USEGLTFLIGHTFALLOFF = false;
+ }
+ else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
+ defines.USEPHYSICALLIGHTFALLOFF = false;
+ defines.USEGLTFLIGHTFALLOFF = true;
+ }
+ else {
+ defines.USEPHYSICALLIGHTFALLOFF = true;
+ defines.USEGLTFLIGHTFALLOFF = false;
+ }
+ defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
+ if (!this.backFaceCulling && this._twoSidedLighting) {
+ defines.TWOSIDEDLIGHTING = true;
+ }
+ else {
+ defines.TWOSIDEDLIGHTING = false;
+ }
+ defines.SPECULARAA = engine.getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
+ }
+ if (defines._areTexturesDirty || defines._areMiscDirty) {
+ defines.ALPHATESTVALUE = `${this._alphaCutOff}${this._alphaCutOff % 1 === 0 ? "." : ""}`;
+ defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;
+ defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
+ defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
+ defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
+ }
+ if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
+ this._imageProcessingConfiguration.prepareDefines(defines);
+ }
+ defines.FORCENORMALFORWARD = this._forceNormalForward;
+ defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
+ defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
+ // Misc.
+ if (defines._areMiscDirty) {
+ PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines, this._applyDecalMapAfterDetailMap);
+ defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind));
+ defines.DEBUGMODE = this._debugMode;
+ }
+ // Values that need to be evaluated on every frame
+ PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances ? true : false, useClipPlane, useThinInstances);
+ // External config
+ this._eventInfo.defines = defines;
+ this._eventInfo.mesh = mesh;
+ this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo);
+ // Attribs
+ PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE);
+ // External config
+ this._callbackPluginEventPrepareDefines(this._eventInfo);
+ }
+ /**
+ * Force shader compilation
+ * @param mesh - Define the mesh we want to force the compilation for
+ * @param onCompiled - Define a callback triggered when the compilation completes
+ * @param options - Define the options used to create the compilation
+ */
+ forceCompilation(mesh, onCompiled, options) {
+ const localOptions = {
+ clipPlane: false,
+ useInstances: false,
+ ...options,
+ };
+ if (!this._uniformBufferLayoutBuilt) {
+ this.buildUniformLayout();
+ }
+ this._callbackPluginEventGeneric(4 /* MaterialPluginEvent.GetDefineNames */, this._eventInfo);
+ const checkReady = () => {
+ if (this._breakShaderLoadedCheck) {
+ return;
+ }
+ const defines = new PBRMaterialDefines(this._eventInfo.defineNames);
+ const effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane, mesh.hasThinInstances);
+ if (this._onEffectCreatedObservable) {
+ onCreatedEffectParameters$1.effect = effect;
+ onCreatedEffectParameters$1.subMesh = null;
+ this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters$1);
+ }
+ if (effect.isReady()) {
+ if (onCompiled) {
+ onCompiled(this);
+ }
+ }
+ else {
+ effect.onCompileObservable.add(() => {
+ if (onCompiled) {
+ onCompiled(this);
+ }
+ });
+ }
+ };
+ checkReady();
+ }
+ /**
+ * Initializes the uniform buffer layout for the shader.
+ */
+ buildUniformLayout() {
+ // Order is important !
+ const ubo = this._uniformBuffer;
+ ubo.addUniform("vAlbedoInfos", 2);
+ ubo.addUniform("vBaseWeightInfos", 2);
+ ubo.addUniform("vAmbientInfos", 4);
+ ubo.addUniform("vOpacityInfos", 2);
+ ubo.addUniform("vEmissiveInfos", 2);
+ ubo.addUniform("vLightmapInfos", 2);
+ ubo.addUniform("vReflectivityInfos", 3);
+ ubo.addUniform("vMicroSurfaceSamplerInfos", 2);
+ ubo.addUniform("vReflectionInfos", 2);
+ ubo.addUniform("vReflectionFilteringInfo", 2);
+ ubo.addUniform("vReflectionPosition", 3);
+ ubo.addUniform("vReflectionSize", 3);
+ ubo.addUniform("vBumpInfos", 3);
+ ubo.addUniform("albedoMatrix", 16);
+ ubo.addUniform("baseWeightMatrix", 16);
+ ubo.addUniform("ambientMatrix", 16);
+ ubo.addUniform("opacityMatrix", 16);
+ ubo.addUniform("emissiveMatrix", 16);
+ ubo.addUniform("lightmapMatrix", 16);
+ ubo.addUniform("reflectivityMatrix", 16);
+ ubo.addUniform("microSurfaceSamplerMatrix", 16);
+ ubo.addUniform("bumpMatrix", 16);
+ ubo.addUniform("vTangentSpaceParams", 2);
+ ubo.addUniform("reflectionMatrix", 16);
+ ubo.addUniform("vReflectionColor", 3);
+ ubo.addUniform("vAlbedoColor", 4);
+ ubo.addUniform("baseWeight", 1);
+ ubo.addUniform("vLightingIntensity", 4);
+ ubo.addUniform("vReflectionMicrosurfaceInfos", 3);
+ ubo.addUniform("pointSize", 1);
+ ubo.addUniform("vReflectivityColor", 4);
+ ubo.addUniform("vEmissiveColor", 3);
+ ubo.addUniform("vAmbientColor", 3);
+ ubo.addUniform("vDebugMode", 2);
+ ubo.addUniform("vMetallicReflectanceFactors", 4);
+ ubo.addUniform("vMetallicReflectanceInfos", 2);
+ ubo.addUniform("metallicReflectanceMatrix", 16);
+ ubo.addUniform("vReflectanceInfos", 2);
+ ubo.addUniform("reflectanceMatrix", 16);
+ ubo.addUniform("vSphericalL00", 3);
+ ubo.addUniform("vSphericalL1_1", 3);
+ ubo.addUniform("vSphericalL10", 3);
+ ubo.addUniform("vSphericalL11", 3);
+ ubo.addUniform("vSphericalL2_2", 3);
+ ubo.addUniform("vSphericalL2_1", 3);
+ ubo.addUniform("vSphericalL20", 3);
+ ubo.addUniform("vSphericalL21", 3);
+ ubo.addUniform("vSphericalL22", 3);
+ ubo.addUniform("vSphericalX", 3);
+ ubo.addUniform("vSphericalY", 3);
+ ubo.addUniform("vSphericalZ", 3);
+ ubo.addUniform("vSphericalXX_ZZ", 3);
+ ubo.addUniform("vSphericalYY_ZZ", 3);
+ ubo.addUniform("vSphericalZZ", 3);
+ ubo.addUniform("vSphericalXY", 3);
+ ubo.addUniform("vSphericalYZ", 3);
+ ubo.addUniform("vSphericalZX", 3);
+ super.buildUniformLayout();
+ }
+ /**
+ * Binds the submesh data.
+ * @param world - The world matrix.
+ * @param mesh - The BJS mesh.
+ * @param subMesh - A submesh of the BJS mesh.
+ */
+ bindForSubMesh(world, mesh, subMesh) {
+ const scene = this.getScene();
+ const defines = subMesh.materialDefines;
+ if (!defines) {
+ return;
+ }
+ const effect = subMesh.effect;
+ if (!effect) {
+ return;
+ }
+ this._activeEffect = effect;
+ // Matrices Mesh.
+ mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
+ mesh.transferToEffect(world);
+ const engine = scene.getEngine();
+ // Binding unconditionally
+ this._uniformBuffer.bindToEffect(effect, "Material");
+ this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen);
+ MaterialHelperGeometryRendering.Bind(engine.currentRenderPassId, this._activeEffect, mesh, world, this);
+ this._eventInfo.subMesh = subMesh;
+ this._callbackPluginEventHardBindForSubMesh(this._eventInfo);
+ // Normal Matrix
+ if (defines.OBJECTSPACE_NORMALMAP) {
+ world.toNormalMatrix(this._normalMatrix);
+ this.bindOnlyNormalMatrix(this._normalMatrix);
+ }
+ const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility);
+ // Bones
+ BindBonesParameters(mesh, this._activeEffect, this.prePassConfiguration);
+ let reflectionTexture = null;
+ const ubo = this._uniformBuffer;
+ if (mustRebind) {
+ this.bindViewProjection(effect);
+ reflectionTexture = this._getReflectionTexture();
+ if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || subMesh._drawWrapper._forceRebindOnNextCall) {
+ // Texture uniforms
+ if (scene.texturesEnabled) {
+ if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
+ ubo.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
+ BindTextureMatrix(this._albedoTexture, ubo, "albedo");
+ }
+ if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) {
+ ubo.updateFloat2("vBaseWeightInfos", this._baseWeightTexture.coordinatesIndex, this._baseWeightTexture.level);
+ BindTextureMatrix(this._baseWeightTexture, ubo, "baseWeight");
+ }
+ if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
+ ubo.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
+ BindTextureMatrix(this._ambientTexture, ubo, "ambient");
+ }
+ if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
+ ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
+ BindTextureMatrix(this._opacityTexture, ubo, "opacity");
+ }
+ if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
+ ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
+ ubo.updateFloat2("vReflectionInfos", reflectionTexture.level * scene.iblIntensity, 0);
+ if (reflectionTexture.boundingBoxSize) {
+ const cubeTexture = reflectionTexture;
+ ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
+ ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
+ }
+ if (this.realTimeFiltering) {
+ const width = reflectionTexture.getSize().width;
+ ubo.updateFloat2("vReflectionFilteringInfo", width, Math.log2(width));
+ }
+ if (!defines.USEIRRADIANCEMAP) {
+ const polynomials = reflectionTexture.sphericalPolynomial;
+ if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
+ if (defines.SPHERICAL_HARMONICS) {
+ const preScaledHarmonics = polynomials.preScaledHarmonics;
+ ubo.updateVector3("vSphericalL00", preScaledHarmonics.l00);
+ ubo.updateVector3("vSphericalL1_1", preScaledHarmonics.l1_1);
+ ubo.updateVector3("vSphericalL10", preScaledHarmonics.l10);
+ ubo.updateVector3("vSphericalL11", preScaledHarmonics.l11);
+ ubo.updateVector3("vSphericalL2_2", preScaledHarmonics.l2_2);
+ ubo.updateVector3("vSphericalL2_1", preScaledHarmonics.l2_1);
+ ubo.updateVector3("vSphericalL20", preScaledHarmonics.l20);
+ ubo.updateVector3("vSphericalL21", preScaledHarmonics.l21);
+ ubo.updateVector3("vSphericalL22", preScaledHarmonics.l22);
+ }
+ else {
+ ubo.updateFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
+ ubo.updateFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
+ ubo.updateFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
+ ubo.updateFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
+ ubo.updateFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
+ ubo.updateFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
+ ubo.updateFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
+ ubo.updateFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
+ ubo.updateFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
+ }
+ }
+ }
+ ubo.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
+ }
+ if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
+ ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
+ BindTextureMatrix(this._emissiveTexture, ubo, "emissive");
+ }
+ if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
+ ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
+ BindTextureMatrix(this._lightmapTexture, ubo, "lightmap");
+ }
+ if (MaterialFlags.SpecularTextureEnabled) {
+ if (this._metallicTexture) {
+ ubo.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
+ BindTextureMatrix(this._metallicTexture, ubo, "reflectivity");
+ }
+ else if (this._reflectivityTexture) {
+ ubo.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
+ BindTextureMatrix(this._reflectivityTexture, ubo, "reflectivity");
+ }
+ if (this._metallicReflectanceTexture) {
+ ubo.updateFloat2("vMetallicReflectanceInfos", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level);
+ BindTextureMatrix(this._metallicReflectanceTexture, ubo, "metallicReflectance");
+ }
+ if (this._reflectanceTexture && defines.REFLECTANCE) {
+ ubo.updateFloat2("vReflectanceInfos", this._reflectanceTexture.coordinatesIndex, this._reflectanceTexture.level);
+ BindTextureMatrix(this._reflectanceTexture, ubo, "reflectance");
+ }
+ if (this._microSurfaceTexture) {
+ ubo.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
+ BindTextureMatrix(this._microSurfaceTexture, ubo, "microSurfaceSampler");
+ }
+ }
+ if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
+ ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
+ BindTextureMatrix(this._bumpTexture, ubo, "bump");
+ if (scene._mirroredCameraPosition) {
+ ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1, this._invertNormalMapY ? 1.0 : -1);
+ }
+ else {
+ ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1.0, this._invertNormalMapY ? -1 : 1.0);
+ }
+ }
+ }
+ // Point size
+ if (this.pointsCloud) {
+ ubo.updateFloat("pointSize", this.pointSize);
+ }
+ // Colors
+ if (defines.METALLICWORKFLOW) {
+ TmpColors.Color3[0].r = this._metallic === undefined || this._metallic === null ? 1 : this._metallic;
+ TmpColors.Color3[0].g = this._roughness === undefined || this._roughness === null ? 1 : this._roughness;
+ ubo.updateColor4("vReflectivityColor", TmpColors.Color3[0], 1);
+ const ior = this.subSurface?._indexOfRefraction ?? 1.5;
+ const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader.
+ // We are here deriving our default reflectance from a common value for none metallic surface.
+ // Based of the schlick fresnel approximation model
+ // for dielectrics.
+ const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2);
+ // Tweak the default F0 and F90 based on our given setup
+ this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]);
+ const metallicF90 = this._metallicF0Factor;
+ ubo.updateColor4("vMetallicReflectanceFactors", TmpColors.Color3[0], metallicF90);
+ }
+ else {
+ ubo.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
+ }
+ ubo.updateColor3("vEmissiveColor", MaterialFlags.EmissiveTextureEnabled ? this._emissiveColor : Color3.BlackReadOnly);
+ ubo.updateColor3("vReflectionColor", this._reflectionColor);
+ if (!defines.SS_REFRACTION && this.subSurface?._linkRefractionWithTransparency) {
+ ubo.updateColor4("vAlbedoColor", this._albedoColor, 1);
+ }
+ else {
+ ubo.updateColor4("vAlbedoColor", this._albedoColor, this.alpha);
+ }
+ ubo.updateFloat("baseWeight", this._baseWeight);
+ // Misc
+ this._lightingInfos.x = this._directIntensity;
+ this._lightingInfos.y = this._emissiveIntensity;
+ this._lightingInfos.z = this._environmentIntensity * scene.environmentIntensity;
+ this._lightingInfos.w = this._specularIntensity;
+ ubo.updateVector4("vLightingIntensity", this._lightingInfos);
+ // Colors
+ scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
+ ubo.updateColor3("vAmbientColor", this._globalAmbientColor);
+ ubo.updateFloat2("vDebugMode", this.debugLimit, this.debugFactor);
+ }
+ // Textures
+ if (scene.texturesEnabled) {
+ if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
+ ubo.setTexture("albedoSampler", this._albedoTexture);
+ }
+ if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) {
+ ubo.setTexture("baseWeightSampler", this._baseWeightTexture);
+ }
+ if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
+ ubo.setTexture("ambientSampler", this._ambientTexture);
+ }
+ if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
+ ubo.setTexture("opacitySampler", this._opacityTexture);
+ }
+ if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
+ if (defines.LODBASEDMICROSFURACE) {
+ ubo.setTexture("reflectionSampler", reflectionTexture);
+ }
+ else {
+ ubo.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
+ ubo.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
+ ubo.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
+ }
+ if (defines.USEIRRADIANCEMAP) {
+ ubo.setTexture("irradianceSampler", reflectionTexture.irradianceTexture);
+ }
+ //if realtime filtering and using CDF maps, set them.
+ const cdfGenerator = this.getScene().iblCdfGenerator;
+ if (this.realTimeFiltering && cdfGenerator) {
+ ubo.setTexture("icdfSampler", cdfGenerator.getIcdfTexture());
+ }
+ }
+ if (defines.ENVIRONMENTBRDF) {
+ ubo.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
+ }
+ if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
+ ubo.setTexture("emissiveSampler", this._emissiveTexture);
+ }
+ if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
+ ubo.setTexture("lightmapSampler", this._lightmapTexture);
+ }
+ if (MaterialFlags.SpecularTextureEnabled) {
+ if (this._metallicTexture) {
+ ubo.setTexture("reflectivitySampler", this._metallicTexture);
+ }
+ else if (this._reflectivityTexture) {
+ ubo.setTexture("reflectivitySampler", this._reflectivityTexture);
+ }
+ if (this._metallicReflectanceTexture) {
+ ubo.setTexture("metallicReflectanceSampler", this._metallicReflectanceTexture);
+ }
+ if (this._reflectanceTexture && defines.REFLECTANCE) {
+ ubo.setTexture("reflectanceSampler", this._reflectanceTexture);
+ }
+ if (this._microSurfaceTexture) {
+ ubo.setTexture("microSurfaceSampler", this._microSurfaceTexture);
+ }
+ }
+ if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
+ ubo.setTexture("bumpSampler", this._bumpTexture);
+ }
+ }
+ // OIT with depth peeling
+ if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) {
+ this.getScene().depthPeelingRenderer.bind(effect);
+ }
+ this._eventInfo.subMesh = subMesh;
+ this._callbackPluginEventBindForSubMesh(this._eventInfo);
+ // Clip plane
+ bindClipPlane(this._activeEffect, this, scene);
+ this.bindEyePosition(effect);
+ }
+ else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {
+ this._needToBindSceneUbo = true;
+ }
+ if (mustRebind || !this.isFrozen) {
+ // Lights
+ if (scene.lightsEnabled && !this._disableLighting) {
+ BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights);
+ }
+ // View
+ if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) ||
+ reflectionTexture ||
+ this.subSurface.refractionTexture ||
+ mesh.receiveShadows ||
+ defines.PREPASS) {
+ this.bindView(effect);
+ }
+ // Fog
+ BindFogParameters(scene, mesh, this._activeEffect, true);
+ // Morph targets
+ if (defines.NUM_MORPH_INFLUENCERS) {
+ BindMorphTargetParameters(mesh, this._activeEffect);
+ }
+ if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) {
+ mesh.bakedVertexAnimationManager?.bind(effect, defines.INSTANCES);
+ }
+ // image processing
+ this._imageProcessingConfiguration.bind(this._activeEffect);
+ // Log. depth
+ BindLogDepth(defines, this._activeEffect, scene);
+ }
+ this._afterBind(mesh, this._activeEffect, subMesh);
+ ubo.update();
+ }
+ /**
+ * Returns the animatable textures.
+ * If material have animatable metallic texture, then reflectivity texture will not be returned, even if it has animations.
+ * @returns - Array of animatable textures.
+ */
+ getAnimatables() {
+ const results = super.getAnimatables();
+ if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
+ results.push(this._albedoTexture);
+ }
+ if (this._baseWeightTexture && this._baseWeightTexture.animations && this._baseWeightTexture.animations.length > 0) {
+ results.push(this._baseWeightTexture);
+ }
+ if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
+ results.push(this._ambientTexture);
+ }
+ if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
+ results.push(this._opacityTexture);
+ }
+ if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
+ results.push(this._reflectionTexture);
+ }
+ if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
+ results.push(this._emissiveTexture);
+ }
+ if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
+ results.push(this._metallicTexture);
+ }
+ else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
+ results.push(this._reflectivityTexture);
+ }
+ if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
+ results.push(this._bumpTexture);
+ }
+ if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
+ results.push(this._lightmapTexture);
+ }
+ if (this._metallicReflectanceTexture && this._metallicReflectanceTexture.animations && this._metallicReflectanceTexture.animations.length > 0) {
+ results.push(this._metallicReflectanceTexture);
+ }
+ if (this._reflectanceTexture && this._reflectanceTexture.animations && this._reflectanceTexture.animations.length > 0) {
+ results.push(this._reflectanceTexture);
+ }
+ if (this._microSurfaceTexture && this._microSurfaceTexture.animations && this._microSurfaceTexture.animations.length > 0) {
+ results.push(this._microSurfaceTexture);
+ }
+ return results;
+ }
+ /**
+ * Returns the texture used for reflections.
+ * @returns - Reflection texture if present. Otherwise, returns the environment texture.
+ */
+ _getReflectionTexture() {
+ if (this._reflectionTexture) {
+ return this._reflectionTexture;
+ }
+ return this.getScene().environmentTexture;
+ }
+ /**
+ * Returns an array of the actively used textures.
+ * @returns - Array of BaseTextures
+ */
+ getActiveTextures() {
+ const activeTextures = super.getActiveTextures();
+ if (this._albedoTexture) {
+ activeTextures.push(this._albedoTexture);
+ }
+ if (this._baseWeightTexture) {
+ activeTextures.push(this._baseWeightTexture);
+ }
+ if (this._ambientTexture) {
+ activeTextures.push(this._ambientTexture);
+ }
+ if (this._opacityTexture) {
+ activeTextures.push(this._opacityTexture);
+ }
+ if (this._reflectionTexture) {
+ activeTextures.push(this._reflectionTexture);
+ }
+ if (this._emissiveTexture) {
+ activeTextures.push(this._emissiveTexture);
+ }
+ if (this._reflectivityTexture) {
+ activeTextures.push(this._reflectivityTexture);
+ }
+ if (this._metallicTexture) {
+ activeTextures.push(this._metallicTexture);
+ }
+ if (this._metallicReflectanceTexture) {
+ activeTextures.push(this._metallicReflectanceTexture);
+ }
+ if (this._reflectanceTexture) {
+ activeTextures.push(this._reflectanceTexture);
+ }
+ if (this._microSurfaceTexture) {
+ activeTextures.push(this._microSurfaceTexture);
+ }
+ if (this._bumpTexture) {
+ activeTextures.push(this._bumpTexture);
+ }
+ if (this._lightmapTexture) {
+ activeTextures.push(this._lightmapTexture);
+ }
+ return activeTextures;
+ }
+ /**
+ * Checks to see if a texture is used in the material.
+ * @param texture - Base texture to use.
+ * @returns - Boolean specifying if a texture is used in the material.
+ */
+ hasTexture(texture) {
+ if (super.hasTexture(texture)) {
+ return true;
+ }
+ if (this._albedoTexture === texture) {
+ return true;
+ }
+ if (this._baseWeightTexture === texture) {
+ return true;
+ }
+ if (this._ambientTexture === texture) {
+ return true;
+ }
+ if (this._opacityTexture === texture) {
+ return true;
+ }
+ if (this._reflectionTexture === texture) {
+ return true;
+ }
+ if (this._emissiveTexture === texture) {
+ return true;
+ }
+ if (this._reflectivityTexture === texture) {
+ return true;
+ }
+ if (this._metallicTexture === texture) {
+ return true;
+ }
+ if (this._metallicReflectanceTexture === texture) {
+ return true;
+ }
+ if (this._reflectanceTexture === texture) {
+ return true;
+ }
+ if (this._microSurfaceTexture === texture) {
+ return true;
+ }
+ if (this._bumpTexture === texture) {
+ return true;
+ }
+ if (this._lightmapTexture === texture) {
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Sets the required values to the prepass renderer.
+ * It can't be sets when subsurface scattering of this material is disabled.
+ * When scene have ability to enable subsurface prepass effect, it will enable.
+ * @returns - If prepass is enabled or not.
+ */
+ setPrePassRenderer() {
+ if (!this.subSurface?.isScatteringEnabled) {
+ return false;
+ }
+ const subSurfaceConfiguration = this.getScene().enableSubSurfaceForPrePass();
+ if (subSurfaceConfiguration) {
+ subSurfaceConfiguration.enabled = true;
+ }
+ return true;
+ }
+ /**
+ * Disposes the resources of the material.
+ * @param forceDisposeEffect - Forces the disposal of effects.
+ * @param forceDisposeTextures - Forces the disposal of all textures.
+ */
+ dispose(forceDisposeEffect, forceDisposeTextures) {
+ this._breakShaderLoadedCheck = true;
+ if (forceDisposeTextures) {
+ if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) {
+ this._environmentBRDFTexture.dispose();
+ }
+ this._albedoTexture?.dispose();
+ this._baseWeightTexture?.dispose();
+ this._ambientTexture?.dispose();
+ this._opacityTexture?.dispose();
+ this._reflectionTexture?.dispose();
+ this._emissiveTexture?.dispose();
+ this._metallicTexture?.dispose();
+ this._reflectivityTexture?.dispose();
+ this._bumpTexture?.dispose();
+ this._lightmapTexture?.dispose();
+ this._metallicReflectanceTexture?.dispose();
+ this._reflectanceTexture?.dispose();
+ this._microSurfaceTexture?.dispose();
+ }
+ this._renderTargets.dispose();
+ if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
+ this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
+ }
+ super.dispose(forceDisposeEffect, forceDisposeTextures);
+ }
+}
+/**
+ * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
+ */
+PBRBaseMaterial.PBRMATERIAL_OPAQUE = Material.MATERIAL_OPAQUE;
+/**
+ * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
+ */
+PBRBaseMaterial.PBRMATERIAL_ALPHATEST = Material.MATERIAL_ALPHATEST;
+/**
+ * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
+ */
+PBRBaseMaterial.PBRMATERIAL_ALPHABLEND = Material.MATERIAL_ALPHABLEND;
+/**
+ * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
+ * They are also discarded below the alpha cutoff threshold to improve performances.
+ */
+PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = Material.MATERIAL_ALPHATESTANDBLEND;
+/**
+ * Defines the default value of how much AO map is occluding the analytical lights
+ * (point spot...).
+ */
+PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0;
+/**
+ * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
+ */
+PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
+/**
+ * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
+ * to enhance interoperability with other engines.
+ */
+PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
+/**
+ * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
+ * to enhance interoperability with other materials.
+ */
+PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
+/**
+ * Force all the PBR materials to compile to glsl even on WebGPU engines.
+ * False by default. This is mostly meant for backward compatibility.
+ */
+PBRBaseMaterial.ForceGLSL = false;
+__decorate([
+ serializeAsImageProcessingConfiguration()
+], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRBaseMaterial.prototype, "debugMode", void 0);
+
+/**
+ * The Physically based material of BJS.
+ *
+ * This offers the main features of a standard PBR material.
+ * For more information, please refer to the documentation :
+ * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR
+ */
+class PBRMaterial extends PBRBaseMaterial {
+ /**
+ * Stores the refracted light information in a texture.
+ */
+ get refractionTexture() {
+ return this.subSurface.refractionTexture;
+ }
+ set refractionTexture(value) {
+ this.subSurface.refractionTexture = value;
+ if (value) {
+ this.subSurface.isRefractionEnabled = true;
+ }
+ else if (!this.subSurface.linkRefractionWithTransparency) {
+ this.subSurface.isRefractionEnabled = false;
+ }
+ }
+ /**
+ * Index of refraction of the material base layer.
+ * https://en.wikipedia.org/wiki/List_of_refractive_indices
+ *
+ * This does not only impact refraction but also the Base F0 of Dielectric Materials.
+ *
+ * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI))
+ */
+ get indexOfRefraction() {
+ return this.subSurface.indexOfRefraction;
+ }
+ set indexOfRefraction(value) {
+ this.subSurface.indexOfRefraction = value;
+ }
+ /**
+ * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
+ */
+ get invertRefractionY() {
+ return this.subSurface.invertRefractionY;
+ }
+ set invertRefractionY(value) {
+ this.subSurface.invertRefractionY = value;
+ }
+ /**
+ * This parameters will make the material used its opacity to control how much it is refracting against not.
+ * Materials half opaque for instance using refraction could benefit from this control.
+ */
+ get linkRefractionWithTransparency() {
+ return this.subSurface.linkRefractionWithTransparency;
+ }
+ set linkRefractionWithTransparency(value) {
+ this.subSurface.linkRefractionWithTransparency = value;
+ if (value) {
+ this.subSurface.isRefractionEnabled = true;
+ }
+ }
+ /**
+ * BJS is using an hardcoded light falloff based on a manually sets up range.
+ * In PBR, one way to represents the falloff is to use the inverse squared root algorithm.
+ * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
+ */
+ get usePhysicalLightFalloff() {
+ return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
+ }
+ /**
+ * BJS is using an hardcoded light falloff based on a manually sets up range.
+ * In PBR, one way to represents the falloff is to use the inverse squared root algorithm.
+ * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
+ */
+ set usePhysicalLightFalloff(value) {
+ if (value !== this.usePhysicalLightFalloff) {
+ // Ensure the effect will be rebuilt.
+ this._markAllSubMeshesAsTexturesDirty();
+ if (value) {
+ this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
+ }
+ else {
+ this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
+ }
+ }
+ }
+ /**
+ * In order to support the falloff compatibility with gltf, a special mode has been added
+ * to reproduce the gltf light falloff.
+ */
+ get useGLTFLightFalloff() {
+ return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF;
+ }
+ /**
+ * In order to support the falloff compatibility with gltf, a special mode has been added
+ * to reproduce the gltf light falloff.
+ */
+ set useGLTFLightFalloff(value) {
+ if (value !== this.useGLTFLightFalloff) {
+ // Ensure the effect will be rebuilt.
+ this._markAllSubMeshesAsTexturesDirty();
+ if (value) {
+ this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_GLTF;
+ }
+ else {
+ this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
+ }
+ }
+ }
+ /**
+ * Gets the image processing configuration used either in this material.
+ */
+ get imageProcessingConfiguration() {
+ return this._imageProcessingConfiguration;
+ }
+ /**
+ * Sets the Default image processing configuration used either in the this material.
+ *
+ * If sets to null, the scene one is in use.
+ */
+ set imageProcessingConfiguration(value) {
+ this._attachImageProcessingConfiguration(value);
+ // Ensure the effect will be rebuilt.
+ this._markAllSubMeshesAsTexturesDirty();
+ }
+ /**
+ * Gets whether the color curves effect is enabled.
+ */
+ get cameraColorCurvesEnabled() {
+ return this.imageProcessingConfiguration.colorCurvesEnabled;
+ }
+ /**
+ * Sets whether the color curves effect is enabled.
+ */
+ set cameraColorCurvesEnabled(value) {
+ this.imageProcessingConfiguration.colorCurvesEnabled = value;
+ }
+ /**
+ * Gets whether the color grading effect is enabled.
+ */
+ get cameraColorGradingEnabled() {
+ return this.imageProcessingConfiguration.colorGradingEnabled;
+ }
+ /**
+ * Gets whether the color grading effect is enabled.
+ */
+ set cameraColorGradingEnabled(value) {
+ this.imageProcessingConfiguration.colorGradingEnabled = value;
+ }
+ /**
+ * Gets whether tonemapping is enabled or not.
+ */
+ get cameraToneMappingEnabled() {
+ return this._imageProcessingConfiguration.toneMappingEnabled;
+ }
+ /**
+ * Sets whether tonemapping is enabled or not
+ */
+ set cameraToneMappingEnabled(value) {
+ this._imageProcessingConfiguration.toneMappingEnabled = value;
+ }
+ /**
+ * The camera exposure used on this material.
+ * This property is here and not in the camera to allow controlling exposure without full screen post process.
+ * This corresponds to a photographic exposure.
+ */
+ get cameraExposure() {
+ return this._imageProcessingConfiguration.exposure;
+ }
+ /**
+ * The camera exposure used on this material.
+ * This property is here and not in the camera to allow controlling exposure without full screen post process.
+ * This corresponds to a photographic exposure.
+ */
+ set cameraExposure(value) {
+ this._imageProcessingConfiguration.exposure = value;
+ }
+ /**
+ * Gets The camera contrast used on this material.
+ */
+ get cameraContrast() {
+ return this._imageProcessingConfiguration.contrast;
+ }
+ /**
+ * Sets The camera contrast used on this material.
+ */
+ set cameraContrast(value) {
+ this._imageProcessingConfiguration.contrast = value;
+ }
+ /**
+ * Gets the Color Grading 2D Lookup Texture.
+ */
+ get cameraColorGradingTexture() {
+ return this._imageProcessingConfiguration.colorGradingTexture;
+ }
+ /**
+ * Sets the Color Grading 2D Lookup Texture.
+ */
+ set cameraColorGradingTexture(value) {
+ this._imageProcessingConfiguration.colorGradingTexture = value;
+ }
+ /**
+ * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).
+ * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
+ * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
+ * corresponding to low luminance, medium luminance, and high luminance areas respectively.
+ */
+ get cameraColorCurves() {
+ return this._imageProcessingConfiguration.colorCurves;
+ }
+ /**
+ * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).
+ * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
+ * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
+ * corresponding to low luminance, medium luminance, and high luminance areas respectively.
+ */
+ set cameraColorCurves(value) {
+ this._imageProcessingConfiguration.colorCurves = value;
+ }
+ /**
+ * Instantiates a new PBRMaterial instance.
+ *
+ * @param name The material name
+ * @param scene The scene the material will be use in.
+ * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false
+ */
+ constructor(name, scene, forceGLSL = false) {
+ super(name, scene, forceGLSL);
+ /**
+ * Intensity of the direct lights e.g. the four lights available in your scene.
+ * This impacts both the direct diffuse and specular highlights.
+ */
+ this.directIntensity = 1.0;
+ /**
+ * Intensity of the emissive part of the material.
+ * This helps controlling the emissive effect without modifying the emissive color.
+ */
+ this.emissiveIntensity = 1.0;
+ /**
+ * Intensity of the environment e.g. how much the environment will light the object
+ * either through harmonics for rough material or through the reflection for shiny ones.
+ */
+ this.environmentIntensity = 1.0;
+ /**
+ * This is a special control allowing the reduction of the specular highlights coming from the
+ * four lights of the scene. Those highlights may not be needed in full environment lighting.
+ */
+ this.specularIntensity = 1.0;
+ /**
+ * Debug Control allowing disabling the bump map on this material.
+ */
+ this.disableBumpMap = false;
+ /**
+ * AKA Occlusion Texture Intensity in other nomenclature.
+ */
+ this.ambientTextureStrength = 1.0;
+ /**
+ * Defines how much the AO map is occluding the analytical lights (point spot...).
+ * 1 means it completely occludes it
+ * 0 mean it has no impact
+ */
+ this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
+ /**
+ * In metallic workflow, specifies an F0 factor to help configuring the material F0.
+ * By default the indexOfrefraction is used to compute F0;
+ *
+ * This is used as a factor against the default reflectance at normal incidence to tweak it.
+ *
+ * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;
+ * F90 = metallicReflectanceColor;
+ */
+ this.metallicF0Factor = 1;
+ /**
+ * In metallic workflow, specifies an F0 color.
+ * By default the F90 is always 1;
+ *
+ * Please note that this factor is also used as a factor against the default reflectance at normal incidence.
+ *
+ * F0 = defaultF0_from_IOR * metallicF0Factor * metallicReflectanceColor
+ * F90 = metallicF0Factor;
+ */
+ this.metallicReflectanceColor = Color3.White();
+ /**
+ * Specifies that only the A channel from metallicReflectanceTexture should be used.
+ * If false, both RGB and A channels will be used
+ */
+ this.useOnlyMetallicFromMetallicReflectanceTexture = false;
+ /**
+ * The color of a material in ambient lighting.
+ */
+ this.ambientColor = new Color3(0, 0, 0);
+ /**
+ * AKA Diffuse Color in other nomenclature.
+ */
+ this.albedoColor = new Color3(1, 1, 1);
+ /**
+ * OpenPBR Base Weight (multiplier to the diffuse and metal lobes).
+ */
+ this.baseWeight = 1;
+ /**
+ * AKA Specular Color in other nomenclature.
+ */
+ this.reflectivityColor = new Color3(1, 1, 1);
+ /**
+ * The color reflected from the material.
+ */
+ this.reflectionColor = new Color3(1.0, 1.0, 1.0);
+ /**
+ * The color emitted from the material.
+ */
+ this.emissiveColor = new Color3(0, 0, 0);
+ /**
+ * AKA Glossiness in other nomenclature.
+ */
+ this.microSurface = 1.0;
+ /**
+ * If true, the light map contains occlusion information instead of lighting info.
+ */
+ this.useLightmapAsShadowmap = false;
+ /**
+ * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
+ */
+ this.useAlphaFromAlbedoTexture = false;
+ /**
+ * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
+ */
+ this.forceAlphaTest = false;
+ /**
+ * Defines the alpha limits in alpha test mode.
+ */
+ this.alphaCutOff = 0.4;
+ /**
+ * Specifies that the material will keep the specular highlights over a transparent surface (only the most luminous ones).
+ * A car glass is a good example of that. When sun reflects on it you can not see what is behind.
+ */
+ this.useSpecularOverAlpha = true;
+ /**
+ * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
+ */
+ this.useMicroSurfaceFromReflectivityMapAlpha = false;
+ /**
+ * Specifies if the metallic texture contains the roughness information in its alpha channel.
+ */
+ this.useRoughnessFromMetallicTextureAlpha = true;
+ /**
+ * Specifies if the metallic texture contains the roughness information in its green channel.
+ * Needs useRoughnessFromMetallicTextureAlpha to be false.
+ */
+ this.useRoughnessFromMetallicTextureGreen = false;
+ /**
+ * Specifies if the metallic texture contains the metallness information in its blue channel.
+ */
+ this.useMetallnessFromMetallicTextureBlue = false;
+ /**
+ * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
+ */
+ this.useAmbientOcclusionFromMetallicTextureRed = false;
+ /**
+ * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
+ */
+ this.useAmbientInGrayScale = false;
+ /**
+ * In case the reflectivity map does not contain the microsurface information in its alpha channel,
+ * The material will try to infer what glossiness each pixel should be.
+ */
+ this.useAutoMicroSurfaceFromReflectivityMap = false;
+ /**
+ * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).
+ * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind.
+ */
+ this.useRadianceOverAlpha = true;
+ /**
+ * Allows using an object space normal map (instead of tangent space).
+ */
+ this.useObjectSpaceNormalMap = false;
+ /**
+ * Allows using the bump map in parallax mode.
+ */
+ this.useParallax = false;
+ /**
+ * Allows using the bump map in parallax occlusion mode.
+ */
+ this.useParallaxOcclusion = false;
+ /**
+ * Controls the scale bias of the parallax mode.
+ */
+ this.parallaxScaleBias = 0.05;
+ /**
+ * If sets to true, disables all the lights affecting the material.
+ */
+ this.disableLighting = false;
+ /**
+ * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
+ */
+ this.forceIrradianceInFragment = false;
+ /**
+ * Number of Simultaneous lights allowed on the material.
+ */
+ this.maxSimultaneousLights = 4;
+ /**
+ * If sets to true, x component of normal map value will invert (x = 1.0 - x).
+ */
+ this.invertNormalMapX = false;
+ /**
+ * If sets to true, y component of normal map value will invert (y = 1.0 - y).
+ */
+ this.invertNormalMapY = false;
+ /**
+ * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
+ */
+ this.twoSidedLighting = false;
+ /**
+ * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
+ * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
+ */
+ this.useAlphaFresnel = false;
+ /**
+ * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
+ * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
+ */
+ this.useLinearAlphaFresnel = false;
+ /**
+ * Let user defines the brdf lookup texture used for IBL.
+ * A default 8bit version is embedded but you could point at :
+ * * Default texture: https://assets.babylonjs.com/environments/correlatedMSBRDF_RGBD.png
+ * * Default 16bit pixel depth texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.dds
+ * * LEGACY Default None correlated https://assets.babylonjs.com/environments/uncorrelatedBRDF_RGBD.png
+ * * LEGACY Default None correlated 16bit pixel depth https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds
+ */
+ this.environmentBRDFTexture = null;
+ /**
+ * Force normal to face away from face.
+ */
+ this.forceNormalForward = false;
+ /**
+ * Enables specular anti aliasing in the PBR shader.
+ * It will both interacts on the Geometry for analytical and IBL lighting.
+ * It also prefilter the roughness map based on the bump values.
+ */
+ this.enableSpecularAntiAliasing = false;
+ /**
+ * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
+ * makes the reflect vector face the model (under horizon).
+ */
+ this.useHorizonOcclusion = true;
+ /**
+ * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
+ * too much the area relying on ambient texture to define their ambient occlusion.
+ */
+ this.useRadianceOcclusion = true;
+ /**
+ * If set to true, no lighting calculations will be applied.
+ */
+ this.unlit = false;
+ /**
+ * If sets to true, the decal map will be applied after the detail map. Else, it is applied before (default: false)
+ */
+ this.applyDecalMapAfterDetailMap = false;
+ this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene());
+ }
+ /**
+ * @returns the name of this material class.
+ */
+ getClassName() {
+ return "PBRMaterial";
+ }
+ /**
+ * Makes a duplicate of the current material.
+ * @param name - name to use for the new material.
+ * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false.
+ * @param rootUrl defines the root URL to use to load textures
+ * @returns cloned material instance
+ */
+ clone(name, cloneTexturesOnlyOnce = true, rootUrl = "") {
+ const clone = SerializationHelper.Clone(() => new PBRMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce });
+ clone.id = name;
+ clone.name = name;
+ this.stencil.copyTo(clone.stencil);
+ this._clonePlugins(clone, rootUrl);
+ return clone;
+ }
+ /**
+ * Serializes this PBR Material.
+ * @returns - An object with the serialized material.
+ */
+ serialize() {
+ const serializationObject = super.serialize();
+ serializationObject.customType = "BABYLON.PBRMaterial";
+ return serializationObject;
+ }
+ // Statics
+ /**
+ * Parses a PBR Material from a serialized object.
+ * @param source - Serialized object.
+ * @param scene - BJS scene instance.
+ * @param rootUrl - url for the scene object
+ * @returns - PBRMaterial
+ */
+ static Parse(source, scene, rootUrl) {
+ const material = SerializationHelper.Parse(() => new PBRMaterial(source.name, scene), source, scene, rootUrl);
+ if (source.stencil) {
+ material.stencil.parse(source.stencil, scene, rootUrl);
+ }
+ Material._ParsePlugins(source, material, scene, rootUrl);
+ // The code block below ensures backward compatibility with serialized materials before plugins are automatically serialized.
+ if (source.clearCoat) {
+ material.clearCoat.parse(source.clearCoat, scene, rootUrl);
+ }
+ if (source.anisotropy) {
+ material.anisotropy.parse(source.anisotropy, scene, rootUrl);
+ }
+ if (source.brdf) {
+ material.brdf.parse(source.brdf, scene, rootUrl);
+ }
+ if (source.sheen) {
+ material.sheen.parse(source.sheen, scene, rootUrl);
+ }
+ if (source.subSurface) {
+ material.subSurface.parse(source.subSurface, scene, rootUrl);
+ }
+ if (source.iridescence) {
+ material.iridescence.parse(source.iridescence, scene, rootUrl);
+ }
+ return material;
+ }
+}
+/**
+ * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
+ */
+PBRMaterial.PBRMATERIAL_OPAQUE = PBRBaseMaterial.PBRMATERIAL_OPAQUE;
+/**
+ * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
+ */
+PBRMaterial.PBRMATERIAL_ALPHATEST = PBRBaseMaterial.PBRMATERIAL_ALPHATEST;
+/**
+ * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
+ */
+PBRMaterial.PBRMATERIAL_ALPHABLEND = PBRBaseMaterial.PBRMATERIAL_ALPHABLEND;
+/**
+ * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
+ * They are also discarded below the alpha cutoff threshold to improve performances.
+ */
+PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND;
+/**
+ * Defines the default value of how much AO map is occluding the analytical lights
+ * (point spot...).
+ */
+PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "directIntensity", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "emissiveIntensity", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "environmentIntensity", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "specularIntensity", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "disableBumpMap", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "albedoTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "baseWeightTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "ambientTexture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "ambientTextureStrength", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
+], PBRMaterial.prototype, "opacityTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "reflectionTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "emissiveTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "reflectivityTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "metallicTexture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "metallic", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "roughness", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "metallicF0Factor", void 0);
+__decorate([
+ serializeAsColor3(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "metallicReflectanceColor", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useOnlyMetallicFromMetallicReflectanceTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "metallicReflectanceTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "reflectanceTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "microSurfaceTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "bumpTexture", void 0);
+__decorate([
+ serializeAsTexture(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
+], PBRMaterial.prototype, "lightmapTexture", void 0);
+__decorate([
+ serializeAsColor3("ambient"),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "ambientColor", void 0);
+__decorate([
+ serializeAsColor3("albedo"),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "albedoColor", void 0);
+__decorate([
+ serialize("baseWeight"),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "baseWeight", void 0);
+__decorate([
+ serializeAsColor3("reflectivity"),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "reflectivityColor", void 0);
+__decorate([
+ serializeAsColor3("reflection"),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "reflectionColor", void 0);
+__decorate([
+ serializeAsColor3("emissive"),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "emissiveColor", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "microSurface", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
+], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
+], PBRMaterial.prototype, "forceAlphaTest", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
+], PBRMaterial.prototype, "alphaCutOff", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
+__decorate([
+ serialize()
+], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
+__decorate([
+ serialize()
+], PBRMaterial.prototype, "useGLTFLightFalloff", null);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useParallax", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "parallaxScaleBias", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsLightsDirty")
+], PBRMaterial.prototype, "disableLighting", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsLightsDirty")
+], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "invertNormalMapX", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "invertNormalMapY", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "twoSidedLighting", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useAlphaFresnel", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
+__decorate([
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "forceNormalForward", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsTexturesDirty")
+], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRMaterial.prototype, "unlit", void 0);
+__decorate([
+ serialize(),
+ expandToProperty("_markAllSubMeshesAsMiscDirty")
+], PBRMaterial.prototype, "applyDecalMapAfterDetailMap", void 0);
+RegisterClass("BABYLON.PBRMaterial", PBRMaterial);
+
+/**
+ * Defines a target to use with MorphTargetManager
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets
+ */
+class MorphTarget {
+ /**
+ * Gets or sets the influence of this target (ie. its weight in the overall morphing)
+ */
+ get influence() {
+ return this._influence;
+ }
+ set influence(influence) {
+ if (this._influence === influence) {
+ return;
+ }
+ const previous = this._influence;
+ this._influence = influence;
+ if (this.onInfluenceChanged.hasObservers()) {
+ this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
+ }
+ }
+ /**
+ * Gets or sets the animation properties override
+ */
+ get animationPropertiesOverride() {
+ if (!this._animationPropertiesOverride && this._scene) {
+ return this._scene.animationPropertiesOverride;
+ }
+ return this._animationPropertiesOverride;
+ }
+ set animationPropertiesOverride(value) {
+ this._animationPropertiesOverride = value;
+ }
+ /**
+ * Creates a new MorphTarget
+ * @param name defines the name of the target
+ * @param influence defines the influence to use
+ * @param scene defines the scene the morphtarget belongs to
+ */
+ constructor(
+ /** defines the name of the target */
+ name, influence = 0, scene = null) {
+ this.name = name;
+ /**
+ * Gets or sets the list of animations
+ */
+ this.animations = [];
+ this._positions = null;
+ this._normals = null;
+ this._tangents = null;
+ this._uvs = null;
+ this._uv2s = null;
+ this._colors = null;
+ this._uniqueId = 0;
+ /**
+ * Observable raised when the influence changes
+ */
+ this.onInfluenceChanged = new Observable();
+ /** @internal */
+ this._onDataLayoutChanged = new Observable();
+ this._animationPropertiesOverride = null;
+ this.id = name;
+ this._scene = scene || EngineStore.LastCreatedScene;
+ this.influence = influence;
+ if (this._scene) {
+ this._uniqueId = this._scene.getUniqueId();
+ }
+ }
+ /**
+ * Gets the unique ID of this manager
+ */
+ get uniqueId() {
+ return this._uniqueId;
+ }
+ /**
+ * Gets a boolean defining if the target contains position data
+ */
+ get hasPositions() {
+ return !!this._positions;
+ }
+ /**
+ * Gets a boolean defining if the target contains normal data
+ */
+ get hasNormals() {
+ return !!this._normals;
+ }
+ /**
+ * Gets a boolean defining if the target contains tangent data
+ */
+ get hasTangents() {
+ return !!this._tangents;
+ }
+ /**
+ * Gets a boolean defining if the target contains texture coordinates data
+ */
+ get hasUVs() {
+ return !!this._uvs;
+ }
+ /**
+ * Gets a boolean defining if the target contains texture coordinates 2 data
+ */
+ get hasUV2s() {
+ return !!this._uv2s;
+ }
+ get hasColors() {
+ return !!this._colors;
+ }
+ /**
+ * Gets the number of vertices stored in this target
+ */
+ get vertexCount() {
+ return this._positions
+ ? this._positions.length / 3
+ : this._normals
+ ? this._normals.length / 3
+ : this._tangents
+ ? this._tangents.length / 3
+ : this._uvs
+ ? this._uvs.length / 2
+ : this._uv2s
+ ? this._uv2s.length / 2
+ : this._colors
+ ? this._colors.length / 4
+ : 0;
+ }
+ /**
+ * Affects position data to this target
+ * @param data defines the position data to use
+ */
+ setPositions(data) {
+ const hadPositions = this.hasPositions;
+ this._positions = data;
+ if (hadPositions !== this.hasPositions) {
+ this._onDataLayoutChanged.notifyObservers(undefined);
+ }
+ }
+ /**
+ * Gets the position data stored in this target
+ * @returns a FloatArray containing the position data (or null if not present)
+ */
+ getPositions() {
+ return this._positions;
+ }
+ /**
+ * Affects normal data to this target
+ * @param data defines the normal data to use
+ */
+ setNormals(data) {
+ const hadNormals = this.hasNormals;
+ this._normals = data;
+ if (hadNormals !== this.hasNormals) {
+ this._onDataLayoutChanged.notifyObservers(undefined);
+ }
+ }
+ /**
+ * Gets the normal data stored in this target
+ * @returns a FloatArray containing the normal data (or null if not present)
+ */
+ getNormals() {
+ return this._normals;
+ }
+ /**
+ * Affects tangent data to this target
+ * @param data defines the tangent data to use
+ */
+ setTangents(data) {
+ const hadTangents = this.hasTangents;
+ this._tangents = data;
+ if (hadTangents !== this.hasTangents) {
+ this._onDataLayoutChanged.notifyObservers(undefined);
+ }
+ }
+ /**
+ * Gets the tangent data stored in this target
+ * @returns a FloatArray containing the tangent data (or null if not present)
+ */
+ getTangents() {
+ return this._tangents;
+ }
+ /**
+ * Affects texture coordinates data to this target
+ * @param data defines the texture coordinates data to use
+ */
+ setUVs(data) {
+ const hadUVs = this.hasUVs;
+ this._uvs = data;
+ if (hadUVs !== this.hasUVs) {
+ this._onDataLayoutChanged.notifyObservers(undefined);
+ }
+ }
+ /**
+ * Gets the texture coordinates data stored in this target
+ * @returns a FloatArray containing the texture coordinates data (or null if not present)
+ */
+ getUVs() {
+ return this._uvs;
+ }
+ /**
+ * Affects texture coordinates 2 data to this target
+ * @param data defines the texture coordinates 2 data to use
+ */
+ setUV2s(data) {
+ const hadUV2s = this.hasUV2s;
+ this._uv2s = data;
+ if (hadUV2s !== this.hasUV2s) {
+ this._onDataLayoutChanged.notifyObservers(undefined);
+ }
+ }
+ /**
+ * Gets the texture coordinates 2 data stored in this target
+ * @returns a FloatArray containing the texture coordinates 2 data (or null if not present)
+ */
+ getUV2s() {
+ return this._uv2s;
+ }
+ /**
+ * Affects color data to this target
+ * @param data defines the color data to use
+ */
+ setColors(data) {
+ const hadColors = this.hasColors;
+ this._colors = data;
+ if (hadColors !== this.hasColors) {
+ this._onDataLayoutChanged.notifyObservers(undefined);
+ }
+ }
+ /**
+ * Gets the color data stored in this target
+ * @returns a FloatArray containing the color data (or null if not present)
+ */
+ getColors() {
+ return this._colors;
+ }
+ /**
+ * Clone the current target
+ * @returns a new MorphTarget
+ */
+ clone() {
+ const newOne = SerializationHelper.Clone(() => new MorphTarget(this.name, this.influence, this._scene), this);
+ newOne._positions = this._positions;
+ newOne._normals = this._normals;
+ newOne._tangents = this._tangents;
+ newOne._uvs = this._uvs;
+ newOne._uv2s = this._uv2s;
+ newOne._colors = this._colors;
+ return newOne;
+ }
+ /**
+ * Serializes the current target into a Serialization object
+ * @returns the serialized object
+ */
+ serialize() {
+ const serializationObject = {};
+ serializationObject.name = this.name;
+ serializationObject.influence = this.influence;
+ serializationObject.positions = Array.prototype.slice.call(this.getPositions());
+ if (this.id != null) {
+ serializationObject.id = this.id;
+ }
+ if (this.hasNormals) {
+ serializationObject.normals = Array.prototype.slice.call(this.getNormals());
+ }
+ if (this.hasTangents) {
+ serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
+ }
+ if (this.hasUVs) {
+ serializationObject.uvs = Array.prototype.slice.call(this.getUVs());
+ }
+ if (this.hasUV2s) {
+ serializationObject.uv2s = Array.prototype.slice.call(this.getUV2s());
+ }
+ if (this.hasColors) {
+ serializationObject.colors = Array.prototype.slice.call(this.getColors());
+ }
+ // Animations
+ SerializationHelper.AppendSerializedAnimations(this, serializationObject);
+ return serializationObject;
+ }
+ /**
+ * Returns the string "MorphTarget"
+ * @returns "MorphTarget"
+ */
+ getClassName() {
+ return "MorphTarget";
+ }
+ // Statics
+ /**
+ * Creates a new target from serialized data
+ * @param serializationObject defines the serialized data to use
+ * @param scene defines the hosting scene
+ * @returns a new MorphTarget
+ */
+ static Parse(serializationObject, scene) {
+ const result = new MorphTarget(serializationObject.name, serializationObject.influence);
+ result.setPositions(serializationObject.positions);
+ if (serializationObject.id != null) {
+ result.id = serializationObject.id;
+ }
+ if (serializationObject.normals) {
+ result.setNormals(serializationObject.normals);
+ }
+ if (serializationObject.tangents) {
+ result.setTangents(serializationObject.tangents);
+ }
+ if (serializationObject.uvs) {
+ result.setUVs(serializationObject.uvs);
+ }
+ if (serializationObject.uv2s) {
+ result.setUV2s(serializationObject.uv2s);
+ }
+ if (serializationObject.colors) {
+ result.setColors(serializationObject.colors);
+ }
+ // Animations
+ if (serializationObject.animations) {
+ for (let animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
+ const parsedAnimation = serializationObject.animations[animationIndex];
+ const internalClass = GetClass("BABYLON.Animation");
+ if (internalClass) {
+ result.animations.push(internalClass.Parse(parsedAnimation));
+ }
+ }
+ if (serializationObject.autoAnimate && scene) {
+ scene.beginAnimation(result, serializationObject.autoAnimateFrom, serializationObject.autoAnimateTo, serializationObject.autoAnimateLoop, serializationObject.autoAnimateSpeed || 1.0);
+ }
+ }
+ return result;
+ }
+ /**
+ * Creates a MorphTarget from mesh data
+ * @param mesh defines the source mesh
+ * @param name defines the name to use for the new target
+ * @param influence defines the influence to attach to the target
+ * @returns a new MorphTarget
+ */
+ static FromMesh(mesh, name, influence) {
+ if (!name) {
+ name = mesh.name;
+ }
+ const result = new MorphTarget(name, influence, mesh.getScene());
+ result.setPositions(mesh.getVerticesData(VertexBuffer.PositionKind));
+ if (mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
+ result.setNormals(mesh.getVerticesData(VertexBuffer.NormalKind));
+ }
+ if (mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {
+ result.setTangents(mesh.getVerticesData(VertexBuffer.TangentKind));
+ }
+ if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
+ result.setUVs(mesh.getVerticesData(VertexBuffer.UVKind));
+ }
+ if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
+ result.setUV2s(mesh.getVerticesData(VertexBuffer.UV2Kind));
+ }
+ if (mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
+ result.setColors(mesh.getVerticesData(VertexBuffer.ColorKind));
+ }
+ return result;
+ }
+}
+__decorate([
+ serialize()
+], MorphTarget.prototype, "id", void 0);
+
+/**
+ * Class used to store 2D array textures containing user data
+ */
+class RawTexture2DArray extends Texture {
+ /**
+ * Gets the number of layers of the texture
+ */
+ get depth() {
+ return this._depth;
+ }
+ /**
+ * Create a new RawTexture2DArray
+ * @param data defines the data of the texture
+ * @param width defines the width of the texture
+ * @param height defines the height of the texture
+ * @param depth defines the number of layers of the texture
+ * @param format defines the texture format to use
+ * @param scene defines the hosting scene
+ * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
+ * @param invertY defines if texture must be stored with Y axis inverted
+ * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default)
+ * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_BYTE, Engine.TEXTURETYPE_FLOAT...)
+ * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
+ */
+ constructor(data, width, height, depth,
+ /** Gets or sets the texture format to use */
+ format, scene, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, textureType = 0, creationFlags) {
+ super(null, scene, !generateMipMaps, invertY);
+ this.format = format;
+ this._texture = scene.getEngine().createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType, creationFlags);
+ this._depth = depth;
+ this.is2DArray = true;
+ }
+ /**
+ * Update the texture with new data
+ * @param data defines the data to store in the texture
+ */
+ update(data) {
+ if (!this._texture) {
+ return;
+ }
+ this._getEngine().updateRawTexture2DArray(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type);
+ }
+ /**
+ * Creates a RGBA texture from some data.
+ * @param data Define the texture data
+ * @param width Define the width of the texture
+ * @param height Define the height of the texture
+ * @param depth defines the number of layers of the texture
+ * @param scene defines the scene the texture will belong to
+ * @param generateMipMaps Define whether or not to create mip maps for the texture
+ * @param invertY define if the data should be flipped on Y when uploaded to the GPU
+ * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
+ * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
+ * @returns the RGBA texture
+ */
+ static CreateRGBATexture(data, width, height, depth, scene, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0) {
+ return new RawTexture2DArray(data, width, height, depth, 5, scene, generateMipMaps, invertY, samplingMode, type);
+ }
+}
+
+/**
+ * This class is used to deform meshes using morphing between different targets
+ * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets
+ */
+class MorphTargetManager {
+ /**
+ * Sets a boolean indicating that adding new target or updating an existing target will not update the underlying data buffers
+ */
+ set areUpdatesFrozen(block) {
+ if (block) {
+ this._blockCounter++;
+ }
+ else {
+ this._blockCounter--;
+ if (this._blockCounter <= 0) {
+ this._blockCounter = 0;
+ this._syncActiveTargets(this._forceUpdateWhenUnfrozen);
+ this._forceUpdateWhenUnfrozen = false;
+ }
+ }
+ }
+ get areUpdatesFrozen() {
+ return this._blockCounter > 0;
+ }
+ /**
+ * Creates a new MorphTargetManager
+ * @param scene defines the current scene
+ */
+ constructor(scene = null) {
+ this._targets = new Array();
+ this._targetInfluenceChangedObservers = new Array();
+ this._targetDataLayoutChangedObservers = new Array();
+ this._activeTargets = new SmartArray(16);
+ this._supportsPositions = false;
+ this._supportsNormals = false;
+ this._supportsTangents = false;
+ this._supportsUVs = false;
+ this._supportsUV2s = false;
+ this._supportsColors = false;
+ this._vertexCount = 0;
+ this._uniqueId = 0;
+ this._tempInfluences = new Array();
+ this._canUseTextureForTargets = false;
+ this._blockCounter = 0;
+ this._mustSynchronize = true;
+ this._forceUpdateWhenUnfrozen = false;
+ /** @internal */
+ this._textureVertexStride = 0;
+ /** @internal */
+ this._textureWidth = 0;
+ /** @internal */
+ this._textureHeight = 1;
+ /** @internal */
+ this._parentContainer = null;
+ /**
+ * Gets or sets a boolean indicating if influencers must be optimized (eg. recompiling the shader if less influencers are used)
+ */
+ this.optimizeInfluencers = true;
+ /**
+ * Gets or sets a boolean indicating if positions must be morphed
+ */
+ this.enablePositionMorphing = true;
+ /**
+ * Gets or sets a boolean indicating if normals must be morphed
+ */
+ this.enableNormalMorphing = true;
+ /**
+ * Gets or sets a boolean indicating if tangents must be morphed
+ */
+ this.enableTangentMorphing = true;
+ /**
+ * Gets or sets a boolean indicating if UV must be morphed
+ */
+ this.enableUVMorphing = true;
+ /**
+ * Gets or sets a boolean indicating if UV2 must be morphed
+ */
+ this.enableUV2Morphing = true;
+ /**
+ * Gets or sets a boolean indicating if colors must be morphed
+ */
+ this.enableColorMorphing = true;
+ this._numMaxInfluencers = 0;
+ this._useTextureToStoreTargets = true;
+ if (!scene) {
+ scene = EngineStore.LastCreatedScene;
+ }
+ this._scene = scene;
+ if (this._scene) {
+ this._scene.addMorphTargetManager(this);
+ this._uniqueId = this._scene.getUniqueId();
+ const engineCaps = this._scene.getEngine().getCaps();
+ this._canUseTextureForTargets =
+ engineCaps.canUseGLVertexID && engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0 && engineCaps.texture2DArrayMaxLayerCount > 1;
+ }
+ }
+ /**
+ * Gets or sets the maximum number of influencers (targets) (default value: 0).
+ * Setting a value for this property can lead to a smoother experience, as only one shader will be compiled, which will use this value as the maximum number of influencers.
+ * If you leave the value at 0 (default), a new shader will be compiled every time the number of active influencers changes. This can cause problems, as compiling a shader takes time.
+ * If you assign a non-zero value to this property, you need to ensure that this value is greater than the maximum number of (active) influencers you'll need for this morph manager.
+ * Otherwise, the number of active influencers will be truncated at the value you set for this property, which can lead to unexpected results.
+ * Note that this property has no effect if "useTextureToStoreTargets" is false.
+ */
+ get numMaxInfluencers() {
+ return this._numMaxInfluencers;
+ }
+ set numMaxInfluencers(value) {
+ if (this._numMaxInfluencers === value) {
+ return;
+ }
+ this._numMaxInfluencers = value;
+ this._mustSynchronize = true;
+ this._syncActiveTargets();
+ }
+ /**
+ * Gets the unique ID of this manager
+ */
+ get uniqueId() {
+ return this._uniqueId;
+ }
+ /**
+ * Gets the number of vertices handled by this manager
+ */
+ get vertexCount() {
+ return this._vertexCount;
+ }
+ /**
+ * Gets a boolean indicating if this manager supports morphing of positions
+ */
+ get supportsPositions() {
+ return this._supportsPositions && this.enablePositionMorphing;
+ }
+ /**
+ * Gets a boolean indicating if this manager supports morphing of normals
+ */
+ get supportsNormals() {
+ return this._supportsNormals && this.enableNormalMorphing;
+ }
+ /**
+ * Gets a boolean indicating if this manager supports morphing of tangents
+ */
+ get supportsTangents() {
+ return this._supportsTangents && this.enableTangentMorphing;
+ }
+ /**
+ * Gets a boolean indicating if this manager supports morphing of texture coordinates
+ */
+ get supportsUVs() {
+ return this._supportsUVs && this.enableUVMorphing;
+ }
+ /**
+ * Gets a boolean indicating if this manager supports morphing of texture coordinates 2
+ */
+ get supportsUV2s() {
+ return this._supportsUV2s && this.enableUV2Morphing;
+ }
+ /**
+ * Gets a boolean indicating if this manager supports morphing of colors
+ */
+ get supportsColors() {
+ return this._supportsColors && this.enableColorMorphing;
+ }
+ /**
+ * Gets a boolean indicating if this manager has data for morphing positions
+ */
+ get hasPositions() {
+ return this._supportsPositions;
+ }
+ /**
+ * Gets a boolean indicating if this manager has data for morphing normals
+ */
+ get hasNormals() {
+ return this._supportsNormals;
+ }
+ /**
+ * Gets a boolean indicating if this manager has data for morphing tangents
+ */
+ get hasTangents() {
+ return this._supportsTangents;
+ }
+ /**
+ * Gets a boolean indicating if this manager has data for morphing texture coordinates
+ */
+ get hasUVs() {
+ return this._supportsUVs;
+ }
+ /**
+ * Gets a boolean indicating if this manager has data for morphing texture coordinates 2
+ */
+ get hasUV2s() {
+ return this._supportsUV2s;
+ }
+ /**
+ * Gets a boolean indicating if this manager has data for morphing colors
+ */
+ get hasColors() {
+ return this._supportsColors;
+ }
+ /**
+ * Gets the number of targets stored in this manager
+ */
+ get numTargets() {
+ return this._targets.length;
+ }
+ /**
+ * Gets the number of influencers (ie. the number of targets with influences > 0)
+ */
+ get numInfluencers() {
+ return this._activeTargets.length;
+ }
+ /**
+ * Gets the list of influences (one per target)
+ */
+ get influences() {
+ return this._influences;
+ }
+ /**
+ * Gets or sets a boolean indicating that targets should be stored as a texture instead of using vertex attributes (default is true).
+ * Please note that this option is not available if the hardware does not support it
+ */
+ get useTextureToStoreTargets() {
+ return this._useTextureToStoreTargets;
+ }
+ set useTextureToStoreTargets(value) {
+ if (this._useTextureToStoreTargets === value) {
+ return;
+ }
+ this._useTextureToStoreTargets = value;
+ this._mustSynchronize = true;
+ this._syncActiveTargets();
+ }
+ /**
+ * Gets a boolean indicating that the targets are stored into a texture (instead of as attributes)
+ */
+ get isUsingTextureForTargets() {
+ return (MorphTargetManager.EnableTextureStorage &&
+ this.useTextureToStoreTargets &&
+ this._canUseTextureForTargets &&
+ !this._scene?.getEngine().getCaps().disableMorphTargetTexture);
+ }
+ /**
+ * Gets the active target at specified index. An active target is a target with an influence > 0
+ * @param index defines the index to check
+ * @returns the requested target
+ */
+ getActiveTarget(index) {
+ return this._activeTargets.data[index];
+ }
+ /**
+ * Gets the target at specified index
+ * @param index defines the index to check
+ * @returns the requested target
+ */
+ getTarget(index) {
+ return this._targets[index];
+ }
+ /**
+ * Gets the first target with the specified name
+ * @param name defines the name to check
+ * @returns the requested target
+ */
+ getTargetByName(name) {
+ for (const target of this._targets) {
+ if (target.name === name) {
+ return target;
+ }
+ }
+ return null;
+ }
+ /**
+ * Add a new target to this manager
+ * @param target defines the target to add
+ */
+ addTarget(target) {
+ this._targets.push(target);
+ this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add((needUpdate) => {
+ if (this.areUpdatesFrozen && needUpdate) {
+ this._forceUpdateWhenUnfrozen = true;
+ }
+ this._syncActiveTargets(needUpdate);
+ }));
+ this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(() => {
+ this._mustSynchronize = true;
+ this._syncActiveTargets();
+ }));
+ this._mustSynchronize = true;
+ this._syncActiveTargets();
+ }
+ /**
+ * Removes a target from the manager
+ * @param target defines the target to remove
+ */
+ removeTarget(target) {
+ const index = this._targets.indexOf(target);
+ if (index >= 0) {
+ this._targets.splice(index, 1);
+ target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
+ target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
+ this._mustSynchronize = true;
+ this._syncActiveTargets();
+ }
+ if (this._scene) {
+ this._scene.stopAnimation(target);
+ }
+ }
+ /**
+ * @internal
+ */
+ _bind(effect) {
+ effect.setFloat3("morphTargetTextureInfo", this._textureVertexStride, this._textureWidth, this._textureHeight);
+ effect.setFloatArray("morphTargetTextureIndices", this._morphTargetTextureIndices);
+ effect.setTexture("morphTargets", this._targetStoreTexture);
+ effect.setInt("morphTargetCount", this.numInfluencers);
+ }
+ /**
+ * Clone the current manager
+ * @returns a new MorphTargetManager
+ */
+ clone() {
+ const copy = new MorphTargetManager(this._scene);
+ for (const target of this._targets) {
+ copy.addTarget(target.clone());
+ }
+ copy.enablePositionMorphing = this.enablePositionMorphing;
+ copy.enableNormalMorphing = this.enableNormalMorphing;
+ copy.enableTangentMorphing = this.enableTangentMorphing;
+ copy.enableUVMorphing = this.enableUVMorphing;
+ copy.enableUV2Morphing = this.enableUV2Morphing;
+ copy.enableColorMorphing = this.enableColorMorphing;
+ return copy;
+ }
+ /**
+ * Serializes the current manager into a Serialization object
+ * @returns the serialized object
+ */
+ serialize() {
+ const serializationObject = {};
+ serializationObject.id = this.uniqueId;
+ serializationObject.targets = [];
+ for (const target of this._targets) {
+ serializationObject.targets.push(target.serialize());
+ }
+ return serializationObject;
+ }
+ _syncActiveTargets(needUpdate = false) {
+ if (this.areUpdatesFrozen) {
+ return;
+ }
+ const wasUsingTextureForTargets = !!this._targetStoreTexture;
+ const isUsingTextureForTargets = this.isUsingTextureForTargets;
+ if (this._mustSynchronize || wasUsingTextureForTargets !== isUsingTextureForTargets) {
+ this._mustSynchronize = false;
+ this.synchronize();
+ }
+ let influenceCount = 0;
+ this._activeTargets.reset();
+ if (!this._morphTargetTextureIndices || this._morphTargetTextureIndices.length !== this._targets.length) {
+ this._morphTargetTextureIndices = new Float32Array(this._targets.length);
+ }
+ let targetIndex = -1;
+ for (const target of this._targets) {
+ targetIndex++;
+ if (target.influence === 0 && this.optimizeInfluencers) {
+ continue;
+ }
+ if (this._activeTargets.length >= MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode && !this.isUsingTextureForTargets) {
+ break;
+ }
+ this._activeTargets.push(target);
+ this._morphTargetTextureIndices[influenceCount] = targetIndex;
+ this._tempInfluences[influenceCount++] = target.influence;
+ }
+ if (this._morphTargetTextureIndices.length !== influenceCount) {
+ this._morphTargetTextureIndices = this._morphTargetTextureIndices.slice(0, influenceCount);
+ }
+ if (!this._influences || this._influences.length !== influenceCount) {
+ this._influences = new Float32Array(influenceCount);
+ }
+ for (let index = 0; index < influenceCount; index++) {
+ this._influences[index] = this._tempInfluences[index];
+ }
+ if (needUpdate && this._scene) {
+ for (const mesh of this._scene.meshes) {
+ if (mesh.morphTargetManager === this) {
+ if (isUsingTextureForTargets) {
+ mesh._markSubMeshesAsAttributesDirty();
+ }
+ else {
+ mesh._syncGeometryWithMorphTargetManager();
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Synchronize the targets with all the meshes using this morph target manager
+ */
+ synchronize() {
+ if (!this._scene || this.areUpdatesFrozen) {
+ return;
+ }
+ const engine = this._scene.getEngine();
+ this._supportsPositions = true;
+ this._supportsNormals = true;
+ this._supportsTangents = true;
+ this._supportsUVs = true;
+ this._supportsUV2s = true;
+ this._supportsColors = true;
+ this._vertexCount = 0;
+ this._targetStoreTexture?.dispose();
+ this._targetStoreTexture = null;
+ if (this.isUsingTextureForTargets && this._targets.length > engine.getCaps().texture2DArrayMaxLayerCount) {
+ this.useTextureToStoreTargets = false;
+ }
+ for (const target of this._targets) {
+ this._supportsPositions = this._supportsPositions && target.hasPositions;
+ this._supportsNormals = this._supportsNormals && target.hasNormals;
+ this._supportsTangents = this._supportsTangents && target.hasTangents;
+ this._supportsUVs = this._supportsUVs && target.hasUVs;
+ this._supportsUV2s = this._supportsUV2s && target.hasUV2s;
+ this._supportsColors = this._supportsColors && target.hasColors;
+ const vertexCount = target.vertexCount;
+ if (this._vertexCount === 0) {
+ this._vertexCount = vertexCount;
+ }
+ else if (this._vertexCount !== vertexCount) {
+ Logger.Error(`Incompatible target. Targets must all have the same vertices count. Current vertex count: ${this._vertexCount}, vertex count for target "${target.name}": ${vertexCount}`);
+ return;
+ }
+ }
+ if (this.isUsingTextureForTargets) {
+ this._textureVertexStride = 0;
+ this._supportsPositions && this._textureVertexStride++;
+ this._supportsNormals && this._textureVertexStride++;
+ this._supportsTangents && this._textureVertexStride++;
+ this._supportsUVs && this._textureVertexStride++;
+ this._supportsUV2s && this._textureVertexStride++;
+ this._supportsColors && this._textureVertexStride++;
+ this._textureWidth = this._vertexCount * this._textureVertexStride || 1;
+ this._textureHeight = 1;
+ const maxTextureSize = engine.getCaps().maxTextureSize;
+ if (this._textureWidth > maxTextureSize) {
+ this._textureHeight = Math.ceil(this._textureWidth / maxTextureSize);
+ this._textureWidth = maxTextureSize;
+ }
+ const targetCount = this._targets.length;
+ const data = new Float32Array(targetCount * this._textureWidth * this._textureHeight * 4);
+ let offset = 0;
+ for (let index = 0; index < targetCount; index++) {
+ const target = this._targets[index];
+ const positions = target.getPositions();
+ const normals = target.getNormals();
+ const uvs = target.getUVs();
+ const tangents = target.getTangents();
+ const uv2s = target.getUV2s();
+ const colors = target.getColors();
+ offset = index * this._textureWidth * this._textureHeight * 4;
+ for (let vertex = 0; vertex < this._vertexCount; vertex++) {
+ if (this._supportsPositions && positions) {
+ data[offset] = positions[vertex * 3];
+ data[offset + 1] = positions[vertex * 3 + 1];
+ data[offset + 2] = positions[vertex * 3 + 2];
+ offset += 4;
+ }
+ if (this._supportsNormals && normals) {
+ data[offset] = normals[vertex * 3];
+ data[offset + 1] = normals[vertex * 3 + 1];
+ data[offset + 2] = normals[vertex * 3 + 2];
+ offset += 4;
+ }
+ if (this._supportsUVs && uvs) {
+ data[offset] = uvs[vertex * 2];
+ data[offset + 1] = uvs[vertex * 2 + 1];
+ offset += 4;
+ }
+ if (this._supportsTangents && tangents) {
+ data[offset] = tangents[vertex * 3];
+ data[offset + 1] = tangents[vertex * 3 + 1];
+ data[offset + 2] = tangents[vertex * 3 + 2];
+ offset += 4;
+ }
+ if (this._supportsUV2s && uv2s) {
+ data[offset] = uv2s[vertex * 2];
+ data[offset + 1] = uv2s[vertex * 2 + 1];
+ offset += 4;
+ }
+ if (this._supportsColors && colors) {
+ data[offset] = colors[vertex * 4];
+ data[offset + 1] = colors[vertex * 4 + 1];
+ data[offset + 2] = colors[vertex * 4 + 2];
+ data[offset + 3] = colors[vertex * 4 + 3];
+ offset += 4;
+ }
+ }
+ }
+ this._targetStoreTexture = RawTexture2DArray.CreateRGBATexture(data, this._textureWidth, this._textureHeight, targetCount, this._scene, false, false, 1, 1);
+ this._targetStoreTexture.name = `Morph texture_${this.uniqueId}`;
+ }
+ // Flag meshes as dirty to resync with the active targets
+ for (const mesh of this._scene.meshes) {
+ if (mesh.morphTargetManager === this) {
+ mesh._syncGeometryWithMorphTargetManager();
+ }
+ }
+ }
+ /**
+ * Release all resources
+ */
+ dispose() {
+ if (this._targetStoreTexture) {
+ this._targetStoreTexture.dispose();
+ }
+ this._targetStoreTexture = null;
+ // Remove from scene
+ if (this._scene) {
+ this._scene.removeMorphTargetManager(this);
+ if (this._parentContainer) {
+ const index = this._parentContainer.morphTargetManagers.indexOf(this);
+ if (index > -1) {
+ this._parentContainer.morphTargetManagers.splice(index, 1);
+ }
+ this._parentContainer = null;
+ }
+ for (const morph of this._targets) {
+ this._scene.stopAnimation(morph);
+ }
+ }
+ }
+ // Statics
+ /**
+ * Creates a new MorphTargetManager from serialized data
+ * @param serializationObject defines the serialized data
+ * @param scene defines the hosting scene
+ * @returns the new MorphTargetManager
+ */
+ static Parse(serializationObject, scene) {
+ const result = new MorphTargetManager(scene);
+ for (const targetData of serializationObject.targets) {
+ result.addTarget(MorphTarget.Parse(targetData, scene));
+ }
+ return result;
+ }
+}
+/** Enable storing morph target data into textures when set to true (true by default) */
+MorphTargetManager.EnableTextureStorage = true;
+/** Maximum number of active morph targets supported in the "vertex attribute" mode (i.e., not the "texture" mode) */
+MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode = 8;
+
+const _registeredGLTFExtensions = new Map();
+/**
+ * All currently registered glTF 2.0 loader extensions.
+ */
+const registeredGLTFExtensions = _registeredGLTFExtensions;
+/**
+ * Registers a loader extension.
+ * @param name The name of the loader extension.
+ * @param isGLTFExtension If the loader extension is a glTF extension, then it will only be used for glTF files that use the corresponding glTF extension. Otherwise, it will be used for all loaded glTF files.
+ * @param factory The factory function that creates the loader extension.
+ */
+function registerGLTFExtension(name, isGLTFExtension, factory) {
+ if (unregisterGLTFExtension(name)) {
+ Logger.Warn(`Extension with the name '${name}' already exists`);
+ }
+ _registeredGLTFExtensions.set(name, {
+ isGLTFExtension,
+ factory,
+ });
+}
+/**
+ * Unregisters a loader extension.
+ * @param name The name of the loader extension.
+ * @returns A boolean indicating whether the extension has been unregistered
+ */
+function unregisterGLTFExtension(name) {
+ return _registeredGLTFExtensions.delete(name);
+}
+
+/**
+ * A converter that takes a glTF Object Model JSON Pointer
+ * and transforms it into an ObjectAccessorContainer, allowing
+ * objects referenced in the glTF to be associated with their
+ * respective Babylon.js objects.
+ */
+class GLTFPathToObjectConverter {
+ constructor(_gltf, _infoTree) {
+ this._gltf = _gltf;
+ this._infoTree = _infoTree;
+ }
+ /**
+ * The pointer string is represented by a [JSON pointer](https://datatracker.ietf.org/doc/html/rfc6901).
+ * See also https://github.com/KhronosGroup/glTF/blob/main/specification/2.0/ObjectModel.adoc#core-pointers
+ * := ///
+ * := "nodes" | "materials" | "meshes" | "cameras" | "extensions"
+ * := |
+ * := |
+ * := "extensions"//
+ * := | /
+ * := W+
+ * := D+
+ *
+ * Examples:
+ * - "/nodes/0/rotation"
+ * - "/nodes.length"
+ * - "/materials/2/emissiveFactor"
+ * - "/materials/2/pbrMetallicRoughness/baseColorFactor"
+ * - "/materials/2/extensions/KHR_materials_emissive_strength/emissiveStrength"
+ *
+ * @param path The path to convert
+ * @returns The object and info associated with the path
+ */
+ convert(path) {
+ let objectTree = this._gltf;
+ let infoTree = this._infoTree;
+ let target = undefined;
+ if (!path.startsWith("/")) {
+ throw new Error("Path must start with a /");
+ }
+ const parts = path.split("/");
+ parts.shift();
+ //if the last part has ".length" in it, separate that as an extra part
+ if (parts[parts.length - 1].includes(".length")) {
+ const lastPart = parts[parts.length - 1];
+ const split = lastPart.split(".");
+ parts.pop();
+ parts.push(...split);
+ }
+ let ignoreObjectTree = false;
+ for (const part of parts) {
+ const isLength = part === "length";
+ if (isLength && !infoTree.__array__) {
+ throw new Error(`Path ${path} is invalid`);
+ }
+ if (infoTree.__ignoreObjectTree__) {
+ ignoreObjectTree = true;
+ }
+ if (infoTree.__array__ && !isLength) {
+ infoTree = infoTree.__array__;
+ }
+ else {
+ infoTree = infoTree[part];
+ if (!infoTree) {
+ throw new Error(`Path ${path} is invalid`);
+ }
+ }
+ if (!ignoreObjectTree) {
+ if (objectTree === undefined) {
+ throw new Error(`Path ${path} is invalid`);
+ }
+ if (!isLength) {
+ objectTree = objectTree?.[part];
+ }
+ }
+ if (infoTree.__target__ || isLength) {
+ target = objectTree;
+ }
+ }
+ return {
+ object: target,
+ info: infoTree,
+ };
+ }
+}
+
+/* eslint-disable @typescript-eslint/naming-convention */
+const nodesTree = {
+ length: {
+ type: "number",
+ get: (nodes) => nodes.length,
+ getTarget: (nodes) => nodes.map((node) => node._babylonTransformNode),
+ getPropertyName: [() => "length"],
+ },
+ __array__: {
+ __target__: true,
+ translation: {
+ type: "Vector3",
+ get: (node) => node._babylonTransformNode?.position,
+ set: (value, node) => node._babylonTransformNode?.position.copyFrom(value),
+ getTarget: (node) => node._babylonTransformNode,
+ getPropertyName: [() => "position"],
+ },
+ rotation: {
+ type: "Quaternion",
+ get: (node) => node._babylonTransformNode?.rotationQuaternion,
+ set: (value, node) => node._babylonTransformNode?.rotationQuaternion?.copyFrom(value),
+ getTarget: (node) => node._babylonTransformNode,
+ getPropertyName: [() => "rotationQuaternion"],
+ },
+ scale: {
+ type: "Vector3",
+ get: (node) => node._babylonTransformNode?.scaling,
+ set: (value, node) => node._babylonTransformNode?.scaling.copyFrom(value),
+ getTarget: (node) => node._babylonTransformNode,
+ getPropertyName: [() => "scaling"],
+ },
+ weights: {
+ length: {
+ type: "number",
+ get: (node) => node._numMorphTargets,
+ getTarget: (node) => node._babylonTransformNode,
+ getPropertyName: [() => "influence"],
+ },
+ __array__: {
+ __target__: true,
+ type: "number",
+ get: (node, index) => (index !== undefined ? node._primitiveBabylonMeshes?.[0].morphTargetManager?.getTarget(index).influence : undefined),
+ // set: (value: number, node: INode, index?: number) => node._babylonTransformNode?.getMorphTargetManager()?.getTarget(index)?.setInfluence(value),
+ getTarget: (node) => node._babylonTransformNode,
+ getPropertyName: [() => "influence"],
+ },
+ type: "number[]",
+ get: (node, index) => [0], // TODO: get the weights correctly
+ // set: (value: number, node: INode, index?: number) => node._babylonTransformNode?.getMorphTargetManager()?.getTarget(index)?.setInfluence(value),
+ getTarget: (node) => node._babylonTransformNode,
+ getPropertyName: [() => "influence"],
+ },
+ // readonly!
+ matrix: {
+ type: "Matrix",
+ get: (node) => Matrix.Compose(node._babylonTransformNode?.scaling, node._babylonTransformNode?.rotationQuaternion, node._babylonTransformNode?.position),
+ getTarget: (node) => node._babylonTransformNode,
+ isReadOnly: true,
+ },
+ globalMatrix: {
+ type: "Matrix",
+ get: (node) => {
+ const matrix = Matrix.Identity();
+ // RHS/LHS support
+ let rootNode = node.parent;
+ while (rootNode && rootNode.parent) {
+ rootNode = rootNode.parent;
+ }
+ const forceUpdate = node._babylonTransformNode?.position._isDirty || node._babylonTransformNode?.rotationQuaternion?._isDirty || node._babylonTransformNode?.scaling._isDirty;
+ if (rootNode) {
+ // take the parent root node's world matrix, invert it, and multiply it with the current node's world matrix
+ // This will provide the global matrix, ignoring the RHS->LHS conversion
+ const rootMatrix = rootNode._babylonTransformNode?.computeWorldMatrix(true).invert();
+ if (rootMatrix) {
+ node._babylonTransformNode?.computeWorldMatrix(forceUpdate)?.multiplyToRef(rootMatrix, matrix);
+ }
+ }
+ else if (node._babylonTransformNode) {
+ matrix.copyFrom(node._babylonTransformNode.computeWorldMatrix(forceUpdate));
+ }
+ return matrix;
+ },
+ getTarget: (node) => node._babylonTransformNode,
+ isReadOnly: true,
+ },
+ extensions: {
+ EXT_lights_ies: {
+ multiplier: {
+ type: "number",
+ get: (node) => {
+ return node._babylonTransformNode?.getChildren((child) => child instanceof SpotLight, true)[0]?.intensity;
+ },
+ getTarget: (node) => node._babylonTransformNode?.getChildren((child) => child instanceof SpotLight, true)[0],
+ set: (value, node) => {
+ if (node._babylonTransformNode) {
+ const light = node._babylonTransformNode.getChildren((child) => child instanceof SpotLight, true)[0];
+ if (light) {
+ light.intensity = value;
+ }
+ }
+ },
+ },
+ color: {
+ type: "Color3",
+ get: (node) => {
+ return node._babylonTransformNode?.getChildren((child) => child instanceof SpotLight, true)[0]?.diffuse;
+ },
+ getTarget: (node) => node._babylonTransformNode?.getChildren((child) => child instanceof SpotLight, true)[0],
+ set: (value, node) => {
+ if (node._babylonTransformNode) {
+ const light = node._babylonTransformNode.getChildren((child) => child instanceof SpotLight, true)[0];
+ if (light) {
+ light.diffuse = value;
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+};
+const animationsTree = {
+ length: {
+ type: "number",
+ get: (animations) => animations.length,
+ getTarget: (animations) => animations.map((animation) => animation._babylonAnimationGroup),
+ getPropertyName: [() => "length"],
+ },
+ __array__: {},
+};
+const meshesTree = {
+ length: {
+ type: "number",
+ get: (meshes) => meshes.length,
+ getTarget: (meshes) => meshes.map((mesh) => mesh.primitives[0]._instanceData?.babylonSourceMesh),
+ getPropertyName: [() => "length"],
+ },
+ __array__: {},
+};
+const camerasTree = {
+ __array__: {
+ __target__: true,
+ orthographic: {
+ xmag: {
+ componentsCount: 2,
+ type: "Vector2",
+ get: (camera) => new Vector2(camera._babylonCamera?.orthoLeft ?? 0, camera._babylonCamera?.orthoRight ?? 0),
+ set: (value, camera) => {
+ if (camera._babylonCamera) {
+ camera._babylonCamera.orthoLeft = value.x;
+ camera._babylonCamera.orthoRight = value.y;
+ }
+ },
+ getTarget: (camera) => camera,
+ getPropertyName: [() => "orthoLeft", () => "orthoRight"],
+ },
+ ymag: {
+ componentsCount: 2,
+ type: "Vector2",
+ get: (camera) => new Vector2(camera._babylonCamera?.orthoBottom ?? 0, camera._babylonCamera?.orthoTop ?? 0),
+ set: (value, camera) => {
+ if (camera._babylonCamera) {
+ camera._babylonCamera.orthoBottom = value.x;
+ camera._babylonCamera.orthoTop = value.y;
+ }
+ },
+ getTarget: (camera) => camera,
+ getPropertyName: [() => "orthoBottom", () => "orthoTop"],
+ },
+ zfar: {
+ type: "number",
+ get: (camera) => camera._babylonCamera?.maxZ,
+ set: (value, camera) => {
+ if (camera._babylonCamera) {
+ camera._babylonCamera.maxZ = value;
+ }
+ },
+ getTarget: (camera) => camera,
+ getPropertyName: [() => "maxZ"],
+ },
+ znear: {
+ type: "number",
+ get: (camera) => camera._babylonCamera?.minZ,
+ set: (value, camera) => {
+ if (camera._babylonCamera) {
+ camera._babylonCamera.minZ = value;
+ }
+ },
+ getTarget: (camera) => camera,
+ getPropertyName: [() => "minZ"],
+ },
+ },
+ perspective: {
+ aspectRatio: {
+ type: "number",
+ get: (camera) => camera._babylonCamera?.getEngine().getAspectRatio(camera._babylonCamera),
+ getTarget: (camera) => camera,
+ getPropertyName: [() => "aspectRatio"],
+ isReadOnly: true, // might not be the case for glTF?
+ },
+ yfov: {
+ type: "number",
+ get: (camera) => camera._babylonCamera?.fov,
+ set: (value, camera) => {
+ if (camera._babylonCamera) {
+ camera._babylonCamera.fov = value;
+ }
+ },
+ getTarget: (camera) => camera,
+ getPropertyName: [() => "fov"],
+ },
+ zfar: {
+ type: "number",
+ get: (camera) => camera._babylonCamera?.maxZ,
+ set: (value, camera) => {
+ if (camera._babylonCamera) {
+ camera._babylonCamera.maxZ = value;
+ }
+ },
+ getTarget: (camera) => camera,
+ getPropertyName: [() => "maxZ"],
+ },
+ znear: {
+ type: "number",
+ get: (camera) => camera._babylonCamera?.minZ,
+ set: (value, camera) => {
+ if (camera._babylonCamera) {
+ camera._babylonCamera.minZ = value;
+ }
+ },
+ getTarget: (camera) => camera,
+ getPropertyName: [() => "minZ"],
+ },
+ },
+ },
+};
+const materialsTree = {
+ __array__: {
+ __target__: true,
+ emissiveFactor: {
+ type: "Color3",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).emissiveColor,
+ set: (value, material, index, payload) => _GetMaterial(material, index, payload).emissiveColor.copyFrom(value),
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "emissiveColor"],
+ },
+ emissiveTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("emissiveTexture"),
+ },
+ },
+ normalTexture: {
+ scale: {
+ type: "number",
+ get: (material, index, payload) => _GetTexture(material, payload, "bumpTexture")?.level,
+ set: (value, material, index, payload) => {
+ const texture = _GetTexture(material, payload, "bumpTexture");
+ if (texture) {
+ texture.level = value;
+ }
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "level"],
+ },
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("bumpTexture"),
+ },
+ },
+ occlusionTexture: {
+ strength: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).ambientTextureStrength,
+ set: (value, material, index, payload) => {
+ const mat = _GetMaterial(material, index, payload);
+ if (mat) {
+ mat.ambientTextureStrength = value;
+ }
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "ambientTextureStrength"],
+ },
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("ambientTexture"),
+ },
+ },
+ pbrMetallicRoughness: {
+ baseColorFactor: {
+ type: "Color4",
+ get: (material, index, payload) => {
+ const mat = _GetMaterial(material, index, payload);
+ return Color4.FromColor3(mat.albedoColor, mat.alpha);
+ },
+ set: (value, material, index, payload) => {
+ const mat = _GetMaterial(material, index, payload);
+ mat.albedoColor.set(value.r, value.g, value.b);
+ mat.alpha = value.a;
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ // This is correct on the animation level, but incorrect as a single property of a type Color4
+ getPropertyName: [() => "albedoColor", () => "alpha"],
+ },
+ baseColorTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("albedoTexture"),
+ },
+ },
+ metallicFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).metallic,
+ set: (value, material, index, payload) => {
+ const mat = _GetMaterial(material, index, payload);
+ if (mat) {
+ mat.metallic = value;
+ }
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "metallic"],
+ },
+ roughnessFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).roughness,
+ set: (value, material, index, payload) => {
+ const mat = _GetMaterial(material, index, payload);
+ if (mat) {
+ mat.roughness = value;
+ }
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "roughness"],
+ },
+ metallicRoughnessTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("metallicTexture"),
+ },
+ },
+ },
+ extensions: {
+ KHR_materials_anisotropy: {
+ anisotropyStrength: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).anisotropy.intensity,
+ set: (value, material, index, payload) => {
+ _GetMaterial(material, index, payload).anisotropy.intensity = value;
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "anisotropy.intensity"],
+ },
+ anisotropyRotation: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).anisotropy.angle,
+ set: (value, material, index, payload) => {
+ _GetMaterial(material, index, payload).anisotropy.angle = value;
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "anisotropy.angle"],
+ },
+ anisotropyTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("anisotropy", "texture"),
+ },
+ },
+ },
+ KHR_materials_clearcoat: {
+ clearcoatFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).clearCoat.intensity,
+ set: (value, material, index, payload) => {
+ _GetMaterial(material, index, payload).clearCoat.intensity = value;
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "clearCoat.intensity"],
+ },
+ clearcoatRoughnessFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).clearCoat.roughness,
+ set: (value, material, index, payload) => {
+ _GetMaterial(material, index, payload).clearCoat.roughness = value;
+ },
+ getTarget: (material, index, payload) => _GetMaterial(material, index, payload),
+ getPropertyName: [() => "clearCoat.roughness"],
+ },
+ clearcoatTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("clearCoat", "texture"),
+ },
+ },
+ clearcoatNormalTexture: {
+ scale: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).clearCoat.bumpTexture?.level,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).clearCoat.bumpTexture.level = value),
+ },
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("clearCoat", "bumpTexture"),
+ },
+ },
+ clearcoatRoughnessTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("clearCoat", "textureRoughness"),
+ },
+ },
+ },
+ KHR_materials_dispersion: {
+ dispersion: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.dispersion,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.dispersion = value),
+ },
+ },
+ KHR_materials_emissive_strength: {
+ emissiveStrength: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).emissiveIntensity,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).emissiveIntensity = value),
+ },
+ },
+ KHR_materials_ior: {
+ ior: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).indexOfRefraction,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).indexOfRefraction = value),
+ },
+ },
+ KHR_materials_iridescence: {
+ iridescenceFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).iridescence.intensity,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).iridescence.intensity = value),
+ },
+ iridescenceIor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).iridescence.indexOfRefraction,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).iridescence.indexOfRefraction = value),
+ },
+ iridescenceTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("iridescence", "texture"),
+ },
+ },
+ iridescenceThicknessMaximum: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).iridescence.maximumThickness,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).iridescence.maximumThickness = value),
+ },
+ iridescenceThicknessMinimum: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).iridescence.minimumThickness,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).iridescence.minimumThickness = value),
+ },
+ iridescenceThicknessTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("iridescence", "thicknessTexture"),
+ },
+ },
+ },
+ KHR_materials_sheen: {
+ sheenColorFactor: {
+ type: "Color3",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).sheen.color,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => _GetMaterial(material, index, payload).sheen.color.copyFrom(value),
+ },
+ sheenColorTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("sheen", "texture"),
+ },
+ },
+ sheenRoughnessFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).sheen.intensity,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).sheen.intensity = value),
+ },
+ sheenRoughnessTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("sheen", "thicknessTexture"),
+ },
+ },
+ },
+ KHR_materials_specular: {
+ specularFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).metallicF0Factor,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).metallicF0Factor = value),
+ getPropertyName: [() => "metallicF0Factor"],
+ },
+ specularColorFactor: {
+ type: "Color3",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).metallicReflectanceColor,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => _GetMaterial(material, index, payload).metallicReflectanceColor.copyFrom(value),
+ getPropertyName: [() => "metallicReflectanceColor"],
+ },
+ specularTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("metallicReflectanceTexture"),
+ },
+ },
+ specularColorTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("reflectanceTexture"),
+ },
+ },
+ },
+ KHR_materials_transmission: {
+ transmissionFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.refractionIntensity,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.refractionIntensity = value),
+ getPropertyName: [() => "subSurface.refractionIntensity"],
+ },
+ transmissionTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("subSurface", "refractionIntensityTexture"),
+ },
+ },
+ },
+ KHR_materials_diffuse_transmission: {
+ diffuseTransmissionFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.translucencyIntensity,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.translucencyIntensity = value),
+ },
+ diffuseTransmissionTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("subSurface", "translucencyIntensityTexture"),
+ },
+ },
+ diffuseTransmissionColorFactor: {
+ type: "Color3",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.translucencyColor,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => value && _GetMaterial(material, index, payload).subSurface.translucencyColor?.copyFrom(value),
+ },
+ diffuseTransmissionColorTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("subSurface", "translucencyColorTexture"),
+ },
+ },
+ },
+ KHR_materials_volume: {
+ attenuationColor: {
+ type: "Color3",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.tintColor,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => _GetMaterial(material, index, payload).subSurface.tintColor.copyFrom(value),
+ },
+ attenuationDistance: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.tintColorAtDistance,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.tintColorAtDistance = value),
+ },
+ thicknessFactor: {
+ type: "number",
+ get: (material, index, payload) => _GetMaterial(material, index, payload).subSurface.maximumThickness,
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => (_GetMaterial(material, index, payload).subSurface.maximumThickness = value),
+ },
+ thicknessTexture: {
+ extensions: {
+ KHR_texture_transform: _GenerateTextureMap("subSurface", "thicknessTexture"),
+ },
+ },
+ },
+ },
+ },
+};
+const extensionsTree = {
+ KHR_lights_punctual: {
+ lights: {
+ length: {
+ type: "number",
+ get: (lights) => lights.length,
+ getTarget: (lights) => lights.map((light) => light._babylonLight),
+ getPropertyName: [(_lights) => "length"],
+ },
+ __array__: {
+ __target__: true,
+ color: {
+ type: "Color3",
+ get: (light) => light._babylonLight?.diffuse,
+ set: (value, light) => light._babylonLight?.diffuse.copyFrom(value),
+ getTarget: (light) => light._babylonLight,
+ getPropertyName: [(_light) => "diffuse"],
+ },
+ intensity: {
+ type: "number",
+ get: (light) => light._babylonLight?.intensity,
+ set: (value, light) => (light._babylonLight ? (light._babylonLight.intensity = value) : undefined),
+ getTarget: (light) => light._babylonLight,
+ getPropertyName: [(_light) => "intensity"],
+ },
+ range: {
+ type: "number",
+ get: (light) => light._babylonLight?.range,
+ set: (value, light) => (light._babylonLight ? (light._babylonLight.range = value) : undefined),
+ getTarget: (light) => light._babylonLight,
+ getPropertyName: [(_light) => "range"],
+ },
+ spot: {
+ innerConeAngle: {
+ type: "number",
+ get: (light) => light._babylonLight?.innerAngle,
+ set: (value, light) => (light._babylonLight ? (light._babylonLight.innerAngle = value) : undefined),
+ getTarget: (light) => light._babylonLight,
+ getPropertyName: [(_light) => "innerConeAngle"],
+ },
+ outerConeAngle: {
+ type: "number",
+ get: (light) => light._babylonLight?.angle,
+ set: (value, light) => (light._babylonLight ? (light._babylonLight.angle = value) : undefined),
+ getTarget: (light) => light._babylonLight,
+ getPropertyName: [(_light) => "outerConeAngle"],
+ },
+ },
+ },
+ },
+ },
+ EXT_lights_ies: {
+ lights: {
+ length: {
+ type: "number",
+ get: (lights) => lights.length,
+ getTarget: (lights) => lights.map((light) => light._babylonLight),
+ getPropertyName: [(_lights) => "length"],
+ },
+ },
+ },
+ EXT_lights_image_based: {
+ lights: {
+ length: {
+ type: "number",
+ get: (lights) => lights.length,
+ getTarget: (lights) => lights.map((light) => light._babylonTexture),
+ getPropertyName: [(_lights) => "length"],
+ },
+ __array__: {
+ __target__: true,
+ intensity: {
+ type: "number",
+ get: (light) => light._babylonTexture?.level,
+ set: (value, light) => {
+ if (light._babylonTexture)
+ light._babylonTexture.level = value;
+ },
+ getTarget: (light) => light._babylonTexture,
+ },
+ rotation: {
+ type: "Quaternion",
+ get: (light) => light._babylonTexture && Quaternion.FromRotationMatrix(light._babylonTexture?.getReflectionTextureMatrix()),
+ set: (value, light) => {
+ if (!light._babylonTexture)
+ return;
+ // Invert the rotation so that positive rotation is counter-clockwise.
+ if (!light._babylonTexture.getScene()?.useRightHandedSystem) {
+ value = Quaternion.Inverse(value);
+ }
+ Matrix.FromQuaternionToRef(value, light._babylonTexture.getReflectionTextureMatrix());
+ },
+ getTarget: (light) => light._babylonTexture,
+ },
+ },
+ },
+ },
+};
+function _GetTexture(material, payload, textureType, textureInObject) {
+ const babylonMaterial = _GetMaterial(material);
+ return textureInObject ? babylonMaterial[textureType][textureInObject] : babylonMaterial[textureType];
+}
+function _GetMaterial(material, _index, payload) {
+ return material._data?.[payload?.fillMode ?? Constants.MATERIAL_TriangleFillMode]?.babylonMaterial;
+}
+function _GenerateTextureMap(textureType, textureInObject) {
+ return {
+ offset: {
+ componentsCount: 2,
+ // assuming two independent values for u and v, and NOT a Vector2
+ type: "Vector2",
+ get: (material, _index, payload) => {
+ const texture = _GetTexture(material, payload, textureType, textureInObject);
+ return new Vector2(texture?.uOffset, texture?.vOffset);
+ },
+ getTarget: _GetMaterial,
+ set: (value, material, _index, payload) => {
+ const texture = _GetTexture(material, payload, textureType, textureInObject);
+ (texture.uOffset = value.x), (texture.vOffset = value.y);
+ },
+ getPropertyName: [
+ () => `${textureType}${textureInObject ? "." + textureInObject : ""}.uOffset`,
+ () => `${textureType}${textureInObject ? "." + textureInObject : ""}.vOffset`,
+ ],
+ },
+ rotation: {
+ type: "number",
+ get: (material, _index, payload) => _GetTexture(material, payload, textureType, textureInObject)?.wAng,
+ getTarget: _GetMaterial,
+ set: (value, material, _index, payload) => (_GetTexture(material, payload, textureType, textureInObject).wAng = value),
+ getPropertyName: [() => `${textureType}${textureInObject ? "." + textureInObject : ""}.wAng`],
+ },
+ scale: {
+ componentsCount: 2,
+ type: "Vector2",
+ get: (material, _index, payload) => {
+ const texture = _GetTexture(material, payload, textureType, textureInObject);
+ return new Vector2(texture?.uScale, texture?.vScale);
+ },
+ getTarget: _GetMaterial,
+ set: (value, material, index, payload) => {
+ const texture = _GetTexture(material, payload, textureType, textureInObject);
+ (texture.uScale = value.x), (texture.vScale = value.y);
+ },
+ getPropertyName: [
+ () => `${textureType}${textureInObject ? "." + textureInObject : ""}.uScale`,
+ () => `${textureType}${textureInObject ? "." + textureInObject : ""}.vScale`,
+ ],
+ },
+ };
+}
+const objectModelMapping = {
+ cameras: camerasTree,
+ nodes: nodesTree,
+ materials: materialsTree,
+ extensions: extensionsTree,
+ animations: animationsTree,
+ meshes: meshesTree,
+};
+/**
+ * get a path-to-object converter for the given glTF tree
+ * @param gltf the glTF tree to use
+ * @returns a path-to-object converter for the given glTF tree
+ */
+function GetPathToObjectConverter(gltf) {
+ return new GLTFPathToObjectConverter(gltf, objectModelMapping);
+}
+/**
+ * This function will return the object accessor for the given key in the object model
+ * If the key is not found, it will return undefined
+ * @param key the key to get the mapping for, for example /materials/\{\}/emissiveFactor
+ * @returns an object accessor for the given key, or undefined if the key is not found
+ */
+function GetMappingForKey(key) {
+ // replace every `{}` in key with __array__ to match the object model
+ const keyParts = key.split("/").map((part) => part.replace(/{}/g, "__array__"));
+ let current = objectModelMapping;
+ for (const part of keyParts) {
+ // make sure part is not empty
+ if (!part) {
+ continue;
+ }
+ current = current[part];
+ }
+ // validate that current is an object accessor
+ if (current && current.type && current.get) {
+ return current;
+ }
+ return undefined;
+}
+/**
+ * Set interpolation for a specific key in the object model
+ * @param key the key to set, for example /materials/\{\}/emissiveFactor
+ * @param interpolation the interpolation elements array
+ */
+function SetInterpolationForKey(key, interpolation) {
+ // replace every `{}` in key with __array__ to match the object model
+ const keyParts = key.split("/").map((part) => part.replace(/{}/g, "__array__"));
+ let current = objectModelMapping;
+ for (const part of keyParts) {
+ // make sure part is not empty
+ if (!part) {
+ continue;
+ }
+ current = current[part];
+ }
+ // validate that the current object is an object accessor
+ if (current && current.type && current.get) {
+ current.interpolation = interpolation;
+ }
+}
+/**
+ * This will ad a new object accessor in the object model at the given key.
+ * Note that this will NOT change the typescript types. To do that you will need to change the interface itself (extending it in the module that uses it)
+ * @param key the key to add the object accessor at. For example /cameras/\{\}/perspective/aspectRatio
+ * @param accessor the object accessor to add
+ */
+function AddObjectAccessorToKey(key, accessor) {
+ // replace every `{}` in key with __array__ to match the object model
+ const keyParts = key.split("/").map((part) => part.replace(/{}/g, "__array__"));
+ let current = objectModelMapping;
+ for (const part of keyParts) {
+ // make sure part is not empty
+ if (!part) {
+ continue;
+ }
+ if (!current[part]) {
+ if (part === "?") {
+ current.__ignoreObjectTree__ = true;
+ continue;
+ }
+ current[part] = {};
+ // if the part is __array__ then add the __target__ property
+ if (part === "__array__") {
+ current[part].__target__ = true;
+ }
+ }
+ current = current[part];
+ }
+ Object.assign(current, accessor);
+}
+
+// https://stackoverflow.com/a/48218209
+/**
+ * Merges a series of objects into a single object, deeply.
+ * @param objects The objects to merge (objects later in the list take precedence).
+ * @returns The merged object.
+ */
+function deepMerge(...objects) {
+ const isRecord = (obj) => !!obj && typeof obj === "object";
+ return objects.reduce((prev, obj) => {
+ Object.keys(obj).forEach((key) => {
+ const pVal = prev[key];
+ const oVal = obj[key];
+ if (Array.isArray(pVal) && Array.isArray(oVal)) {
+ prev[key] = pVal.concat(...oVal);
+ }
+ else if (isRecord(pVal) && isRecord(oVal)) {
+ prev[key] = deepMerge(pVal, oVal);
+ }
+ else {
+ prev[key] = oVal;
+ }
+ });
+ return prev;
+ }, {});
+}
+
+/**
+ * Helper class for working with arrays when loading the glTF asset
+ */
+class 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
+ */
+ static Get(context, array, index) {
+ if (!array || index == undefined || !array[index]) {
+ throw new Error(`${context}: Failed to find index (${index})`);
+ }
+ return array[index];
+ }
+ /**
+ * Gets an item from the given array or returns null if not available.
+ * @param array The array to get the item from
+ * @param index The index to the array
+ * @returns The array item or null
+ */
+ static TryGet(array, index) {
+ if (!array || index == undefined || !array[index]) {
+ return null;
+ }
+ return array[index];
+ }
+ /**
+ * Assign an `index` field to each item of the given array.
+ * @param array The array of items
+ */
+ static Assign(array) {
+ if (array) {
+ for (let index = 0; index < array.length; index++) {
+ array[index].index = index;
+ }
+ }
+ }
+}
+/** @internal */
+function LoadBoundingInfoFromPositionAccessor(accessor) {
+ if (accessor.min && accessor.max) {
+ const minArray = accessor.min;
+ const maxArray = accessor.max;
+ const minVector = TmpVectors.Vector3[0].copyFromFloats(minArray[0], minArray[1], minArray[2]);
+ const maxVector = TmpVectors.Vector3[1].copyFromFloats(maxArray[0], maxArray[1], maxArray[2]);
+ if (accessor.normalized && accessor.componentType !== 5126 /* AccessorComponentType.FLOAT */) {
+ let divider = 1;
+ switch (accessor.componentType) {
+ case 5120 /* AccessorComponentType.BYTE */:
+ divider = 127.0;
+ break;
+ case 5121 /* AccessorComponentType.UNSIGNED_BYTE */:
+ divider = 255.0;
+ break;
+ case 5122 /* AccessorComponentType.SHORT */:
+ divider = 32767.0;
+ break;
+ case 5123 /* AccessorComponentType.UNSIGNED_SHORT */:
+ divider = 65535.0;
+ break;
+ }
+ const oneOverDivider = 1 / divider;
+ minVector.scaleInPlace(oneOverDivider);
+ maxVector.scaleInPlace(oneOverDivider);
+ }
+ return new BoundingInfo(minVector, maxVector);
+ }
+ return null;
+}
+/**
+ * The glTF 2.0 loader
+ */
+class GLTFLoader {
+ /**
+ * Registers a loader extension.
+ * @param name The name of the loader extension.
+ * @param factory The factory function that creates the loader extension.
+ * @deprecated Please use registerGLTFExtension instead.
+ */
+ static RegisterExtension(name, factory) {
+ registerGLTFExtension(name, false, factory);
+ }
+ /**
+ * Unregisters a loader extension.
+ * @param name The name of the loader extension.
+ * @returns A boolean indicating whether the extension has been unregistered
+ * @deprecated Please use unregisterGLTFExtension instead.
+ */
+ static UnregisterExtension(name) {
+ return unregisterGLTFExtension(name);
+ }
+ /**
+ * The object that represents the glTF JSON.
+ */
+ get gltf() {
+ if (!this._gltf) {
+ throw new Error("glTF JSON is not available");
+ }
+ return this._gltf;
+ }
+ /**
+ * The BIN chunk of a binary glTF.
+ */
+ get bin() {
+ return this._bin;
+ }
+ /**
+ * The parent file loader.
+ */
+ get parent() {
+ return this._parent;
+ }
+ /**
+ * The Babylon scene when loading the asset.
+ */
+ get babylonScene() {
+ if (!this._babylonScene) {
+ throw new Error("Scene is not available");
+ }
+ return this._babylonScene;
+ }
+ /**
+ * The root Babylon node when loading the asset.
+ */
+ get rootBabylonMesh() {
+ return this._rootBabylonMesh;
+ }
+ /**
+ * The root url when loading the asset.
+ */
+ get rootUrl() {
+ return this._rootUrl;
+ }
+ /**
+ * @internal
+ */
+ constructor(parent) {
+ /** @internal */
+ this._completePromises = new Array();
+ /** @internal */
+ this._assetContainer = null;
+ /** Storage */
+ this._babylonLights = [];
+ /** @internal */
+ this._disableInstancedMesh = 0;
+ /** @internal */
+ this._allMaterialsDirtyRequired = false;
+ /** @internal */
+ this._skipStartAnimationStep = false;
+ this._extensions = new Array();
+ this._disposed = false;
+ this._rootUrl = null;
+ this._fileName = null;
+ this._uniqueRootUrl = null;
+ this._bin = null;
+ this._rootBabylonMesh = null;
+ this._defaultBabylonMaterialData = {};
+ this._postSceneLoadActions = new Array();
+ this._parent = parent;
+ }
+ /** @internal */
+ dispose() {
+ if (this._disposed) {
+ return;
+ }
+ this._disposed = true;
+ this._completePromises.length = 0;
+ this._extensions.forEach((extension) => extension.dispose && extension.dispose());
+ this._extensions.length = 0;
+ this._gltf = null; // TODO
+ this._bin = null;
+ this._babylonScene = null; // TODO
+ this._rootBabylonMesh = null;
+ this._defaultBabylonMaterialData = {};
+ this._postSceneLoadActions.length = 0;
+ this._parent.dispose();
+ }
+ /**
+ * @internal
+ */
+ importMeshAsync(meshesNames, scene, container, data, rootUrl, onProgress, fileName = "") {
+ return Promise.resolve().then(() => {
+ this._babylonScene = scene;
+ this._assetContainer = container;
+ this._loadData(data);
+ let nodes = null;
+ if (meshesNames) {
+ const nodeMap = {};
+ if (this._gltf.nodes) {
+ for (const node of this._gltf.nodes) {
+ if (node.name) {
+ nodeMap[node.name] = node.index;
+ }
+ }
+ }
+ const names = meshesNames instanceof Array ? meshesNames : [meshesNames];
+ nodes = names.map((name) => {
+ const node = nodeMap[name];
+ if (node === undefined) {
+ throw new Error(`Failed to find node '${name}'`);
+ }
+ return node;
+ });
+ }
+ return this._loadAsync(rootUrl, fileName, nodes, () => {
+ return {
+ meshes: this._getMeshes(),
+ particleSystems: [],
+ skeletons: this._getSkeletons(),
+ animationGroups: this._getAnimationGroups(),
+ lights: this._babylonLights,
+ transformNodes: this._getTransformNodes(),
+ geometries: this._getGeometries(),
+ spriteManagers: [],
+ };
+ });
+ });
+ }
+ /**
+ * @internal
+ */
+ loadAsync(scene, data, rootUrl, onProgress, fileName = "") {
+ return Promise.resolve().then(() => {
+ this._babylonScene = scene;
+ this._loadData(data);
+ return this._loadAsync(rootUrl, fileName, null, () => undefined);
+ });
+ }
+ _loadAsync(rootUrl, fileName, nodes, resultFunc) {
+ return Promise.resolve()
+ .then(async () => {
+ this._rootUrl = rootUrl;
+ this._uniqueRootUrl = !rootUrl.startsWith("file:") && fileName ? rootUrl : `${rootUrl}${Date.now()}/`;
+ this._fileName = fileName;
+ this._allMaterialsDirtyRequired = false;
+ await this._loadExtensionsAsync();
+ const loadingToReadyCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.READY]}`;
+ const loadingToCompleteCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.COMPLETE]}`;
+ this._parent._startPerformanceCounter(loadingToReadyCounterName);
+ this._parent._startPerformanceCounter(loadingToCompleteCounterName);
+ this._parent._setState(GLTFLoaderState.LOADING);
+ this._extensionsOnLoading();
+ const promises = new Array();
+ // Block the marking of materials dirty until the scene is loaded.
+ const oldBlockMaterialDirtyMechanism = this._babylonScene.blockMaterialDirtyMechanism;
+ this._babylonScene.blockMaterialDirtyMechanism = true;
+ if (!this.parent.loadOnlyMaterials) {
+ if (nodes) {
+ promises.push(this.loadSceneAsync("/nodes", { nodes: nodes, index: -1 }));
+ }
+ else if (this._gltf.scene != undefined || (this._gltf.scenes && this._gltf.scenes[0])) {
+ const scene = ArrayItem.Get(`/scene`, this._gltf.scenes, this._gltf.scene || 0);
+ promises.push(this.loadSceneAsync(`/scenes/${scene.index}`, scene));
+ }
+ }
+ if (!this.parent.skipMaterials && this.parent.loadAllMaterials && this._gltf.materials) {
+ for (let m = 0; m < this._gltf.materials.length; ++m) {
+ const material = this._gltf.materials[m];
+ const context = "/materials/" + m;
+ const babylonDrawMode = Material.TriangleFillMode;
+ promises.push(this._loadMaterialAsync(context, material, null, babylonDrawMode, () => { }));
+ }
+ }
+ // Restore the blocking of material dirty.
+ if (this._allMaterialsDirtyRequired) {
+ // This can happen if we add a light for instance as it will impact the whole scene.
+ // This automatically resets everything if needed.
+ this._babylonScene.blockMaterialDirtyMechanism = oldBlockMaterialDirtyMechanism;
+ }
+ else {
+ // By default a newly created material is dirty so there is no need to flag the full scene as dirty.
+ // For perf reasons, we then bypass blockMaterialDirtyMechanism as this would "dirty" the entire scene.
+ this._babylonScene._forceBlockMaterialDirtyMechanism(oldBlockMaterialDirtyMechanism);
+ }
+ if (this._parent.compileMaterials) {
+ promises.push(this._compileMaterialsAsync());
+ }
+ if (this._parent.compileShadowGenerators) {
+ promises.push(this._compileShadowGeneratorsAsync());
+ }
+ const resultPromise = Promise.all(promises).then(() => {
+ if (this._rootBabylonMesh && this._rootBabylonMesh !== this._parent.customRootNode) {
+ this._rootBabylonMesh.setEnabled(true);
+ }
+ // Making sure we enable enough lights to have all lights together
+ for (const material of this._babylonScene.materials) {
+ const mat = material;
+ if (mat.maxSimultaneousLights !== undefined) {
+ mat.maxSimultaneousLights = Math.max(mat.maxSimultaneousLights, this._babylonScene.lights.length);
+ }
+ }
+ this._extensionsOnReady();
+ this._parent._setState(GLTFLoaderState.READY);
+ if (!this._skipStartAnimationStep) {
+ this._startAnimations();
+ }
+ return resultFunc();
+ });
+ return resultPromise.then((result) => {
+ this._parent._endPerformanceCounter(loadingToReadyCounterName);
+ Tools.SetImmediate(() => {
+ if (!this._disposed) {
+ Promise.all(this._completePromises).then(() => {
+ this._parent._endPerformanceCounter(loadingToCompleteCounterName);
+ this._parent._setState(GLTFLoaderState.COMPLETE);
+ this._parent.onCompleteObservable.notifyObservers(undefined);
+ this._parent.onCompleteObservable.clear();
+ this.dispose();
+ }, (error) => {
+ this._parent.onErrorObservable.notifyObservers(error);
+ this._parent.onErrorObservable.clear();
+ this.dispose();
+ });
+ }
+ });
+ return result;
+ });
+ })
+ .catch((error) => {
+ if (!this._disposed) {
+ this._parent.onErrorObservable.notifyObservers(error);
+ this._parent.onErrorObservable.clear();
+ this.dispose();
+ }
+ throw error;
+ });
+ }
+ _loadData(data) {
+ this._gltf = data.json;
+ this._setupData();
+ if (data.bin) {
+ const buffers = this._gltf.buffers;
+ if (buffers && buffers[0] && !buffers[0].uri) {
+ const binaryBuffer = buffers[0];
+ if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
+ Logger.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`);
+ }
+ this._bin = data.bin;
+ }
+ else {
+ Logger.Warn("Unexpected BIN chunk");
+ }
+ }
+ }
+ _setupData() {
+ 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) {
+ const nodeParents = {};
+ for (const node of this._gltf.nodes) {
+ if (node.children) {
+ for (const index of node.children) {
+ nodeParents[index] = node.index;
+ }
+ }
+ }
+ const rootNode = this._createRootNode();
+ for (const node of this._gltf.nodes) {
+ const parentIndex = nodeParents[node.index];
+ node.parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
+ }
+ }
+ }
+ async _loadExtensionsAsync() {
+ const extensionPromises = [];
+ registeredGLTFExtensions.forEach((registeredExtension, name) => {
+ // Don't load explicitly disabled extensions.
+ if (this.parent.extensionOptions[name]?.enabled === false) {
+ // But warn if the disabled extension is used by the model.
+ if (registeredExtension.isGLTFExtension && this.isExtensionUsed(name)) {
+ Logger.Warn(`Extension ${name} is used but has been explicitly disabled.`);
+ }
+ }
+ // Load loader extensions that are not a glTF extension, as well as extensions that are glTF extensions and are used by the model.
+ else if (!registeredExtension.isGLTFExtension || this.isExtensionUsed(name)) {
+ extensionPromises.push((async () => {
+ const extension = await registeredExtension.factory(this);
+ if (extension.name !== name) {
+ Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${extension.name} !== ${name}`);
+ }
+ this._parent.onExtensionLoadedObservable.notifyObservers(extension);
+ return extension;
+ })());
+ }
+ });
+ this._extensions.push(...(await Promise.all(extensionPromises)));
+ this._extensions.sort((a, b) => (a.order || Number.MAX_VALUE) - (b.order || Number.MAX_VALUE));
+ this._parent.onExtensionLoadedObservable.clear();
+ if (this._gltf.extensionsRequired) {
+ for (const name of this._gltf.extensionsRequired) {
+ const available = this._extensions.some((extension) => extension.name === name && extension.enabled);
+ if (!available) {
+ if (this.parent.extensionOptions[name]?.enabled === false) {
+ throw new Error(`Required extension ${name} is disabled`);
+ }
+ throw new Error(`Required extension ${name} is not available`);
+ }
+ }
+ }
+ }
+ _createRootNode() {
+ if (this._parent.customRootNode !== undefined) {
+ this._rootBabylonMesh = this._parent.customRootNode;
+ return {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ _babylonTransformNode: this._rootBabylonMesh === null ? undefined : this._rootBabylonMesh,
+ index: -1,
+ };
+ }
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ const rootMesh = new Mesh("__root__", this._babylonScene);
+ this._rootBabylonMesh = rootMesh;
+ this._rootBabylonMesh._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ this._rootBabylonMesh.setEnabled(false);
+ const rootNode = {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ _babylonTransformNode: this._rootBabylonMesh,
+ index: -1,
+ };
+ switch (this._parent.coordinateSystemMode) {
+ case GLTFLoaderCoordinateSystemMode.AUTO: {
+ if (!this._babylonScene.useRightHandedSystem) {
+ rootNode.rotation = [0, 1, 0, 0];
+ rootNode.scale = [1, 1, -1];
+ GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
+ }
+ break;
+ }
+ case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
+ this._babylonScene.useRightHandedSystem = true;
+ break;
+ }
+ default: {
+ throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`);
+ }
+ }
+ this._parent.onMeshLoadedObservable.notifyObservers(rootMesh);
+ 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
+ */
+ loadSceneAsync(context, scene) {
+ const extensionPromise = this._extensionsLoadSceneAsync(context, scene);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ const promises = new Array();
+ this.logOpen(`${context} ${scene.name || ""}`);
+ if (scene.nodes) {
+ for (const index of scene.nodes) {
+ const node = ArrayItem.Get(`${context}/nodes/${index}`, this._gltf.nodes, index);
+ promises.push(this.loadNodeAsync(`/nodes/${node.index}`, node, (babylonMesh) => {
+ babylonMesh.parent = this._rootBabylonMesh;
+ }));
+ }
+ }
+ for (const action of this._postSceneLoadActions) {
+ action();
+ }
+ promises.push(this._loadAnimationsAsync());
+ this.logClose();
+ return Promise.all(promises).then(() => { });
+ }
+ _forEachPrimitive(node, callback) {
+ if (node._primitiveBabylonMeshes) {
+ for (const babylonMesh of node._primitiveBabylonMeshes) {
+ callback(babylonMesh);
+ }
+ }
+ }
+ _getGeometries() {
+ const geometries = [];
+ const nodes = this._gltf.nodes;
+ if (nodes) {
+ for (const node of nodes) {
+ this._forEachPrimitive(node, (babylonMesh) => {
+ const geometry = babylonMesh.geometry;
+ if (geometry && geometries.indexOf(geometry) === -1) {
+ geometries.push(geometry);
+ }
+ });
+ }
+ }
+ return geometries;
+ }
+ _getMeshes() {
+ const meshes = [];
+ // Root mesh is always first, if available.
+ if (this._rootBabylonMesh instanceof AbstractMesh) {
+ meshes.push(this._rootBabylonMesh);
+ }
+ const nodes = this._gltf.nodes;
+ if (nodes) {
+ for (const node of nodes) {
+ this._forEachPrimitive(node, (babylonMesh) => {
+ meshes.push(babylonMesh);
+ });
+ }
+ }
+ return meshes;
+ }
+ _getTransformNodes() {
+ const transformNodes = [];
+ const nodes = this._gltf.nodes;
+ if (nodes) {
+ for (const node of nodes) {
+ if (node._babylonTransformNode && node._babylonTransformNode.getClassName() === "TransformNode") {
+ transformNodes.push(node._babylonTransformNode);
+ }
+ if (node._babylonTransformNodeForSkin) {
+ transformNodes.push(node._babylonTransformNodeForSkin);
+ }
+ }
+ }
+ return transformNodes;
+ }
+ _getSkeletons() {
+ const skeletons = [];
+ const skins = this._gltf.skins;
+ if (skins) {
+ for (const skin of skins) {
+ if (skin._data) {
+ skeletons.push(skin._data.babylonSkeleton);
+ }
+ }
+ }
+ return skeletons;
+ }
+ _getAnimationGroups() {
+ const animationGroups = [];
+ const animations = this._gltf.animations;
+ if (animations) {
+ for (const animation of animations) {
+ if (animation._babylonAnimationGroup) {
+ animationGroups.push(animation._babylonAnimationGroup);
+ }
+ }
+ }
+ return animationGroups;
+ }
+ _startAnimations() {
+ switch (this._parent.animationStartMode) {
+ case GLTFLoaderAnimationStartMode.NONE: {
+ // do nothing
+ break;
+ }
+ case GLTFLoaderAnimationStartMode.FIRST: {
+ const babylonAnimationGroups = this._getAnimationGroups();
+ if (babylonAnimationGroups.length !== 0) {
+ babylonAnimationGroups[0].start(true);
+ }
+ break;
+ }
+ case GLTFLoaderAnimationStartMode.ALL: {
+ const babylonAnimationGroups = this._getAnimationGroups();
+ for (const babylonAnimationGroup of babylonAnimationGroups) {
+ babylonAnimationGroup.start(true);
+ }
+ break;
+ }
+ default: {
+ Logger.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
+ */
+ loadNodeAsync(context, node, assign = () => { }) {
+ const extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ if (node._babylonTransformNode) {
+ throw new Error(`${context}: Invalid recursive node hierarchy`);
+ }
+ const promises = new Array();
+ this.logOpen(`${context} ${node.name || ""}`);
+ const loadNode = (babylonTransformNode) => {
+ GLTFLoader.AddPointerMetadata(babylonTransformNode, context);
+ GLTFLoader._LoadTransform(node, babylonTransformNode);
+ if (node.camera != undefined) {
+ const camera = ArrayItem.Get(`${context}/camera`, this._gltf.cameras, node.camera);
+ promises.push(this.loadCameraAsync(`/cameras/${camera.index}`, camera, (babylonCamera) => {
+ babylonCamera.parent = babylonTransformNode;
+ }));
+ }
+ if (node.children) {
+ for (const index of node.children) {
+ const childNode = ArrayItem.Get(`${context}/children/${index}`, this._gltf.nodes, index);
+ promises.push(this.loadNodeAsync(`/nodes/${childNode.index}`, childNode, (childBabylonMesh) => {
+ childBabylonMesh.parent = babylonTransformNode;
+ }));
+ }
+ }
+ assign(babylonTransformNode);
+ };
+ const hasMesh = node.mesh != undefined;
+ const hasSkin = this._parent.loadSkins && node.skin != undefined;
+ if (!hasMesh || hasSkin) {
+ const nodeName = node.name || `node${node.index}`;
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ const transformNode = new TransformNode(nodeName, this._babylonScene);
+ transformNode._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ if (node.mesh == undefined) {
+ node._babylonTransformNode = transformNode;
+ }
+ else {
+ node._babylonTransformNodeForSkin = transformNode;
+ }
+ loadNode(transformNode);
+ }
+ if (hasMesh) {
+ if (hasSkin) {
+ // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
+ // This code path will place the skinned mesh as a sibling of the skeleton root node without loading the
+ // transform, which effectively ignores the transform of the skinned mesh, as per spec.
+ const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh);
+ promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, (babylonTransformNode) => {
+ const babylonTransformNodeForSkin = node._babylonTransformNodeForSkin;
+ // Merge the metadata from the skin node to the skinned mesh in case a loader extension added metadata.
+ babylonTransformNode.metadata = deepMerge(babylonTransformNodeForSkin.metadata, babylonTransformNode.metadata || {});
+ const skin = ArrayItem.Get(`${context}/skin`, this._gltf.skins, node.skin);
+ promises.push(this._loadSkinAsync(`/skins/${skin.index}`, node, skin, (babylonSkeleton) => {
+ this._forEachPrimitive(node, (babylonMesh) => {
+ babylonMesh.skeleton = babylonSkeleton;
+ });
+ // Wait until all the nodes are parented before parenting the skinned mesh.
+ this._postSceneLoadActions.push(() => {
+ if (skin.skeleton != undefined) {
+ // Place the skinned mesh node as a sibling of the skeleton root node.
+ // Handle special case when the parent of the skeleton root is the skinned mesh.
+ const parentNode = ArrayItem.Get(`/skins/${skin.index}/skeleton`, this._gltf.nodes, skin.skeleton).parent;
+ if (node.index === parentNode.index) {
+ babylonTransformNode.parent = babylonTransformNodeForSkin.parent;
+ }
+ else {
+ babylonTransformNode.parent = parentNode._babylonTransformNode;
+ }
+ }
+ else {
+ babylonTransformNode.parent = this._rootBabylonMesh;
+ }
+ this._parent.onSkinLoadedObservable.notifyObservers({ node: babylonTransformNodeForSkin, skinnedNode: babylonTransformNode });
+ });
+ }));
+ }));
+ }
+ else {
+ const 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(() => {
+ this._forEachPrimitive(node, (babylonMesh) => {
+ const asMesh = babylonMesh;
+ if (!asMesh.isAnInstance && asMesh.geometry && asMesh.geometry.useBoundingInfoFromGeometry) {
+ // simply apply the world matrices to the bounding info - the extends are already ok
+ babylonMesh._updateBoundingInfo();
+ }
+ else {
+ babylonMesh.refreshBoundingInfo(true, true);
+ }
+ });
+ return node._babylonTransformNode;
+ });
+ }
+ _loadMeshAsync(context, node, mesh, assign) {
+ const primitives = mesh.primitives;
+ if (!primitives || !primitives.length) {
+ throw new Error(`${context}: Primitives are missing`);
+ }
+ if (primitives[0].index == undefined) {
+ ArrayItem.Assign(primitives);
+ }
+ const promises = new Array();
+ this.logOpen(`${context} ${mesh.name || ""}`);
+ const name = node.name || `node${node.index}`;
+ if (primitives.length === 1) {
+ const primitive = mesh.primitives[0];
+ promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, name, node, mesh, primitive, (babylonMesh) => {
+ node._babylonTransformNode = babylonMesh;
+ node._primitiveBabylonMeshes = [babylonMesh];
+ }));
+ }
+ else {
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ node._babylonTransformNode = new TransformNode(name, this._babylonScene);
+ node._babylonTransformNode._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ node._primitiveBabylonMeshes = [];
+ for (const primitive of primitives) {
+ promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, `${name}_primitive${primitive.index}`, node, mesh, primitive, (babylonMesh) => {
+ babylonMesh.parent = node._babylonTransformNode;
+ node._primitiveBabylonMeshes.push(babylonMesh);
+ }));
+ }
+ }
+ assign(node._babylonTransformNode);
+ this.logClose();
+ return Promise.all(promises).then(() => {
+ return node._babylonTransformNode;
+ });
+ }
+ /**
+ * @internal Define this method to modify the default behavior when loading data for mesh primitives.
+ * @param context The context when loading the asset
+ * @param name The mesh name when loading the asset
+ * @param node The glTF node when loading the asset
+ * @param mesh The glTF mesh when loading the asset
+ * @param primitive The glTF mesh primitive property
+ * @param assign A function called synchronously after parsing the glTF properties
+ * @returns A promise that resolves with the loaded mesh when the load is complete or null if not handled
+ */
+ _loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) {
+ const extensionPromise = this._extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ this.logOpen(`${context}`);
+ const shouldInstance = this._disableInstancedMesh === 0 && this._parent.createInstances && node.skin == undefined && !mesh.primitives[0].targets;
+ let babylonAbstractMesh;
+ let promise;
+ if (shouldInstance && primitive._instanceData) {
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ babylonAbstractMesh = primitive._instanceData.babylonSourceMesh.createInstance(name);
+ babylonAbstractMesh._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ promise = primitive._instanceData.promise;
+ }
+ else {
+ const promises = new Array();
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ const babylonMesh = new Mesh(name, this._babylonScene);
+ babylonMesh._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ babylonMesh.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
+ this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
+ promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then((babylonGeometry) => {
+ return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {
+ if (this._disposed) {
+ return;
+ }
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ babylonGeometry.applyToMesh(babylonMesh);
+ babylonGeometry._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ });
+ }));
+ const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
+ if (primitive.material == undefined) {
+ let babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
+ if (!babylonMaterial) {
+ babylonMaterial = this._createDefaultMaterial("__GLTFLoader._default", babylonDrawMode);
+ this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
+ this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
+ }
+ babylonMesh.material = babylonMaterial;
+ }
+ else if (!this.parent.skipMaterials) {
+ const material = ArrayItem.Get(`${context}/material`, this._gltf.materials, primitive.material);
+ promises.push(this._loadMaterialAsync(`/materials/${material.index}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => {
+ babylonMesh.material = babylonMaterial;
+ }));
+ }
+ promise = Promise.all(promises);
+ if (shouldInstance) {
+ primitive._instanceData = {
+ babylonSourceMesh: babylonMesh,
+ promise: promise,
+ };
+ }
+ babylonAbstractMesh = babylonMesh;
+ }
+ GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context);
+ this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);
+ assign(babylonAbstractMesh);
+ this.logClose();
+ return promise.then(() => {
+ return babylonAbstractMesh;
+ });
+ }
+ _loadVertexDataAsync(context, primitive, babylonMesh) {
+ const extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ const attributes = primitive.attributes;
+ if (!attributes) {
+ throw new Error(`${context}: Attributes are missing`);
+ }
+ const promises = new Array();
+ const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene);
+ if (primitive.indices == undefined) {
+ babylonMesh.isUnIndexed = true;
+ }
+ else {
+ const accessor = ArrayItem.Get(`${context}/indices`, this._gltf.accessors, primitive.indices);
+ promises.push(this._loadIndicesAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
+ babylonGeometry.setIndices(data);
+ }));
+ }
+ const loadAttribute = (name, kind, callback) => {
+ if (attributes[name] == undefined) {
+ return;
+ }
+ babylonMesh._delayInfo = babylonMesh._delayInfo || [];
+ if (babylonMesh._delayInfo.indexOf(kind) === -1) {
+ babylonMesh._delayInfo.push(kind);
+ }
+ const accessor = ArrayItem.Get(`${context}/attributes/${name}`, this._gltf.accessors, attributes[name]);
+ promises.push(this._loadVertexAccessorAsync(`/accessors/${accessor.index}`, accessor, kind).then((babylonVertexBuffer) => {
+ if (babylonVertexBuffer.getKind() === VertexBuffer.PositionKind && !this.parent.alwaysComputeBoundingBox && !babylonMesh.skeleton) {
+ const babylonBoundingInfo = LoadBoundingInfoFromPositionAccessor(accessor);
+ if (babylonBoundingInfo) {
+ babylonGeometry._boundingInfo = babylonBoundingInfo;
+ babylonGeometry.useBoundingInfoFromGeometry = true;
+ }
+ }
+ babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
+ }));
+ if (kind == VertexBuffer.MatricesIndicesExtraKind) {
+ babylonMesh.numBoneInfluencers = 8;
+ }
+ if (callback) {
+ callback(accessor);
+ }
+ };
+ loadAttribute("POSITION", VertexBuffer.PositionKind);
+ loadAttribute("NORMAL", VertexBuffer.NormalKind);
+ loadAttribute("TANGENT", VertexBuffer.TangentKind);
+ loadAttribute("TEXCOORD_0", VertexBuffer.UVKind);
+ loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind);
+ loadAttribute("TEXCOORD_2", VertexBuffer.UV3Kind);
+ loadAttribute("TEXCOORD_3", VertexBuffer.UV4Kind);
+ loadAttribute("TEXCOORD_4", VertexBuffer.UV5Kind);
+ loadAttribute("TEXCOORD_5", VertexBuffer.UV6Kind);
+ loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind);
+ loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind);
+ loadAttribute("JOINTS_1", VertexBuffer.MatricesIndicesExtraKind);
+ loadAttribute("WEIGHTS_1", VertexBuffer.MatricesWeightsExtraKind);
+ loadAttribute("COLOR_0", VertexBuffer.ColorKind, (accessor) => {
+ if (accessor.type === "VEC4" /* AccessorType.VEC4 */) {
+ babylonMesh.hasVertexAlpha = true;
+ }
+ });
+ return Promise.all(promises).then(() => {
+ return babylonGeometry;
+ });
+ }
+ _createMorphTargets(context, node, mesh, primitive, babylonMesh) {
+ if (!primitive.targets || !this._parent.loadMorphTargets) {
+ 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`);
+ }
+ const targetNames = mesh.extras ? mesh.extras.targetNames : null;
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ babylonMesh.morphTargetManager = new MorphTargetManager(this._babylonScene);
+ babylonMesh.morphTargetManager._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ babylonMesh.morphTargetManager.areUpdatesFrozen = true;
+ for (let index = 0; index < primitive.targets.length; index++) {
+ const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
+ const name = targetNames ? targetNames[index] : `morphTarget${index}`;
+ babylonMesh.morphTargetManager.addTarget(new MorphTarget(name, weight, babylonMesh.getScene()));
+ // TODO: tell the target whether it has positions, normals, tangents
+ }
+ }
+ _loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry) {
+ if (!primitive.targets || !this._parent.loadMorphTargets) {
+ return Promise.resolve();
+ }
+ const promises = new Array();
+ const morphTargetManager = babylonMesh.morphTargetManager;
+ for (let index = 0; index < morphTargetManager.numTargets; index++) {
+ const babylonMorphTarget = morphTargetManager.getTarget(index);
+ promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));
+ }
+ return Promise.all(promises).then(() => {
+ morphTargetManager.areUpdatesFrozen = false;
+ });
+ }
+ _loadMorphTargetVertexDataAsync(context, babylonGeometry, attributes, babylonMorphTarget) {
+ const promises = new Array();
+ const loadAttribute = (attribute, kind, setData) => {
+ if (attributes[attribute] == undefined) {
+ return;
+ }
+ const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
+ if (!babylonVertexBuffer) {
+ return;
+ }
+ const accessor = ArrayItem.Get(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]);
+ promises.push(this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
+ setData(babylonVertexBuffer, data);
+ }));
+ };
+ loadAttribute("POSITION", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {
+ const positions = new Float32Array(data.length);
+ babylonVertexBuffer.forEach(data.length, (value, index) => {
+ positions[index] = data[index] + value;
+ });
+ babylonMorphTarget.setPositions(positions);
+ });
+ loadAttribute("NORMAL", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {
+ const normals = new Float32Array(data.length);
+ babylonVertexBuffer.forEach(normals.length, (value, index) => {
+ normals[index] = data[index] + value;
+ });
+ babylonMorphTarget.setNormals(normals);
+ });
+ loadAttribute("TANGENT", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {
+ const tangents = new Float32Array((data.length / 3) * 4);
+ let dataIndex = 0;
+ babylonVertexBuffer.forEach((data.length / 3) * 4, (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) {
+ tangents[dataIndex] = data[dataIndex] + value;
+ dataIndex++;
+ }
+ });
+ babylonMorphTarget.setTangents(tangents);
+ });
+ loadAttribute("TEXCOORD_0", VertexBuffer.UVKind, (babylonVertexBuffer, data) => {
+ const uvs = new Float32Array(data.length);
+ babylonVertexBuffer.forEach(data.length, (value, index) => {
+ uvs[index] = data[index] + value;
+ });
+ babylonMorphTarget.setUVs(uvs);
+ });
+ loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind, (babylonVertexBuffer, data) => {
+ const uvs = new Float32Array(data.length);
+ babylonVertexBuffer.forEach(data.length, (value, index) => {
+ uvs[index] = data[index] + value;
+ });
+ babylonMorphTarget.setUV2s(uvs);
+ });
+ loadAttribute("COLOR_0", VertexBuffer.ColorKind, (babylonVertexBuffer, data) => {
+ let colors = null;
+ const componentSize = babylonVertexBuffer.getSize();
+ if (componentSize === 3) {
+ colors = new Float32Array((data.length / 3) * 4);
+ babylonVertexBuffer.forEach(data.length, (value, index) => {
+ const pixid = Math.floor(index / 3);
+ const channel = index % 3;
+ colors[4 * pixid + channel] = data[3 * pixid + channel] + value;
+ });
+ for (let i = 0; i < data.length / 3; ++i) {
+ colors[4 * i + 3] = 1;
+ }
+ }
+ else if (componentSize === 4) {
+ colors = new Float32Array(data.length);
+ babylonVertexBuffer.forEach(data.length, (value, index) => {
+ colors[index] = data[index] + value;
+ });
+ }
+ else {
+ throw new Error(`${context}: Invalid number of components (${componentSize}) for COLOR_0 attribute`);
+ }
+ babylonMorphTarget.setColors(colors);
+ });
+ return Promise.all(promises).then(() => { });
+ }
+ static _LoadTransform(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;
+ }
+ let position = Vector3.Zero();
+ let rotation = Quaternion.Identity();
+ let scaling = Vector3.One();
+ if (node.matrix) {
+ const matrix = Matrix.FromArray(node.matrix);
+ matrix.decompose(scaling, rotation, position);
+ }
+ else {
+ if (node.translation) {
+ position = Vector3.FromArray(node.translation);
+ }
+ if (node.rotation) {
+ rotation = Quaternion.FromArray(node.rotation);
+ }
+ if (node.scale) {
+ scaling = Vector3.FromArray(node.scale);
+ }
+ }
+ babylonNode.position = position;
+ babylonNode.rotationQuaternion = rotation;
+ babylonNode.scaling = scaling;
+ }
+ _loadSkinAsync(context, node, skin, assign) {
+ if (!this._parent.loadSkins) {
+ return Promise.resolve();
+ }
+ const extensionPromise = this._extensionsLoadSkinAsync(context, node, skin);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ if (skin._data) {
+ assign(skin._data.babylonSkeleton);
+ return skin._data.promise;
+ }
+ const skeletonId = `skeleton${skin.index}`;
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
+ babylonSkeleton._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ this._loadBones(context, skin, babylonSkeleton);
+ const promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then((inverseBindMatricesData) => {
+ this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
+ });
+ skin._data = {
+ babylonSkeleton: babylonSkeleton,
+ promise: promise,
+ };
+ assign(babylonSkeleton);
+ return promise;
+ }
+ _loadBones(context, skin, babylonSkeleton) {
+ if (skin.skeleton == undefined || this._parent.alwaysComputeSkeletonRootNode) {
+ const rootNode = this._findSkeletonRootNode(`${context}/joints`, skin.joints);
+ if (rootNode) {
+ if (skin.skeleton === undefined) {
+ skin.skeleton = rootNode.index;
+ }
+ else {
+ const isParent = (a, b) => {
+ for (; b.parent; b = b.parent) {
+ if (b.parent === a) {
+ return true;
+ }
+ }
+ return false;
+ };
+ const skeletonNode = ArrayItem.Get(`${context}/skeleton`, this._gltf.nodes, skin.skeleton);
+ if (skeletonNode !== rootNode && !isParent(skeletonNode, rootNode)) {
+ Logger.Warn(`${context}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`);
+ skin.skeleton = rootNode.index;
+ }
+ }
+ }
+ else {
+ Logger.Warn(`${context}: Failed to find common root`);
+ }
+ }
+ const babylonBones = {};
+ for (const index of skin.joints) {
+ const node = ArrayItem.Get(`${context}/joints/${index}`, this._gltf.nodes, index);
+ this._loadBone(node, skin, babylonSkeleton, babylonBones);
+ }
+ }
+ _findSkeletonRootNode(context, joints) {
+ if (joints.length === 0) {
+ return null;
+ }
+ const paths = {};
+ for (const index of joints) {
+ const path = [];
+ let node = ArrayItem.Get(`${context}/${index}`, this._gltf.nodes, index);
+ while (node.index !== -1) {
+ path.unshift(node);
+ node = node.parent;
+ }
+ paths[index] = path;
+ }
+ let rootNode = null;
+ for (let i = 0;; ++i) {
+ let path = paths[joints[0]];
+ if (i >= path.length) {
+ return rootNode;
+ }
+ const node = path[i];
+ for (let j = 1; j < joints.length; ++j) {
+ path = paths[joints[j]];
+ if (i >= path.length || node !== path[i]) {
+ return rootNode;
+ }
+ }
+ rootNode = node;
+ }
+ }
+ _loadBone(node, skin, babylonSkeleton, babylonBones) {
+ node._isJoint = true;
+ let babylonBone = babylonBones[node.index];
+ if (babylonBone) {
+ return babylonBone;
+ }
+ let parentBabylonBone = null;
+ if (node.index !== skin.skeleton) {
+ if (node.parent && node.parent.index !== -1) {
+ parentBabylonBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);
+ }
+ else if (skin.skeleton !== undefined) {
+ Logger.Warn(`/skins/${skin.index}/skeleton: Skeleton node is not a common root`);
+ }
+ }
+ const boneIndex = skin.joints.indexOf(node.index);
+ babylonBone = new Bone(node.name || `joint${node.index}`, babylonSkeleton, parentBabylonBone, this._getNodeMatrix(node), null, null, boneIndex);
+ babylonBones[node.index] = babylonBone;
+ // Wait until the scene is loaded to ensure the transform nodes are loaded.
+ this._postSceneLoadActions.push(() => {
+ // Link the Babylon bone with the corresponding Babylon transform node.
+ // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D.
+ babylonBone.linkTransformNode(node._babylonTransformNode);
+ });
+ return babylonBone;
+ }
+ _loadSkinInverseBindMatricesDataAsync(context, skin) {
+ if (skin.inverseBindMatrices == undefined) {
+ return Promise.resolve(null);
+ }
+ const accessor = ArrayItem.Get(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices);
+ return this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor);
+ }
+ _updateBoneMatrices(babylonSkeleton, inverseBindMatricesData) {
+ for (const babylonBone of babylonSkeleton.bones) {
+ const baseMatrix = Matrix.Identity();
+ const boneIndex = babylonBone._index;
+ if (inverseBindMatricesData && boneIndex !== -1) {
+ Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
+ baseMatrix.invertToRef(baseMatrix);
+ }
+ const babylonParentBone = babylonBone.getParent();
+ if (babylonParentBone) {
+ baseMatrix.multiplyToRef(babylonParentBone.getAbsoluteInverseBindMatrix(), baseMatrix);
+ }
+ babylonBone.updateMatrix(baseMatrix, false, false);
+ babylonBone._updateAbsoluteBindMatrices(undefined, false);
+ }
+ }
+ _getNodeMatrix(node) {
+ return node.matrix
+ ? Matrix.FromArray(node.matrix)
+ : Matrix.Compose(node.scale ? Vector3.FromArray(node.scale) : Vector3.One(), node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(), node.translation ? Vector3.FromArray(node.translation) : 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
+ */
+ loadCameraAsync(context, camera, assign = () => { }) {
+ const extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ const promises = new Array();
+ this.logOpen(`${context} ${camera.name || ""}`);
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ const babylonCamera = new FreeCamera(camera.name || `camera${camera.index}`, Vector3.Zero(), this._babylonScene, false);
+ babylonCamera._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ babylonCamera.ignoreParentScaling = true;
+ camera._babylonCamera = babylonCamera;
+ // Rotation by 180 as glTF has a different convention than Babylon.
+ babylonCamera.rotation.set(0, Math.PI, 0);
+ switch (camera.type) {
+ case "perspective" /* CameraType.PERSPECTIVE */: {
+ const 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 || 0;
+ break;
+ }
+ case "orthographic" /* CameraType.ORTHOGRAPHIC */: {
+ if (!camera.orthographic) {
+ throw new Error(`${context}: Camera orthographic properties are missing`);
+ }
+ babylonCamera.mode = 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);
+ this.logClose();
+ return Promise.all(promises).then(() => {
+ return babylonCamera;
+ });
+ }
+ _loadAnimationsAsync() {
+ const animations = this._gltf.animations;
+ if (!animations) {
+ return Promise.resolve();
+ }
+ const promises = new Array();
+ for (let index = 0; index < animations.length; index++) {
+ const animation = animations[index];
+ promises.push(this.loadAnimationAsync(`/animations/${animation.index}`, animation).then((animationGroup) => {
+ // Delete the animation group if it ended up not having any animations in it.
+ if (animationGroup.targetedAnimations.length === 0) {
+ animationGroup.dispose();
+ }
+ }));
+ }
+ return Promise.all(promises).then(() => { });
+ }
+ /**
+ * 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
+ */
+ loadAnimationAsync(context, animation) {
+ const promise = this._extensionsLoadAnimationAsync(context, animation);
+ if (promise) {
+ return promise;
+ }
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ return Promise.resolve().then(() => animationGroup).then(({ AnimationGroup }) => {
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation.index}`, this._babylonScene);
+ babylonAnimationGroup._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ animation._babylonAnimationGroup = babylonAnimationGroup;
+ const promises = new Array();
+ ArrayItem.Assign(animation.channels);
+ ArrayItem.Assign(animation.samplers);
+ for (const channel of animation.channels) {
+ promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel.index}`, context, animation, channel, (babylonTarget, babylonAnimation) => {
+ babylonTarget.animations = babylonTarget.animations || [];
+ babylonTarget.animations.push(babylonAnimation);
+ babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonTarget);
+ }));
+ }
+ return Promise.all(promises).then(() => {
+ babylonAnimationGroup.normalize(0);
+ return babylonAnimationGroup;
+ });
+ });
+ }
+ /**
+ * @hidden
+ * Loads a glTF animation channel.
+ * @param context The context when loading the asset
+ * @param animationContext The context of the animation when loading the asset
+ * @param animation The glTF animation property
+ * @param channel The glTF animation channel property
+ * @param onLoad Called for each animation loaded
+ * @returns A void promise that resolves when the load is complete
+ */
+ async _loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) {
+ const promise = this._extensionsLoadAnimationChannelAsync(context, animationContext, animation, channel, onLoad);
+ if (promise) {
+ return promise;
+ }
+ if (channel.target.node == undefined) {
+ return Promise.resolve();
+ }
+ const targetNode = ArrayItem.Get(`${context}/target/node`, this._gltf.nodes, channel.target.node);
+ const channelTargetPath = channel.target.path;
+ const pathIsWeights = channelTargetPath === "weights" /* AnimationChannelTargetPath.WEIGHTS */;
+ // Ignore animations that have no animation targets.
+ if ((pathIsWeights && !targetNode._numMorphTargets) || (!pathIsWeights && !targetNode._babylonTransformNode)) {
+ return Promise.resolve();
+ }
+ // Don't load node animations if disabled.
+ if (!this._parent.loadNodeAnimations && !pathIsWeights && !targetNode._isJoint) {
+ return Promise.resolve();
+ }
+ // async-load the animation sampler to provide the interpolation of the channelTargetPath
+ await Promise.resolve().then(() => glTFLoaderAnimation);
+ let properties;
+ switch (channelTargetPath) {
+ case "translation" /* AnimationChannelTargetPath.TRANSLATION */: {
+ properties = GetMappingForKey("/nodes/{}/translation")?.interpolation;
+ break;
+ }
+ case "rotation" /* AnimationChannelTargetPath.ROTATION */: {
+ properties = GetMappingForKey("/nodes/{}/rotation")?.interpolation;
+ break;
+ }
+ case "scale" /* AnimationChannelTargetPath.SCALE */: {
+ properties = GetMappingForKey("/nodes/{}/scale")?.interpolation;
+ break;
+ }
+ case "weights" /* AnimationChannelTargetPath.WEIGHTS */: {
+ properties = GetMappingForKey("/nodes/{}/weights")?.interpolation;
+ break;
+ }
+ default: {
+ throw new Error(`${context}/target/path: Invalid value (${channel.target.path})`);
+ }
+ }
+ // stay safe
+ if (!properties) {
+ throw new Error(`${context}/target/path: Could not find interpolation properties for target path (${channel.target.path})`);
+ }
+ const targetInfo = {
+ object: targetNode,
+ info: properties,
+ };
+ return this._loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad);
+ }
+ /**
+ * @hidden
+ * Loads a glTF animation channel.
+ * @param context The context when loading the asset
+ * @param animationContext The context of the animation when loading the asset
+ * @param animation The glTF animation property
+ * @param channel The glTF animation channel property
+ * @param targetInfo The glTF target and properties
+ * @param onLoad Called for each animation loaded
+ * @returns A void promise that resolves when the load is complete
+ */
+ _loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad) {
+ const fps = this.parent.targetFps;
+ const invfps = 1 / fps;
+ const sampler = ArrayItem.Get(`${context}/sampler`, animation.samplers, channel.sampler);
+ return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then((data) => {
+ let numAnimations = 0;
+ const target = targetInfo.object;
+ const propertyInfos = targetInfo.info;
+ // Extract the corresponding values from the read value.
+ // GLTF values may be dispatched to several Babylon properties.
+ // For example, baseColorFactor [`r`, `g`, `b`, `a`] is dispatched to
+ // - albedoColor as Color3(`r`, `g`, `b`)
+ // - alpha as `a`
+ for (const propertyInfo of propertyInfos) {
+ const stride = propertyInfo.getStride(target);
+ const input = data.input;
+ const output = data.output;
+ const keys = new Array(input.length);
+ let outputOffset = 0;
+ switch (data.interpolation) {
+ case "STEP" /* AnimationSamplerInterpolation.STEP */: {
+ for (let index = 0; index < input.length; index++) {
+ const value = propertyInfo.getValue(target, output, outputOffset, 1);
+ outputOffset += stride;
+ keys[index] = {
+ frame: input[index] * fps,
+ value: value,
+ interpolation: 1 /* AnimationKeyInterpolation.STEP */,
+ };
+ }
+ break;
+ }
+ case "CUBICSPLINE" /* AnimationSamplerInterpolation.CUBICSPLINE */: {
+ for (let index = 0; index < input.length; index++) {
+ const inTangent = propertyInfo.getValue(target, output, outputOffset, invfps);
+ outputOffset += stride;
+ const value = propertyInfo.getValue(target, output, outputOffset, 1);
+ outputOffset += stride;
+ const outTangent = propertyInfo.getValue(target, output, outputOffset, invfps);
+ outputOffset += stride;
+ keys[index] = {
+ frame: input[index] * fps,
+ inTangent: inTangent,
+ value: value,
+ outTangent: outTangent,
+ };
+ }
+ break;
+ }
+ case "LINEAR" /* AnimationSamplerInterpolation.LINEAR */: {
+ for (let index = 0; index < input.length; index++) {
+ const value = propertyInfo.getValue(target, output, outputOffset, 1);
+ outputOffset += stride;
+ keys[index] = {
+ frame: input[index] * fps,
+ value: value,
+ };
+ }
+ break;
+ }
+ }
+ if (outputOffset > 0) {
+ const name = `${animation.name || `animation${animation.index}`}_channel${channel.index}_${numAnimations}`;
+ const babylonAnimations = propertyInfo.buildAnimations(target, name, fps, keys);
+ for (const babylonAnimation of babylonAnimations) {
+ numAnimations++;
+ onLoad(babylonAnimation.babylonAnimatable, babylonAnimation.babylonAnimation);
+ }
+ }
+ }
+ });
+ }
+ _loadAnimationSamplerAsync(context, sampler) {
+ if (sampler._data) {
+ return sampler._data;
+ }
+ const interpolation = sampler.interpolation || "LINEAR" /* AnimationSamplerInterpolation.LINEAR */;
+ switch (interpolation) {
+ case "STEP" /* AnimationSamplerInterpolation.STEP */:
+ case "LINEAR" /* AnimationSamplerInterpolation.LINEAR */:
+ case "CUBICSPLINE" /* AnimationSamplerInterpolation.CUBICSPLINE */: {
+ break;
+ }
+ default: {
+ throw new Error(`${context}/interpolation: Invalid value (${sampler.interpolation})`);
+ }
+ }
+ const inputAccessor = ArrayItem.Get(`${context}/input`, this._gltf.accessors, sampler.input);
+ const 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(([inputData, outputData]) => {
+ return {
+ input: inputData,
+ interpolation: interpolation,
+ output: outputData,
+ };
+ });
+ return sampler._data;
+ }
+ /**
+ * Loads a glTF buffer.
+ * @param context The context when loading the asset
+ * @param buffer The glTF buffer property
+ * @param byteOffset The byte offset to use
+ * @param byteLength The byte length to use
+ * @returns A promise that resolves with the loaded data when the load is complete
+ */
+ loadBufferAsync(context, buffer, byteOffset, byteLength) {
+ const extensionPromise = this._extensionsLoadBufferAsync(context, buffer, byteOffset, byteLength);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ if (!buffer._data) {
+ if (buffer.uri) {
+ buffer._data = this.loadUriAsync(`${context}/uri`, buffer, buffer.uri);
+ }
+ else {
+ if (!this._bin) {
+ throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`);
+ }
+ buffer._data = this._bin.readAsync(0, buffer.byteLength);
+ }
+ }
+ return buffer._data.then((data) => {
+ try {
+ return new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
+ }
+ catch (e) {
+ throw new Error(`${context}: ${e.message}`);
+ }
+ });
+ }
+ /**
+ * 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
+ */
+ loadBufferViewAsync(context, bufferView) {
+ const extensionPromise = this._extensionsLoadBufferViewAsync(context, bufferView);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ if (bufferView._data) {
+ return bufferView._data;
+ }
+ const buffer = ArrayItem.Get(`${context}/buffer`, this._gltf.buffers, bufferView.buffer);
+ bufferView._data = this.loadBufferAsync(`/buffers/${buffer.index}`, buffer, bufferView.byteOffset || 0, bufferView.byteLength);
+ return bufferView._data;
+ }
+ _loadAccessorAsync(context, accessor, constructor) {
+ if (accessor._data) {
+ return accessor._data;
+ }
+ const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
+ const byteStride = numComponents * VertexBuffer.GetTypeByteLength(accessor.componentType);
+ const length = numComponents * accessor.count;
+ if (accessor.bufferView == undefined) {
+ accessor._data = Promise.resolve(new constructor(length));
+ }
+ else {
+ const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
+ accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
+ if (accessor.componentType === 5126 /* AccessorComponentType.FLOAT */ && !accessor.normalized && (!bufferView.byteStride || bufferView.byteStride === byteStride)) {
+ return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
+ }
+ else {
+ const typedArray = new constructor(length);
+ VertexBuffer.ForEach(data, accessor.byteOffset || 0, bufferView.byteStride || byteStride, numComponents, accessor.componentType, typedArray.length, accessor.normalized || false, (value, index) => {
+ typedArray[index] = value;
+ });
+ return typedArray;
+ }
+ });
+ }
+ if (accessor.sparse) {
+ const sparse = accessor.sparse;
+ accessor._data = accessor._data.then((data) => {
+ const typedArray = data;
+ const indicesBufferView = ArrayItem.Get(`${context}/sparse/indices/bufferView`, this._gltf.bufferViews, sparse.indices.bufferView);
+ const valuesBufferView = ArrayItem.Get(`${context}/sparse/values/bufferView`, this._gltf.bufferViews, sparse.values.bufferView);
+ return Promise.all([
+ this.loadBufferViewAsync(`/bufferViews/${indicesBufferView.index}`, indicesBufferView),
+ this.loadBufferViewAsync(`/bufferViews/${valuesBufferView.index}`, valuesBufferView),
+ ]).then(([indicesData, valuesData]) => {
+ const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count);
+ const sparseLength = numComponents * sparse.count;
+ let values;
+ if (accessor.componentType === 5126 /* AccessorComponentType.FLOAT */ && !accessor.normalized) {
+ values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength);
+ }
+ else {
+ const sparseData = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength);
+ values = new constructor(sparseLength);
+ VertexBuffer.ForEach(sparseData, 0, byteStride, numComponents, accessor.componentType, values.length, accessor.normalized || false, (value, index) => {
+ values[index] = value;
+ });
+ }
+ let valuesIndex = 0;
+ for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
+ let dataIndex = indices[indicesIndex] * numComponents;
+ for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {
+ typedArray[dataIndex++] = values[valuesIndex++];
+ }
+ }
+ return typedArray;
+ });
+ });
+ }
+ return accessor._data;
+ }
+ /**
+ * @internal
+ */
+ _loadFloatAccessorAsync(context, accessor) {
+ return this._loadAccessorAsync(context, accessor, Float32Array);
+ }
+ /**
+ * @internal
+ */
+ _loadIndicesAccessorAsync(context, accessor) {
+ if (accessor.type !== "SCALAR" /* AccessorType.SCALAR */) {
+ throw new Error(`${context}/type: Invalid value ${accessor.type}`);
+ }
+ if (accessor.componentType !== 5121 /* AccessorComponentType.UNSIGNED_BYTE */ &&
+ accessor.componentType !== 5123 /* AccessorComponentType.UNSIGNED_SHORT */ &&
+ accessor.componentType !== 5125 /* AccessorComponentType.UNSIGNED_INT */) {
+ throw new Error(`${context}/componentType: Invalid value ${accessor.componentType}`);
+ }
+ if (accessor._data) {
+ return accessor._data;
+ }
+ if (accessor.sparse) {
+ const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, accessor.componentType);
+ accessor._data = this._loadAccessorAsync(context, accessor, constructor);
+ }
+ else {
+ const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
+ accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
+ return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
+ });
+ }
+ return accessor._data;
+ }
+ /**
+ * @internal
+ */
+ _loadVertexBufferViewAsync(bufferView) {
+ if (bufferView._babylonBuffer) {
+ return bufferView._babylonBuffer;
+ }
+ const engine = this._babylonScene.getEngine();
+ bufferView._babylonBuffer = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
+ return new Buffer(engine, data, false);
+ });
+ return bufferView._babylonBuffer;
+ }
+ /**
+ * @internal
+ */
+ _loadVertexAccessorAsync(context, accessor, kind) {
+ if (accessor._babylonVertexBuffer?.[kind]) {
+ return accessor._babylonVertexBuffer[kind];
+ }
+ if (!accessor._babylonVertexBuffer) {
+ accessor._babylonVertexBuffer = {};
+ }
+ const engine = this._babylonScene.getEngine();
+ if (accessor.sparse || accessor.bufferView == undefined) {
+ accessor._babylonVertexBuffer[kind] = this._loadFloatAccessorAsync(context, accessor).then((data) => {
+ return new VertexBuffer(engine, data, kind, false);
+ });
+ }
+ else {
+ const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
+ accessor._babylonVertexBuffer[kind] = this._loadVertexBufferViewAsync(bufferView).then((babylonBuffer) => {
+ const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
+ return new VertexBuffer(engine, babylonBuffer, kind, false, undefined, bufferView.byteStride, undefined, accessor.byteOffset, numComponents, accessor.componentType, accessor.normalized, true, undefined, true);
+ });
+ }
+ return accessor._babylonVertexBuffer[kind];
+ }
+ _loadMaterialMetallicRoughnessPropertiesAsync(context, properties, babylonMaterial) {
+ if (!(babylonMaterial instanceof PBRMaterial)) {
+ throw new Error(`${context}: Material type not supported`);
+ }
+ const promises = new Array();
+ if (properties) {
+ if (properties.baseColorFactor) {
+ babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);
+ babylonMaterial.alpha = properties.baseColorFactor[3];
+ }
+ else {
+ babylonMaterial.albedoColor = 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, (texture) => {
+ texture.name = `${babylonMaterial.name} (Base Color)`;
+ babylonMaterial.albedoTexture = texture;
+ }));
+ }
+ if (properties.metallicRoughnessTexture) {
+ properties.metallicRoughnessTexture.nonColorData = true;
+ promises.push(this.loadTextureInfoAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, (texture) => {
+ texture.name = `${babylonMaterial.name} (Metallic Roughness)`;
+ babylonMaterial.metallicTexture = texture;
+ }));
+ babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
+ babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
+ babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
+ }
+ }
+ return Promise.all(promises).then(() => { });
+ }
+ /**
+ * @internal
+ */
+ _loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign = () => { }) {
+ const extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ material._data = material._data || {};
+ let babylonData = material._data[babylonDrawMode];
+ if (!babylonData) {
+ this.logOpen(`${context} ${material.name || ""}`);
+ const 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();
+ }
+ if (babylonMesh) {
+ babylonData.babylonMeshes.push(babylonMesh);
+ babylonMesh.onDisposeObservable.addOnce(() => {
+ const index = babylonData.babylonMeshes.indexOf(babylonMesh);
+ if (index !== -1) {
+ babylonData.babylonMeshes.splice(index, 1);
+ }
+ });
+ }
+ assign(babylonData.babylonMaterial);
+ return babylonData.promise.then(() => {
+ return babylonData.babylonMaterial;
+ });
+ }
+ _createDefaultMaterial(name, babylonDrawMode) {
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ const babylonMaterial = new PBRMaterial(name, this._babylonScene);
+ babylonMaterial._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ // Moved to mesh so user can change materials on gltf meshes: babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
+ babylonMaterial.fillMode = babylonDrawMode;
+ babylonMaterial.enableSpecularAntiAliasing = true;
+ babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
+ babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
+ babylonMaterial.transparencyMode = 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
+ */
+ createMaterial(context, material, babylonDrawMode) {
+ const extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ const name = material.name || `material${material.index}`;
+ const 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
+ */
+ loadMaterialPropertiesAsync(context, material, babylonMaterial) {
+ const extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ const 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(() => { });
+ }
+ /**
+ * 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
+ */
+ loadMaterialBasePropertiesAsync(context, material, babylonMaterial) {
+ if (!(babylonMaterial instanceof PBRMaterial)) {
+ throw new Error(`${context}: Material type not supported`);
+ }
+ const promises = new Array();
+ babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
+ if (material.doubleSided) {
+ babylonMaterial.backFaceCulling = false;
+ babylonMaterial.twoSidedLighting = true;
+ }
+ if (material.normalTexture) {
+ material.normalTexture.nonColorData = true;
+ promises.push(this.loadTextureInfoAsync(`${context}/normalTexture`, material.normalTexture, (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) {
+ babylonMaterial.bumpTexture.level = material.normalTexture.scale;
+ }
+ babylonMaterial.forceIrradianceInFragment = true;
+ }
+ if (material.occlusionTexture) {
+ material.occlusionTexture.nonColorData = true;
+ promises.push(this.loadTextureInfoAsync(`${context}/occlusionTexture`, material.occlusionTexture, (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, (texture) => {
+ texture.name = `${babylonMaterial.name} (Emissive)`;
+ babylonMaterial.emissiveTexture = texture;
+ }));
+ }
+ return Promise.all(promises).then(() => { });
+ }
+ /**
+ * 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
+ */
+ loadMaterialAlphaProperties(context, material, babylonMaterial) {
+ if (!(babylonMaterial instanceof PBRMaterial)) {
+ throw new Error(`${context}: Material type not supported`);
+ }
+ const alphaMode = material.alphaMode || "OPAQUE" /* MaterialAlphaMode.OPAQUE */;
+ switch (alphaMode) {
+ case "OPAQUE" /* MaterialAlphaMode.OPAQUE */: {
+ babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
+ babylonMaterial.alpha = 1.0; // Force alpha to 1.0 for opaque mode.
+ break;
+ }
+ case "MASK" /* MaterialAlphaMode.MASK */: {
+ babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
+ babylonMaterial.alphaCutOff = material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff;
+ if (babylonMaterial.albedoTexture) {
+ babylonMaterial.albedoTexture.hasAlpha = true;
+ }
+ break;
+ }
+ case "BLEND" /* MaterialAlphaMode.BLEND */: {
+ babylonMaterial.transparencyMode = 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
+ */
+ loadTextureInfoAsync(context, textureInfo, assign = () => { }) {
+ const extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ this.logOpen(`${context}`);
+ if (textureInfo.texCoord >= 6) {
+ throw new Error(`${context}/texCoord: Invalid value (${textureInfo.texCoord})`);
+ }
+ const texture = ArrayItem.Get(`${context}/index`, this._gltf.textures, textureInfo.index);
+ texture._textureInfo = textureInfo;
+ const promise = this._loadTextureAsync(`/textures/${textureInfo.index}`, texture, (babylonTexture) => {
+ babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
+ GLTFLoader.AddPointerMetadata(babylonTexture, context);
+ this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
+ assign(babylonTexture);
+ });
+ this.logClose();
+ return promise;
+ }
+ /**
+ * @internal
+ */
+ _loadTextureAsync(context, texture, assign = () => { }) {
+ const extensionPromise = this._extensionsLoadTextureAsync(context, texture, assign);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ this.logOpen(`${context} ${texture.name || ""}`);
+ const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._gltf.samplers, texture.sampler);
+ const image = ArrayItem.Get(`${context}/source`, this._gltf.images, texture.source);
+ const promise = this._createTextureAsync(context, sampler, image, assign, undefined, !texture._textureInfo.nonColorData);
+ this.logClose();
+ return promise;
+ }
+ /**
+ * @internal
+ */
+ _createTextureAsync(context, sampler, image, assign = () => { }, textureLoaderOptions, useSRGBBuffer) {
+ const samplerData = this._loadSampler(`/samplers/${sampler.index}`, sampler);
+ const promises = new Array();
+ const deferred = new Deferred();
+ this._babylonScene._blockEntityCollection = !!this._assetContainer;
+ const textureCreationOptions = {
+ noMipmap: samplerData.noMipMaps,
+ invertY: false,
+ samplingMode: samplerData.samplingMode,
+ onLoad: () => {
+ if (!this._disposed) {
+ deferred.resolve();
+ }
+ },
+ onError: (message, exception) => {
+ if (!this._disposed) {
+ deferred.reject(new Error(`${context}: ${exception && exception.message ? exception.message : message || "Failed to load texture"}`));
+ }
+ },
+ mimeType: image.mimeType,
+ loaderOptions: textureLoaderOptions,
+ useSRGBBuffer: !!useSRGBBuffer && this._parent.useSRGBBuffers,
+ };
+ const babylonTexture = new Texture(null, this._babylonScene, textureCreationOptions);
+ babylonTexture._parentContainer = this._assetContainer;
+ this._babylonScene._blockEntityCollection = false;
+ promises.push(deferred.promise);
+ promises.push(this.loadImageAsync(`/images/${image.index}`, image).then((data) => {
+ const name = image.uri || `${this._fileName}#image${image.index}`;
+ const dataUrl = `data:${this._uniqueRootUrl}${name}`;
+ babylonTexture.updateURL(dataUrl, data);
+ // Set the internal texture label.
+ const internalTexture = babylonTexture.getInternalTexture();
+ if (internalTexture) {
+ internalTexture.label = image.name;
+ }
+ }));
+ babylonTexture.wrapU = samplerData.wrapU;
+ babylonTexture.wrapV = samplerData.wrapV;
+ assign(babylonTexture);
+ if (this._parent.useGltfTextureNames) {
+ babylonTexture.name = image.name || image.uri || `image${image.index}`;
+ }
+ return Promise.all(promises).then(() => {
+ return babylonTexture;
+ });
+ }
+ _loadSampler(context, sampler) {
+ if (!sampler._data) {
+ sampler._data = {
+ noMipMaps: sampler.minFilter === 9728 /* TextureMinFilter.NEAREST */ || sampler.minFilter === 9729 /* TextureMinFilter.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
+ */
+ loadImageAsync(context, image) {
+ if (!image._data) {
+ this.logOpen(`${context} ${image.name || ""}`);
+ if (image.uri) {
+ image._data = this.loadUriAsync(`${context}/uri`, image, image.uri);
+ }
+ else {
+ const 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 property The glTF property associated with the uri
+ * @param uri The base64 or relative uri
+ * @returns A promise that resolves with the loaded data when the load is complete
+ */
+ loadUriAsync(context, property, uri) {
+ const extensionPromise = this._extensionsLoadUriAsync(context, property, uri);
+ if (extensionPromise) {
+ return extensionPromise;
+ }
+ if (!GLTFLoader._ValidateUri(uri)) {
+ throw new Error(`${context}: '${uri}' is invalid`);
+ }
+ if (IsBase64DataUrl(uri)) {
+ const data = new Uint8Array(DecodeBase64UrlToBinary(uri));
+ this.log(`${context}: Decoded ${uri.substring(0, 64)}... (${data.length} bytes)`);
+ return Promise.resolve(data);
+ }
+ this.log(`${context}: Loading ${uri}`);
+ return this._parent.preprocessUrlAsync(this._rootUrl + uri).then((url) => {
+ return new Promise((resolve, reject) => {
+ this._parent._loadFile(this._babylonScene, url, (data) => {
+ if (!this._disposed) {
+ this.log(`${context}: Loaded ${uri} (${data.byteLength} bytes)`);
+ resolve(new Uint8Array(data));
+ }
+ }, true, (request) => {
+ reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? ": " + request.status + " " + request.statusText : ""}`, request));
+ });
+ });
+ });
+ }
+ /**
+ * Adds a JSON pointer to the _internalMetadata of the Babylon object at `