var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
for (var name260 in all)
__defProp(target, name260, { get: all[name260], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i = decorators.length - 1, decorator; i >= 0; i--)
if (decorator = decorators[i])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/observable.js
var IsWeakRefSupported, EventState, Observer, Observable;
var init_observable = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/observable.js"() {
IsWeakRefSupported = typeof WeakRef !== "undefined";
EventState = class {
static {
__name(this, "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;
}
};
Observer = class {
static {
__name(this, "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(callback, mask, scope = null) {
this.callback = callback;
this.mask = mask;
this.scope = scope;
this._willBeUnregistered = false;
this.unregisterOnNextCall = false;
this._remove = null;
}
/**
* Remove the observer from its observable
* This can be used instead of using the observable's remove function.
* @param defer if true, the removal will be deferred to avoid callback skipping (default: false)
*/
remove(defer = false) {
if (this._remove) {
this._remove(defer);
}
}
};
Observable = class _Observable {
static {
__name(this, "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, 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 (this._hasNotified && this.notifyIfTriggered) {
if (this._lastNotifiedValue !== void 0) {
this.notifyObserver(observer, this._lastNotifiedValue);
}
}
const observableWeakRef = IsWeakRefSupported ? new WeakRef(this) : { deref: /* @__PURE__ */ __name(() => this, "deref") };
observer._remove = (defer = false) => {
const observable = observableWeakRef.deref();
if (observable) {
defer ? observable.remove(observer) : observable._remove(observer);
}
};
return observer;
}
addOnce(callback) {
return this.add(callback, void 0, void 0, void 0, 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) {
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) {
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 = void 0;
}
/**
* 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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/domManagement.js
function IsWindowObjectExist() {
return typeof window !== "undefined";
}
function IsNavigatorAvailable() {
return typeof navigator !== "undefined";
}
function IsDocumentAvailable() {
return typeof document !== "undefined";
}
function GetDOMTextContent(element) {
let result = "";
let child = element.firstChild;
while (child) {
if (child.nodeType === 3) {
result += child.textContent;
}
child = child.nextSibling;
}
return result;
}
var DomManagement;
var init_domManagement = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/domManagement.js"() {
__name(IsWindowObjectExist, "IsWindowObjectExist");
__name(IsNavigatorAvailable, "IsNavigatorAvailable");
__name(IsDocumentAvailable, "IsDocumentAvailable");
__name(GetDOMTextContent, "GetDOMTextContent");
DomManagement = {
/**
* Checks if the window object exists
* @returns true if the window object exists
*/
IsWindowObjectExist,
/**
* Checks if the navigator object exists
* @returns true if the navigator object exists
*/
IsNavigatorAvailable,
/**
* Check if the document object exists
* @returns true if the document object exists
*/
IsDocumentAvailable,
/**
* Extracts text content from a DOM element hierarchy
* @param element defines the root element
* @returns a string
*/
GetDOMTextContent
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/logger.js
var Logger;
var init_logger = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/logger.js"() {
Logger = class _Logger {
static {
__name(this, "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 = /* @__PURE__ */ __name((i) => i < 10 ? "0" + i : "" + i, "padStr");
const date = /* @__PURE__ */ 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) {
}
static _LogEnabled(level = 1, message, limit) {
const msg = Array.isArray(message) ? message[0] : message;
if (limit !== void 0 && !_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;
const levels = [_Logger.MessageLogLevel, _Logger.WarningLogLevel, _Logger.ErrorLogLevel];
for (const l of levels) {
if ((level & l) === l) {
const type = this._Levels[l];
_Logger[type.name] = _Logger._LogEnabled.bind(_Logger, l);
}
}
}
};
Logger.NoneLogLevel = 0;
Logger.MessageLogLevel = 1;
Logger.WarningLogLevel = 2;
Logger.ErrorLogLevel = 4;
Logger.AllLogLevel = 7;
Logger.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";
Logger._LogCache = "";
Logger._LogLimitOutputs = {};
Logger._Levels = [
{},
{ color: "white", logFunc: console.log, name: "Log" },
{ color: "orange", logFunc: console.warn, name: "Warn" },
{},
{ color: "red", logFunc: console.error, name: "Error" }
];
Logger.errorsCount = 0;
Logger.Log = Logger._LogEnabled.bind(Logger, Logger.MessageLogLevel);
Logger.Warn = Logger._LogEnabled.bind(Logger, Logger.WarningLogLevel);
Logger.Error = Logger._LogEnabled.bind(Logger, Logger.ErrorLogLevel);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/deepCopier.js
function GetAllPropertyNames(obj) {
const props = [];
do {
const propNames = Object.getOwnPropertyNames(obj);
for (const prop of propNames) {
if (props.indexOf(prop) === -1) {
props.push(prop);
}
}
} while (obj = Object.getPrototypeOf(obj));
return props;
}
var CloneValue, DeepCopier;
var init_deepCopier = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/deepCopier.js"() {
init_logger();
CloneValue = /* @__PURE__ */ __name((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;
}, "CloneValue");
__name(GetAllPropertyNames, "GetAllPropertyNames");
DeepCopier = class {
static {
__name(this, "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) {
destination[prop].push(clonedValue);
}
}
} else {
destination[prop] = sourceValue.slice(0);
}
}
} else {
destination[prop] = CloneValue(sourceValue, destination, shallowCopyValues);
}
} else {
destination[prop] = sourceValue;
}
} catch (e) {
Logger.Warn(e.message);
}
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/precisionDate.js
var PrecisionDate;
var init_precisionDate = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/precisionDate.js"() {
init_domManagement();
PrecisionDate = class {
static {
__name(this, "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();
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/devTools.js
function _WarnImport(name260, warnOnce = false) {
if (warnOnce && WarnedMap[name260]) {
return;
}
WarnedMap[name260] = true;
return `${name260} needs to be imported before as it contains a side-effect required by your code.`;
}
var WarnedMap;
var init_devTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/devTools.js"() {
WarnedMap = {};
__name(_WarnImport, "_WarnImport");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/webRequest.js
function createXMLHttpRequest() {
if (typeof _native !== "undefined" && _native.XMLHttpRequest) {
return new _native.XMLHttpRequest();
} else {
return new XMLHttpRequest();
}
}
var WebRequest;
var init_webRequest = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/webRequest.js"() {
__name(createXMLHttpRequest, "createXMLHttpRequest");
WebRequest = class _WebRequest {
static {
__name(this, "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;
}
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(name260, value) {
this._xhr.setRequestHeader(name260, 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(name260) {
return this._xhr.getResponseHeader(name260);
}
};
WebRequest.CustomRequestHeaders = {};
WebRequest.CustomRequestModifiers = new Array();
WebRequest.SkipRequestModificationForBabylonCDN = true;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engineStore.js
var EngineStore;
var init_engineStore = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engineStore.js"() {
init_observable();
EngineStore = class {
static {
__name(this, "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;
}
};
EngineStore.Instances = [];
EngineStore.OnEnginesDisposedObservable = new Observable();
EngineStore._LastCreatedScene = null;
EngineStore.UseFallbackTexture = true;
EngineStore.FallbackTexture = "";
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/filesInputStore.js
var FilesInputStore;
var init_filesInputStore = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/filesInputStore.js"() {
FilesInputStore = class {
static {
__name(this, "FilesInputStore");
}
};
FilesInputStore.FilesToLoad = {};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/retryStrategy.js
var RetryStrategy;
var init_retryStrategy = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/retryStrategy.js"() {
RetryStrategy = class {
static {
__name(this, "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;
};
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/error.js
var BaseError, ErrorCodes, RuntimeError, AbortError;
var init_error = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/error.js"() {
BaseError = class extends Error {
static {
__name(this, "BaseError");
}
};
BaseError._setPrototypeOf = Object.setPrototypeOf || ((o, proto) => {
o.__proto__ = proto;
return o;
});
ErrorCodes = {
// Mesh errors 0-999
/** Invalid or empty mesh vertex positions. */
MeshInvalidPositionsError: 0,
// Texture errors 1000-1999
/** Unsupported texture found. */
UnsupportedTextureError: 1e3,
// GLTFLoader errors 2000-2999
/** Unexpected magic number found in GLTF file header. */
GLTFLoaderUnexpectedMagicError: 2e3,
// SceneLoader errors 3000-3999
/** SceneLoader generic error code. Ideally wraps the inner exception. */
SceneLoaderError: 3e3,
// File related errors 4000-4999
/** Load file error */
LoadFileError: 4e3,
/** Request file error */
RequestFileError: 4001,
/** Read file error */
ReadFileError: 4002
};
RuntimeError = class _RuntimeError extends BaseError {
static {
__name(this, "RuntimeError");
}
/**
* 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);
}
};
AbortError = class _AbortError extends BaseError {
static {
__name(this, "AbortError");
}
constructor(message = "Operation aborted") {
super(message);
this.name = "AbortError";
BaseError._setPrototypeOf(this, _AbortError.prototype);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/stringTools.js
var EndsWith, StartsWith, Decode, EncodeArrayBufferToBase64, DecodeBase64ToString, DecodeBase64ToBinary, PadNumber, StringTools;
var init_stringTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/stringTools.js"() {
EndsWith = /* @__PURE__ */ __name((str, suffix) => {
return str.endsWith(suffix);
}, "EndsWith");
StartsWith = /* @__PURE__ */ __name((str, suffix) => {
if (!str) {
return false;
}
return str.startsWith(suffix);
}, "StartsWith");
Decode = /* @__PURE__ */ __name((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;
}, "Decode");
EncodeArrayBufferToBase64 = /* @__PURE__ */ __name((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;
}, "EncodeArrayBufferToBase64");
DecodeBase64ToString = /* @__PURE__ */ __name((base64Data) => {
return atob(base64Data);
}, "DecodeBase64ToString");
DecodeBase64ToBinary = /* @__PURE__ */ __name((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;
}, "DecodeBase64ToBinary");
PadNumber = /* @__PURE__ */ __name((num, length) => {
let str = String(num);
while (str.length < length) {
str = "0" + str;
}
return str;
}, "PadNumber");
StringTools = {
EndsWith,
StartsWith,
Decode,
EncodeArrayBufferToBase64,
DecodeBase64ToString,
DecodeBase64ToBinary,
PadNumber
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeNode.js
var DefaultAttributeKeywordName, DefaultVaryingKeywordName, ShaderCodeNode;
var init_shaderCodeNode = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeNode.js"() {
DefaultAttributeKeywordName = "attribute";
DefaultVaryingKeywordName = "varying";
ShaderCodeNode = class {
static {
__name(this, "ShaderCodeNode");
}
constructor() {
this.children = [];
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
isValid(preprocessors) {
return true;
}
process(preprocessors, options, preProcessorsFromCode) {
let result = "";
if (this.line) {
let value = this.line;
const processor = options.processor;
if (processor) {
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)) {
if (processor.uniformProcessor) {
value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext);
}
} else {
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";
}
for (const child of this.children) {
result += child.process(preprocessors, options, preProcessorsFromCode);
}
if (this.additionalDefineKey) {
preprocessors[this.additionalDefineKey] = this.additionalDefineValue || "true";
preProcessorsFromCode[this.additionalDefineKey] = preprocessors[this.additionalDefineKey];
}
return result;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeCursor.js
var ShaderCodeCursor;
var init_shaderCodeCursor = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeCursor.js"() {
ShaderCodeCursor = class {
static {
__name(this, "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) {
if (!line || line === "\r") {
continue;
}
if (line[0] === "#") {
this._lines.push(line);
continue;
}
const trimmedLine = line.trim();
if (!trimmedLine) {
continue;
}
if (trimmedLine.startsWith("//")) {
this._lines.push(line);
continue;
}
const semicolonIndex = trimmedLine.indexOf(";");
if (semicolonIndex === -1) {
this._lines.push(trimmedLine);
} else if (semicolonIndex === trimmedLine.length - 1) {
if (trimmedLine.length > 1) {
this._lines.push(trimmedLine);
}
} else {
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 ? ";" : ""));
}
}
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeConditionNode.js
var ShaderCodeConditionNode;
var init_shaderCodeConditionNode = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeConditionNode.js"() {
init_shaderCodeNode();
ShaderCodeConditionNode = class extends ShaderCodeNode {
static {
__name(this, "ShaderCodeConditionNode");
}
process(preprocessors, options, preProcessorsFromCode) {
for (let index = 0; index < this.children.length; index++) {
const node = this.children[index];
if (node.isValid(preprocessors)) {
return node.process(preprocessors, options, preProcessorsFromCode);
}
}
return "";
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeTestNode.js
var ShaderCodeTestNode;
var init_shaderCodeTestNode = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeTestNode.js"() {
init_shaderCodeNode();
ShaderCodeTestNode = class extends ShaderCodeNode {
static {
__name(this, "ShaderCodeTestNode");
}
isValid(preprocessors) {
return this.testExpression.isTrue(preprocessors);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/shaderDefineExpression.js
var ShaderDefineExpression;
var init_shaderDefineExpression = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/shaderDefineExpression.js"() {
ShaderDefineExpression = class _ShaderDefineExpression {
static {
__name(this, "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] === void 0) {
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) {
const cacheItem = _ShaderDefineExpression._InfixToPostfixCache.get(infix);
if (cacheItem) {
cacheItem.accessTime = Date.now();
return cacheItem.result;
}
if (!infix.includes("&&") && !infix.includes("||") && !infix.includes(")") && !infix.includes("(")) {
return [infix];
}
const result = [];
let stackIdx = -1;
const pushOperand = /* @__PURE__ */ __name(() => {
operand = operand.trim();
if (operand !== "") {
result.push(operand);
operand = "";
}
}, "pushOperand");
const push = /* @__PURE__ */ __name((s) => {
if (stackIdx < _ShaderDefineExpression._Stack.length - 1) {
_ShaderDefineExpression._Stack[++stackIdx] = s;
}
}, "push");
const peek = /* @__PURE__ */ __name(() => _ShaderDefineExpression._Stack[stackIdx], "peek");
const pop = /* @__PURE__ */ __name(() => stackIdx === -1 ? "!!INVALID EXPRESSION!!" : _ShaderDefineExpression._Stack[stackIdx--], "pop");
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 (_ShaderDefineExpression._InfixToPostfixCache.size >= _ShaderDefineExpression.InfixToPostfixCacheLimitSize) {
_ShaderDefineExpression.ClearCache();
}
_ShaderDefineExpression._InfixToPostfixCache.set(infix, { result, accessTime: Date.now() });
return result;
}
static ClearCache() {
const sortedCache = Array.from(_ShaderDefineExpression._InfixToPostfixCache.entries()).sort((a, b) => a[1].accessTime - b[1].accessTime);
for (let i = 0; i < _ShaderDefineExpression.InfixToPostfixCacheCleanupSize; i++) {
_ShaderDefineExpression._InfixToPostfixCache.delete(sortedCache[i][0]);
}
}
};
ShaderDefineExpression.InfixToPostfixCacheLimitSize = 5e4;
ShaderDefineExpression.InfixToPostfixCacheCleanupSize = 25e3;
ShaderDefineExpression._InfixToPostfixCache = /* @__PURE__ */ new Map();
ShaderDefineExpression._OperatorPriority = {
")": 0,
"(": 1,
"||": 2,
"&&": 3
};
ShaderDefineExpression._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""];
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.js
var ShaderDefineIsDefinedOperator;
var init_shaderDefineIsDefinedOperator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.js"() {
init_shaderDefineExpression();
ShaderDefineIsDefinedOperator = class extends ShaderDefineExpression {
static {
__name(this, "ShaderDefineIsDefinedOperator");
}
constructor(define, not = false) {
super();
this.define = define;
this.not = not;
}
isTrue(preprocessors) {
let condition = preprocessors[this.define] !== void 0;
if (this.not) {
condition = !condition;
}
return condition;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineOrOperator.js
var ShaderDefineOrOperator;
var init_shaderDefineOrOperator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineOrOperator.js"() {
init_shaderDefineExpression();
ShaderDefineOrOperator = class extends ShaderDefineExpression {
static {
__name(this, "ShaderDefineOrOperator");
}
isTrue(preprocessors) {
return this.leftOperand.isTrue(preprocessors) || this.rightOperand.isTrue(preprocessors);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineAndOperator.js
var ShaderDefineAndOperator;
var init_shaderDefineAndOperator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineAndOperator.js"() {
init_shaderDefineExpression();
ShaderDefineAndOperator = class extends ShaderDefineExpression {
static {
__name(this, "ShaderDefineAndOperator");
}
isTrue(preprocessors) {
return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.js
var ShaderDefineArithmeticOperator;
var init_shaderDefineArithmeticOperator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.js"() {
init_shaderDefineExpression();
ShaderDefineArithmeticOperator = class extends ShaderDefineExpression {
static {
__name(this, "ShaderDefineArithmeticOperator");
}
constructor(define, operand, testValue) {
super();
this.define = define;
this.operand = operand;
this.testValue = testValue;
}
toString() {
return `${this.define} ${this.operand} ${this.testValue}`;
}
isTrue(preprocessors) {
let condition = false;
const left = parseInt(preprocessors[this.define] != void 0 ? preprocessors[this.define] : this.define);
const right = parseInt(preprocessors[this.testValue] != void 0 ? preprocessors[this.testValue] : this.testValue);
if (isNaN(left) || isNaN(right)) {
return false;
}
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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/abstractEngine.functions.js
function _ConcatenateShader(source, defines, shaderVersion = "") {
return shaderVersion + (defines ? defines + "\n" : "") + source;
}
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");
}
function getHostDocument(renderingCanvas = null) {
if (renderingCanvas && renderingCanvas.ownerDocument) {
return renderingCanvas.ownerDocument;
}
return IsDocumentAvailable() ? document : null;
}
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;
}
}
function allocateAndCopyTypedBuffer(type, sizeOrDstBuffer, sizeInBytes = false, copyBuffer) {
switch (type) {
case 3: {
const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int8Array(sizeOrDstBuffer) : new Int8Array(sizeOrDstBuffer);
if (copyBuffer) {
buffer2.set(new Int8Array(copyBuffer));
}
return buffer2;
}
case 0: {
const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);
if (copyBuffer) {
buffer2.set(new Uint8Array(copyBuffer));
}
return buffer2;
}
case 4: {
const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int16Array(sizeOrDstBuffer) : new Int16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);
if (copyBuffer) {
buffer2.set(new Int16Array(copyBuffer));
}
return buffer2;
}
case 5:
case 8:
case 9:
case 10:
case 2: {
const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint16Array(sizeOrDstBuffer) : new Uint16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);
if (copyBuffer) {
buffer2.set(new Uint16Array(copyBuffer));
}
return buffer2;
}
case 6: {
const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int32Array(sizeOrDstBuffer) : new Int32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
if (copyBuffer) {
buffer2.set(new Int32Array(copyBuffer));
}
return buffer2;
}
case 7:
case 11:
case 12:
case 13:
case 14:
case 15: {
const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint32Array(sizeOrDstBuffer) : new Uint32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
if (copyBuffer) {
buffer2.set(new Uint32Array(copyBuffer));
}
return buffer2;
}
case 1: {
const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Float32Array(sizeOrDstBuffer) : new Float32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
if (copyBuffer) {
buffer2.set(new Float32Array(copyBuffer));
}
return buffer2;
}
}
const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);
if (copyBuffer) {
buffer.set(new Uint8Array(copyBuffer));
}
return buffer;
}
var EngineFunctionContext;
var init_abstractEngine_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/abstractEngine.functions.js"() {
init_devTools();
init_domManagement();
EngineFunctionContext = {};
__name(_ConcatenateShader, "_ConcatenateShader");
__name(_LoadFile, "_LoadFile");
__name(getHostDocument, "getHostDocument");
__name(_GetGlobalDefines, "_GetGlobalDefines");
__name(allocateAndCopyTypedBuffer, "allocateAndCopyTypedBuffer");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderProcessor.js
function Initialize(options) {
if (options.processor && options.processor.initializeShaders) {
options.processor.initializeShaders(options.processingContext);
}
}
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);
});
}
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);
});
}
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) {
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)");
}
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, preProcessorsFromCode) {
let line = cursor.currentLine;
while (MoveCursor(cursor, ifNode, preProcessorsFromCode)) {
line = cursor.currentLine;
const first5 = line.substring(0, 5).toLowerCase();
if (first5 === "#else") {
const elseNode = new ShaderCodeNode();
rootNode.children.push(elseNode);
MoveCursor(cursor, elseNode, preProcessorsFromCode);
return;
} else if (first5 === "#elif") {
const elifNode = BuildExpression(line, 5);
rootNode.children.push(elifNode);
ifNode = elifNode;
}
}
}
function MoveCursor(cursor, rootNode, preProcessorsFromCode) {
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, preProcessorsFromCode);
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, preProcessorsFromCode);
break;
}
case "#if": {
const newRootNode = new ShaderCodeConditionNode();
const ifNode = BuildExpression(line, 3);
rootNode.children.push(newRootNode);
newRootNode.children.push(ifNode);
MoveCursorWithinIf(cursor, newRootNode, ifNode, preProcessorsFromCode);
break;
}
}
continue;
}
}
const newNode = new ShaderCodeNode();
newNode.line = line;
rootNode.children.push(newNode);
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, preProcessorsFromCode) {
const rootNode = new ShaderCodeNode();
const cursor = new ShaderCodeCursor();
cursor.lineIndex = -1;
cursor.lines = sourceCode.split("\n");
MoveCursor(cursor, rootNode, preProcessorsFromCode);
return rootNode.process(preprocessors, options, preProcessorsFromCode);
}
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) {
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;
}
if (options.processor.shaderLanguage === 0 && 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);
if (options.processor.preProcessor) {
preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext);
}
const preProcessorsFromCode = {};
preparedSourceCode = EvaluatePreProcessors(preparedSourceCode, preprocessors, options, preProcessorsFromCode);
if (options.processor.postProcessor) {
preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine ? {
drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true
} : {}, preprocessors, preProcessorsFromCode);
}
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);
if (options.processor?.preProcessor) {
preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext);
}
const preProcessorsFromCode = {};
preparedSourceCode = EvaluatePreProcessors(preparedSourceCode, preprocessors, options, preProcessorsFromCode);
if (options.processor?.postProcessor) {
preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine ? {
drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true
} : {}, preprocessors, preProcessorsFromCode);
}
if (engine._features.needShaderCodeInlining) {
preparedSourceCode = engine.inlineShaderCode(preparedSourceCode);
}
return preparedSourceCode;
}
function ProcessIncludes(sourceCode, options, callback) {
ReusableMatches.length = 0;
let match;
while ((match = RegexShaderInclude.exec(sourceCode)) !== null) {
ReusableMatches.push(match);
}
let returnValue = String(sourceCode);
let parts = [sourceCode];
let keepProcessing = false;
for (const match2 of ReusableMatches) {
let includeFile = match2[1];
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]) {
let includeContent = options.includesShadersStore[includeFile];
if (match2[2]) {
const splits = match2[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 (match2[4]) {
const indexString = match2[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) {
sourceIncludeContent = sourceIncludeContent.replace(RegexLightX, (str, p1) => {
return p1 + "{X}";
});
}
includeContent += sourceIncludeContent.replace(RegexX, i.toString()) + "\n";
}
} else {
if (!options.supportsUniformBuffers) {
includeContent = includeContent.replace(RegexLightX, (str, p1) => {
return p1 + "{X}";
});
}
includeContent = includeContent.replace(RegexX, indexString);
}
}
const newParts = [];
for (const part of parts) {
const splitPart = part.split(match2[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);
}
}
var RegexSe, RegexSeRevert, RegexShaderInclude, RegexShaderDecl, RegexLightX, RegexX, ReusableMatches, MoveCursorRegex, _FunctionContainer;
var init_shaderProcessor = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderProcessor.js"() {
init_shaderCodeNode();
init_shaderCodeCursor();
init_shaderCodeConditionNode();
init_shaderCodeTestNode();
init_shaderDefineIsDefinedOperator();
init_shaderDefineOrOperator();
init_shaderDefineAndOperator();
init_shaderDefineExpression();
init_shaderDefineArithmeticOperator();
init_devTools();
init_abstractEngine_functions();
RegexSe = /defined\s*?\((.+?)\)/g;
RegexSeRevert = /defined\s*?\[(.+?)\]/g;
RegexShaderInclude = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g;
RegexShaderDecl = /__decl__/;
RegexLightX = /light\{X\}.(\w*)/g;
RegexX = /\{X\}/g;
ReusableMatches = [];
MoveCursorRegex = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;
__name(Initialize, "Initialize");
__name(Process, "Process");
__name(PreProcess, "PreProcess");
__name(Finalize, "Finalize");
__name(ProcessPrecision, "ProcessPrecision");
__name(ExtractOperation, "ExtractOperation");
__name(BuildSubExpression, "BuildSubExpression");
__name(BuildExpression, "BuildExpression");
__name(MoveCursorWithinIf, "MoveCursorWithinIf");
__name(MoveCursor, "MoveCursor");
__name(EvaluatePreProcessors, "EvaluatePreProcessors");
__name(PreparePreProcessors, "PreparePreProcessors");
__name(ProcessShaderConversion, "ProcessShaderConversion");
__name(ApplyPreProcessing, "ApplyPreProcessing");
__name(ProcessIncludes, "ProcessIncludes");
_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: /* @__PURE__ */ __name((url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) => {
throw _WarnImport("FileTools");
}, "loadFile")
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/timingTools.js
function RunWithCondition(condition, onSuccess, onError) {
try {
if (condition()) {
onSuccess();
return true;
}
} catch (e) {
onError?.(e);
return true;
}
return false;
}
var ImmediateQueue, TimingTools, _RetryWithInterval;
var init_timingTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/timingTools.js"() {
ImmediateQueue = [];
TimingTools = class {
static {
__name(this, "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(() => {
const functionsToCall = ImmediateQueue;
ImmediateQueue = [];
for (const func of functionsToCall) {
func();
}
}, 1);
}
ImmediateQueue.push(action);
}
};
__name(RunWithCondition, "RunWithCondition");
_RetryWithInterval = /* @__PURE__ */ __name((condition, onSuccess, onError, step = 16, maxTimeout = 3e4, checkConditionOnCall = true, additionalStringOnTimeout) => {
if (checkConditionOnCall) {
if (RunWithCondition(condition, onSuccess, onError)) {
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);
}, "_RetryWithInterval");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/shaderStore.js
var ShaderStore;
var init_shaderStore = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/shaderStore.js"() {
ShaderStore = class _ShaderStore {
static {
__name(this, "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) {
return shaderLanguage === 0 ? _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) {
return shaderLanguage === 0 ? _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) {
return shaderLanguage === 0 ? _ShaderStore.IncludesShadersStore : _ShaderStore.IncludesShadersStoreWGSL;
}
};
ShaderStore.ShadersRepository = "src/Shaders/";
ShaderStore.ShadersStore = {};
ShaderStore.IncludesShadersStore = {};
ShaderStore.ShadersRepositoryWGSL = "src/ShadersWGSL/";
ShaderStore.ShadersStoreWGSL = {};
ShaderStore.IncludesShadersStoreWGSL = {};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLPipelineContext.js
var WebGLPipelineContext;
var init_webGLPipelineContext = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLPipelineContext.js"() {
WebGLPipelineContext = class {
static {
__name(this, "WebGLPipelineContext");
}
constructor() {
this._valueCache = {};
this.vertexCompilationError = null;
this.fragmentCompilationError = null;
this.programLinkError = null;
this.programValidationError = null;
this._isDisposed = false;
}
// eslint-disable-next-line no-restricted-syntax
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 name260 in uniformBuffersNames) {
effect.bindUniformBlock(name260, uniformBuffersNames[name260]);
}
}
const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames);
effectAvailableUniforms.forEach((uniform, index2) => {
uniforms[uniformsNames[index2]] = 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((name260, index2) => {
samplers[name260] = index2;
});
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 !== void 0 && 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 !== void 0 && 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 !== void 0 && 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 !== void 0 && 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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/thinEngine.functions.js
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") || void 0,
cachedPipelines: {}
};
StateObject.set(context, state);
}
return state;
}
function deleteStateObject(context) {
StateObject.delete(context);
}
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);
}
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);
}
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;
}
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;
}
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;
}
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) {
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(vertexShader);
if (log) {
pipelineContext.vertexCompilationError = log;
throw new Error("VERTEX SHADER " + log);
}
}
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 = void 0;
pipelineContext.fragmentShader = void 0;
if (pipelineContext.onCompiled) {
pipelineContext.onCompiled();
pipelineContext.onCompiled = void 0;
}
}
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 shader260 = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
if (!shader260) {
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(shader260, source);
gl.compileShader(shader260);
return shader260;
}
function _setProgram(program, gl) {
gl.useProgram(program);
}
function _executeWhenRenderingStateIsCompiled(pipelineContext, action) {
const webGLPipelineContext = pipelineContext;
if (!webGLPipelineContext.isParallelCompiled) {
action(pipelineContext);
return;
}
const oldHandler = webGLPipelineContext.onCompiled;
webGLPipelineContext.onCompiled = () => {
oldHandler?.();
action(pipelineContext);
};
}
var StateObject, SingleStateObject;
var init_thinEngine_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/thinEngine.functions.js"() {
init_webGLPipelineContext();
init_abstractEngine_functions();
StateObject = /* @__PURE__ */ new WeakMap();
SingleStateObject = {
_webGLVersion: 2,
cachedPipelines: {}
};
__name(getStateObject, "getStateObject");
__name(deleteStateObject, "deleteStateObject");
__name(createRawShaderProgram, "createRawShaderProgram");
__name(createShaderProgram, "createShaderProgram");
__name(createPipelineContext, "createPipelineContext");
__name(_createShaderProgram, "_createShaderProgram");
__name(_isRenderingStateCompiled, "_isRenderingStateCompiled");
__name(_finalizePipelineContext, "_finalizePipelineContext");
__name(_preparePipelineContext, "_preparePipelineContext");
__name(CompileShader, "CompileShader");
__name(CompileRawShader, "CompileRawShader");
__name(_setProgram, "_setProgram");
__name(_executeWhenRenderingStateIsCompiled, "_executeWhenRenderingStateIsCompiled");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effect.functions.js
function getCachedPipeline(name260, context) {
const stateObject = getStateObject(context);
return stateObject.cachedPipelines[name260];
}
function resetCachedPipeline(pipeline) {
const name260 = pipeline._name;
const context = pipeline.context;
if (name260 && context) {
const stateObject = getStateObject(context);
const cachedPipeline = stateObject.cachedPipelines[name260];
cachedPipeline?.dispose();
delete stateObject.cachedPipelines[name260];
}
}
function _ProcessShaderCode(processorOptions, baseName, processFinalCode, onFinalCodeReady, shaderLanguage, engine, effectContext) {
let vertexSource;
let fragmentSource;
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 = [void 0, void 0];
const shadersLoaded = /* @__PURE__ */ __name(() => {
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);
}
}, "shadersLoaded");
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(shader260, key, optionalKey, callback, shaderLanguage, _loadFileInjection) {
if (typeof HTMLElement !== "undefined") {
if (shader260 instanceof HTMLElement) {
const shaderCode = GetDOMTextContent(shader260);
callback(shaderCode);
return;
}
}
if (shader260.substring(0, 7) === "source:") {
callback(shader260.substring(7));
return;
}
if (shader260.substring(0, 7) === "base64:") {
const shaderBinary = window.atob(shader260.substring(7));
callback(shaderBinary);
return;
}
const shaderStore = ShaderStore.GetShadersStore(shaderLanguage);
if (shaderStore[shader260 + key + "Shader"]) {
callback(shaderStore[shader260 + key + "Shader"]);
return;
}
if (optionalKey && shaderStore[shader260 + optionalKey + "Shader"]) {
callback(shaderStore[shader260 + optionalKey + "Shader"]);
return;
}
let shaderUrl;
if (shader260[0] === "." || shader260[0] === "/" || shader260.indexOf("http") > -1) {
shaderUrl = shader260;
} else {
shaderUrl = ShaderStore.GetShadersRepository(shaderLanguage) + shader260;
}
_loadFileInjection = _loadFileInjection || _LoadFile;
if (!_loadFileInjection) {
throw new Error("loadFileInjection is not defined");
}
_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 ? "//" : "") + "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode,
fragmentSourceCode: (shaderLanguage === 1 ? "//" : "") + "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode
};
} else {
return {
vertexSourceCode: migratedVertexCode,
fragmentSourceCode: migratedFragmentCode
};
}
}
var createAndPreparePipelineContext;
var init_effect_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effect.functions.js"() {
init_domManagement();
init_thinEngine_functions();
init_shaderStore();
init_logger();
init_shaderProcessor();
init_abstractEngine_functions();
__name(getCachedPipeline, "getCachedPipeline");
__name(resetCachedPipeline, "resetCachedPipeline");
__name(_ProcessShaderCode, "_ProcessShaderCode");
__name(LoadShader, "LoadShader");
__name(UseFinalCode, "UseFinalCode");
createAndPreparePipelineContext = /* @__PURE__ */ __name((options, createPipelineContext2, _preparePipelineContext2, _executeWhenRenderingStateIsCompiled2) => {
try {
const stateObject = options.context ? getStateObject(options.context) : null;
if (stateObject) {
stateObject.disableParallelShaderCompile = options.disableParallelCompilation;
}
const pipelineContext = options.existingPipelineContext || createPipelineContext2(options.shaderProcessingContext);
pipelineContext._name = options.name;
if (options.name && stateObject) {
stateObject.cachedPipelines[options.name] = pipelineContext;
}
_preparePipelineContext2(pipelineContext, options.vertex, options.fragment, !!options.createAsRaw, "", "", options.rebuildRebind, options.defines, options.transformFeedbackVaryings, "", () => {
_executeWhenRenderingStateIsCompiled2(pipelineContext, () => {
options.onRenderingStateCompiled?.(pipelineContext);
});
});
return pipelineContext;
} catch (e) {
Logger.Error("Error compiling effect");
throw e;
}
}, "createAndPreparePipelineContext");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effect.js
var Effect;
var init_effect = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effect.js"() {
init_observable();
init_logger();
init_shaderStore();
init_effect_functions();
init_timingTools();
Effect = class _Effect {
static {
__name(this, "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, extraInitializationsAsync) {
this.defines = "";
this.onCompiled = null;
this.onError = null;
this.onBind = null;
this.uniqueId = 0;
this.onCompileObservable = new Observable();
this.onErrorObservable = new Observable();
this._onBindObservable = null;
this._isDisposed = false;
this._refCount = 1;
this._bonesComputationForcedToCPU = false;
this._uniformBuffersNames = {};
this._multiTarget = false;
this._samplers = {};
this._isReady = false;
this._compilationError = "";
this._allFallbacksProcessed = false;
this._uniforms = {};
this._key = "";
this._fallbacks = null;
this._vertexSourceCodeOverride = "";
this._fragmentSourceCodeOverride = "";
this._transformFeedbackVaryings = null;
this._disableParallelShaderCompilation = false;
this._pipelineContext = null;
this._vertexSourceCode = "";
this._fragmentSourceCode = "";
this._vertexSourceCodeBeforeMigration = "";
this._fragmentSourceCodeBeforeMigration = "";
this._rawVertexSourceCode = "";
this._rawFragmentSourceCode = "";
this._processCodeAfterIncludes = void 0;
this._processFinalCode = null;
this._onReleaseEffectsObserver = null;
this.name = baseName;
this._key = key;
const pipelineName = this._key.replace(/\r/g, "").replace(/\n/g, "|");
let cachedPipeline = void 0;
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;
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 ?? void 0;
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;
}
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);
if (this._pipelineContext.program) {
this._pipelineContext.program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
}
}
this._onReleaseEffectsObserver = this._engine.onReleaseEffectsObservable.addOnce(() => {
this._onReleaseEffectsObserver = null;
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) {
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(name260) {
return this._attributeLocationByName[name260];
}
/**
* 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.
*/
async whenCompiledAsync() {
return await 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;
}, () => {
}, (e) => {
this._processCompilationErrors(e, previousPipelineContext);
}, 16, 12e4, 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);
if (this._attributesNames) {
for (let i = 0; i < this._attributesNames.length; i++) {
const name260 = this._attributesNames[i];
this._attributeLocationByName[name260] = 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();
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 : void 0,
rebuildRebind: /* @__PURE__ */ __name((vertexSourceCode, fragmentSourceCode, onCompiled, onError) => this._rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError), "rebuildRebind"),
defines,
transformFeedbackVaryings: this._transformFeedbackVaryings,
name: this._key.replace(/\r/g, "").replace(/\n/g, "|"),
createAsRaw: overrides,
disableParallelCompilation: this._disableParallelShaderCompilation,
shaderProcessingContext: this._processingContext,
onRenderingStateCompiled: /* @__PURE__ */ __name((pipelineContext) => {
if (previousPipelineContext && !keepExistingPipelineContext) {
this._engine._deletePipelineContext(previousPipelineContext);
}
if (pipelineContext) {
this._onRenderingStateCompiled(pipelineContext);
}
}, "onRenderingStateCompiled")
}, this._engine.createPipelineContext.bind(this._engine), this._engine._preparePipelineContextAsync.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;
Logger.Error("Unable to compile effect:");
Logger.Error(`Uniforms: ${this._uniformsNames.join(" ")}`);
Logger.Error(`Attributes: ${attributesNames.join(" ")}`);
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 = /* @__PURE__ */ __name(() => {
if (this.onError) {
this.onError(this, this._compilationError);
}
this.onErrorObservable.notifyObservers(this);
this._engine.onEffectErrorObservable.notifyObservers({ effect: this, errors: this._compilationError });
}, "notifyErrors");
if (previousPipelineContext) {
this._pipelineContext = previousPipelineContext;
this._isReady = true;
notifyErrors();
}
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 {
this._allFallbacksProcessed = true;
notifyErrors();
this.onErrorObservable.clear();
if (this._fallbacks) {
this._fallbacks.unBindMesh();
}
}
} else {
this._allFallbacksProcessed = true;
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);
}
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, name260) {
const bufferName = this._uniformBuffersNames[name260];
if (bufferName === void 0 || _Effect._BaseCache[bufferName] === buffer && this._engine._features.useUBOBindingCache) {
return;
}
_Effect._BaseCache[bufferName] = buffer;
this._engine.bindUniformBufferBase(buffer, bufferName, name260);
}
/**
* 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) {
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) {
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) {
return;
}
if (this._onReleaseEffectsObserver) {
this._engine.onReleaseEffectsObservable.remove(this._onReleaseEffectsObserver);
this._onReleaseEffectsObserver = null;
}
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(name260, pixelShader, vertexShader, shaderLanguage = 0) {
if (pixelShader) {
ShaderStore.GetShadersStore(shaderLanguage)[`${name260}PixelShader`] = pixelShader;
}
if (vertexShader) {
ShaderStore.GetShadersStore(shaderLanguage)[`${name260}VertexShader`] = vertexShader;
}
}
/**
* Resets the cache of effects.
*/
static ResetCache() {
_Effect._BaseCache = {};
}
};
Effect.LogShaderCodeOnCompilationError = true;
Effect.PersistentMode = false;
Effect.AutomaticallyClearCodeCache = false;
Effect._UniqueIdSeed = 0;
Effect._BaseCache = {};
Effect.ShadersStore = ShaderStore.ShadersStore;
Effect.IncludesShadersStore = ShaderStore.IncludesShadersStore;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/performanceConfigurator.js
var PerformanceConfigurator;
var init_performanceConfigurator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/performanceConfigurator.js"() {
PerformanceConfigurator = class _PerformanceConfigurator {
static {
__name(this, "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;
}
};
PerformanceConfigurator.MatrixUse64Bits = false;
PerformanceConfigurator.MatrixTrackPrecisionChange = true;
PerformanceConfigurator.MatrixCurrentType = Float32Array;
PerformanceConfigurator.MatrixTrackedMatrices = [];
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/depthCullingState.js
var DepthCullingState;
var init_depthCullingState = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/depthCullingState.js"() {
DepthCullingState = class {
static {
__name(this, "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;
}
if (this._isCullDirty) {
if (this.cull) {
gl.enable(gl.CULL_FACE);
} else {
gl.disable(gl.CULL_FACE);
}
this._isCullDirty = false;
}
if (this._isCullFaceDirty) {
gl.cullFace(this.cullFace);
this._isCullFaceDirty = false;
}
if (this._isDepthMaskDirty) {
gl.depthMask(this.depthMask);
this._isDepthMaskDirty = false;
}
if (this._isDepthTestDirty) {
if (this.depthTest) {
gl.enable(gl.DEPTH_TEST);
} else {
gl.disable(gl.DEPTH_TEST);
}
this._isDepthTestDirty = false;
}
if (this._isDepthFuncDirty) {
gl.depthFunc(this.depthFunc);
this._isDepthFuncDirty = false;
}
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;
}
if (this._isFrontFaceDirty) {
gl.frontFace(this.frontFace);
this._isFrontFaceDirty = false;
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/stencilStateComposer.js
var StencilStateComposer;
var init_stencilStateComposer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/stencilStateComposer.js"() {
StencilStateComposer = class {
static {
__name(this, "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 backFunc() {
return this._func;
}
set backFunc(value) {
if (this._backFunc === value) {
return;
}
this._backFunc = 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 backOpStencilFail() {
return this._backOpStencilFail;
}
set backOpStencilFail(value) {
if (this._backOpStencilFail === value) {
return;
}
this._backOpStencilFail = value;
this._isStencilOpDirty = true;
}
get backOpDepthFail() {
return this._backOpDepthFail;
}
set backOpDepthFail(value) {
if (this._backOpDepthFail === value) {
return;
}
this._backOpDepthFail = value;
this._isStencilOpDirty = true;
}
get backOpStencilDepthPass() {
return this._backOpStencilDepthPass;
}
set backOpStencilDepthPass(value) {
if (this._backOpStencilDepthPass === value) {
return;
}
this._backOpStencilDepthPass = 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 = void 0;
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.backFunc = stencilMaterialEnabled ? this.stencilMaterial.backFunc : this.stencilGlobal.backFunc;
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.backOpStencilFail = stencilMaterialEnabled ? this.stencilMaterial.backOpStencilFail : this.stencilGlobal.backOpStencilFail;
this.backOpDepthFail = stencilMaterialEnabled ? this.stencilMaterial.backOpDepthFail : this.stencilGlobal.backOpDepthFail;
this.backOpStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.backOpStencilDepthPass : this.stencilGlobal.backOpStencilDepthPass;
this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask;
if (!this.isDirty) {
return;
}
if (this._isStencilTestDirty) {
if (this.enabled) {
gl.enable(gl.STENCIL_TEST);
} else {
gl.disable(gl.STENCIL_TEST);
}
this._isStencilTestDirty = false;
}
if (this._isStencilMaskDirty) {
gl.stencilMask(this.mask);
this._isStencilMaskDirty = false;
}
if (this._isStencilFuncDirty) {
gl.stencilFuncSeparate(gl.FRONT, this.func, this.funcRef, this.funcMask);
gl.stencilFuncSeparate(gl.BACK, this.backFunc, this.funcRef, this.funcMask);
this._isStencilFuncDirty = false;
}
if (this._isStencilOpDirty) {
gl.stencilOpSeparate(gl.FRONT, this.opStencilFail, this.opDepthFail, this.opStencilDepthPass);
gl.stencilOpSeparate(gl.BACK, this.backOpStencilFail, this.backOpDepthFail, this.backOpStencilDepthPass);
this._isStencilOpDirty = false;
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/stencilState.js
var StencilState;
var init_stencilState = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/stencilState.js"() {
StencilState = class _StencilState {
static {
__name(this, "StencilState");
}
constructor() {
this.reset();
}
reset() {
this.enabled = false;
this.mask = 255;
this.funcRef = 1;
this.funcMask = 255;
this.func = _StencilState.ALWAYS;
this.opStencilFail = _StencilState.KEEP;
this.opDepthFail = _StencilState.KEEP;
this.opStencilDepthPass = _StencilState.REPLACE;
this.backFunc = _StencilState.ALWAYS;
this.backOpStencilFail = _StencilState.KEEP;
this.backOpDepthFail = _StencilState.KEEP;
this.backOpStencilDepthPass = _StencilState.REPLACE;
}
get stencilFunc() {
return this.func;
}
set stencilFunc(value) {
this.func = value;
}
get stencilBackFunc() {
return this.backFunc;
}
set stencilBackFunc(value) {
this.backFunc = 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 stencilBackOpStencilFail() {
return this.backOpStencilFail;
}
set stencilBackOpStencilFail(value) {
this.backOpStencilFail = value;
}
get stencilBackOpDepthFail() {
return this.backOpDepthFail;
}
set stencilBackOpDepthFail(value) {
this.backOpDepthFail = value;
}
get stencilBackOpStencilDepthPass() {
return this.backOpStencilDepthPass;
}
set stencilBackOpStencilDepthPass(value) {
this.backOpStencilDepthPass = value;
}
get stencilMask() {
return this.mask;
}
set stencilMask(value) {
this.mask = value;
}
get stencilTest() {
return this.enabled;
}
set stencilTest(value) {
this.enabled = value;
}
};
StencilState.ALWAYS = 519;
StencilState.KEEP = 7680;
StencilState.REPLACE = 7681;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/alphaCullingState.js
var AlphaState;
var init_alphaCullingState = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/alphaCullingState.js"() {
AlphaState = class {
static {
__name(this, "AlphaState");
}
/**
* Initializes the state.
* @param _supportBlendParametersPerTarget - Whether blend parameters per target is supported
*/
constructor(_supportBlendParametersPerTarget) {
this._supportBlendParametersPerTarget = _supportBlendParametersPerTarget;
this._blendFunctionParameters = new Array(4 * 8);
this._blendEquationParameters = new Array(2 * 8);
this._blendConstants = new Array(4);
this._isBlendConstantsDirty = false;
this._alphaBlend = Array(8).fill(false);
this._numTargetEnabled = 0;
this._isAlphaBlendDirty = false;
this._isBlendFunctionParametersDirty = false;
this._isBlendEquationParametersDirty = false;
this.reset();
}
get isDirty() {
return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty;
}
get alphaBlend() {
return this._numTargetEnabled > 0;
}
setAlphaBlend(value, targetIndex = 0) {
if (this._alphaBlend[targetIndex] === value) {
return;
}
if (value) {
this._numTargetEnabled++;
} else {
this._numTargetEnabled--;
}
this._alphaBlend[targetIndex] = 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(srcRGBFactor, dstRGBFactor, srcAlphaFactor, dstAlphaFactor, targetIndex = 0) {
const offset = targetIndex * 4;
if (this._blendFunctionParameters[offset + 0] === srcRGBFactor && this._blendFunctionParameters[offset + 1] === dstRGBFactor && this._blendFunctionParameters[offset + 2] === srcAlphaFactor && this._blendFunctionParameters[offset + 3] === dstAlphaFactor) {
return;
}
this._blendFunctionParameters[offset + 0] = srcRGBFactor;
this._blendFunctionParameters[offset + 1] = dstRGBFactor;
this._blendFunctionParameters[offset + 2] = srcAlphaFactor;
this._blendFunctionParameters[offset + 3] = dstAlphaFactor;
this._isBlendFunctionParametersDirty = true;
}
setAlphaEquationParameters(rgbEquation, alphaEquation, targetIndex = 0) {
const offset = targetIndex * 2;
if (this._blendEquationParameters[offset + 0] === rgbEquation && this._blendEquationParameters[offset + 1] === alphaEquation) {
return;
}
this._blendEquationParameters[offset + 0] = rgbEquation;
this._blendEquationParameters[offset + 1] = alphaEquation;
this._isBlendEquationParametersDirty = true;
}
reset() {
this._alphaBlend.fill(false);
this._numTargetEnabled = 0;
this._blendFunctionParameters.fill(null);
this._blendEquationParameters.fill(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, numTargets = 1) {
if (!this.isDirty) {
return;
}
if (this._isBlendConstantsDirty) {
gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
this._isBlendConstantsDirty = false;
}
if (numTargets === 1 || !this._supportBlendParametersPerTarget) {
if (this._isAlphaBlendDirty) {
if (this._alphaBlend[0]) {
gl.enable(gl.BLEND);
} else {
gl.disable(gl.BLEND);
}
this._isAlphaBlendDirty = false;
}
if (this._isBlendFunctionParametersDirty) {
gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
this._isBlendFunctionParametersDirty = false;
}
if (this._isBlendEquationParametersDirty) {
gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
this._isBlendEquationParametersDirty = false;
}
return;
}
const gl2 = gl;
if (this._isAlphaBlendDirty) {
for (let i = 0; i < numTargets; i++) {
const index = i < this._numTargetEnabled ? i : 0;
if (this._alphaBlend[index]) {
gl2.enableIndexed(gl.BLEND, i);
} else {
gl2.disableIndexed(gl.BLEND, i);
}
}
this._isAlphaBlendDirty = false;
}
if (this._isBlendFunctionParametersDirty) {
for (let i = 0; i < numTargets; i++) {
const offset = i < this._numTargetEnabled ? i * 4 : 0;
gl2.blendFuncSeparateIndexed(i, this._blendFunctionParameters[offset + 0], this._blendFunctionParameters[offset + 1], this._blendFunctionParameters[offset + 2], this._blendFunctionParameters[offset + 3]);
}
this._isBlendFunctionParametersDirty = false;
}
if (this._isBlendEquationParametersDirty) {
for (let i = 0; i < numTargets; i++) {
const offset = i < this._numTargetEnabled ? i * 2 : 0;
gl2.blendEquationSeparateIndexed(i, this._blendEquationParameters[offset + 0], this._blendEquationParameters[offset + 1]);
}
this._isBlendEquationParametersDirty = false;
}
}
setAlphaMode(mode, targetIndex) {
let equation = 32774;
switch (mode) {
case 0:
break;
case 7:
this.setAlphaBlendFunctionParameters(1, 771, 1, 1, targetIndex);
break;
case 8:
this.setAlphaBlendFunctionParameters(1, 771, 1, 771, targetIndex);
break;
case 2:
this.setAlphaBlendFunctionParameters(770, 771, 1, 1, targetIndex);
break;
case 6:
this.setAlphaBlendFunctionParameters(1, 1, 0, 1, targetIndex);
break;
case 1:
this.setAlphaBlendFunctionParameters(770, 1, 0, 1, targetIndex);
break;
case 3:
this.setAlphaBlendFunctionParameters(0, 769, 1, 1, targetIndex);
equation = 32778;
break;
case 4:
this.setAlphaBlendFunctionParameters(774, 0, 1, 1, targetIndex);
break;
case 5:
this.setAlphaBlendFunctionParameters(770, 769, 1, 1, targetIndex);
break;
case 9:
this.setAlphaBlendFunctionParameters(32769, 32770, 32771, 32772, targetIndex);
break;
case 10:
this.setAlphaBlendFunctionParameters(1, 769, 1, 771, targetIndex);
break;
case 11:
this.setAlphaBlendFunctionParameters(1, 1, 1, 1, targetIndex);
break;
case 12:
this.setAlphaBlendFunctionParameters(772, 1, 0, 0, targetIndex);
break;
case 13:
this.setAlphaBlendFunctionParameters(775, 769, 773, 771, targetIndex);
break;
case 14:
this.setAlphaBlendFunctionParameters(1, 771, 1, 771, targetIndex);
break;
case 15:
this.setAlphaBlendFunctionParameters(1, 1, 1, 0, targetIndex);
break;
case 16:
this.setAlphaBlendFunctionParameters(775, 769, 0, 1, targetIndex);
break;
case 17:
this.setAlphaBlendFunctionParameters(770, 771, 1, 771, targetIndex);
break;
case 18:
this.setAlphaBlendFunctionParameters(1, 1, 1, 1, targetIndex);
equation = 32775;
break;
case 19:
this.setAlphaBlendFunctionParameters(1, 1, 1, 1, targetIndex);
equation = 32776;
break;
case 20:
this.setAlphaBlendFunctionParameters(1, 35065, 0, 1, targetIndex);
break;
}
this.setAlphaEquationParameters(equation, equation, targetIndex);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureSampler.js
var TextureSampler;
var init_textureSampler = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureSampler.js"() {
TextureSampler = class {
static {
__name(this, "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() {
this.samplingMode = -1;
this._useMipMaps = true;
this._cachedWrapU = null;
this._cachedWrapV = null;
this._cachedWrapR = null;
this._cachedAnisotropicFilteringLevel = null;
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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/internalTexture.js
var InternalTextureSource, InternalTexture;
var init_internalTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/internalTexture.js"() {
init_observable();
init_textureSampler();
(function(InternalTextureSource2) {
InternalTextureSource2[InternalTextureSource2["Unknown"] = 0] = "Unknown";
InternalTextureSource2[InternalTextureSource2["Url"] = 1] = "Url";
InternalTextureSource2[InternalTextureSource2["Temp"] = 2] = "Temp";
InternalTextureSource2[InternalTextureSource2["Raw"] = 3] = "Raw";
InternalTextureSource2[InternalTextureSource2["Dynamic"] = 4] = "Dynamic";
InternalTextureSource2[InternalTextureSource2["RenderTarget"] = 5] = "RenderTarget";
InternalTextureSource2[InternalTextureSource2["MultiRenderTarget"] = 6] = "MultiRenderTarget";
InternalTextureSource2[InternalTextureSource2["Cube"] = 7] = "Cube";
InternalTextureSource2[InternalTextureSource2["CubeRaw"] = 8] = "CubeRaw";
InternalTextureSource2[InternalTextureSource2["CubePrefiltered"] = 9] = "CubePrefiltered";
InternalTextureSource2[InternalTextureSource2["Raw3D"] = 10] = "Raw3D";
InternalTextureSource2[InternalTextureSource2["Raw2DArray"] = 11] = "Raw2DArray";
InternalTextureSource2[InternalTextureSource2["DepthStencil"] = 12] = "DepthStencil";
InternalTextureSource2[InternalTextureSource2["CubeRawRGBD"] = 13] = "CubeRawRGBD";
InternalTextureSource2[InternalTextureSource2["Depth"] = 14] = "Depth";
})(InternalTextureSource || (InternalTextureSource = {}));
InternalTexture = class _InternalTexture extends TextureSampler {
static {
__name(this, "InternalTexture");
}
/**
* 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();
this.isReady = false;
this.isCube = false;
this.is3D = false;
this.is2DArray = false;
this.isMultiview = false;
this.url = "";
this.generateMipMaps = false;
this.samples = 0;
this.type = -1;
this.format = -1;
this.onLoadedObservable = new Observable();
this.onErrorObservable = new Observable();
this.onRebuildCallback = null;
this.width = 0;
this.height = 0;
this.depth = 0;
this.baseWidth = 0;
this.baseHeight = 0;
this.baseDepth = 0;
this.invertY = false;
this._invertVScale = false;
this._associatedChannel = -1;
this._source = 0;
this._buffer = null;
this._bufferView = null;
this._bufferViewArray = null;
this._bufferViewArrayArray = null;
this._size = 0;
this._extension = "";
this._files = null;
this._workingCanvas = null;
this._workingContext = null;
this._cachedCoordinatesMode = null;
this._isDisabled = false;
this._compression = null;
this._sphericalPolynomial = null;
this._sphericalPolynomialPromise = null;
this._sphericalPolynomialComputed = false;
this._lodGenerationScale = 0;
this._lodGenerationOffset = 0;
this._useSRGBBuffer = false;
this._creationFlags = 0;
this._lodTextureHigh = null;
this._lodTextureMid = null;
this._lodTextureLow = null;
this._isRGBD = false;
this._linearSpecularLOD = false;
this._irradianceTexture = null;
this._hardwareTexture = null;
this._maxLodLevel = null;
this._references = 1;
this._gammaSpace = null;
this._premulAlpha = false;
this._dynamicTextureSource = null;
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 = /* @__PURE__ */ __name((proxyInternalTexture) => {
proxyInternalTexture._swapAndDie(this, false);
this.isReady = data.isReady;
}, "swapAndSetIsReady");
if (data.isAsync) {
data.proxy.then(swapAndSetIsReady);
} else {
swapAndSetIsReady(data.proxy);
}
return;
}
let proxy;
switch (this.source) {
case 2:
break;
case 1:
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,
void 0,
this.format,
this._extension,
void 0,
void 0,
void 0,
this._useSRGBBuffer
);
return;
case 3:
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:
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:
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:
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);
}
break;
case 7:
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, void 0, this._useSRGBBuffer, ArrayBuffer.isView(this._buffer) ? this._buffer : null);
return;
case 8:
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:
return;
case 9:
proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy2) => {
if (proxy2) {
proxy2._swapAndDie(this, false);
}
this.isReady = true;
}, null, this.format, this._extension);
proxy._sphericalPolynomial = this._sphericalPolynomial;
return;
case 12:
case 14: {
break;
}
}
}
/**
* @internal
*/
_swapAndDie(target, swapAll = true) {
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;
}
}
};
InternalTexture._Counter = 0;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.scalar.functions.js
function ExtractAsInt(value) {
return parseInt(value.toString().replace(/\W/g, ""));
}
function WithinEpsilon(a, b, epsilon = 1401298e-51) {
return Math.abs(a - b) <= epsilon;
}
function OutsideRange(num, min, max, epsilon = 1401298e-51) {
return num < min - epsilon || num > max + epsilon;
}
function RandomRange(min, max) {
if (min === max) {
return min;
}
return Math.random() * (max - min) + min;
}
function Lerp(start, end, amount) {
return start + (end - start) * amount;
}
function LerpAngle(start, end, amount) {
let num = Repeat(end - start, 360);
if (num > 180) {
num -= 360;
}
return start + num * Clamp(amount);
}
function InverseLerp(a, b, value) {
let result = 0;
if (a != b) {
result = Clamp((value - a) / (b - a));
} else {
result = 0;
}
return result;
}
function Hermite(value1, tangent1, value2, tangent2, amount) {
const squared = amount * amount;
const cubed = amount * squared;
const part1 = 2 * cubed - 3 * squared + 1;
const part2 = -2 * cubed + 3 * squared;
const part3 = cubed - 2 * squared + amount;
const part4 = cubed - squared;
return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4;
}
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;
}
function Clamp(value, min = 0, max = 1) {
return Math.min(max, Math.max(min, value));
}
function NormalizeRadians(angle) {
angle -= Math.PI * 2 * Math.floor((angle + Math.PI) / (Math.PI * 2));
return angle;
}
function ToHex(i) {
const str = i.toString(16);
if (i <= 15) {
return ("0" + str).toUpperCase();
}
return str.toUpperCase();
}
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;
}
function Repeat(value, length) {
return value - Math.floor(value / length) * length;
}
function Normalize(value, min, max) {
return (value - min) / (max - min);
}
function Denormalize(normalized, min, max) {
return normalized * (max - min) + min;
}
function DeltaAngle(current, target) {
let num = Repeat(target - current, 360);
if (num > 180) {
num -= 360;
}
return num;
}
function PingPong(tx, length) {
const t = Repeat(tx, length * 2);
return length - Math.abs(t - length);
}
function SmoothStep(from, to, tx) {
let t = Clamp(tx);
t = -2 * t * t * t + 3 * t * t;
return to * t + from * (1 - t);
}
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;
}
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;
}
function RangeToPercent(number, min, max) {
return (number - min) / (max - min);
}
function PercentToRange(percent, min, max) {
return (max - min) * percent + min;
}
function HighestCommonFactor(a, b) {
const r = a % b;
if (r === 0) {
return b;
}
return HighestCommonFactor(b, r);
}
var init_math_scalar_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.scalar.functions.js"() {
__name(ExtractAsInt, "ExtractAsInt");
__name(WithinEpsilon, "WithinEpsilon");
__name(OutsideRange, "OutsideRange");
__name(RandomRange, "RandomRange");
__name(Lerp, "Lerp");
__name(LerpAngle, "LerpAngle");
__name(InverseLerp, "InverseLerp");
__name(Hermite, "Hermite");
__name(Hermite1stDerivative, "Hermite1stDerivative");
__name(Clamp, "Clamp");
__name(NormalizeRadians, "NormalizeRadians");
__name(ToHex, "ToHex");
__name(ILog2, "ILog2");
__name(Repeat, "Repeat");
__name(Normalize, "Normalize");
__name(Denormalize, "Denormalize");
__name(DeltaAngle, "DeltaAngle");
__name(PingPong, "PingPong");
__name(SmoothStep, "SmoothStep");
__name(MoveTowards, "MoveTowards");
__name(MoveTowardsAngle, "MoveTowardsAngle");
__name(RangeToPercent, "RangeToPercent");
__name(PercentToRange, "PercentToRange");
__name(HighestCommonFactor, "HighestCommonFactor");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/IES/iesLoader.js
function LineToArray(line) {
return line.split(" ").filter((x) => x !== "").map((x) => parseFloat(x));
}
function ReadArray(dataPointer, count, targetArray) {
while (targetArray.length !== count) {
const line = LineToArray(dataPointer.lines[dataPointer.index++]);
targetArray.push(...line);
}
}
function InterpolateCandelaValues(data, phi, theta) {
let phiIndex = 0;
let thetaIndex = 0;
let startTheta = 0;
let endTheta = 0;
let startPhi = 0;
let endPhi = 0;
for (let index = 0; index < data.numberOfHorizontalAngles - 1; index++) {
if (theta < data.horizontalAngles[index + 1] || index === data.numberOfHorizontalAngles - 2) {
thetaIndex = index;
startTheta = data.horizontalAngles[index];
endTheta = data.horizontalAngles[index + 1];
break;
}
}
for (let index = 0; index < data.numberOfVerticalAngles - 1; index++) {
if (phi < data.verticalAngles[index + 1] || index === data.numberOfVerticalAngles - 2) {
phiIndex = index;
startPhi = data.verticalAngles[index];
endPhi = data.verticalAngles[index + 1];
break;
}
}
const deltaTheta = endTheta - startTheta;
const deltaPhi = endPhi - startPhi;
if (deltaPhi === 0) {
return 0;
}
const t1 = deltaTheta === 0 ? 0 : (theta - startTheta) / deltaTheta;
const t2 = (phi - startPhi) / deltaPhi;
const nextThetaIndex = deltaTheta === 0 ? thetaIndex : thetaIndex + 1;
const v1 = Lerp(data.candelaValues[thetaIndex][phiIndex], data.candelaValues[nextThetaIndex][phiIndex], t1);
const v2 = Lerp(data.candelaValues[thetaIndex][phiIndex + 1], data.candelaValues[nextThetaIndex][phiIndex + 1], t1);
const v = Lerp(v1, v2, t2);
return v;
}
function LoadIESData(uint8Array) {
const decoder = new TextDecoder("utf-8");
const source = decoder.decode(uint8Array);
const dataPointer = {
lines: source.split("\n"),
index: 0
};
const data = { version: dataPointer.lines[0], candelaValues: [], horizontalAngles: [], verticalAngles: [], numberOfHorizontalAngles: 0, numberOfVerticalAngles: 0 };
dataPointer.index = 1;
while (dataPointer.lines.length > 0 && !dataPointer.lines[dataPointer.index].includes("TILT=")) {
dataPointer.index++;
}
if (dataPointer.lines[dataPointer.index].includes("INCLUDE")) {
}
dataPointer.index++;
const header = LineToArray(dataPointer.lines[dataPointer.index++]);
data.numberOfLights = header[0];
data.lumensPerLamp = header[1];
data.candelaMultiplier = header[2];
data.numberOfVerticalAngles = header[3];
data.numberOfHorizontalAngles = header[4];
data.photometricType = header[5];
data.unitsType = header[6];
data.width = header[7];
data.length = header[8];
data.height = header[9];
const additionalData = LineToArray(dataPointer.lines[dataPointer.index++]);
data.ballastFactor = additionalData[0];
data.fileGenerationType = additionalData[1];
data.inputWatts = additionalData[2];
for (let index = 0; index < data.numberOfHorizontalAngles; index++) {
data.candelaValues[index] = [];
}
ReadArray(dataPointer, data.numberOfVerticalAngles, data.verticalAngles);
ReadArray(dataPointer, data.numberOfHorizontalAngles, data.horizontalAngles);
for (let index = 0; index < data.numberOfHorizontalAngles; index++) {
ReadArray(dataPointer, data.numberOfVerticalAngles, data.candelaValues[index]);
}
let maxCandela = -1;
for (let index = 0; index < data.numberOfHorizontalAngles; index++) {
for (let subIndex = 0; subIndex < data.numberOfVerticalAngles; subIndex++) {
data.candelaValues[index][subIndex] *= data.candelaValues[index][subIndex] * data.candelaMultiplier * data.ballastFactor * data.fileGenerationType;
maxCandela = Math.max(maxCandela, data.candelaValues[index][subIndex]);
}
}
if (maxCandela > 0) {
for (let index = 0; index < data.numberOfHorizontalAngles; index++) {
for (let subIndex = 0; subIndex < data.numberOfVerticalAngles; subIndex++) {
data.candelaValues[index][subIndex] /= maxCandela;
}
}
}
const height = 180;
const width = height * 2;
const size = width * height;
const arrayBuffer = new Float32Array(width * height);
const startTheta = data.horizontalAngles[0];
const endTheta = data.horizontalAngles[data.numberOfHorizontalAngles - 1];
for (let index = 0; index < size; index++) {
let theta = index % width;
const phi = Math.floor(index / width);
if (endTheta - startTheta !== 0 && (theta < startTheta || theta >= endTheta)) {
theta %= endTheta * 2;
if (theta > endTheta) {
theta = endTheta * 2 - theta;
}
}
arrayBuffer[phi + theta * height] = InterpolateCandelaValues(data, phi, theta);
}
return {
width: width / 2,
height: 1,
data: arrayBuffer
};
}
var init_iesLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/IES/iesLoader.js"() {
init_math_scalar_functions();
__name(LineToArray, "LineToArray");
__name(ReadArray, "ReadArray");
__name(InterpolateCandelaValues, "InterpolateCandelaValues");
__name(LoadIESData, "LoadIESData");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/iesTextureLoader.js
var iesTextureLoader_exports = {};
__export(iesTextureLoader_exports, {
_IESTextureLoader: () => _IESTextureLoader
});
var _IESTextureLoader;
var init_iesTextureLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/iesTextureLoader.js"() {
init_iesLoader();
_IESTextureLoader = class {
static {
__name(this, "_IESTextureLoader");
}
constructor() {
this.supportCascades = false;
}
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
*/
loadCubeData() {
throw ".ies not supported in Cube.";
}
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
loadData(data, texture, callback) {
const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
const textureData = LoadIESData(uint8array);
callback(textureData.width, textureData.height, texture.useMipMaps, false, () => {
const engine = texture.getEngine();
texture.type = 1;
texture.format = 6;
texture._gammaSpace = false;
engine._uploadDataToTextureDirectly(texture, textureData.data);
});
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.constants.js
var ToGammaSpace, ToLinearSpace, PHI, Epsilon;
var init_math_constants = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.constants.js"() {
ToGammaSpace = 1 / 2.2;
ToLinearSpace = 2.2;
PHI = (1 + Math.sqrt(5)) / 2;
Epsilon = 1e-3;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/arrayTools.js
function BuildArray(size, itemBuilder) {
const a = [];
for (let i = 0; i < size; ++i) {
a.push(itemBuilder());
}
return a;
}
function BuildTuple(size, itemBuilder) {
return BuildArray(size, itemBuilder);
}
function ObserveArrayFunction(object, functionName, callback) {
const oldFunction = object[functionName];
if (typeof oldFunction !== "function") {
return null;
}
const newFunction = /* @__PURE__ */ __name(function() {
const previousLength = object.length;
const returnValue = newFunction.previous.apply(object, arguments);
callback(functionName, previousLength);
return returnValue;
}, "newFunction");
oldFunction.next = newFunction;
newFunction.previous = oldFunction;
object[functionName] = newFunction;
return () => {
const previous = newFunction.previous;
if (!previous) {
return;
}
const next = newFunction.next;
if (next) {
previous.next = next;
next.previous = previous;
} else {
previous.next = void 0;
object[functionName] = previous;
}
newFunction.next = void 0;
newFunction.previous = void 0;
};
}
function _ObserveArray(array, callback) {
const unObserveFunctions = observedArrayFunctions.map((name260) => {
return ObserveArrayFunction(array, name260, callback);
});
return () => {
for (const unObserveFunction of unObserveFunctions) {
unObserveFunction?.();
}
};
}
var observedArrayFunctions;
var init_arrayTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/arrayTools.js"() {
__name(BuildArray, "BuildArray");
__name(BuildTuple, "BuildTuple");
__name(ObserveArrayFunction, "ObserveArrayFunction");
observedArrayFunctions = ["push", "splice", "pop", "shift", "unshift"];
__name(_ObserveArray, "_ObserveArray");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/typeStore.js
function RegisterClass(className2, type) {
RegisteredTypes[className2] = type;
}
function GetClass(fqdn) {
return RegisteredTypes[fqdn];
}
function GetClassName(obj) {
for (const key in RegisteredTypes) {
if (obj instanceof RegisteredTypes[key] && !key.includes("Abstract")) {
return key;
}
}
return "Unknown";
}
var RegisteredTypes;
var init_typeStore = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/typeStore.js"() {
RegisteredTypes = {};
__name(RegisterClass, "RegisterClass");
__name(GetClass, "GetClass");
__name(GetClassName, "GetClassName");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/ThinMaths/thinMath.matrix.functions.js
function SetMatrixData(result, m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15) {
const mat = result.asArray();
mat[0] = m0;
mat[1] = m1;
mat[2] = m2;
mat[3] = m3;
mat[4] = m4;
mat[5] = m5;
mat[6] = m6;
mat[7] = m7;
mat[8] = m8;
mat[9] = m9;
mat[10] = m10;
mat[11] = m11;
mat[12] = m12;
mat[13] = m13;
mat[14] = m14;
mat[15] = m15;
MarkAsDirty(result);
}
function MarkAsDirty(matrix) {
matrix.updateFlag = MatrixManagement._UpdateFlagSeed++;
}
function IdentityMatrixToRef(result) {
SetMatrixData(result, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
}
function TranslationMatrixToRef(x, y, z, result) {
SetMatrixData(result, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1);
}
function ScalingMatrixToRef(x, y, z, result) {
SetMatrixData(result, x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
}
function MultiplyMatricesToArray(a, b, output, offset = 0) {
const m = a.asArray();
const otherM = b.asArray();
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];
output[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
output[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
output[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
output[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
output[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
output[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
output[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
output[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
output[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
output[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
output[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
output[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
output[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
output[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
output[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
output[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
}
function MultiplyMatricesToRef(a, b, result, offset = 0) {
MultiplyMatricesToArray(a, b, result.asArray(), offset);
MarkAsDirty(result);
}
function CopyMatrixToRef(matrix, target) {
CopyMatrixToArray(matrix, target.asArray());
MarkAsDirty(target);
}
function CopyMatrixToArray(matrix, array, offset = 0) {
const source = matrix.asArray();
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];
}
function InvertMatrixToRef(source, target) {
const result = InvertMatrixToArray(source, target.asArray());
if (result) {
MarkAsDirty(target);
}
return result;
}
function InvertMatrixToArray(source, target) {
const m = source.asArray();
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) {
return false;
}
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);
target[0] = cofact_00 * detInv;
target[1] = cofact_10 * detInv;
target[2] = cofact_20 * detInv;
target[3] = cofact_30 * detInv;
target[4] = cofact_01 * detInv;
target[5] = cofact_11 * detInv;
target[6] = cofact_21 * detInv;
target[7] = cofact_31 * detInv;
target[8] = cofact_02 * detInv;
target[9] = cofact_12 * detInv;
target[10] = cofact_22 * detInv;
target[11] = cofact_32 * detInv;
target[12] = cofact_03 * detInv;
target[13] = cofact_13 * detInv;
target[14] = cofact_23 * detInv;
target[15] = cofact_33 * detInv;
return true;
}
var MatrixManagement;
var init_thinMath_matrix_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/ThinMaths/thinMath.matrix.functions.js"() {
MatrixManagement = class {
static {
__name(this, "MatrixManagement");
}
};
MatrixManagement._UpdateFlagSeed = 0;
__name(SetMatrixData, "SetMatrixData");
__name(MarkAsDirty, "MarkAsDirty");
__name(IdentityMatrixToRef, "IdentityMatrixToRef");
__name(TranslationMatrixToRef, "TranslationMatrixToRef");
__name(ScalingMatrixToRef, "ScalingMatrixToRef");
__name(MultiplyMatricesToArray, "MultiplyMatricesToArray");
__name(MultiplyMatricesToRef, "MultiplyMatricesToRef");
__name(CopyMatrixToRef, "CopyMatrixToRef");
__name(CopyMatrixToArray, "CopyMatrixToArray");
__name(InvertMatrixToRef, "InvertMatrixToRef");
__name(InvertMatrixToArray, "InvertMatrixToArray");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.vector.js
var ExtractAsInt2, Vector2, Vector3, Vector4, Quaternion, Matrix, MathTmp, TmpVectors, mtxConvertNDCToHalfZRange;
var init_math_vector = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.vector.js"() {
init_math_constants();
init_arrayTools();
init_typeStore();
init_performanceConfigurator();
init_engineStore();
init_math_scalar_functions();
init_thinMath_matrix_functions();
ExtractAsInt2 = /* @__PURE__ */ __name((value) => {
return parseInt(value.toString().replace(/\W/g, ""));
}, "ExtractAsInt");
Vector2 = class _Vector2 {
static {
__name(this, "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(x = 0, 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 = ExtractAsInt2(this.x);
const y = ExtractAsInt2(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 Vector2 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;
}
/**
* Gets a new Vector2 rotated by the given angle
* @param angle defines the rotation angle
* @returns a new Vector2
*/
rotate(angle) {
return this.rotateToRef(angle, new _Vector2());
}
/**
* 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);
result.x = cos * this.x - sin * this.y;
result.y = sin * this.x + cos * this.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) {
return this;
}
return this.scaleInPlace(1 / 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 / 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 * value2.x + (-value1.x + value3.x) * amount + (2 * value1.x - 5 * value2.x + 4 * value3.x - value4.x) * squared + (-value1.x + 3 * value2.x - 3 * value3.x + value4.x) * cubed);
const y = 0.5 * (2 * value2.y + (-value1.y + value3.y) * amount + (2 * value1.y - 5 * value2.y + 4 * value3.y - value4.y) * squared + (-value1.y + 3 * value2.y - 3 * 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 * cubed - 3 * squared + 1;
const part2 = -2 * cubed + 3 * squared;
const part3 = cubed - 2 * 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) {
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);
}
};
Vector2._V8PerformanceHack = new Vector2(0.5, 0.5);
Vector2._ZeroReadOnly = Vector2.Zero();
Vector2;
Object.defineProperties(Vector2.prototype, {
dimension: { value: [2] },
rank: { value: 1 }
});
Vector3 = class _Vector3 {
static {
__name(this, "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) {
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 = ExtractAsInt2(this._x);
const y = ExtractAsInt2(this._y);
const z = ExtractAsInt2(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) {
const radius = this.length();
let theta = Math.acos(this._y / radius);
const phi = Math.atan2(this._z, this._x);
if (theta > Math.PI / 2) {
theta -= Math.PI / 2;
} else {
theta += Math.PI / 2;
}
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) {
const vx = this._x, vy = this._y, vz = this._z;
const qx = q._x, qy = q._y, qz = q._z, qw = q._w;
const tx = 2 * (qy * vz - qz * vy);
const ty = 2 * (qz * vx - qx * vz);
const tz = 2 * (qx * vy - qy * vx);
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];
this.subtractToRef(origin, V);
V.normalize();
const denom = _Vector3.Dot(V, n);
if (Math.abs(denom) < 1e-10) {
result.setAll(Infinity);
} else {
const t = -(_Vector3.Dot(origin, n) + d) / denom;
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) {
return this;
}
return this.scaleInPlace(1 / 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) {
result._x = this._x;
result._y = this._y;
result._z = this._z;
result._isDirty = true;
return result;
}
return this.scaleToRef(1 / 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);
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 {
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);
}
/**
* Returns a new Vector3 set to (1.0, 1.0, 1.0)
* @returns a new Vector3
*/
static One() {
return new _Vector3(1, 1, 1);
}
/**
* 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, 1, 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, -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 forward Vector3
*/
static Forward(rightHandedSystem = false) {
return new _Vector3(0, 0, rightHandedSystem ? -1 : 1);
}
/**
* 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, rightHandedSystem ? 1 : -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);
}
/**
* 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);
}
/**
* 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 * value2._x + (-value1._x + value3._x) * amount + (2 * value1._x - 5 * value2._x + 4 * value3._x - value4._x) * squared + (-value1._x + 3 * value2._x - 3 * value3._x + value4._x) * cubed);
const y = 0.5 * (2 * value2._y + (-value1._y + value3._y) * amount + (2 * value1._y - 5 * value2._y + 4 * value3._y - value4._y) * squared + (-value1._y + 3 * value2._y - 3 * value3._y + value4._y) * cubed);
const z = 0.5 * (2 * value2._z + (-value1._z + value3._z) * amount + (2 * value1._z - 5 * value2._z + 4 * value3._z - value4._z) * squared + (-value1._z + 3 * value2._z - 3 * 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 * cubed - 3 * squared + 1;
const part2 = -2 * cubed + 3 * squared;
const part3 = cubed - 2 * 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, -ch / 2, 0, 0, 0, 0, zScale, 0, cx + cw / 2, ch / 2 + 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);
}
/**
* 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;
}
_Vector3.TransformCoordinatesToRef(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];
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) {
ref.copyFrom(p0);
return _Vector3.Distance(vector, p0);
}
vector.subtractToRef(p0, vectorp0);
_Vector3.CrossToRef(p1p0, p2p0, normal);
const nl = normal.length();
if (nl < Epsilon) {
ref.copyFrom(p0);
return _Vector3.Distance(vector, p0);
}
normal.normalizeFromLength(nl);
let l = vectorp0.length();
if (l < Epsilon) {
ref.copyFrom(p0);
return 0;
}
vectorp0.normalizeFromLength(l);
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);
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);
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;
}
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 (!isOutside) {
ref.copyFrom(proj);
return Math.abs(l * cosA);
}
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) {
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));
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;
}
};
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();
Vector3;
Object.defineProperties(Vector3.prototype, {
dimension: { value: [3] },
rank: { value: 1 }
});
Vector4 = class _Vector4 {
static {
__name(this, "Vector4");
}
// ---------------------------------
// Getters / setters (same pattern as 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;
}
/** Gets or sets the w coordinate */
get w() {
return this._w;
}
set w(value) {
this._w = value;
this._isDirty = true;
}
/**
* 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(x = 0, y = 0, z = 0, w = 0) {
this._isDirty = true;
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 = ExtractAsInt2(this._x);
const y = ExtractAsInt2(this._y);
const z = ExtractAsInt2(this._z);
const w = ExtractAsInt2(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 === void 0) {
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) {
return this;
}
return this.scaleInPlace(1 / 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) {
reference.x = this._x;
reference.y = this._y;
reference.z = this._z;
reference.w = this._w;
return reference;
}
return this.scaleToRef(1 / 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);
}
/**
* Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
* @returns the new vector
*/
static One() {
return new _Vector4(1, 1, 1, 1);
}
/**
* 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;
}
};
Vector4._V8PerformanceHack = new Vector4(0.5, 0.5, 0.5, 0.5);
Vector4._ZeroReadOnly = Vector4.Zero();
Vector4;
Object.defineProperties(Vector4.prototype, {
dimension: { value: [4] },
rank: { value: 1 }
});
Quaternion = class _Quaternion {
static {
__name(this, "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, y = 0, z = 0, w = 1) {
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 = ExtractAsInt2(this._x);
const y = ExtractAsInt2(this._y);
const z = ExtractAsInt2(this._z);
const w = ExtractAsInt2(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);
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) {
return this;
}
return this.scaleInPlace(1 / 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) {
return reference.copyFromFloats(this._x, this._y, this._z, this._w);
}
return this.scaleToRef(1 / 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 * (qx * qy + qz * qw), -sqz - sqx + sqy + sqw);
result._x = Math.asin(-2 * zAxisY);
result._y = Math.atan2(2 * (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;
const sinHalfBeta = Math.sqrt(qx * qx + qy * qy);
const cosHalfBeta = Math.sqrt(qz * qz + qw * qw);
const beta = 2 * Math.atan2(sinHalfBeta, cosHalfBeta);
const gammaPlusAlpha = 2 * Math.atan2(qz, qw);
const gammaMinusAlpha = 2 * Math.atan2(qy, qx);
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;
}
/**
* Converts the current quaternion to an axis angle representation
* @returns the axis and angle in radians
*/
toAxisAngle() {
const axis = Vector3.Zero();
const angle = this.toAxisAngleToRef(axis);
return { axis, angle };
}
/**
* Converts the current quaternion to an axis angle representation
* @param axis defines the target axis vector
* @returns the angle in radians
*/
toAxisAngleToRef(axis) {
let angle = 0;
const sinHalfAngle = Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z);
const cosHalfAngle = this._w;
if (sinHalfAngle > 0) {
angle = 2 * Math.atan2(sinHalfAngle, cosHalfAngle);
axis.set(this._x / sinHalfAngle, this._y / sinHalfAngle, this._z / sinHalfAngle);
} else {
angle = 0;
axis.set(1, 0, 0);
}
return angle;
}
// 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);
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 * Math.sqrt(1 + 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 * Math.sqrt(1 + 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 * Math.sqrt(1 + 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);
}
/**
* 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, 1);
}
/**
* 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#561
* @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) {
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) {
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);
_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 / Math.sin(num5);
num3 = Math.sin((1 - 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 * cubed - 3 * squared + 1;
const part2 = -2 * cubed + 3 * squared;
const part3 = cubed - 2 * 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);
}
};
Quaternion._V8PerformanceHack = new Quaternion(0.5, 0.5, 0.5, 0.5);
Quaternion;
Object.defineProperties(Quaternion.prototype, {
dimension: { value: [4] },
rank: { value: 1 }
});
Matrix = class _Matrix {
static {
__name(this, "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 = MatrixManagement._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;
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 && m[1] === 0 && m[2] === 0 && m[3] === 0 && m[4] === 0 && m[5] === 1 && m[6] === 0 && m[7] === 0 && m[8] === 0 && m[9] === 0 && m[10] === 1 && m[11] === 0 && m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1;
}
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 || this._m[5] !== 1 || this._m[15] !== 1) {
this._isIdentity3x2 = false;
} else if (this._m[1] !== 0 || this._m[2] !== 0 || this._m[3] !== 0 || this._m[4] !== 0 || this._m[6] !== 0 || this._m[7] !== 0 || this._m[8] !== 0 || this._m[9] !== 0 || this._m[10] !== 0 || this._m[11] !== 0 || this._m[12] !== 0 || this._m[13] !== 0 || this._m[14] !== 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];
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]}
${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}
${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}
${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, 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;
}
if (InvertMatrixToArray(this, other.asArray())) {
other.markAsUpdated();
} else {
other.copyFrom(this);
}
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, 1, 0, 0, 0, 0, 1, 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) {
CopyMatrixToArray(this, array, offset);
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) {
MultiplyMatricesToArray(this, other, result, offset);
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 = ExtractAsInt2(this._m[0]);
for (let i = 1; i < 16; i++) {
hash = hash * 397 ^ ExtractAsInt2(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, 1);
}
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, m[4] * sy, m[5] * sy, m[6] * sy, 0, m[8] * sz, m[9] * sz, m[10] * sz, 0, 0, 0, 0, 1, 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, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, 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, m[4] * sy, m[5] * sy, m[6] * sy, 0, m[8] * sz, m[9] * sz, m[10] * sz, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 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);
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, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 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, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1, 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, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 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;
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;
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;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
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) {
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, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1, 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 - 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];
target.subtractToRef(eye, zAxis);
zAxis.normalize();
Vector3.CrossToRef(up, zAxis, xAxis);
const xSquareLength = xAxis.lengthSquared();
if (xSquareLength === 0) {
xAxis.x = 1;
} else {
xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
}
Vector3.CrossToRef(zAxis, xAxis, yAxis);
yAxis.normalize();
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, xAxis._y, yAxis._y, zAxis._y, 0, xAxis._z, yAxis._z, zAxis._z, 0, ex, ey, ez, 1, 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];
eye.subtractToRef(target, zAxis);
zAxis.normalize();
Vector3.CrossToRef(up, zAxis, xAxis);
const xSquareLength = xAxis.lengthSquared();
if (xSquareLength === 0) {
xAxis.x = 1;
} else {
xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
}
Vector3.CrossToRef(zAxis, xAxis, yAxis);
yAxis.normalize();
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, xAxis._y, yAxis._y, zAxis._y, 0, xAxis._z, yAxis._z, zAxis._z, 0, ex, ey, ez, 1, 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);
_Matrix.FromValuesToRef(left._x, left._y, left._z, 0, up._x, up._y, up._z, 0, back._x, back._y, back._z, 0, 0, 0, 0, 1, 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);
_Matrix.FromValuesToRef(right._x, right._y, right._z, 0, up._x, up._y, up._z, 0, forward._x, forward._y, forward._z, 0, 0, 0, 0, 1, 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 / width;
const b = 2 / height;
const c = 2 / (f - n);
const d = -(f + n) / (f - n);
_Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, 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 / (right - left);
const b = 2 / (top - bottom);
const c = 2 / (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, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, 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;
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 * n / width;
const b = 2 * 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, b, 0, rot, 0, 0, c, 1, 0, 0, d, 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 / 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, b, 0, rot, 0, 0, c, 1, 0, 0, d, 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 / 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, b, 0, rot, 0, 0, -znear, 1, 0, 0, 1, 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) {
const n = znear;
const f = zfar;
const t = 1 / 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, b, 0, rot, 0, 0, c, -1, 0, 0, d, 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 / 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, b, 0, rot, 0, 0, -znear, -1, 0, 0, -1, 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, -ch / 2, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2, ch / 2 + cy, zmin, 1);
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();
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, temp * y, temp2 * y + 1, temp3 * y, 0, temp * z, temp2 * z, temp3 * z + 1, 0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1, 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, yaxis._x, yaxis._y, yaxis._z, 0, zaxis._x, zaxis._y, zaxis._z, 0, 0, 0, 0, 1, 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 - 2 * (yy + zz);
result._m[1] = 2 * (xy + zw);
result._m[2] = 2 * (zx - yw);
result._m[3] = 0;
result._m[4] = 2 * (xy - zw);
result._m[5] = 1 - 2 * (zz + xx);
result._m[6] = 2 * (yz + xw);
result._m[7] = 0;
result._m[8] = 2 * (zx + yw);
result._m[9] = 2 * (yz - xw);
result._m[10] = 1 - 2 * (yy + xx);
result._m[11] = 0;
result._m[12] = 0;
result._m[13] = 0;
result._m[14] = 0;
result._m[15] = 1;
result.markAsUpdated();
return result;
}
};
Matrix._IdentityReadOnly = Matrix.Identity();
Object.defineProperties(Matrix.prototype, {
dimension: { value: [4, 4] },
rank: { value: 2 }
});
MathTmp = class {
static {
__name(this, "MathTmp");
}
};
MathTmp.Vector3 = BuildTuple(11, Vector3.Zero);
MathTmp.Matrix = BuildTuple(2, Matrix.Identity);
MathTmp.Quaternion = BuildTuple(3, Quaternion.Zero);
TmpVectors = class {
static {
__name(this, "TmpVectors");
}
};
TmpVectors.Vector2 = BuildTuple(3, Vector2.Zero);
TmpVectors.Vector3 = BuildTuple(13, Vector3.Zero);
TmpVectors.Vector4 = BuildTuple(3, Vector4.Zero);
TmpVectors.Quaternion = BuildTuple(3, Quaternion.Zero);
TmpVectors.Matrix = BuildTuple(8, Matrix.Identity);
RegisterClass("BABYLON.Vector2", Vector2);
RegisterClass("BABYLON.Vector3", Vector3);
RegisterClass("BABYLON.Vector4", Vector4);
RegisterClass("BABYLON.Matrix", Matrix);
mtxConvertNDCToHalfZRange = Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.axis.js
var Space, Axis, Coordinate;
var init_math_axis = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.axis.js"() {
init_math_vector();
(function(Space2) {
Space2[Space2["LOCAL"] = 0] = "LOCAL";
Space2[Space2["WORLD"] = 1] = "WORLD";
Space2[Space2["BONE"] = 2] = "BONE";
})(Space || (Space = {}));
Axis = class {
static {
__name(this, "Axis");
}
};
Axis.X = new Vector3(1, 0, 0);
Axis.Y = new Vector3(0, 1, 0);
Axis.Z = new Vector3(0, 0, 1);
(function(Coordinate2) {
Coordinate2[Coordinate2["X"] = 0] = "X";
Coordinate2[Coordinate2["Y"] = 1] = "Y";
Coordinate2[Coordinate2["Z"] = 2] = "Z";
})(Coordinate || (Coordinate = {}));
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.color.js
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 <= 31308e-7) {
return 12.92 * color;
}
return 1.055 * Math.pow(color, 0.41666) - 0.055;
}
var Color3, Color4, TmpColors;
var init_math_color = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.color.js"() {
init_arrayTools();
init_typeStore();
init_math_constants();
init_math_scalar_functions();
__name(ColorChannelToLinearSpace, "ColorChannelToLinearSpace");
__name(ColorChannelToLinearSpaceExact, "ColorChannelToLinearSpaceExact");
__name(ColorChannelToGammaSpace, "ColorChannelToGammaSpace");
__name(ColorChannelToGammaSpaceExact, "ColorChannelToGammaSpaceExact");
Color3 = class _Color3 {
static {
__name(this, "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(r = 0, g = 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, g / 255, b / 255);
}
/**
* 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);
_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 * cubed - 3 * squared + 1;
const part2 = -2 * cubed + 3 * squared;
const part3 = cubed - 2 * 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, 1);
}
/**
* Returns a Color3 value containing a random color
* @returns a new Color3 object
*/
static Random() {
return new _Color3(Math.random(), Math.random(), Math.random());
}
};
Color3._V8PerformanceHack = new Color3(0.5, 0.5, 0.5);
Color3._BlackReadOnly = Color3.Black();
Object.defineProperties(Color3.prototype, {
dimension: { value: [3] },
rank: { value: 1 }
});
Color4 = class _Color4 {
static {
__name(this, "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(r = 0, g = 0, b = 0, 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);
}
return new _Color4(0, 0, 0, 1).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 * cubed - 3 * squared + 1;
const part2 = -2 * cubed + 3 * squared;
const part3 = cubed - 2 * 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) {
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, g / 255, b / 255, a / 255);
}
/**
* 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) {
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;
}
return colors4;
}
return colors;
}
};
Color4._V8PerformanceHack = new Color4(0.5, 0.5, 0.5, 0.5);
Object.defineProperties(Color4.prototype, {
dimension: { value: [4] },
rank: { value: 1 }
});
TmpColors = class {
static {
__name(this, "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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.plane.js
var Plane;
var init_math_plane = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.plane.js"() {
init_math_vector();
Plane = class _Plane {
static {
__name(this, "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;
if (norm !== 0) {
magnitude = 1 / 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 / pyth;
} else {
invPyth = 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);
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);
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();
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.frustum.js
var Frustum;
var init_math_frustum = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.frustum.js"() {
init_math_plane();
Frustum = class _Frustum {
static {
__name(this, "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));
}
_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) {
_Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
_Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
_Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
_Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
_Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
_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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.path.js
var Orientation, BezierCurve, Angle, Arc2, Path2, Path3D, Curve3;
var init_math_path = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.path.js"() {
init_math_scalar_functions();
init_math_vector();
init_math_constants();
(function(Orientation2) {
Orientation2[Orientation2["CW"] = 0] = "CW";
Orientation2[Orientation2["CCW"] = 1] = "CCW";
})(Orientation || (Orientation = {}));
BezierCurve = class {
static {
__name(this, "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;
}
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 / (3 * f0 * refinedT2 + 2 * f1 * refinedT + f2);
refinedT -= (x - t) * slope;
refinedT = Math.min(1, Math.max(0, refinedT));
}
return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
}
};
Angle = class _Angle {
static {
__name(this, "Angle");
}
/**
* Creates an Angle object of "radians" radians (float).
* @param radians the angle in radians
*/
constructor(radians) {
this._radians = radians;
if (this._radians < 0) {
this._radians += 2 * Math.PI;
}
}
/**
* Get value in degrees
* @returns the Angle value in degrees (float)
*/
degrees() {
return this._radians * 180 / 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);
}
};
Arc2 = class {
static {
__name(this, "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(startPoint, midPoint, 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();
if (a2 - a1 > 180) {
a2 -= 360;
}
if (a2 - a1 < -180) {
a2 += 360;
}
if (a3 - a2 > 180) {
a3 -= 360;
}
if (a3 - a2 < -180) {
a3 += 360;
}
this.orientation = a2 - a1 < 0 ? 0 : 1;
this.angle = Angle.FromDegrees(this.orientation === 0 ? a1 - a3 : a3 - a1);
}
};
Path2 = class _Path2 {
static {
__name(this, "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;
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) {
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 = /* @__PURE__ */ __name((t, val0, val1, val2) => {
const res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
return res;
}, "equation");
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 = /* @__PURE__ */ __name((t, val0, val1, val2, val3) => {
const res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
return res;
}, "equation");
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) {
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 {
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;
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);
}
};
Path3D = class _Path3D {
static {
__name(this, "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(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();
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();
}
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;
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) * Vector3.Distance(point, target) / subLength, 1);
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, end = 1) {
if (start < 0) {
start = 1 - start * -1 % 1;
}
if (end < 0) {
end = 1 - end * -1 % 1;
}
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) {
startIndex++;
slicePoints.push(startPoint);
}
slicePoints.push(...curvePoints.slice(startIndex, endIndex));
if (end !== 1 || start === 1) {
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;
}
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();
}
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;
let prev;
let cur;
let curTang;
let prevNor;
let prevBinor;
for (let i = 1; i < l; i++) {
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();
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) {
tgl = 1;
}
if (va === void 0 || va === null) {
let point;
if (!WithinEpsilon(Math.abs(vt.y) / tgl, 1, Epsilon)) {
point = new Vector3(0, -1, 0);
} else if (!WithinEpsilon(Math.abs(vt.x) / tgl, 1, Epsilon)) {
point = new Vector3(1, 0, 0);
} else if (!WithinEpsilon(Math.abs(vt.z) / tgl, 1, Epsilon)) {
point = new Vector3(0, 0, 1);
} 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) {
if (this._pointAtData.id === position) {
if (!this._pointAtData.interpolateReady) {
this._updateInterpolationMatrix();
}
return this._pointAtData;
} else {
this._pointAtData.id = position;
}
const curvePoints = this.getPoints();
if (position <= 0) {
return this._setPointAtData(0, 0, curvePoints[0], 0, interpolateTNB);
} else if (position >= 1) {
return this._setPointAtData(1, 1, curvePoints[curvePoints.length - 1], curvePoints.length - 1, interpolateTNB);
}
let previousPoint = curvePoints[0];
let currentPoint;
let currentLength = 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, 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);
}
}
};
Curve3 = class _Curve3 {
static {
__name(this, "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 = /* @__PURE__ */ __name((t, val0, val1, val2) => {
const res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
return res;
}, "equation");
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 = /* @__PURE__ */ __name((t, val0, val1, val2, val3) => {
const res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
return res;
}, "equation");
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 / 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 / nbPoints;
let amount = 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);
}
const len1Sq = vec1.lengthSquared();
const len2Sq = vec2.lengthSquared();
const len3Sq = vec3.lengthSquared();
const len4Sq = 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 * len2Sq * dot1 / len4Sq;
const b = -0.5 * len3Sq * dot2 / len4Sq;
const c = -0.5 * len1Sq * dot3 / len4Sq;
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;
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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.size.js
var Size;
var init_math_size = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.size.js"() {
Size = class _Size {
static {
__name(this, "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);
}
/**
* 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);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.vertexFormat.js
var PositionNormalVertex, PositionNormalTextureVertex;
var init_math_vertexFormat = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.vertexFormat.js"() {
init_math_vector();
PositionNormalVertex = class _PositionNormalVertex {
static {
__name(this, "PositionNormalVertex");
}
/**
* Creates a PositionNormalVertex
* @param position the position of the vertex (defaut: 0,0,0)
* @param normal the normal of the vertex (defaut: 0,1,0)
*/
constructor(position = Vector3.Zero(), normal = Vector3.Up()) {
this.position = position;
this.normal = normal;
}
/**
* Clones the PositionNormalVertex
* @returns the cloned PositionNormalVertex
*/
clone() {
return new _PositionNormalVertex(this.position.clone(), this.normal.clone());
}
};
PositionNormalTextureVertex = class _PositionNormalTextureVertex {
static {
__name(this, "PositionNormalTextureVertex");
}
/**
* Creates a PositionNormalTextureVertex
* @param position the position of the vertex (defaut: 0,0,0)
* @param normal the normal of the vertex (defaut: 0,1,0)
* @param uv the uv of the vertex (default: 0,0)
*/
constructor(position = Vector3.Zero(), normal = Vector3.Up(), uv = Vector2.Zero()) {
this.position = position;
this.normal = normal;
this.uv = uv;
}
/**
* Clones the PositionNormalTextureVertex
* @returns the cloned PositionNormalTextureVertex
*/
clone() {
return new _PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.viewport.js
var Viewport;
var init_math_viewport = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.viewport.js"() {
Viewport = class _Viewport {
static {
__name(this, "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(x, y, width, 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);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.js
var init_math = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.js"() {
init_math_axis();
init_math_color();
init_math_constants();
init_math_frustum();
init_math_path();
init_math_plane();
init_math_size();
init_math_vector();
init_math_vertexFormat();
init_math_viewport();
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/sphericalPolynomial.js
var SH3ylmBasisConstants, SH3ylmBasisTrigonometricTerms, applySH3, SHCosKernelConvolution, SphericalHarmonics, SphericalPolynomial;
var init_sphericalPolynomial = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/sphericalPolynomial.js"() {
init_math_vector();
init_math();
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
];
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
];
applySH3 = /* @__PURE__ */ __name((lm, direction) => {
return SH3ylmBasisConstants[lm] * SH3ylmBasisTrigonometricTerms[lm](direction);
}, "applySH3");
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];
SphericalHarmonics = class _SphericalHarmonics {
static {
__name(this, "SphericalHarmonics");
}
constructor() {
this.preScaled = false;
this.l00 = Vector3.Zero();
this.l1_1 = Vector3.Zero();
this.l10 = Vector3.Zero();
this.l11 = Vector3.Zero();
this.l2_2 = Vector3.Zero();
this.l2_1 = Vector3.Zero();
this.l20 = Vector3.Zero();
this.l21 = Vector3.Zero();
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() {
this.l00.scaleInPlace(SHCosKernelConvolution[0]);
this.l1_1.scaleInPlace(SHCosKernelConvolution[1]);
this.l10.scaleInPlace(SHCosKernelConvolution[2]);
this.l11.scaleInPlace(SHCosKernelConvolution[3]);
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 / Math.PI);
}
/**
* 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;
}
};
SphericalPolynomial = class _SphericalPolynomial {
static {
__name(this, "SphericalPolynomial");
}
constructor() {
this.x = Vector3.Zero();
this.y = Vector3.Zero();
this.z = Vector3.Zero();
this.xx = Vector3.Zero();
this.yy = Vector3.Zero();
this.zz = Vector3.Zero();
this.xy = Vector3.Zero();
this.yz = Vector3.Zero();
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 / 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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/cubemapToSphericalPolynomial.js
var FileFaceOrientation, CubeMapToSphericalPolynomialTools;
var init_cubemapToSphericalPolynomial = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/cubemapToSphericalPolynomial.js"() {
init_math_vector();
init_math_scalar_functions();
init_sphericalPolynomial();
init_math_constants();
init_math_color();
FileFaceOrientation = class {
static {
__name(this, "FileFaceOrientation");
}
constructor(name260, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
this.name = name260;
this.worldAxisForNormal = worldAxisForNormal;
this.worldAxisForFileX = worldAxisForFileX;
this.worldAxisForFileY = worldAxisForFileY;
}
};
CubeMapToSphericalPolynomialTools = class {
static {
__name(this, "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) {
return null;
}
texture.getScene()?.getEngine().flushFramebuffer();
const size = texture.getSize().width;
const rightPromise = texture.readPixels(0, void 0, void 0, false);
const leftPromise = texture.readPixels(1, void 0, void 0, false);
let upPromise;
let downPromise;
if (texture.isRenderTarget) {
upPromise = texture.readPixels(3, void 0, void 0, false);
downPromise = texture.readPixels(2, void 0, void 0, false);
} else {
upPromise = texture.readPixels(2, void 0, void 0, false);
downPromise = texture.readPixels(3, void 0, void 0, false);
}
const frontPromise = texture.readPixels(4, void 0, void 0, false);
const backPromise = texture.readPixels(5, void 0, void 0, false);
const gammaSpace = texture.gammaSpace;
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;
const du = 2 / cubeInfo.size;
const dv = du;
const halfTexel = 0.5 * du;
const minUV = halfTexel - 1;
for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
const fileFace = this._FileFaces[faceIndex];
const dataArray = cubeInfo[fileFace.name];
let v = minUV;
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++) {
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];
if (isNaN(r)) {
r = 0;
}
if (isNaN(g)) {
g = 0;
}
if (isNaN(b)) {
b = 0;
}
if (cubeInfo.type === 0) {
r /= 255;
g /= 255;
b /= 255;
}
if (cubeInfo.gammaSpace) {
r = Math.pow(Clamp(r), ToLinearSpace);
g = Math.pow(Clamp(g), ToLinearSpace);
b = Math.pow(Clamp(b), ToLinearSpace);
}
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;
}
}
const sphereSolidAngle = 4 * Math.PI;
const facesProcessed = 6;
const expectedSolidAngle = sphereSolidAngle * facesProcessed / 6;
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
];
CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE = 4096;
CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS = false;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/lodCube.fragment.js
var lodCube_fragment_exports = {};
__export(lodCube_fragment_exports, {
lodCubePixelShader: () => lodCubePixelShader
});
var name, shader, lodCubePixelShader;
var init_lodCube_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/lodCube.fragment.js"() {
init_shaderStore();
name = "lodCubePixelShader";
shader = `precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform int gamma;void main(void)
{vec2 uv=vUV*2.0-1.0;
#ifdef POSITIVEX
gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);
#endif
#ifdef NEGATIVEX
gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);
#endif
#ifdef POSITIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);
#endif
#ifdef NEGATIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);
#endif
#ifdef POSITIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);
#endif
#ifdef NEGATIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);
#endif
if (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}
`;
if (!ShaderStore.ShadersStore[name]) {
ShaderStore.ShadersStore[name] = shader;
}
lodCubePixelShader = { name, shader };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/lod.fragment.js
var lod_fragment_exports = {};
__export(lod_fragment_exports, {
lodPixelShader: () => lodPixelShader
});
var name2, shader2, lodPixelShader;
var init_lod_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/lod.fragment.js"() {
init_shaderStore();
name2 = "lodPixelShader";
shader2 = `precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform int gamma;void main(void)
{ivec2 textureDimensions=textureSize(textureSampler,0);gl_FragColor=texelFetch(textureSampler,ivec2(vUV*vec2(textureDimensions)),int(lod));if (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}
`;
if (!ShaderStore.ShadersStore[name2]) {
ShaderStore.ShadersStore[name2] = shader2;
}
lodPixelShader = { name: name2, shader: shader2 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/lodCube.fragment.js
var lodCube_fragment_exports2 = {};
__export(lodCube_fragment_exports2, {
lodCubePixelShaderWGSL: () => lodCubePixelShaderWGSL
});
var name3, shader3, lodCubePixelShaderWGSL;
var init_lodCube_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/lodCube.fragment.js"() {
init_shaderStore();
name3 = "lodCubePixelShader";
shader3 = `const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube;uniform lod: f32;uniform gamma: i32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let uv=fragmentInputs.vUV*2.0-1.0;
#ifdef POSITIVEX
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x),uniforms.lod);
#endif
#ifdef NEGATIVEX
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x),uniforms.lod);
#endif
#ifdef POSITIVEY
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x),uniforms.lod);
#endif
#ifdef NEGATIVEY
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x),uniforms.lod);
#endif
#ifdef POSITIVEZ
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,1.001),uniforms.lod);
#endif
#ifdef NEGATIVEZ
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,-1.001),uniforms.lod);
#endif
if (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}}
`;
if (!ShaderStore.ShadersStoreWGSL[name3]) {
ShaderStore.ShadersStoreWGSL[name3] = shader3;
}
lodCubePixelShaderWGSL = { name: name3, shader: shader3 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/lod.fragment.js
var lod_fragment_exports2 = {};
__export(lod_fragment_exports2, {
lodPixelShaderWGSL: () => lodPixelShaderWGSL
});
var name4, shader4, lodPixelShaderWGSL;
var init_lod_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/lod.fragment.js"() {
init_shaderStore();
name4 = "lodPixelShader";
shader4 = `const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSampler: texture_2d;uniform lod: f32;uniform gamma: i32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let textureSize=textureDimensions(textureSampler);fragmentOutputs.color=textureLoad(textureSampler,vec2u(fragmentInputs.vUV*vec2f(textureSize)),u32(uniforms.lod));if (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}}
`;
if (!ShaderStore.ShadersStoreWGSL[name4]) {
ShaderStore.ShadersStoreWGSL[name4] = shader4;
}
lodPixelShaderWGSL = { name: name4, shader: shader4 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/tslib.es6.js
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
__name(__, "__");
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
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;
}
function __param(paramIndex, decorator) {
return function(target, key) {
decorator(target, key, paramIndex);
};
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
__name(adopt, "adopt");
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
__name(fulfilled, "fulfilled");
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
__name(rejected, "rejected");
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
__name(step, "step");
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: /* @__PURE__ */ __name(function() {
if (t[0] & 1) throw t[1];
return t[1];
}, "sent"), trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
__name(verb, "verb");
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
__name(step, "step");
}
function __exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: /* @__PURE__ */ __name(function() {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}, "next")
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
return this;
}, i;
function verb(n) {
if (g[n]) i[n] = function(v) {
return new Promise(function(a, b) {
q.push([n, v, a, b]) > 1 || resume(n, v);
});
};
}
__name(verb, "verb");
function resume(n, v) {
try {
step(g[n](v));
} catch (e) {
settle(q[0][3], e);
}
}
__name(resume, "resume");
function step(r) {
r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
}
__name(step, "step");
function fulfill(value) {
resume("next", value);
}
__name(fulfill, "fulfill");
function reject(value) {
resume("throw", value);
}
__name(reject, "reject");
function settle(f, v) {
if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
}
__name(settle, "settle");
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function(e) {
throw e;
}), verb("return"), i[Symbol.iterator] = function() {
return this;
}, i;
function verb(n, f) {
i[n] = o[n] ? function(v) {
return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
} : f;
}
__name(verb, "verb");
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
return this;
}, i);
function verb(n) {
i[n] = o[n] && function(v) {
return new Promise(function(resolve, reject) {
v = o[n](v), settle(resolve, reject, v.done, v.value);
});
};
}
__name(verb, "verb");
function settle(resolve, reject, d, v) {
Promise.resolve(v).then(function(v2) {
resolve({ value: v2, done: d });
}, reject);
}
__name(settle, "settle");
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
} else {
cooked.raw = raw;
}
return cooked;
}
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldIn(state, receiver) {
if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
}
var extendStatics, __assign, __createBinding, __setModuleDefault;
var init_tslib_es6 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/tslib.es6.js"() {
extendStatics = /* @__PURE__ */ __name(function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
};
return extendStatics(d, b);
}, "extendStatics");
__name(__extends, "__extends");
__assign = /* @__PURE__ */ __name(function() {
__assign = Object.assign || /* @__PURE__ */ __name(function __assign2(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}, "__assign");
return __assign.apply(this, arguments);
}, "__assign");
__name(__rest, "__rest");
__name(__decorate, "__decorate");
__name(__param, "__param");
__name(__metadata, "__metadata");
__name(__awaiter, "__awaiter");
__name(__generator, "__generator");
__createBinding = Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
return m[k];
}, "get") };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
};
__name(__exportStar, "__exportStar");
__name(__values, "__values");
__name(__read, "__read");
__name(__spread, "__spread");
__name(__spreadArrays, "__spreadArrays");
__name(__spreadArray, "__spreadArray");
__name(__await, "__await");
__name(__asyncGenerator, "__asyncGenerator");
__name(__asyncDelegator, "__asyncDelegator");
__name(__asyncValues, "__asyncValues");
__name(__makeTemplateObject, "__makeTemplateObject");
;
__setModuleDefault = Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
};
__name(__importStar, "__importStar");
__name(__importDefault, "__importDefault");
__name(__classPrivateFieldGet, "__classPrivateFieldGet");
__name(__classPrivateFieldSet, "__classPrivateFieldSet");
__name(__classPrivateFieldIn, "__classPrivateFieldIn");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.functions.js
function GetDirectStore(target) {
const classKey = target.getClassName();
if (!DecoratorInitialStore[classKey]) {
DecoratorInitialStore[classKey] = {};
}
return DecoratorInitialStore[classKey];
}
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;
}
var MergedStore, DecoratorInitialStore;
var init_decorators_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.functions.js"() {
MergedStore = {};
DecoratorInitialStore = {};
__name(GetDirectStore, "GetDirectStore");
__name(GetMergedStore, "GetMergedStore");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.js
function generateSerializableMember(type, sourceName) {
return (target, propertyKey) => {
const classStore = GetDirectStore(target);
if (!classStore[propertyKey]) {
classStore[propertyKey] = { type, sourceName };
}
};
}
function generateExpandMember(setCallback, targetKey = null) {
return (target, propertyKey) => {
const key = targetKey || "_" + propertyKey;
Object.defineProperty(target, propertyKey, {
get: /* @__PURE__ */ __name(function() {
return this[key];
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
if (typeof this[key]?.equals === "function") {
if (this[key].equals(value)) {
return;
}
}
if (this[key] === value) {
return;
}
this[key] = value;
target[setCallback].apply(this);
}, "set"),
enumerable: true,
configurable: true
});
};
}
function expandToProperty(callback, targetKey = null) {
return generateExpandMember(callback, targetKey);
}
function serialize(sourceName) {
return generateSerializableMember(0, sourceName);
}
function serializeAsTexture(sourceName) {
return generateSerializableMember(1, sourceName);
}
function serializeAsColor3(sourceName) {
return generateSerializableMember(2, sourceName);
}
function serializeAsFresnelParameters(sourceName) {
return generateSerializableMember(3, sourceName);
}
function serializeAsVector2(sourceName) {
return generateSerializableMember(4, sourceName);
}
function serializeAsVector3(sourceName) {
return generateSerializableMember(5, sourceName);
}
function serializeAsMeshReference(sourceName) {
return generateSerializableMember(6, sourceName);
}
function serializeAsColorCurves(sourceName) {
return generateSerializableMember(7, sourceName);
}
function serializeAsColor4(sourceName) {
return generateSerializableMember(8, sourceName);
}
function serializeAsImageProcessingConfiguration(sourceName) {
return generateSerializableMember(9, sourceName);
}
function serializeAsQuaternion(sourceName) {
return generateSerializableMember(10, sourceName);
}
function serializeAsMatrix(sourceName) {
return generateSerializableMember(12, sourceName);
}
function serializeAsCameraReference(sourceName) {
return generateSerializableMember(11, sourceName);
}
function nativeOverride(target, propertyKey, descriptor, predicate) {
const jsFunc = descriptor.value;
descriptor.value = (...params) => {
let func = jsFunc;
if (typeof _native !== "undefined" && _native[propertyKey]) {
const nativeFunc = _native[propertyKey];
if (predicate) {
func = /* @__PURE__ */ __name((...params2) => predicate(...params2) ? nativeFunc(...params2) : jsFunc(...params2), "func");
} else {
func = nativeFunc;
}
}
target[propertyKey] = func;
return func(...params);
};
}
function addAccessorsForMaterialProperty(setCallback, targetKey = null) {
return (target, propertyKey) => {
const key = propertyKey;
const newKey = targetKey || "";
Object.defineProperty(target, newKey, {
get: /* @__PURE__ */ __name(function() {
return this[key].value;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
if (typeof this[key]?.value?.equals === "function") {
if (this[key].value.equals(value)) {
return;
}
}
if (this[key].value === value) {
return;
}
this[key].value = value;
target[setCallback].apply(this);
}, "set"),
enumerable: true,
configurable: true
});
};
}
var init_decorators = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.js"() {
init_decorators_functions();
__name(generateSerializableMember, "generateSerializableMember");
__name(generateExpandMember, "generateExpandMember");
__name(expandToProperty, "expandToProperty");
__name(serialize, "serialize");
__name(serializeAsTexture, "serializeAsTexture");
__name(serializeAsColor3, "serializeAsColor3");
__name(serializeAsFresnelParameters, "serializeAsFresnelParameters");
__name(serializeAsVector2, "serializeAsVector2");
__name(serializeAsVector3, "serializeAsVector3");
__name(serializeAsMeshReference, "serializeAsMeshReference");
__name(serializeAsColorCurves, "serializeAsColorCurves");
__name(serializeAsColor4, "serializeAsColor4");
__name(serializeAsImageProcessingConfiguration, "serializeAsImageProcessingConfiguration");
__name(serializeAsQuaternion, "serializeAsQuaternion");
__name(serializeAsMatrix, "serializeAsMatrix");
__name(serializeAsCameraReference, "serializeAsCameraReference");
__name(nativeOverride, "nativeOverride");
nativeOverride.filter = function(predicate) {
return (target, propertyKey, descriptor) => nativeOverride(target, propertyKey, descriptor, predicate);
};
__name(addAccessorsForMaterialProperty, "addAccessorsForMaterialProperty");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/guid.js
function RandomGUID() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0, v = c === "x" ? r : r & 3 | 8;
return v.toString(16);
});
}
var GUID;
var init_guid = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/guid.js"() {
__name(RandomGUID, "RandomGUID");
GUID = {
/**
* 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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
RandomId: RandomGUID
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/thinTexture.js
var ThinTexture;
var init_thinTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/thinTexture.js"() {
init_math_size();
ThinTexture = class _ThinTexture {
static {
__name(this, "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 !== void 0;
}
/**
* 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;
this.wrapR = 1;
this.anisotropicFilteringLevel = 4;
this.delayLoadState = 0;
this._texture = null;
this._engine = null;
this._cachedSize = Size.Zero();
this._cachedBaseSize = Size.Zero();
this._initialSamplingMode = 2;
this._texture = _ThinTexture._IsRenderTargetWrapper(internalTexture) ? internalTexture.texture : internalTexture;
if (this._texture) {
this._engine = this._texture.getEngine();
this.wrapU = this._texture._cachedWrapU ?? this.wrapU;
this.wrapV = this._texture._cachedWrapV ?? this.wrapV;
this.wrapR = this._texture._cachedWrapR ?? this.wrapR;
}
}
/**
* 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
*@param generateMipMaps Define if the texture should generate mip maps or not. Default is false.
*/
updateSamplingMode(samplingMode, generateMipMaps = false) {
if (this._texture && this._engine) {
this._engine.updateTextureSamplingMode(samplingMode, this._texture, this._texture.generateMipMaps && generateMipMaps);
}
}
/**
* 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;
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/andOrNotEvaluator.js
var AndOrNotEvaluator;
var init_andOrNotEvaluator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/andOrNotEvaluator.js"() {
AndOrNotEvaluator = class _AndOrNotEvaluator {
static {
__name(this, "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) => {
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) {
ori = "false";
break;
}
}
}
if (result || ori === "true") {
result = true;
break;
}
if (ori !== "true" && ori !== "false") {
if (ori[0] === "!") {
result = !evaluateCallback(ori.substring(1));
} else {
result = evaluateCallback(ori);
}
} else {
result = ori === "true" ? true : false;
}
}
}
return result ? "true" : "false";
}
static _SimplifyNegation(booleanString) {
booleanString = booleanString.replace(/^[\s!]+/, (r) => {
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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tags.js
var Tags;
var init_tags = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tags.js"() {
init_andOrNotEvaluator();
Tags = class _Tags {
static {
__name(this, "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(" ");
for (const tag of tags) {
_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 === void 0) {
return true;
}
if (tagsQuery === "") {
return _Tags.HasTags(obj);
}
return AndOrNotEvaluator.Eval(tagsQuery, (r) => _Tags.HasTags(obj) && obj._tags[r]);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.serialization.js
var CopySource, SerializationHelper;
var init_decorators_serialization = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.serialization.js"() {
init_devTools();
init_tags();
init_math_color();
init_math_vector();
init_decorators_functions();
CopySource = /* @__PURE__ */ __name(function(creationFunction, source, instanciate, options = {}) {
const destination = creationFunction();
if (Tags && Tags.HasTags(source)) {
Tags.AddTagsTo(destination, Tags.GetTags(source, true));
}
const classStore = GetMergedStore(destination);
const textureMap = {};
for (const property in classStore) {
const propertyDescriptor = classStore[property];
const sourceProperty = source[property];
const propertyType = propertyDescriptor.type;
if (sourceProperty !== void 0 && sourceProperty !== null && (property !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId)) {
switch (propertyType) {
case 0:
// Value
case 6:
// Mesh reference
case 9:
// Image processing configuration reference
case 11:
destination[property] = sourceProperty;
break;
case 1:
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:
destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
break;
}
}
}
return destination;
}, "CopySource");
SerializationHelper = class _SerializationHelper {
static {
__name(this, "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 = {};
}
if (Tags) {
serializationObject.tags = Tags.GetTags(entity);
}
const serializedProperties = GetMergedStore(entity);
for (const property in serializedProperties) {
const propertyDescriptor = serializedProperties[property];
const targetPropertyName = propertyDescriptor.sourceName || property;
const propertyType = propertyDescriptor.type;
const sourceProperty = entity[property];
if (sourceProperty !== void 0 && sourceProperty !== null && (property !== "uniqueId" || _SerializationHelper.AllowLoadingUniqueId)) {
switch (propertyType) {
case 0:
if (Array.isArray(sourceProperty)) {
serializationObject[targetPropertyName] = sourceProperty.slice();
} else {
serializationObject[targetPropertyName] = sourceProperty;
}
break;
case 1:
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 2:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 3:
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 4:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 5:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 6:
serializationObject[targetPropertyName] = sourceProperty.id;
break;
case 7:
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 8:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 9:
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 10:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 11:
serializationObject[targetPropertyName] = sourceProperty.id;
break;
case 12:
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);
for (const property in classStore) {
const propertyDescriptor = classStore[property];
const sourceProperty = source[propertyDescriptor.sourceName || property];
const propertyType = propertyDescriptor.type;
if (sourceProperty !== void 0 && sourceProperty !== null && (property !== "uniqueId" || _SerializationHelper.AllowLoadingUniqueId)) {
const dest = destination;
switch (propertyType) {
case 0:
dest[property] = sourceProperty;
break;
case 1:
if (scene) {
dest[property] = _SerializationHelper._TextureParser(sourceProperty, scene, rootUrl);
}
break;
case 2:
dest[property] = Color3.FromArray(sourceProperty);
break;
case 3:
dest[property] = _SerializationHelper._FresnelParametersParser(sourceProperty);
break;
case 4:
dest[property] = Vector2.FromArray(sourceProperty);
break;
case 5:
dest[property] = Vector3.FromArray(sourceProperty);
break;
case 6:
if (scene) {
dest[property] = scene.getLastMeshById(sourceProperty);
}
break;
case 7:
dest[property] = _SerializationHelper._ColorCurvesParser(sourceProperty);
break;
case 8:
dest[property] = Color4.FromArray(sourceProperty);
break;
case 9:
dest[property] = _SerializationHelper._ImageProcessingConfigurationParser(sourceProperty);
break;
case 10:
dest[property] = Quaternion.FromArray(sourceProperty);
break;
case 11:
if (scene) {
dest[property] = scene.getCameraById(sourceProperty);
}
break;
case 12:
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();
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);
}
};
SerializationHelper.AllowLoadingUniqueId = false;
SerializationHelper._ImageProcessingConfigurationParser = (sourceProperty) => {
throw _WarnImport("ImageProcessingConfiguration");
};
SerializationHelper._FresnelParametersParser = (sourceProperty) => {
throw _WarnImport("FresnelParameters");
};
SerializationHelper._ColorCurvesParser = (sourceProperty) => {
throw _WarnImport("ColorCurves");
};
SerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => {
throw _WarnImport("Texture");
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/baseTexture.js
var BaseTexture;
var init_baseTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/baseTexture.js"() {
init_tslib_es6();
init_decorators();
init_observable();
init_math_vector();
init_engineStore();
init_guid();
init_fileTools();
init_thinTexture();
init_decorators_serialization();
BaseTexture = class _BaseTexture extends ThinTexture {
static {
__name(this, "BaseTexture");
}
/**
* 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;
}
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;
}
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);
this.metadata = null;
this.reservedDataStore = null;
this._hasAlpha = false;
this._getAlphaFromRGB = false;
this.level = 1;
this._coordinatesIndex = 0;
this.optimizeUVAllocation = true;
this._coordinatesMode = 0;
this.wrapR = 1;
this.anisotropicFilteringLevel = _BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
this._isCube = false;
this._gammaSpace = true;
this.invertZ = false;
this.lodLevelInAlpha = false;
this._dominantDirection = null;
this.isRenderTarget = false;
this._prefiltered = false;
this._forceSerialize = false;
this.animations = [];
this.onDisposeObservable = new Observable();
this._onDisposeObserver = null;
this._scene = null;
this._uid = null;
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 === void 0 || correctedUseSRGBBuffer === texturesCacheEntry._useSRGBBuffer) {
if (invertY === void 0 || invertY === texturesCacheEntry.invertY) {
if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
if (!sampling || sampling === texturesCacheEntry.samplingMode) {
if (isCube === void 0 || 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 !== void 0 ? this._texture.type : 0;
}
/**
* Get the texture underlying format (RGB, RGBA...)
*/
get textureFormat() {
if (!this._texture) {
return 5;
}
return this._texture.format !== void 0 ? 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) {
if (this._scene.stopAnimation) {
this._scene.stopAnimation(this);
}
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 index2 = this._parentContainer.textures.indexOf(this);
if (index2 > -1) {
this._parentContainer.textures.splice(index2, 1);
}
this._parentContainer = null;
}
}
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);
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";
}
};
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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/instantiationTools.js
var InstantiationTools;
var init_instantiationTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/instantiationTools.js"() {
init_logger();
init_typeStore();
InstantiationTools = class {
static {
__name(this, "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(className2) {
if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[className2]) {
return this.RegisteredExternalClasses[className2];
}
const internalClass = GetClass(className2);
if (internalClass) {
return internalClass;
}
Logger.Warn(className2 + " not found, you may have missed an import.");
const arr = className2.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;
}
};
InstantiationTools.RegisteredExternalClasses = {};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/copyTools.js
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");
}
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);
}
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);
}
var CopyTools;
var init_copyTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/copyTools.js"() {
__name(GenerateBase64StringFromPixelData, "GenerateBase64StringFromPixelData");
__name(GenerateBase64StringFromTexture, "GenerateBase64StringFromTexture");
__name(GenerateBase64StringFromTextureAsync, "GenerateBase64StringFromTextureAsync");
CopyTools = {
/**
* 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
*/
GenerateBase64StringFromPixelData,
/**
* 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
*/
GenerateBase64StringFromTexture,
/**
* 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
*/
GenerateBase64StringFromTextureAsync
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Compat/compatibilityOptions.js
function setOpenGLOrientationForUV(value) {
useOpenGLOrientationForUV = value;
}
var useOpenGLOrientationForUV, CompatibilityOptions;
var init_compatibilityOptions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Compat/compatibilityOptions.js"() {
useOpenGLOrientationForUV = false;
__name(setOpenGLOrientationForUV, "setOpenGLOrientationForUV");
CompatibilityOptions = {
/* eslint-disable @typescript-eslint/naming-convention */
get UseOpenGLOrientationForUV() {
return useOpenGLOrientationForUV;
},
set UseOpenGLOrientationForUV(value) {
useOpenGLOrientationForUV = value;
}
/* eslint-enable @typescript-eslint/naming-convention */
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/texture.js
var Texture;
var init_texture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/texture.js"() {
init_tslib_es6();
init_decorators();
init_observable();
init_math_vector();
init_baseTexture();
init_typeStore();
init_devTools();
init_timingTools();
init_instantiationTools();
init_math_plane();
init_stringTools();
init_copyTools();
init_compatibilityOptions();
init_decorators_serialization();
Texture = class _Texture extends BaseTexture {
static {
__name(this, "Texture");
}
/**
* @internal
*/
static _CreateVideoTexture(name260, 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);
this.url = null;
this.uOffset = 0;
this.vOffset = 0;
this.uScale = 1;
this.vScale = 1;
this.uAng = 0;
this.vAng = 0;
this.wAng = 0;
this.uRotationCenter = 0.5;
this.vRotationCenter = 0.5;
this.wRotationCenter = 0.5;
this.homogeneousRotationInUVTransform = false;
this.inspectableCustomProperties = null;
this._noMipmap = false;
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;
this._buffer = null;
this._deleteBuffer = false;
this._format = null;
this._delayedOnLoad = null;
this._delayedOnError = null;
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 ?? !useOpenGLOrientationForUV;
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 === void 0 ? !useOpenGLOrientationForUV : 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 !== void 0) {
this._format = format;
}
const scene = this.getScene();
const engine = this._getEngine();
if (!engine) {
return;
}
engine.onBeforeTextureInitObservable.notifyObservers(this);
const load = /* @__PURE__ */ __name(() => {
if (this._texture) {
if (this._texture._invertVScale) {
this.vScale *= -1;
this.vOffset += 1;
}
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();
}
}, "load");
const errorHandler = /* @__PURE__ */ __name((message, exception) => {
this._loadingError = true;
this._errorObject = { message, exception };
if (onError) {
onError(message, exception);
}
_Texture.OnTextureLoadErrorObservable.notifyObservers(this);
}, "errorHandler");
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, void 0, 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;
const existingOnLoad = this._delayedOnLoad;
const load = /* @__PURE__ */ __name(() => {
if (existingOnLoad) {
existingOnLoad();
} else if (this.onLoadObservable.hasObservers()) {
this.onLoadObservable.notifyObservers(this);
}
if (onLoad) {
onLoad();
}
}, "load");
this._delayedOnLoad = load;
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;
}
let url = this.url;
if (!url && (this.name.indexOf("://") > 0 || this.name.startsWith("data:"))) {
url = this.name;
}
this.delayLoadState = 1;
this._texture = this._getFromCache(url, this._noMipmap, this.samplingMode, this._invertY, this._useSRGBBuffer, this.isCube);
if (!this._texture) {
this._texture = scene.getEngine().createTexture(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);
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, this._t1);
this._prepareRowForTextureGeneration(0, 1, 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, this._t2.x, this._t2.y, this._t2.z, 0, this._t0.x, this._t0.y, this._t0.z, 0, 0, 0, 0, 1, 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) {
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.5, 0, 0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 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) {
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: void 0,
onError: void 0,
buffer: this._texture ? this._texture._buffer : void 0,
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.startsWith("data:")) {
serializationObject.base64String = this._buffer;
serializationObject.name = serializationObject.name.replace("data:", "");
} else if (this.url && this.url.startsWith("data:") && this._buffer instanceof Uint8Array) {
const mimeType = this.mimeType || "image/png";
serializationObject.base64String = `data:${mimeType};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);
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 !== void 0;
if (!parsedTexture.name && !parsedTexture.isRenderTarget && !hasInternalTextureUniqueId) {
return null;
}
let internalTexture;
if (hasInternalTextureUniqueId) {
const cache = scene.getEngine().getLoadedTexturesCache();
for (const texture2 of cache) {
if (texture2.uniqueId === parsedTexture.internalTextureUniqueId) {
internalTexture = texture2;
break;
}
}
}
const onLoaded = /* @__PURE__ */ __name((texture2) => {
if (texture2 && texture2._texture) {
texture2._texture._cachedWrapU = null;
texture2._texture._cachedWrapV = null;
texture2._texture._cachedWrapR = null;
}
if (parsedTexture.samplingMode) {
const sampling = parsedTexture.samplingMode;
if (texture2 && texture2.samplingMode !== sampling) {
texture2.updateSamplingMode(sampling);
}
}
if (texture2 && parsedTexture.animations) {
for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
const parsedAnimation = parsedTexture.animations[animationIndex];
const internalClass = GetClass("BABYLON.Animation");
if (internalClass) {
texture2.animations.push(internalClass.Parse(parsedAnimation));
}
}
}
if (texture2 && texture2._texture) {
if (hasInternalTextureUniqueId && !internalTexture) {
texture2._texture._setUniqueId(parsedTexture.internalTextureUniqueId);
}
texture2._texture.label = parsedTexture.internalTextureLabel;
}
}, "onLoaded");
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 && !parsedTexture.base64String) {
let renderTargetTexture = null;
if (parsedTexture.isCube) {
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 texture2 = _Texture._CreateVideoTexture(rootUrl + (parsedTexture.url || parsedTexture.name), rootUrl + (parsedTexture.src || parsedTexture.url), scene, generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, parsedTexture.settings || {});
onLoaded(texture2);
return texture2;
} else {
let texture2;
if (parsedTexture.base64String && !internalTexture) {
texture2 = _Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.base64String, scene, !generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, () => {
onLoaded(texture2);
}, parsedTexture._creationFlags ?? 0, parsedTexture._useSRGBBuffer ?? false);
texture2.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: /* @__PURE__ */ __name(() => {
onLoaded(texture2);
}, "onLoad"),
internalTexture
};
texture2 = new _Texture(url, scene, options);
}
return texture2;
}
}, 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, name260, scene, noMipmapOrOptions, invertY, samplingMode = _Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) {
return new _Texture("data:" + name260, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, data, false, format, void 0, void 0, 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(name260, buffer, scene, deleteBuffer = false, noMipmapOrOptions, invertY = true, samplingMode = _Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) {
if (name260.substring(0, 5) !== "data:") {
name260 = "data:" + name260;
}
return new _Texture(name260, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format, void 0, void 0, creationFlags, forcedExtension);
}
};
Texture.SerializeBuffers = true;
Texture.ForceSerializeBuffers = false;
Texture.OnTextureLoadErrorObservable = new Observable();
Texture._SerializeInternalTextureUniqueId = false;
Texture._CubeTextureParser = (jsonTexture, scene, rootUrl) => {
throw _WarnImport("CubeTexture");
};
Texture._CreateMirror = (name260, renderTargetSize, scene, generateMipMaps) => {
throw _WarnImport("MirrorTexture");
};
Texture._CreateRenderTargetTexture = (name260, renderTargetSize, scene, generateMipMaps, creationFlags) => {
throw _WarnImport("RenderTargetTexture");
};
Texture.NEAREST_SAMPLINGMODE = 1;
Texture.NEAREST_NEAREST_MIPLINEAR = 8;
Texture.BILINEAR_SAMPLINGMODE = 2;
Texture.LINEAR_LINEAR_MIPNEAREST = 11;
Texture.TRILINEAR_SAMPLINGMODE = 3;
Texture.LINEAR_LINEAR_MIPLINEAR = 3;
Texture.NEAREST_NEAREST_MIPNEAREST = 4;
Texture.NEAREST_LINEAR_MIPNEAREST = 5;
Texture.NEAREST_LINEAR_MIPLINEAR = 6;
Texture.NEAREST_LINEAR = 7;
Texture.NEAREST_NEAREST = 1;
Texture.LINEAR_NEAREST_MIPNEAREST = 9;
Texture.LINEAR_NEAREST_MIPLINEAR = 10;
Texture.LINEAR_LINEAR = 2;
Texture.LINEAR_NEAREST = 12;
Texture.EXPLICIT_MODE = 0;
Texture.SPHERICAL_MODE = 1;
Texture.PLANAR_MODE = 2;
Texture.CUBIC_MODE = 3;
Texture.PROJECTION_MODE = 4;
Texture.SKYBOX_MODE = 5;
Texture.INVCUBIC_MODE = 6;
Texture.EQUIRECTANGULAR_MODE = 7;
Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
Texture.CLAMP_ADDRESSMODE = 0;
Texture.WRAP_ADDRESSMODE = 1;
Texture.MIRROR_ADDRESSMODE = 2;
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);
RegisterClass("BABYLON.Texture", Texture);
SerializationHelper._TextureParser = Texture.Parse;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/drawWrapper.functions.js
function IsWrapper(effect) {
return effect.getPipelineContext === void 0;
}
var init_drawWrapper_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/drawWrapper.functions.js"() {
__name(IsWrapper, "IsWrapper");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLShaderProcessors.js
var WebGLShaderProcessor;
var init_webGLShaderProcessors = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLShaderProcessors.js"() {
WebGLShaderProcessor = class {
static {
__name(this, "WebGLShaderProcessor");
}
constructor() {
this.shaderLanguage = 0;
}
postProcessor(code, defines, isFragment, processingContext, parameters) {
if (parameters.drawBuffersExtensionDisabled) {
const regex = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g;
code = code.replace(regex, "");
}
return code;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGL2ShaderProcessors.js
var VaryingRegex, WebGL2ShaderProcessor;
var init_webGL2ShaderProcessors = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGL2ShaderProcessors.js"() {
VaryingRegex = /(flat\s)?\s*varying\s*.*/;
WebGL2ShaderProcessor = class {
static {
__name(this, "WebGL2ShaderProcessor");
}
constructor() {
this.shaderLanguage = 0;
}
attributeProcessor(attribute) {
return attribute.replace("attribute", "in");
}
varyingCheck(varying, _isFragment) {
return VaryingRegex.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;
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, "");
code = code.replace(/texture2D\s*\(/g, "texture(");
if (isFragment) {
const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1;
const hasDualSourceBlending = defines.indexOf("#define DUAL_SOURCE_BLENDING") !== -1;
const outputDeclaration = hasDualSourceBlending ? "layout(location = 0, index = 0) out vec4 glFragColor;\nlayout(location = 0, index = 1) out vec4 glFragColor2;\n" : "layout(location = 0) out vec4 glFragColor;\n";
if (hasDualSourceBlending) {
code = "#extension GL_EXT_blend_func_extended : require\n" + code;
}
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 ? "" : outputDeclaration) + "void main(");
} else {
if (defines.indexOf("#define VERTEXOUTPUT_INVARIANT") >= 0) {
code = "invariant gl_Position;\n" + code;
}
const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1;
if (hasMultiviewExtension) {
return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code;
}
}
return code;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/dataBuffer.js
var DataBuffer;
var init_dataBuffer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/dataBuffer.js"() {
DataBuffer = class _DataBuffer {
static {
__name(this, "DataBuffer");
}
/**
* Gets the underlying buffer
*/
get underlyingResource() {
return null;
}
/**
* Constructs the buffer
*/
constructor() {
this.references = 0;
this.capacity = 0;
this.is32Bits = false;
this.uniqueId = _DataBuffer._Counter++;
}
};
DataBuffer._Counter = 0;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/WebGL/webGLDataBuffer.js
var WebGLDataBuffer;
var init_webGLDataBuffer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/WebGL/webGLDataBuffer.js"() {
init_dataBuffer();
WebGLDataBuffer = class extends DataBuffer {
static {
__name(this, "WebGLDataBuffer");
}
constructor(resource) {
super();
this._buffer = resource;
}
get underlyingResource() {
return this._buffer;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tools.functions.js
function IsExponentOfTwo(value) {
let count = 1;
do {
count *= 2;
} while (count < value);
return count === value;
}
function Mix(a, b, alpha) {
return a * (1 - alpha) + b * alpha;
}
function NearestPOT(x) {
const c = CeilingPOT(x);
const f = FloorPOT(x);
return c - x > x - f ? f : c;
}
function CeilingPOT(x) {
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
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);
}
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);
}
var init_tools_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tools.functions.js"() {
__name(IsExponentOfTwo, "IsExponentOfTwo");
__name(Mix, "Mix");
__name(NearestPOT, "NearestPOT");
__name(CeilingPOT, "CeilingPOT");
__name(FloorPOT, "FloorPOT");
__name(GetExponentOfTwo, "GetExponentOfTwo");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLHardwareTexture.js
var WebGLHardwareTexture;
var init_webGLHardwareTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLHardwareTexture.js"() {
WebGLHardwareTexture = class {
static {
__name(this, "WebGLHardwareTexture");
}
get underlyingResource() {
return this._webGLTexture;
}
constructor(existingTexture = null, context) {
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();
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureHelper.functions.js
function IsDepthTexture(format) {
return format === 13 || format === 14 || format === 15 || format === 16 || format === 17 || format === 18 || format === 19;
}
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;
}
function HasStencilAspect(format) {
return format === 13 || format === 17 || format === 18 || format === 19;
}
var init_textureHelper_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureHelper.functions.js"() {
__name(IsDepthTexture, "IsDepthTexture");
__name(GetTypeForDepthTexture, "GetTypeForDepthTexture");
__name(HasStencilAspect, "HasStencilAspect");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/thinEngine.js
var thinEngine_exports = {};
__export(thinEngine_exports, {
ThinEngine: () => ThinEngine
});
var BufferPointer, ThinEngine;
var init_thinEngine = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/thinEngine.js"() {
init_thinEngine_functions();
init_drawWrapper_functions();
init_logger();
init_domManagement();
init_webGLShaderProcessors();
init_webGL2ShaderProcessors();
init_webGLDataBuffer();
init_tools_functions();
init_abstractEngine();
init_webGLHardwareTexture();
init_internalTexture();
init_effect();
init_abstractEngine_functions();
init_effect_functions();
init_textureHelper_functions();
init_alphaCullingState();
BufferPointer = class {
static {
__name(this, "BufferPointer");
}
};
ThinEngine = class _ThinEngine extends AbstractEngine {
static {
__name(this, "ThinEngine");
}
/**
* 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);
this._name = "WebGL";
this.forcePOTTextures = false;
this.validateShaderPrograms = false;
this.disableUniformBuffers = false;
this._webGLVersion = 1;
this._vertexAttribArraysEnabled = [];
this._uintIndicesCurrentlySet = false;
this._currentBoundBuffer = new Array();
this._currentFramebuffer = null;
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;
this.enableUnpackFlipYCached = true;
this._boundUniforms = {};
if (!canvasOrContext) {
return;
}
let canvas = null;
if (canvasOrContext.getContext) {
canvas = canvasOrContext;
if (options.preserveDrawingBuffer === void 0) {
options.preserveDrawingBuffer = false;
}
if (options.xrCompatible === void 0) {
options.xrCompatible = false;
}
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;
}
}
}
}
}
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;
}
if (!options.disableWebGL2Support) {
try {
this._gl = canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options);
if (this._gl) {
this._webGLVersion = 2;
this._shaderPlatformName = "WEBGL2";
if (!this._gl.deleteQuery) {
this._webGLVersion = 1;
this._shaderPlatformName = "WEBGL1";
}
}
} catch (e) {
}
}
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;
this._shaderPlatformName = "WEBGL2";
} else {
this._shaderPlatformName = "WEBGL1";
}
const attributes = this._gl.getContextAttributes();
if (attributes) {
options.stencil = attributes.stencil;
}
}
this._sharedInit(canvas);
this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
if (options.useHighPrecisionFloats !== void 0) {
this._highPrecisionShadersAllowed = options.useHighPrecisionFloats;
}
this.resize();
this._initGLContext();
this._initFeatures();
for (let i = 0; i < this._caps.maxVertexAttribs; i++) {
this._currentBufferPointers[i] = new BufferPointer();
}
this._shaderProcessor = this.webGLVersion > 1 ? new WebGL2ShaderProcessor() : new WebGLShaderProcessor();
const versionToLog = `Babylon.js v${_ThinEngine.Version}`;
Logger.Log(versionToLog + ` - ${this.description}`);
if (this._renderingCanvas && this._renderingCanvas.setAttribute) {
this._renderingCanvas.setAttribute("data-engine", versionToLog);
}
const stateObject = getStateObject(this._gl);
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() {
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),
shaderFloatPrecision: 0,
parallelShaderCompile: this._gl.getExtension("KHR_parallel_shader_compile") || void 0,
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")),
blendFloat: this._gl.getExtension("EXT_float_blend") !== null,
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,
blendParametersPerTarget: false,
dualSourceBlending: false
};
this._caps.supportFloatTexturesResolve = this._caps.colorBufferFloat;
this._caps.rg11b10ufColorRenderable = this._caps.colorBufferFloat;
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";
}
if (this._gl.HALF_FLOAT_OES !== 36193) {
this._gl.HALF_FLOAT_OES = 36193;
}
if (this._gl.RGBA16F !== 34842) {
this._gl.RGBA16F = 34842;
}
if (this._gl.RGBA32F !== 34836) {
this._gl.RGBA32F = 34836;
}
if (this._gl.DEPTH24_STENCIL8 !== 35056) {
this._gl.DEPTH24_STENCIL8 = 35056;
}
if (this._caps.timerQuery) {
if (this._webGLVersion === 1) {
this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
}
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 = 33322;
this._gl.RG16_EXT = 33324;
this._gl.RGB16_EXT = 32852;
this._gl.RGBA16_EXT = 32859;
this._gl.R16_SNORM_EXT = 36760;
this._gl.RG16_SNORM_EXT = 36761;
this._gl.RGB16_SNORM_EXT = 36762;
this._gl.RGBA16_SNORM_EXT = 36763;
}
const oesDrawBuffersIndexed = this._gl.getExtension("OES_draw_buffers_indexed");
this._caps.blendParametersPerTarget = oesDrawBuffersIndexed ? true : false;
this._alphaState = new AlphaState(this._caps.blendParametersPerTarget);
if (oesDrawBuffersIndexed) {
this._gl.blendEquationSeparateIndexed = oesDrawBuffersIndexed.blendEquationSeparateiOES.bind(oesDrawBuffersIndexed);
this._gl.blendEquationIndexed = oesDrawBuffersIndexed.blendEquationiOES.bind(oesDrawBuffersIndexed);
this._gl.blendFuncSeparateIndexed = oesDrawBuffersIndexed.blendFuncSeparateiOES.bind(oesDrawBuffersIndexed);
this._gl.blendFuncIndexed = oesDrawBuffersIndexed.blendFunciOES.bind(oesDrawBuffersIndexed);
this._gl.colorMaskIndexed = oesDrawBuffersIndexed.colorMaskiOES.bind(oesDrawBuffersIndexed);
this._gl.disableIndexed = oesDrawBuffersIndexed.disableiOES.bind(oesDrawBuffersIndexed);
this._gl.enableIndexed = oesDrawBuffersIndexed.enableiOES.bind(oesDrawBuffersIndexed);
}
this._caps.dualSourceBlending = this._gl.getExtension("WEBGL_blend_func_extended") ? true : false;
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;
}
if (this._webGLVersion > 1) {
if (this._gl.HALF_FLOAT_OES !== 5131) {
this._gl.HALF_FLOAT_OES = 5131;
}
}
this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
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"];
}
}
}
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;
}
}
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);
}
}
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;
this._caps.shaderFloatPrecision = Math.min(vertexhighp.precision, fragmenthighp.precision);
}
if (!this._shouldUseHighPrecisionShader) {
const vertexmedp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.MEDIUM_FLOAT);
const fragmentmedp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.MEDIUM_FLOAT);
if (vertexmedp && fragmentmedp) {
this._caps.shaderFloatPrecision = Math.min(vertexmedp.precision, fragmentmedp.precision);
}
}
if (this._caps.shaderFloatPrecision < 10) {
this._caps.shaderFloatPrecision = 10;
}
}
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;
}
}
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
};
}
}
if (this._creationOptions) {
const forceSRGBBufferSupportState = this._creationOptions.forceSRGBBufferSupportState;
if (forceSRGBBufferSupportState !== void 0) {
this._caps.supportSRGBBuffers = this._caps.supportSRGBBuffers && forceSRGBBufferSupportState;
}
}
}
this._depthCullingState.depthTest = true;
this._depthCullingState.depthFunc = this._gl.LEQUAL;
this._depthCullingState.depthMask = true;
this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
this._nextFreeTextureSlots.push(slot);
}
if (this._glRenderer === "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
* @param stencilClearValue defines the value to use to clear the stencil buffer (default is 0)
*/
clear(color, backBuffer, depth, stencil = false, stencilClearValue = 0) {
const useStencilGlobalOnly = this.stencilStateComposer.useStencilGlobalOnly;
this.stencilStateComposer.useStencilGlobalOnly = true;
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 !== void 0 ? color.a : 1);
mode |= this._gl.COLOR_BUFFER_BIT;
}
}
if (depth) {
if (this.useReverseDepthBuffer) {
this._depthCullingState.depthFunc = this._gl.GEQUAL;
this._gl.clearDepth(0);
} else {
this._gl.clearDepth(1);
}
mode |= this._gl.DEPTH_BUFFER_BIT;
}
if (stencil) {
this._gl.clearStencil(stencilClearValue);
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();
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._resolveAndGenerateMipMapsFramebuffer(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) {
if (this._depthCullingState.cull !== culling || force) {
this._depthCullingState.cull = culling;
}
this.setStateCullFaceType(cullBackFaces, force);
this.setZOffset(zOffset);
this.setZOffsetUnits(zOffsetUnits);
const frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
if (this._depthCullingState.frontFace !== frontFace || force) {
this._depthCullingState.frontFace = frontFace;
}
this._stencilStateComposer.stencilMaterial = stencil;
}
_resolveAndGenerateMipMapsFramebuffer(texture, disableGenerateMipMaps = false) {
const webglRtWrapper = texture;
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);
}
}
}
/**
* @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, onBeforeUnbind) {
const webglRtWrapper = texture;
this._currentRenderTarget = null;
this._resolveAndGenerateMipMapsFramebuffer(texture, disableGenerateMipMaps);
if (onBeforeUnbind) {
if (webglRtWrapper._MSAAFramebuffer) {
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;
}
if (this._caps.uintIndices) {
if (indices instanceof Uint32Array) {
return indices;
} else {
for (let index = 0; index < indices.length; index++) {
if (indices[index] >= 65535) {
return new Uint32Array(indices);
}
}
return new Uint16Array(indices);
}
}
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 !== void 0) {
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 === void 0) {
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 === void 0 ? 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(name260) {
if (!this._currentEffect) {
return;
}
const attributeLocation = this._currentEffect.getAttributeLocationByName(name260);
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) {
this.applyStates();
this._reportDrawCall();
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) {
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) {
if (this._currentProgram === webGLPipelineContext.program) {
this._setProgram(null);
}
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, 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 !== void 0;
let fullDefines = defines ?? attributesNamesOrOptions.defines ?? "";
if (globalDefines) {
fullDefines += globalDefines;
}
const name260 = vertex + "+" + fragment + "@" + fullDefines;
if (this._compiledEffects[name260]) {
const compiledEffect = this._compiledEffects[name260];
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, name260, attributesNamesOrOptions.shaderLanguage ?? shaderLanguage, attributesNamesOrOptions.extraInitializationsAsync ?? extraInitializationsAsync);
this._compiledEffects[name260] = effect;
return effect;
}
/**
* @internal
*/
_getShaderSource(shader260) {
return this._gl.getShaderSource(shader260);
}
/**
* 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);
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) {
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, shaderProcessingContext);
context.engine = this;
return context;
}
/**
* Creates a new material context
* @returns the new context
*/
createMaterialContext() {
return void 0;
}
/**
* Creates a new draw context
* @returns the new context
*/
createDrawContext() {
return void 0;
}
_finalizePipelineContext(pipelineContext) {
return _finalizePipelineContext(pipelineContext, this._gl, this.validateShaderPrograms);
}
/**
* @internal
*/
// named async but not actually an async function
// eslint-disable-next-line no-restricted-syntax
_preparePipelineContextAsync(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;
if (!effect || effect === this._currentEffect) {
return;
}
this._stencilStateComposer.stencilMaterial = void 0;
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, this._currentRenderTarget && this._currentRenderTarget.textures ? this._currentRenderTarget.textures.length : 1);
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;
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._resetAlphaMode();
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;
let hasMipMaps = false;
switch (samplingMode) {
case 11:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_NEAREST;
} else {
minFilter = gl.LINEAR;
}
break;
case 3:
magFilter = gl.LINEAR;
hasMipMaps = true;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_LINEAR;
} else {
minFilter = gl.LINEAR;
}
break;
case 8:
hasMipMaps = true;
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:
hasMipMaps = true;
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:
hasMipMaps = true;
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,
hasMipMaps
};
}
/** @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) {
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 !== void 0 && typeof options === "object") {
generateMipMaps = !!options.generateMipMaps;
createMipMaps = !!options.createMipMaps;
type = options.type === void 0 ? 0 : options.type;
samplingMode = options.samplingMode === void 0 ? 3 : options.samplingMode;
format = options.format === void 0 ? 5 : options.format;
useSRGBBuffer = options.useSRGBBuffer === void 0 ? 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) {
samplingMode = 1;
} else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
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);
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);
}
}
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,
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) {
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 {
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) {
format = this._getInternalFormat(babylonFormat, useSRGBBuffer);
internalFormat = format;
} else {
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 && filters.hasMipMaps) {
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:
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 {
texture._useSRGBBuffer = false;
}
break;
case 33777:
if (this._caps.s3tc_srgb) {
internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
} else {
texture._useSRGBBuffer = false;
}
break;
case 33779:
if (this._caps.s3tc_srgb) {
internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
} else {
texture._useSRGBBuffer = false;
}
break;
default:
texture._useSRGBBuffer = false;
break;
}
}
if (texture.generateMipMaps) {
const webGLHardwareTexture = texture._hardwareTexture;
if (!webGLHardwareTexture.memoryAllocated) {
gl.texStorage2D(gl.TEXTURE_2D, Math.floor(Math.log2(Math.max(width, height))) + 1, internalFormat, texture.width, texture.height);
webGLHardwareTexture.memoryAllocated = true;
}
this._gl.compressedTexSubImage2D(target, lod, 0, 0, width, height, internalFormat, data);
} else {
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 === void 0 ? 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);
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) {
if (scene) {
scene.removePendingData(texture);
}
return;
}
this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
this._unpackFlipY(invertY === void 0 ? 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);
})) {
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);
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);
this.unbindAllTextures();
const index = this._internalTexturesCache.indexOf(texture);
if (index !== -1) {
this._internalTexturesCache.splice(index, 1);
}
if (texture._lodTextureHigh) {
texture._lodTextureHigh.dispose();
}
if (texture._lodTextureMid) {
texture._lodTextureMid.dispose();
}
if (texture._lodTextureLow) {
texture._lodTextureLow.dispose();
}
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) {
Logger.Error(["_bindTextureDirectly called with a multiview texture!", target, texture]);
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, name260) {
if (channel === void 0) {
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, name260) {
if (channel === void 0) {
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, name260 = "") {
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;
}
if (texture.video) {
this._activeChannel = channel;
const videoInternalTexture = texture.getInternalTexture();
if (videoInternalTexture) {
videoInternalTexture._associatedChannel = channel;
}
texture.update();
} else if (texture.delayLoadState === 4) {
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) {
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, name260) {
if (channel === void 0 || !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;
}
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() {
if (IsWindowObjectExist()) {
if (this._renderingCanvas) {
this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
if (this._onContextRestored) {
this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
}
}
}
super.dispose();
if (this._dummyFramebuffer) {
this._gl.deleteFramebuffer(this._dummyFramebuffer);
}
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();
}
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;
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;
if (successful) {
gl.clear(gl.COLOR_BUFFER_BIT);
successful = successful && gl.getError() === gl.NO_ERROR;
}
if (successful) {
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;
}
gl.deleteTexture(texture);
gl.deleteFramebuffer(fb);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
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:
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 !== void 0) {
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:
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
*/
// Async function, not named Async and not marked as async to avoid breaking changes
// eslint-disable-next-line @typescript-eslint/promise-function-async
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)
*/
// eslint-disable-next-line no-restricted-syntax
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();
}
/**
* 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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
static isSupported() {
if (this._HasMajorPerformanceCaveat !== null) {
return !this._HasMajorPerformanceCaveat;
}
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);
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"] }
];
ThinEngine._ConcatenateShader = _ConcatenateShader;
ThinEngine._IsSupported = null;
ThinEngine._HasMajorPerformanceCaveat = null;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/pass.fragment.js
var pass_fragment_exports = {};
__export(pass_fragment_exports, {
passPixelShader: () => passPixelShader
});
var name5, shader5, passPixelShader;
var init_pass_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/pass.fragment.js"() {
init_shaderStore();
name5 = "passPixelShader";
shader5 = `varying vec2 vUV;uniform sampler2D textureSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(textureSampler,vUV);}`;
if (!ShaderStore.ShadersStore[name5]) {
ShaderStore.ShadersStore[name5] = shader5;
}
passPixelShader = { name: name5, shader: shader5 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/postprocess.vertex.js
var postprocess_vertex_exports = {};
__export(postprocess_vertex_exports, {
postprocessVertexShaderWGSL: () => postprocessVertexShaderWGSL
});
var name6, shader6, postprocessVertexShaderWGSL;
var init_postprocess_vertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/postprocess.vertex.js"() {
init_shaderStore();
name6 = "postprocessVertexShader";
shader6 = `attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}
`;
if (!ShaderStore.ShadersStoreWGSL[name6]) {
ShaderStore.ShadersStoreWGSL[name6] = shader6;
}
postprocessVertexShaderWGSL = { name: name6, shader: shader6 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/postprocess.vertex.js
var postprocess_vertex_exports2 = {};
__export(postprocess_vertex_exports2, {
postprocessVertexShader: () => postprocessVertexShader
});
var name7, shader7, postprocessVertexShader;
var init_postprocess_vertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/postprocess.vertex.js"() {
init_shaderStore();
name7 = "postprocessVertexShader";
shader7 = `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
}`;
if (!ShaderStore.ShadersStore[name7]) {
ShaderStore.ShadersStore[name7] = shader7;
}
postprocessVertexShader = { name: name7, shader: shader7 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/bufferUtils.js
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);
}
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}`);
}
}
}
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}'`);
}
}
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}'`);
}
}
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;
}
}
}
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;
}
function GetTypedArrayData(data, size, type, byteOffset, byteStride, totalVertices, forceCopy) {
const typeByteLength = GetTypeByteLength(type);
const constructor = GetTypedArrayConstructor(type);
const count = totalVertices * size;
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, false, (values, index) => {
for (let i = 0; i < size; i++) {
copy[index + i] = values[i];
}
});
return copy;
}
return new constructor(data.slice(offset, offset + count));
}
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, false, (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);
}
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);
}
}
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;
}
function CreateAlignedTypedArray(type, elementCount) {
let byteSize = elementCount * type.BYTES_PER_ELEMENT;
if ((byteSize & 3) === 0) {
return new type(elementCount);
}
byteSize = byteSize + 3 & ~3;
const backingBuffer = new ArrayBuffer(byteSize);
return new type(backingBuffer, 0, elementCount);
}
var init_bufferUtils = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/bufferUtils.js"() {
init_logger();
__name(GetFloatValue, "GetFloatValue");
__name(SetFloatValue, "SetFloatValue");
__name(GetTypeByteLength, "GetTypeByteLength");
__name(GetTypedArrayConstructor, "GetTypedArrayConstructor");
__name(EnumerateFloatValues, "EnumerateFloatValues");
__name(GetFloatData, "GetFloatData");
__name(GetTypedArrayData, "GetTypedArrayData");
__name(CopyFloatData, "CopyFloatData");
__name(AreIndices32Bits, "AreIndices32Bits");
__name(CreateAlignedTypedArray, "CreateAlignedTypedArray");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/buffer.js
var Buffer2, VertexBuffer;
var init_buffer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/buffer.js"() {
init_dataBuffer();
init_logger();
init_bufferUtils();
Buffer2 = class {
static {
__name(this, "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) {
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) {
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;
return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === void 0 ? this._instanced : instanced, byteOffset, size, void 0, void 0, 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;
}
data = data || this._data;
if (!data) {
return;
}
if (!this._buffer) {
if (this._updatable) {
this._buffer = this._engine.createDynamicVertexBuffer(data, this._label);
this._data = data;
} else {
this._buffer = this._engine.createVertexBuffer(data, void 0, this._label);
}
} else if (this._updatable) {
this._engine.updateDynamicVertexBuffer(this._buffer, data);
this._data = data;
}
}
/** @internal */
_rebuild() {
if (!this._data) {
if (!this._buffer) {
return;
}
if (this._buffer.capacity > 0) {
if (this._updatable) {
this._buffer = this._engine.createDynamicVertexBuffer(this._buffer.capacity, this._label);
} else {
this._buffer = this._engine.createVertexBuffer(this._buffer.capacity, void 0, 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) {
this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : void 0);
if (offset === 0 && vertexCount === void 0) {
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;
}
if (this._engine._releaseBuffer(this._buffer)) {
this._isDisposed = true;
this._data = null;
this._buffer = null;
}
}
};
VertexBuffer = class _VertexBuffer {
static {
__name(this, "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)) {
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) {
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 Buffer2) {
this._buffer = data;
this._ownsBuffer = takeBufferOwnership;
} else {
this._buffer = new Buffer2(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes, divisor, this._label);
this._ownsBuffer = true;
}
this.uniqueId = _VertexBuffer._Counter++;
this._kind = kind;
if (type === void 0) {
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 !== void 0 ? instanced : false;
this._instanceDivisor = instanced ? divisor : 0;
this._alignBuffer();
this._computeHashCode();
}
_computeHashCode() {
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 the raw data from the underlying buffer.
* Note: The data may include more than just this vertex buffer's values.
* @returns the buffer data as a DataArray, or null.
*/
getData() {
return this._buffer.getData();
}
/**
* Gets this vertex 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, void 0, 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;
VertexBuffer.BYTE = 5120;
VertexBuffer.UNSIGNED_BYTE = 5121;
VertexBuffer.SHORT = 5122;
VertexBuffer.UNSIGNED_SHORT = 5123;
VertexBuffer.INT = 5124;
VertexBuffer.UNSIGNED_INT = 5125;
VertexBuffer.FLOAT = 5126;
VertexBuffer.PositionKind = `position`;
VertexBuffer.NormalKind = `normal`;
VertexBuffer.TangentKind = `tangent`;
VertexBuffer.UVKind = `uv`;
VertexBuffer.UV2Kind = `uv2`;
VertexBuffer.UV3Kind = `uv3`;
VertexBuffer.UV4Kind = `uv4`;
VertexBuffer.UV5Kind = `uv5`;
VertexBuffer.UV6Kind = `uv6`;
VertexBuffer.ColorKind = `color`;
VertexBuffer.ColorInstanceKind = `instanceColor`;
VertexBuffer.MatricesIndicesKind = `matricesIndices`;
VertexBuffer.MatricesWeightsKind = `matricesWeights`;
VertexBuffer.MatricesIndicesExtraKind = `matricesIndicesExtra`;
VertexBuffer.MatricesWeightsExtraKind = `matricesWeightsExtra`;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/drawWrapper.js
var DrawWrapper;
var init_drawWrapper = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/drawWrapper.js"() {
init_timingTools();
DrawWrapper = class {
static {
__name(this, "DrawWrapper");
}
/**
* Retrieves the effect from a DrawWrapper or Effect instance.
* @param effect The effect or DrawWrapper instance to retrieve the effect from.
* @returns The effect associated with the given instance, or null if not found.
*/
static GetEffect(effect) {
return effect.getPipelineContext === void 0 ? effect.effect : effect;
}
/**
* Creates a new DrawWrapper instance.
* Note that drawContext is always created (but may end up being undefined if the engine doesn't need draw contexts), but materialContext is optional.
* @param engine The engine to create the draw wrapper for.
* @param createMaterialContext If true, creates a material context for this wrapper (default is true).
*/
constructor(engine, createMaterialContext = true) {
this._wasPreviouslyReady = false;
this._forceRebindOnNextCall = true;
this._wasPreviouslyUsingInstances = null;
this.effect = null;
this.defines = null;
this.drawContext = engine.createDrawContext();
if (createMaterialContext) {
this.materialContext = engine.createMaterialContext();
}
}
/**
* Sets the effect and its associated defines for this wrapper.
* @param effect The effect to associate with this wrapper.
* @param defines The defines to associate with this wrapper.
* @param resetContext If true, resets the draw context (default is true).
*/
setEffect(effect, defines, resetContext = true) {
this.effect = effect;
if (defines !== void 0) {
this.defines = defines;
}
if (resetContext) {
this.drawContext?.reset();
}
}
/**
* Disposes 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();
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effectRenderer.js
var DefaultOptions, EffectRenderer, EffectWrapper;
var init_effectRenderer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effectRenderer.js"() {
init_buffer();
init_math_viewport();
init_observable();
init_effect();
init_drawWrapper();
init_postprocess_vertex2();
DefaultOptions = {
positions: [1, 1, -1, 1, -1, -1, 1, -1],
indices: [0, 1, 2, 0, 2, 3]
};
EffectRenderer = class {
static {
__name(this, "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 = {
// Note, always assumes stride of 2.
[VertexBuffer.PositionKind]: new VertexBuffer(engine, positions, VertexBuffer.PositionKind, false, false, 2)
};
this._indexBuffer = engine.createIndexBuffer(indices);
this._indexBufferLength = indices.length;
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
* @param depthTest Whether to enable depth testing (default: false)
* @param stencilTest Whether to enable stencil testing (default: false)
*/
applyEffectWrapper(effectWrapper, depthTest = false, stencilTest = false) {
this.engine.setState(true);
this.engine.depthCullingState.depthTest = depthTest;
this.engine.stencilState.stencilTest = stencilTest;
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, this._indexBufferLength);
}
_isRenderTargetTexture(texture) {
return texture.renderTarget !== void 0;
}
/**
* 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) {
if (!effectWrapper.effect.isReady()) {
return;
}
this.saveStates();
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;
}
}
};
EffectWrapper = class _EffectWrapper {
static {
__name(this, "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) {
this.alphaMode = 0;
this.onEffectCreatedObservable = new Observable(void 0, true);
this.onApplyObservable = new Observable();
this._shadersLoaded = false;
this._webGPUReady = false;
this._importPromises = [];
this.options = {
...creationOptions,
name: creationOptions.name || "effectWrapper",
engine: creationOptions.engine,
uniforms: creationOptions.uniforms || creationOptions.uniformNames || [],
uniformNames: void 0,
samplers: creationOptions.samplers || creationOptions.samplerNames || [],
samplerNames: void 0,
attributeNames: creationOptions.attributeNames || ["position"],
uniformBuffers: creationOptions.uniformBuffers || [],
defines: creationOptions.defines || "",
useShaderStore: creationOptions.useShaderStore || false,
vertexUrl: creationOptions.vertexUrl || creationOptions.vertexShader || "postprocess",
vertexShader: void 0,
fragmentShader: creationOptions.fragmentShader || "pass",
indexParameters: creationOptions.indexParameters,
blockCompilation: creationOptions.blockCompilation || false,
shaderLanguage: creationOptions.shaderLanguage || 0,
onCompiled: creationOptions.onCompiled || void 0,
extraInitializations: creationOptions.extraInitializations || void 0,
extraInitializationsAsync: creationOptions.extraInitializationsAsync || void 0,
useAsPostProcess: creationOptions.useAsPostProcess ?? false,
allowEmptySourceTexture: creationOptions.allowEmptySourceTexture ?? 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.allowEmptySourceTexture && 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;
this.effect._prepareEffect();
});
}
this._drawWrapper = new DrawWrapper(this.options.engine);
this._webGPUReady = this.options.shaderLanguage === 1;
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;
}
if (useWebGPU && this._webGPUReady) {
list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex(), postprocess_vertex_exports))]));
} else {
list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex2(), postprocess_vertex_exports2))]));
}
}
/** @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 !== void 0) {
extraInitializations(useWebGPU, this._importPromises);
}
if (useWebGPU && this._webGPUReady) {
this.options.shaderLanguage = 1;
}
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 ? void 0 : async () => {
await Promise.all(this._importPromises);
this._shadersLoaded = true;
};
let extraInitializationsAsync;
if (this.options.extraInitializationsAsync) {
extraInitializationsAsync = /* @__PURE__ */ __name(async () => {
waitImportsLoaded?.();
await this.options.extraInitializationsAsync();
}, "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, void 0, onCompiled || this.options.onCompiled, void 0, void 0, void 0, this.options.shaderLanguage, extraInitializationsAsync);
}
this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect);
}
/**
* Binds the data to the effect.
* @param noDefaultBindings if true, the default bindings (scale and alpha mode) will not be set.
*/
bind(noDefaultBindings = false) {
if (this.options.useAsPostProcess && !noDefaultBindings) {
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);
}
};
EffectWrapper.ForceGLSL = false;
EffectWrapper._CustomShaderCodeProcessing = {};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/dumpTools.js
var dumpTools_exports = {};
__export(dumpTools_exports, {
Dispose: () => Dispose,
DumpData: () => DumpData,
DumpDataAsync: () => DumpDataAsync,
DumpFramebuffer: () => DumpFramebuffer,
DumpTools: () => DumpTools
});
async function _CreateDumpResourcesAsync() {
const canvas = EngineStore.LastCreatedEngine?.createCanvas(100, 100) ?? new OffscreenCanvas(100, 100);
if (canvas instanceof OffscreenCanvas) {
Logger.Warn("DumpData: OffscreenCanvas will be used for dumping data. This may result in lossy alpha values.");
}
const { ThinEngine: thinEngineClass } = await Promise.resolve().then(() => (init_thinEngine(), thinEngine_exports));
if (!thinEngineClass.IsSupported) {
if (!canvas.getContext("bitmaprenderer")) {
throw new Error("DumpData: No WebGL or bitmap rendering context available. Cannot dump data.");
}
return { canvas };
}
const options = {
preserveDrawingBuffer: true,
depth: false,
stencil: false,
alpha: true,
premultipliedAlpha: false,
antialias: false,
failIfMajorPerformanceCaveat: false
};
const engine = new thinEngineClass(canvas, false, options);
EngineStore.Instances.pop();
EngineStore.OnEnginesDisposedObservable.add((e) => {
if (engine && e !== engine && !engine.isDisposed && EngineStore.Instances.length === 0) {
Dispose();
}
});
engine.getCaps().parallelShaderCompile = void 0;
const renderer = new EffectRenderer(engine);
const { passPixelShader: passPixelShader2 } = await Promise.resolve().then(() => (init_pass_fragment(), pass_fragment_exports));
const wrapper = new EffectWrapper({
engine,
name: passPixelShader2.name,
fragmentShader: passPixelShader2.shader,
samplerNames: ["textureSampler"]
});
return {
canvas,
dumpEngine: { engine, renderer, wrapper }
};
}
async function _GetDumpResourcesAsync() {
if (!ResourcesPromise) {
ResourcesPromise = _CreateDumpResourcesAsync();
}
return await ResourcesPromise;
}
async function DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) {
const bufferView = await engine.readPixels(0, 0, width, height);
const data = new Uint8Array(bufferView.buffer);
DumpData(width, height, data, successCallback, mimeType, fileName, true, void 0, quality);
}
async function DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) {
if (data instanceof Float32Array) {
const data2 = new Uint8Array(data.length);
let n = data.length;
while (n--) {
const v = data[n];
data2[n] = Math.round(Clamp(v) * 255);
}
data = data2;
}
const resources = await _GetDumpResourcesAsync();
return await new Promise(async (resolve) => {
if (resources.dumpEngine) {
const dumpEngine = resources.dumpEngine;
dumpEngine.engine.setSize(width, height, true);
const texture = dumpEngine.engine.createRawTexture(data, width, height, 5, false, !invertY, 1);
dumpEngine.renderer.setViewport();
dumpEngine.renderer.applyEffectWrapper(dumpEngine.wrapper);
dumpEngine.wrapper.effect._bindTexture("textureSampler", texture);
dumpEngine.renderer.draw();
texture.dispose();
} else {
const ctx = resources.canvas.getContext("bitmaprenderer");
resources.canvas.width = width;
resources.canvas.height = height;
const imageData = new ImageData(width, height);
imageData.data.set(data);
const imageBitmap = await createImageBitmap(imageData, { premultiplyAlpha: "none", imageOrientation: invertY ? "flipY" : "from-image" });
ctx.transferFromImageBitmap(imageBitmap);
}
Tools.ToBlob(resources.canvas, (blob) => {
if (!blob) {
throw new Error("DumpData: Failed to convert canvas to blob.");
}
if (fileName !== void 0) {
Tools.DownloadBlob(blob, fileName);
}
const fileReader = new FileReader();
fileReader.onload = (event) => {
const result = event.target.result;
resolve(result);
};
if (toArrayBuffer) {
fileReader.readAsArrayBuffer(blob);
} else {
fileReader.readAsDataURL(blob);
}
}, mimeType, quality);
});
}
function DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) {
if (fileName === void 0 && !successCallback) {
fileName = "";
}
DumpDataAsync(width, height, data, mimeType, fileName, invertY, toArrayBuffer, quality).then((result) => {
if (successCallback) {
successCallback(result);
}
});
}
function Dispose() {
if (!ResourcesPromise) {
return;
}
ResourcesPromise?.then((resources) => {
if (resources.canvas instanceof HTMLCanvasElement) {
resources.canvas.remove();
}
if (resources.dumpEngine) {
resources.dumpEngine.engine.dispose();
resources.dumpEngine.renderer.dispose();
resources.dumpEngine.wrapper.dispose();
}
});
ResourcesPromise = null;
}
var ResourcesPromise, DumpTools, InitSideEffects;
var init_dumpTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/dumpTools.js"() {
init_effectRenderer();
init_tools();
init_math_scalar_functions();
init_engineStore();
init_logger();
ResourcesPromise = null;
__name(_CreateDumpResourcesAsync, "_CreateDumpResourcesAsync");
__name(_GetDumpResourcesAsync, "_GetDumpResourcesAsync");
__name(DumpFramebuffer, "DumpFramebuffer");
__name(DumpDataAsync, "DumpDataAsync");
__name(DumpData, "DumpData");
__name(Dispose, "Dispose");
DumpTools = {
// eslint-disable-next-line @typescript-eslint/naming-convention
DumpData,
// eslint-disable-next-line @typescript-eslint/naming-convention
DumpDataAsync,
// eslint-disable-next-line @typescript-eslint/naming-convention
DumpFramebuffer,
// eslint-disable-next-line @typescript-eslint/naming-convention
Dispose
};
InitSideEffects = /* @__PURE__ */ __name(() => {
Tools.DumpData = DumpData;
Tools.DumpDataAsync = DumpDataAsync;
Tools.DumpFramebuffer = DumpFramebuffer;
}, "InitSideEffects");
InitSideEffects();
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/postProcessManager.js
var PostProcessManager;
var init_postProcessManager = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/postProcessManager.js"() {
init_buffer();
init_observable();
PostProcessManager = class {
static {
__name(this, "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;
}
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() {
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 !== void 0);
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
* @param numPostsProcesses The number of post processes to render. Defaults to the length of the postProcesses array.
*/
directRender(postProcesses, targetTexture = null, forceFullscreenViewport = false, faceIndex = 0, lodLevel = 0, doNotBindFrambuffer = false, numPostsProcesses = postProcesses.length) {
const engine = this._scene.getEngine();
for (let index = 0; index < numPostsProcesses; index++) {
if (index < postProcesses.length - 1) {
postProcesses[index + 1].activate(this._scene.activeCamera || this._scene, targetTexture?.texture);
} else {
if (targetTexture) {
engine.bindFramebuffer(targetTexture, faceIndex, void 0, void 0, 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);
this._prepareBuffers();
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
engine.drawElementsType(0, 0, 6);
pp.onAfterRenderObservable.notifyObservers(effect);
}
}
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, void 0, void 0, 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);
this._prepareBuffers();
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
engine.drawElementsType(0, 0, 6);
pp.onAfterRenderObservable.notifyObservers(effect);
}
}
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;
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/smartArray.js
var SmartArray, SmartArrayNoDuplicate;
var init_smartArray = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/smartArray.js"() {
SmartArray = class _SmartArray {
static {
__name(this, "SmartArray");
}
/**
* Instantiates a Smart Array.
* @param capacity defines the default capacity of the array.
*/
constructor(capacity) {
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;
}
};
SmartArray._GlobalId = 0;
SmartArrayNoDuplicate = class extends SmartArray {
static {
__name(this, "SmartArrayNoDuplicate");
}
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);
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/renderingGroup.js
var RenderingGroup;
var init_renderingGroup = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/renderingGroup.js"() {
init_smartArray();
init_math_vector();
RenderingGroup = class _RenderingGroup {
static {
__name(this, "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);
this._empty = true;
this._edgesRenderers = new SmartArrayNoDuplicate(16);
this.disableDepthPrePass = false;
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();
if (this._depthOnlySubMeshes.length !== 0) {
engine.setColorWrite(false);
this._renderAlphaTest(this._depthOnlySubMeshes);
engine.setColorWrite(true);
}
if (this._opaqueSubMeshes.length !== 0) {
this._renderOpaque(this._opaqueSubMeshes);
}
if (this._alphaTestSubMeshes.length !== 0) {
this._renderAlphaTest(this._alphaTestSubMeshes);
}
const stencilState = engine.getStencilBuffer();
engine.setStencilBuffer(false);
if (renderSprites) {
this._renderSprites();
}
if (renderParticles) {
this._renderParticles(activeMeshes);
}
if (this.onBeforeTransparentRendering) {
this.onBeforeTransparentRendering();
}
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) {
this._renderTransparent(excludedMeshes);
}
} else {
this._renderTransparent(this._transparentSubMeshes);
}
engine.setAlphaMode(0);
}
engine.setStencilBuffer(false);
if (this._edgesRenderers.length) {
for (let edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
this._edgesRenderers.data[edgesRendererIndex].render();
}
engine.setAlphaMode(0);
}
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, this.disableDepthPrePass);
}
/**
* 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, this.disableDepthPrePass);
}
/**
* 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, this.disableDepthPrePass);
}
/**
* 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
* @param disableDepthPrePass Specifies to disable depth pre-pass if true (default: false)
*/
static _RenderSorted(subMeshes, sortCompareFn, camera, transparent, disableDepthPrePass) {
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 && !disableDepthPrePass) {
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) {
if (a._alphaIndex > b._alphaIndex) {
return 1;
}
if (a._alphaIndex < b._alphaIndex) {
return -1;
}
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) {
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) {
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) {
if (mesh === void 0) {
mesh = subMesh.getMesh();
}
if (material === void 0) {
material = subMesh.getMaterial();
}
if (material === null || material === void 0) {
return;
}
if (material.needAlphaBlendingForMesh(mesh)) {
this._transparentSubMeshes.push(subMesh);
} else if (material.needAlphaTestingForMesh(mesh)) {
if (material.needDepthPrePass && !this.disableDepthPrePass) {
this._depthOnlySubMeshes.push(subMesh);
}
this._alphaTestSubMeshes.push(subMesh);
} else {
if (material.needDepthPrePass && !this.disableDepthPrePass) {
this._depthOnlySubMeshes.push(subMesh);
}
this._opaqueSubMeshes.push(subMesh);
}
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;
}
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;
}
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();
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/renderingManager.js
var RenderingGroupInfo, RenderingManager;
var init_renderingManager = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/renderingManager.js"() {
init_renderingGroup();
RenderingGroupInfo = class {
static {
__name(this, "RenderingGroupInfo");
}
};
RenderingManager = class _RenderingManager {
static {
__name(this, "RenderingManager");
}
/**
* Specifies to disable depth pre-pass if true (default: false)
*/
get disableDepthPrePass() {
return this._disableDepthPrePass;
}
set disableDepthPrePass(value) {
this._disableDepthPrePass = value;
for (const group of this._renderingGroups) {
group.disableDepthPrePass = value;
}
}
/**
* 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) {
this._useSceneAutoClearSetup = false;
this._disableDepthPrePass = 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) {
const info = this._renderingGroupInfo;
info.scene = this._scene;
info.camera = this._scene.activeCamera;
info.renderingManager = this;
if (this._scene.spriteManagers && renderSprites) {
for (let index = 0; index < this._scene.spriteManagers.length; index++) {
const manager = this._scene.spriteManagers[index];
this.dispatchSprites(manager);
}
}
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;
this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
if (_RenderingManager.AUTOCLEAR) {
const autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index];
if (autoClear && autoClear.autoClear) {
this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
}
}
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);
}
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] === void 0) {
this._renderingGroups[renderingGroupId] = new RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
this._renderingGroups[renderingGroupId].disableDepthPrePass = this._disableDepthPrePass;
}
}
/**
* 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 === void 0) {
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,
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];
}
};
RenderingManager.MAX_RENDERINGGROUPS = 4;
RenderingManager.MIN_RENDERINGGROUPS = 0;
RenderingManager.AUTOCLEAR = true;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/lightConstants.js
var LightConstants;
var init_lightConstants = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/lightConstants.js"() {
LightConstants = class {
static {
__name(this, "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) {
if (a.shadowEnabled !== b.shadowEnabled) {
return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
}
return b.renderPriority - a.renderPriority;
}
};
LightConstants.FALLOFF_DEFAULT = 0;
LightConstants.FALLOFF_PHYSICAL = 1;
LightConstants.FALLOFF_GLTF = 2;
LightConstants.FALLOFF_STANDARD = 3;
LightConstants.LIGHTMAP_DEFAULT = 0;
LightConstants.LIGHTMAP_SPECULAR = 1;
LightConstants.LIGHTMAP_SHADOWSONLY = 2;
LightConstants.INTENSITYMODE_AUTOMATIC = 0;
LightConstants.INTENSITYMODE_LUMINOUSPOWER = 1;
LightConstants.INTENSITYMODE_LUMINOUSINTENSITY = 2;
LightConstants.INTENSITYMODE_ILLUMINANCE = 3;
LightConstants.INTENSITYMODE_LUMINANCE = 4;
LightConstants.LIGHTTYPEID_POINTLIGHT = 0;
LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
LightConstants.LIGHTTYPEID_SPOTLIGHT = 2;
LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
LightConstants.LIGHTTYPEID_RECT_AREALIGHT = 4;
LightConstants.LIGHTTYPEID_CLUSTERED_CONTAINER = 5;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/objectRenderer.js
var ObjectRenderer;
var init_objectRenderer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/objectRenderer.js"() {
init_observable();
init_renderingManager();
init_arrayTools();
init_timingTools();
init_logger();
init_smartArray();
init_lightConstants();
ObjectRenderer = class _ObjectRenderer {
static {
__name(this, "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 without any image processing applied.
* If false (default value), the renderer will use the current setting of the scene's image processing configuration.
*/
get disableImageProcessing() {
return this._disableImageProcessing;
}
set disableImageProcessing(value) {
if (value === this._disableImageProcessing) {
return;
}
this._disableImageProcessing = value;
this._scene.markAllMaterialsAsDirty(64);
}
/**
* Specifies to disable depth pre-pass if true (default: false)
*/
get disableDepthPrePass() {
return this._disableDepthPrePass;
}
set disableDepthPrePass(value) {
this._disableDepthPrePass = value;
this._renderingManager.disableDepthPrePass = value;
}
/**
* Friendly name of the object renderer
*/
get name() {
return this._name;
}
set name(value) {
if (this._name === value) {
return;
}
this._name = value;
if (this._sceneUBOs) {
for (let i = 0; i < this._sceneUBOs.length; ++i) {
this._sceneUBOs[i].name = `Scene ubo #${i} for ${this.name}`;
}
}
if (!this._scene) {
return;
}
for (let i = 0; i < this._renderPassIds.length; ++i) {
const renderPassId = this._renderPassIds[i];
this._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;
}
/**
* Gets the array of active meshes
* @returns an array of AbstractMesh
*/
getActiveMeshes() {
return this._activeMeshes;
}
/**
* 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) {
let mesh2 = meshes[j];
if (meshes[j].isAnInstance) {
mesh2 = meshes[j].sourceMesh;
}
mesh2.setMaterialForRenderPass(this._renderPassIds[i], material !== void 0 ? Array.isArray(material) ? material[i] : material : void 0);
}
}
}
/** @internal */
_freezeActiveMeshes(freezeMeshes) {
this._freezeActiveMeshesCancel = _RetryWithInterval(() => {
return this._checkReadiness();
}, () => {
this._freezeActiveMeshesCancel = null;
if (freezeMeshes) {
for (let index = 0; index < this._activeMeshes.length; index++) {
this._activeMeshes.data[index]._freeze();
}
}
this._prepareRenderingManager(0, true);
this._isFrozen = true;
}, (err, isTimeout) => {
this._freezeActiveMeshesCancel = null;
if (!isTimeout) {
Logger.Error("ObjectRenderer: An unexpected error occurred while waiting for the renderer to be ready.");
if (err) {
Logger.Error(err);
if (err.stack) {
Logger.Error(err.stack);
}
}
} else {
Logger.Error(`ObjectRenderer: Timeout while waiting for the renderer to be ready.`);
if (err) {
Logger.Error(err);
}
}
});
}
/** @internal */
_unfreezeActiveMeshes() {
this._freezeActiveMeshesCancel?.();
this._freezeActiveMeshesCancel = null;
for (let index = 0; index < this._activeMeshes.length; index++) {
this._activeMeshes.data[index]._unFreeze();
}
this._isFrozen = false;
}
/**
* 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(name260, scene, options) {
this._unObserveRenderList = null;
this._renderListHasChanged = (_functionName, previousLength) => {
const newLength = this._renderList ? this._renderList.length : 0;
if (previousLength === 0 && newLength > 0 || newLength === 0) {
for (const mesh of this._scene.meshes) {
mesh._markSubMeshesAsLightDirty();
}
}
};
this.particleSystemList = null;
this.getCustomRenderList = null;
this.renderParticles = true;
this.renderSprites = false;
this.forceLayerMaskCheck = false;
this.enableBoundingBoxRendering = false;
this.enableOutlineRendering = true;
this._disableImageProcessing = false;
this.dontSetTransformationMatrix = false;
this._disableDepthPrePass = false;
this.onBeforeRenderObservable = new Observable();
this.onAfterRenderObservable = new Observable();
this.onBeforeRenderingManagerRenderObservable = new Observable();
this.onAfterRenderingManagerRenderObservable = new Observable();
this.onInitRenderingObservable = new Observable();
this.onFinishRenderingObservable = new Observable();
this.onFastPathRenderObservable = new Observable();
this._currentRefreshId = -1;
this._refreshRate = 1;
this._currentApplyByPostProcessSetting = false;
this._activeMeshes = new SmartArray(256);
this._activeBoundingBoxes = new SmartArray(32);
this._currentFrameId = -1;
this._currentSceneUBOIndex = 0;
this._isFrozen = false;
this._freezeActiveMeshesCancel = null;
this._currentSceneCamera = null;
this.name = name260;
this._scene = scene;
this._engine = this._scene.getEngine();
this._useUBO = this._engine.supportsUniformBuffers;
if (this._useUBO) {
this._sceneUBOs = [];
this._createSceneUBO();
}
this.renderList = [];
this._renderPassIds = [];
this.options = {
numPasses: 1,
doNotChangeAspectRatio: true,
enableClusteredLights: false,
...options
};
this._createRenderPassId();
this.renderPassId = this._renderPassIds[0];
this._renderingManager = new RenderingManager(scene);
this._renderingManager._useSceneAutoClearSetup = true;
if (this.options.enableClusteredLights) {
this.onInitRenderingObservable.add(() => {
for (const light of this._scene.lights) {
if (light.getTypeID() === LightConstants.LIGHTTYPEID_CLUSTERED_CONTAINER && light.isSupported) {
light._updateBatches(this.activeCamera).render();
}
}
});
}
this._scene.addObjectRenderer(this);
}
_releaseRenderPassId() {
for (let i = 0; i < this.options.numPasses; ++i) {
this._engine.releaseRenderPassId(this._renderPassIds[i]);
}
this._renderPassIds.length = 0;
}
_createRenderPassId() {
this._releaseRenderPassId();
for (let i = 0; i < this.options.numPasses; ++i) {
this._renderPassIds[i] = this._engine.createRenderPassId(`${this.name}#${i}`);
}
}
_createSceneUBO() {
const index = this._sceneUBOs.length;
this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene ubo #${index} for ${this.name}`, false));
}
_getSceneUBO() {
if (this._currentFrameId !== this._engine.frameId) {
this._currentSceneUBOIndex = 0;
this._currentFrameId = this._engine.frameId;
}
if (this._currentSceneUBOIndex >= this._sceneUBOs.length) {
this._createSceneUBO();
}
const ubo = this._sceneUBOs[this._currentSceneUBOIndex++];
ubo.unbindEffect();
return ubo;
}
/**
* 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) {
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 = void 0;
}
if (this.renderListPredicate) {
if (this.renderList) {
this.renderList.length = 0;
} 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;
if (this._disableImageProcessing) {
this._scene.imageProcessingConfiguration._applyByPostProcess = this._disableImageProcessing;
}
}
/**
* 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 camera = this.activeCamera ?? this._scene.activeCamera;
this._currentSceneCamera = this._scene.activeCamera;
if (this._useUBO) {
this._currentSceneUBO = this._scene.getSceneUniformBuffer();
this._currentSceneUBO.unbindEffect();
this._scene.setSceneUniformBuffer(this._getSceneUBO());
}
this.onInitRenderingObservable.notifyObservers(this);
if (camera) {
if (!this.dontSetTransformationMatrix) {
this._scene.setTransformMatrix(camera.getViewMatrix(), camera.getProjectionMatrix(true));
}
this._scene.activeCamera = camera;
this._engine.setViewport(camera.rigParent ? camera.rigParent.viewport : camera.viewport, viewportWidth, viewportHeight);
}
if (this._useUBO) {
this._scene.finalizeSceneUbo();
}
this._defaultRenderListPrepared = false;
}
/**
* This method must be called after the "render" call(s), to complete the rendering process.
*/
finishRender() {
const scene = this._scene;
if (this._useUBO) {
this._scene.setSceneUniformBuffer(this._currentSceneUBO);
}
if (this._disableImageProcessing) {
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));
}
this._engine.setViewport(this._currentSceneCamera.viewport);
}
scene.resetCachedMaterial();
this.onFinishRenderingObservable.notifyObservers(this);
}
/**
* 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 currentRenderPassId = this._engine.currentRenderPassId;
this._engine.currentRenderPassId = this._renderPassIds[passIndex];
this.onBeforeRenderObservable.notifyObservers(passIndex);
const fastPath = this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1;
if (!fastPath) {
const currentRenderList = this._prepareRenderingManager(passIndex);
const outlineRenderer = this._scene.getOutlineRenderer?.();
const outlineRendererIsEnabled = outlineRenderer?.enabled;
if (outlineRenderer) {
outlineRenderer.enabled = this.enableOutlineRendering;
}
this.onBeforeRenderingManagerRenderObservable.notifyObservers(passIndex);
this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
this.onAfterRenderingManagerRenderObservable.notifyObservers(passIndex);
if (outlineRenderer) {
outlineRenderer.enabled = outlineRendererIsEnabled;
}
} else {
this.onFastPathRenderObservable.notifyObservers(passIndex);
}
if (!skipOnAfterRenderObservable) {
this.onAfterRenderObservable.notifyObservers(passIndex);
}
this._engine.currentRenderPassId = currentRenderPassId;
}
/** @internal */
_checkReadiness() {
const scene = this._scene;
const currentRenderPassId = this._engine.currentRenderPassId;
let returnValue = true;
if (!scene.getViewMatrix()) {
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.frameGraph ? scene.meshes : scene.getActiveMeshes().data;
const defaultRenderListLength = this.renderList ? this.renderList.length : scene.frameGraph ? scene.meshes.length : scene.getActiveMeshes().length;
this._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;
}
}
this._engine.currentRenderPassId = currentRenderPassId;
return returnValue;
}
_prepareRenderingManager(passIndex = 0, winterIsComing = false) {
const scene = this._scene;
let currentRenderList = null;
let currentRenderListLength = 0;
let checkLayerMask = false;
const defaultRenderList = this.renderList ? this.renderList : scene.frameGraph ? scene.meshes : scene.getActiveMeshes().data;
const defaultRenderListLength = this.renderList ? this.renderList.length : scene.frameGraph ? scene.meshes.length : scene.getActiveMeshes().length;
if (this.getCustomRenderList) {
currentRenderList = this.getCustomRenderList(passIndex, defaultRenderList, defaultRenderListLength);
}
if (!currentRenderList) {
if (this._defaultRenderListPrepared && !winterIsComing) {
return defaultRenderList;
}
this._defaultRenderListPrepared = true;
currentRenderList = defaultRenderList;
currentRenderListLength = defaultRenderListLength;
checkLayerMask = !this.renderList || this.forceLayerMaskCheck;
} else {
currentRenderListLength = currentRenderList.length;
checkLayerMask = this.forceLayerMaskCheck;
}
const camera = scene.activeCamera;
const cameraForLOD = this.cameraForLOD ?? camera;
const boundingBoxRenderer = scene.getBoundingBoxRenderer?.();
if (scene._activeMeshesFrozen && this._isFrozen) {
this._renderingManager.resetSprites();
if (this.enableBoundingBoxRendering && boundingBoxRenderer) {
boundingBoxRenderer.reset();
for (let i = 0; i < this._activeBoundingBoxes.length; i++) {
const boundingBox = this._activeBoundingBoxes.data[i];
boundingBoxRenderer.renderList.push(boundingBox);
}
}
return currentRenderList;
}
this._renderingManager.reset();
this._activeMeshes.reset();
this._activeBoundingBoxes.reset();
boundingBoxRenderer && boundingBoxRenderer.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();
}
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) {
this._activeMeshes.push(mesh);
meshToRender._internalAbstractMeshDataInfo._wasActiveLastFrame = true;
if (meshToRender !== mesh) {
meshToRender._activate(sceneRenderId, true);
}
this.enableBoundingBoxRendering && boundingBoxRenderer && boundingBoxRenderer._preActiveMesh(mesh);
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.enableBoundingBoxRendering && boundingBoxRenderer && boundingBoxRenderer._evaluateSubMesh(mesh, subMesh);
this._renderingManager.dispatch(subMesh, meshToRender);
}
}
mesh._postActivate();
}
}
}
if (this.enableBoundingBoxRendering && boundingBoxRenderer && winterIsComing) {
for (let i = 0; i < boundingBoxRenderer.renderList.length; i++) {
const boundingBox = boundingBoxRenderer.renderList.data[i];
this._activeBoundingBoxes.push(boundingBox);
}
}
if (this._scene.particlesEnabled) {
this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
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);
}
this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
}
return currentRenderList;
}
/**
* Gets the rendering manager
*/
get renderingManager() {
return this._renderingManager;
}
/**
* 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 && mesh.getMaterialForRenderPass(this.renderPassId) !== void 0) {
mesh.setMaterialForRenderPass(this.renderPassId, void 0);
}
}
this.onInitRenderingObservable.clear();
this.onFinishRenderingObservable.clear();
this.onBeforeRenderObservable.clear();
this.onAfterRenderObservable.clear();
this.onBeforeRenderingManagerRenderObservable.clear();
this.onAfterRenderingManagerRenderObservable.clear();
this.onFastPathRenderObservable.clear();
this._releaseRenderPassId();
this.renderList = null;
if (this._sceneUBOs) {
for (const ubo of this._sceneUBOs) {
ubo.dispose();
}
}
this._sceneUBOs = void 0;
this._scene.removeObjectRenderer(this);
}
/** @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();
}
}
};
ObjectRenderer.REFRESHRATE_RENDER_ONCE = 0;
ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/renderTargetTexture.js
var RenderTargetTexture;
var init_renderTargetTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/renderTargetTexture.js"() {
init_observable();
init_math_vector();
init_texture();
init_postProcessManager();
init_tools_functions();
init_effect();
init_logger();
init_objectRenderer();
Effect.prototype.setDepthStencilTexture = function(channel, texture) {
this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture, channel);
};
RenderTargetTexture = class _RenderTargetTexture extends Texture {
static {
__name(this, "RenderTargetTexture");
}
/**
* 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;
}
/**
* Define if bounding box rendering should be enabled (still subject to Mesh.showBoundingBox or scene.forceShowBoundingBoxes). (Default: false).
*/
get enableBoundingBoxRendering() {
return this._objectRenderer.enableBoundingBoxRendering;
}
set enableBoundingBoxRendering(value) {
this._objectRenderer.enableBoundingBoxRendering = value;
}
/**
* Define if outline/overlay rendering should be enabled (still subject to Mesh.renderOutline/Mesh.renderOverlay). (Default: true).
*/
get enableOutlineRendering() {
return this._objectRenderer.enableOutlineRendering;
}
set enableOutlineRendering(value) {
this._objectRenderer.enableOutlineRendering = 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, the renderer will render all objects without any image processing applied.
* If false (default value), the renderer will use the current setting of the scene's image processing configuration.
*/
get disableImageProcessing() {
return this._objectRenderer.disableImageProcessing;
}
set disableImageProcessing(value) {
this._objectRenderer.disableImageProcessing = 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(name260, 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 = void 0;
let gammaSpace = true;
let existingObjectRenderer = void 0;
let enableClusteredLights = false;
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;
enableClusteredLights = !!options.enableClusteredLights;
}
super(null, scene, !generateMipMaps, void 0, samplingMode, void 0, void 0, void 0, void 0, format);
this.ignoreCameraViewport = false;
this.onBeforeBindObservable = new Observable();
this.onAfterUnbindObservable = new Observable();
this.onClearObservable = new Observable();
this.onResizeObservable = new Observable();
this._cleared = false;
this.skipInitialClear = false;
this._samples = 1;
this._canRescale = true;
this._renderTarget = null;
this._dontDisposeObjectRenderer = false;
this.boundingBoxPosition = Vector3.Zero();
this._disableEngineStages = false;
this._dumpToolsLoading = false;
scene = this.getScene();
if (!scene) {
return;
}
const engine = this.getScene().getEngine();
this._gammaSpace = gammaSpace;
this._coordinatesMode = Texture.PROJECTION_MODE;
this.name = name260;
this.isRenderTarget = true;
this._initialSizeParameter = size;
this._dontDisposeObjectRenderer = !!existingObjectRenderer;
this._processSizeParameter(size);
this._objectRenderer = existingObjectRenderer ?? new ObjectRenderer(name260, scene, {
numPasses: isCube ? 6 : this.getRenderLayers() || 1,
doNotChangeAspectRatio,
enableClusteredLights
});
this._onBeforeRenderingManagerRenderObserver = this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(() => {
if (!this._disableEngineStages) {
for (const step of this._scene._beforeRenderTargetClearStage) {
step.action(this, this._currentFaceIndex, this._currentLayer);
}
}
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);
}
if (!this._disableEngineStages) {
for (const step of this._scene._beforeRenderTargetDrawStage) {
step.action(this, this._currentFaceIndex, this._currentLayer);
}
}
});
this._onAfterRenderingManagerRenderObserver = this._objectRenderer.onAfterRenderingManagerRenderObservable.add(() => {
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 (this._postProcessManager) {
this._postProcessManager._finalizeFrame(false, this._renderTarget ?? void 0, this._currentFaceIndex, this._postProcesses, this.ignoreCameraViewport);
} else if (this._currentUseCameraPostProcess) {
this._scene.postProcessManager._finalizeFrame(false, this._renderTarget ?? void 0, 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);
}
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,
type,
format: this._format ?? void 0,
samplingMode: this.samplingMode,
generateDepthBuffer,
generateStencilBuffer,
samples,
creationFlags,
noColorAttachment,
useSRGBBuffer,
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 !== void 0) {
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 !== void 0) {
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;
Promise.resolve().then(() => (init_dumpTools(), dumpTools_exports)).then((module2) => this._dumpTools = module2);
}
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 !== void 0) {
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));
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 : void 0, void 0, void 0, 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) {
if (!this._postProcessManager._prepareFrame(this._texture, this._postProcesses)) {
this._bindFrameBuffer(faceIndex, layer);
}
}
} 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);
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, void 0, this._renderTargetOptions.format, void 0, this._renderTargetOptions.samples);
newTexture.hasAlpha = this.hasAlpha;
newTexture.level = this.level;
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;
}
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;
}
};
RenderTargetTexture.REFRESHRATE_RENDER_ONCE = ObjectRenderer.REFRESHRATE_RENDER_ONCE;
RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME;
RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
Texture._CreateRenderTargetTexture = (name260, renderTargetSize, scene, generateMipMaps, creationFlags) => {
return new RenderTargetTexture(name260, renderTargetSize, scene, generateMipMaps);
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/postProcess.js
var PostProcess;
var init_postProcess = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/postProcess.js"() {
init_tslib_es6();
init_smartArray();
init_observable();
init_math_vector();
init_effect();
init_decorators();
init_decorators_serialization();
init_typeStore();
init_abstractEngine();
init_tools_functions();
init_effectRenderer();
AbstractEngine.prototype.setTextureFromPostProcess = function(channel, postProcess, name260) {
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, name260);
};
AbstractEngine.prototype.setTextureFromPostProcessOutput = function(channel, postProcess, name260) {
this._bindTexture(channel, postProcess?._outputTexture?.texture ?? null, name260);
};
Effect.prototype.setTextureFromPostProcess = function(channel, postProcess) {
this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess, channel);
};
Effect.prototype.setTextureFromPostProcessOutput = function(channel, postProcess) {
this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess, channel);
};
PostProcess = class _PostProcess {
static {
__name(this, "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 / this._forcedOutputTexture.width, 1 / this._forcedOutputTexture.height);
}
return this._texelSize;
}
/** @internal */
constructor(name260, fragmentUrl, parameters, samplers, _size, camera, samplingMode = 1, engine, reusable, defines = null, textureType = 0, vertexUrl = "postprocess", indexParameters, blockCompilation = false, textureFormat = 5, shaderLanguage, extraInitializations) {
this._parentContainer = null;
this.width = -1;
this.height = -1;
this.nodeMaterialSource = null;
this._outputTexture = null;
this.autoClear = true;
this.forceAutoClearInAlphaMode = false;
this.animations = [];
this.enablePixelPerfectMode = false;
this.forceFullscreenViewport = true;
this.scaleMode = 1;
this.alwaysForcePOT = false;
this._samples = 1;
this.adaptScaleToCurrentViewport = false;
this._webGPUReady = false;
this._reusable = false;
this._renderId = 0;
this.externalTextureSamplerBinding = false;
this._textures = new SmartArray(2);
this._textureCache = [];
this._currentRenderTextureInd = 0;
this._scaleRatio = new Vector2(1, 1);
this._texelSize = Vector2.Zero();
this.onActivateObservable = new Observable();
this.onSizeChangedObservable = new Observable();
this.onApplyObservable = new Observable();
this.onBeforeRenderObservable = new Observable();
this.onAfterRenderObservable = new Observable();
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;
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: name260,
useShaderStore: true,
useAsPostProcess: true,
fragmentShader: fragmentUrl,
engine: engine || camera?.getScene().getEngine(),
uniforms: parameters,
samplers,
uniformBuffers,
defines,
vertexUrl,
indexParameters,
blockCompilation: true,
shaderLanguage,
extraInitializations: void 0
});
this.name = name260;
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.addPostProcess(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;
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;
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) {
if (useWebGPU && this._webGPUReady) {
list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex(), postprocess_vertex_exports))]));
} else {
list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex2(), postprocess_vertex_exports2))]));
}
}
/**
* 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 / this.width, 1 / 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 !== void 0 ? 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();
}
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, void 0, void 0, this.forceFullscreenViewport);
}
this._engine._debugInsertMarker?.(`post process ${this.name} input`);
this.onActivateObservable.notifyObservers(camera);
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() {
if (!this._effectWrapper.isReady()) {
return null;
}
this._engine.enableEffect(this._effectWrapper.drawWrapper);
this._engine.setState(false);
this._engine.setDepthBuffer(false);
this._engine.setDepthWrite(false);
if (this.alphaConstants) {
this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
}
this._engine.setAlphaMode(this.alphaMode);
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);
}
this._effectWrapper.drawWrapper.effect.setVector2("scale", this._scaleRatio);
this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect);
this._effectWrapper.bind(true);
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.removePostProcess(this);
}
if (this._parentContainer) {
const index2 = this._parentContainer.postProcesses.indexOf(this);
if (index2 > -1) {
this._parentContainer.postProcesses.splice(index2, 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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/pass.fragment.js
var pass_fragment_exports2 = {};
__export(pass_fragment_exports2, {
passPixelShaderWGSL: () => passPixelShaderWGSL
});
var name8, shader8, passPixelShaderWGSL;
var init_pass_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/pass.fragment.js"() {
init_shaderStore();
name8 = "passPixelShader";
shader8 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}`;
if (!ShaderStore.ShadersStoreWGSL[name8]) {
ShaderStore.ShadersStoreWGSL[name8] = shader8;
}
passPixelShaderWGSL = { name: name8, shader: shader8 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/passCube.fragment.js
var passCube_fragment_exports = {};
__export(passCube_fragment_exports, {
passCubePixelShaderWGSL: () => passCubePixelShaderWGSL
});
var name9, shader9, passCubePixelShaderWGSL;
var init_passCube_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/passCube.fragment.js"() {
init_shaderStore();
name9 = "passCubePixelShader";
shader9 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f=input.vUV*2.0-1.0;
#ifdef POSITIVEX
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x));
#endif
#ifdef NEGATIVEX
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x));
#endif
#ifdef POSITIVEY
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x));
#endif
#ifdef NEGATIVEY
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x));
#endif
#ifdef POSITIVEZ
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,1.001));
#endif
#ifdef NEGATIVEZ
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,-1.001));
#endif
}`;
if (!ShaderStore.ShadersStoreWGSL[name9]) {
ShaderStore.ShadersStoreWGSL[name9] = shader9;
}
passCubePixelShaderWGSL = { name: name9, shader: shader9 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/passCube.fragment.js
var passCube_fragment_exports2 = {};
__export(passCube_fragment_exports2, {
passCubePixelShader: () => passCubePixelShader
});
var name10, shader10, passCubePixelShader;
var init_passCube_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/passCube.fragment.js"() {
init_shaderStore();
name10 = "passCubePixelShader";
shader10 = `varying vec2 vUV;uniform samplerCube textureSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 uv=vUV*2.0-1.0;
#ifdef POSITIVEX
gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));
#endif
#ifdef NEGATIVEX
gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));
#endif
#ifdef POSITIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));
#endif
#ifdef NEGATIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));
#endif
#ifdef POSITIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,1.001));
#endif
#ifdef NEGATIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));
#endif
}`;
if (!ShaderStore.ShadersStore[name10]) {
ShaderStore.ShadersStore[name10] = shader10;
}
passCubePixelShader = { name: name10, shader: shader10 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/performanceMonitor.js
var PerformanceMonitor, RollingAverage;
var init_performanceMonitor = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/performanceMonitor.js"() {
init_precisionDate();
PerformanceMonitor = class {
static {
__name(this, "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 1e3 / 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 1e3 / 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;
this._lastFrameTimeMs = null;
}
/**
* Returns true if sampling is enabled
*/
get isEnabled() {
return this._enabled;
}
/**
* Resets performance monitor
*/
reset() {
this._lastFrameTimeMs = null;
this._rollingFrameTime.reset();
}
};
RollingAverage = class {
static {
__name(this, "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) {
let delta;
if (this.isSaturated()) {
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++;
}
delta = v - this.average;
this.average += delta / this._sampleCount;
this._m2 += delta * (v - this.average);
this.variance = this._m2 / (this._sampleCount - 1);
this._samples[this._pos] = v;
this._pos++;
this._pos %= this._samples.length;
}
/**
* 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);
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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.alpha.js
var init_engine_alpha = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.alpha.js"() {
init_thinEngine();
ThinEngine.prototype.setAlphaMode = function(mode, noDepthWriteChange = false, targetIndex = 0) {
if (this._alphaMode[targetIndex] === mode) {
if (!noDepthWriteChange) {
const depthMask = mode === 0;
if (this.depthCullingState.depthMask !== depthMask) {
this.depthCullingState.depthMask = depthMask;
}
}
return;
}
const alphaBlendDisabled = mode === 0;
this._alphaState.setAlphaBlend(!alphaBlendDisabled, targetIndex);
this._alphaState.setAlphaMode(mode, targetIndex);
if (!noDepthWriteChange) {
this.depthCullingState.depthMask = alphaBlendDisabled;
}
this._alphaMode[targetIndex] = mode;
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.rawTexture.js
function ConvertRGBtoRGBATextureData(rgbData, width, height, textureType) {
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;
} else if (textureType === 7) {
rgbaData = new Uint32Array(width * height * 4);
} else {
rgbaData = new Uint8Array(width * height * 4);
}
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;
rgbaData[newIndex + 0] = rgbData[index + 0];
rgbaData[newIndex + 1] = rgbData[index + 1];
rgbaData[newIndex + 2] = rgbData[index + 2];
rgbaData[newIndex + 3] = val1;
}
}
return rgbaData;
}
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 : 11;
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);
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;
};
}
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 === void 0 ? 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);
texture.isReady = true;
};
}
var init_engine_rawTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.rawTexture.js"() {
init_internalTexture();
init_logger();
init_thinEngine();
init_tools_functions();
ThinEngine.prototype.updateRawTexture = function(texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {
if (!texture) {
return;
}
const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);
const internalFormat = this._getInternalFormat(format);
const textureType = this._getWebGLTextureType(type);
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
this._unpackFlipY(invertY === void 0 ? 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);
texture.isReady = true;
};
ThinEngine.prototype.createRawTexture = function(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, 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);
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;
}
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;
const isPot = !this.needPOTTextures || IsExponentOfTwo(texture.width) && IsExponentOfTwo(texture.height);
if (!isPot) {
generateMipMaps = false;
}
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, void 0);
} 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);
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 === void 0 ? true : invertY ? true : false);
if (texture.width % 4 !== 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
}
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(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);
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 = /* @__PURE__ */ __name((request, exception) => {
scene?.removePendingData(texture);
if (onError && request) {
onError(request.status + " " + request.statusText, exception);
}
}, "onerror");
const internalCallbackAsync = /* @__PURE__ */ __name(async (data) => {
if (!texture._hardwareTexture) {
return;
}
const faceDataArraysResult = callback(data);
if (!faceDataArraysResult) {
return;
}
const faceDataArrays = faceDataArraysResult instanceof Promise ? await faceDataArraysResult : faceDataArraysResult;
const width = texture.width;
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(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;
scene?.removePendingData(texture);
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
}, "internalCallbackAsync");
this._loadFile(url, (data) => {
internalCallbackAsync(data).catch((err) => {
onerror(void 0, err);
});
}, void 0, scene?.offlineProvider, true, onerror);
return texture;
};
__name(ConvertRGBtoRGBATextureData, "ConvertRGBtoRGBATextureData");
__name(MakeCreateRawTextureFunction, "MakeCreateRawTextureFunction");
ThinEngine.prototype.createRawTexture2DArray = MakeCreateRawTextureFunction(false);
ThinEngine.prototype.createRawTexture3D = MakeCreateRawTextureFunction(true);
__name(MakeUpdateRawTextureFunction, "MakeUpdateRawTextureFunction");
ThinEngine.prototype.updateRawTexture2DArray = MakeUpdateRawTextureFunction(false);
ThinEngine.prototype.updateRawTexture3D = MakeUpdateRawTextureFunction(true);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.readTexture.js
var init_engine_readTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.readTexture.js"() {
init_thinEngine();
init_abstractEngine_functions();
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 !== void 0 ? 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));
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicBuffer.js
var init_engine_dynamicBuffer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicBuffer.js"() {
init_thinEngine();
ThinEngine.prototype.updateDynamicIndexBuffer = function(indexBuffer, indices, offset = 0) {
this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
this.bindIndexBuffer(indexBuffer);
let view;
if (indexBuffer.is32Bits) {
view = indices instanceof Uint32Array ? indices : new Uint32Array(indices);
} else {
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 === void 0) {
byteOffset = 0;
}
const dataLength = data.byteLength || data.length;
if (byteLength === void 0 || 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();
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.cubeTexture.js
var init_engine_cubeTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.cubeTexture.js"() {
init_thinEngine();
init_internalTexture();
init_logger();
init_tools_functions();
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);
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 !== void 0 && 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);
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/renderTargetWrapper.js
var RenderTargetWrapper;
var init_renderTargetWrapper = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/renderTargetWrapper.js"() {
init_textureHelper_functions();
RenderTargetWrapper = class {
static {
__name(this, "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;
this._samples = 1;
this._attachments = null;
this._generateStencilBuffer = false;
this._generateDepthBuffer = false;
this._depthStencilTextureWithStencil = false;
this.disableAutomaticMSAAResolve = false;
this.resolveMSAAColors = true;
this.resolveMSAADepth = false;
this.resolveMSAAStencil = false;
this.depthReadOnly = false;
this.stencilReadOnly = 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 !== void 0 && layer >= 0) {
this._layerIndices[index] = layer;
}
if (face !== void 0 && 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 || lastTextureSource === 12) {
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 !== void 0) {
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.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 : void 0
};
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);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLRenderTargetWrapper.js
var WebGLRenderTargetWrapper;
var init_webGLRenderTargetWrapper = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLRenderTargetWrapper.js"() {
init_renderTargetWrapper();
init_textureHelper_functions();
WebGLRenderTargetWrapper = class extends RenderTargetWrapper {
static {
__name(this, "WebGLRenderTargetWrapper");
}
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);
this._framebuffer = null;
this._depthStencilBuffer = null;
this._MSAAFramebuffer = null;
this._colorTextureArray = null;
this._depthStencilTextureArray = null;
this._disposeOnlyFramebuffers = false;
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;
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) {
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 {
const gl = this._context;
attachment = gl["COLOR_ATTACHMENT" + attachmentIndex + "_WEBGL"];
const target = faceIndexOrLayer !== void 0 ? 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;
}
const textureCount = this._attachments?.length ?? this.textures.length;
for (let index = 0; index < textureCount; index++) {
const texture = this.textures[index];
if (!texture) {
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);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.texture.js
var init_abstractEngine_texture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.texture.js"() {
init_abstractEngine();
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);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTarget.js
var init_engine_renderTarget = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTarget.js"() {
init_internalTexture();
init_logger();
init_thinEngine();
init_webGLRenderTargetWrapper();
init_textureHelper_functions();
init_abstractEngine_texture();
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 = void 0;
let samples = 1;
let label = void 0;
if (options !== void 0 && 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;
const framebuffer = gl.createFramebuffer();
this._bindUnboundFramebuffer(framebuffer);
rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
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 !== void 0) {
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);
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, 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 : void 0;
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);
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);
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetTexture.js
var init_engine_renderTargetTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetTexture.js"() {
init_thinEngine();
ThinEngine.prototype.setDepthStencilTexture = function(channel, uniform, texture, name260) {
if (channel === void 0) {
return;
}
if (uniform) {
this._boundUniforms[channel] = uniform;
}
if (!texture || !texture.depthStencilTexture) {
this._setTexture(channel, null, void 0, void 0, name260);
} else {
this._setTexture(channel, texture, false, true, name260);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetCube.js
var init_engine_renderTargetCube = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetCube.js"() {
init_internalTexture();
init_logger();
init_thinEngine();
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) {
fullOptions.samplingMode = 1;
} else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
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);
}
const framebuffer = gl.createFramebuffer();
this._bindUnboundFramebuffer(framebuffer);
rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
if (fullOptions.generateMipMaps) {
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
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;
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.prefilteredCubeTexture.js
var init_engine_prefilteredCubeTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.prefilteredCubeTexture.js"() {
init_thinEngine();
init_internalTexture();
init_logger();
init_sphericalPolynomial();
init_baseTexture();
ThinEngine.prototype.createPrefilteredCubeTexture = function(rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) {
const callbackAsync = /* @__PURE__ */ __name(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;
if (this.getCaps().textureLOD) {
if (onLoad) {
onLoad(texture);
}
return;
}
const mipSlices = 3;
const gl = this._gl;
const width = loadData.width;
if (!width) {
return;
}
const { DDSTools: DDSTools2 } = await Promise.resolve().then(() => (init_dds(), dds_exports));
const textures = [];
for (let i = 0; i < mipSlices; i++) {
const smoothness = i / (mipSlices - 1);
const roughness = 1 - smoothness;
const minLODIndex = lodOffset;
const maxLODIndex = Math.log2(width) * lodScale + lodOffset;
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);
DDSTools2.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);
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);
}
}, "callbackAsync");
return this.createCubeTexture(rootUrl, scene, null, false, callbackAsync, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.uniformBuffer.js
var init_engine_uniformBuffer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.uniformBuffer.js"() {
init_thinEngine();
init_webGLDataBuffer();
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 === void 0) {
offset = 0;
}
if (count === void 0) {
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);
};
ThinEngine.prototype.bindUniformBufferBase = function(buffer, location2, name260) {
this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location2, buffer ? buffer.underlyingResource : null);
};
ThinEngine.prototype.bindUniformBlock = function(pipelineContext, blockName, index) {
const program = pipelineContext.program;
const uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
if (uniformLocation !== 4294967295) {
this._gl.uniformBlockBinding(program, uniformLocation, index);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.loadingScreen.js
var init_abstractEngine_loadingScreen = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.loadingScreen.js"() {
init_domManagement();
init_abstractEngine();
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: /* @__PURE__ */ __name(function() {
if (!this._loadingScreen && this._renderingCanvas) {
this._loadingScreen = AbstractEngine.DefaultLoadingScreenFactory(this._renderingCanvas);
}
return this._loadingScreen;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
this._loadingScreen = value;
}, "set"),
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractEngine.prototype, "loadingUIText", {
set: /* @__PURE__ */ __name(function(value) {
this.loadingScreen.loadingUIText = value;
}, "set"),
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractEngine.prototype, "loadingUIBackgroundColor", {
set: /* @__PURE__ */ __name(function(value) {
this.loadingScreen.loadingUIBackgroundColor = value;
}, "set"),
enumerable: true,
configurable: true
});
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.dom.js
var init_abstractEngine_dom = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.dom.js"() {
init_abstractEngine();
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?.();
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.alpha.js
var init_abstractEngine_alpha = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.alpha.js"() {
init_abstractEngine();
AbstractEngine.prototype.setAlphaEquation = function(equation, targetIndex = 0) {
if (this._alphaEquation[targetIndex] === equation) {
return;
}
switch (equation) {
case 0:
this._alphaState.setAlphaEquationParameters(32774, 32774, targetIndex);
break;
case 1:
this._alphaState.setAlphaEquationParameters(32778, 32778, targetIndex);
break;
case 2:
this._alphaState.setAlphaEquationParameters(32779, 32779, targetIndex);
break;
case 3:
this._alphaState.setAlphaEquationParameters(32776, 32776, targetIndex);
break;
case 4:
this._alphaState.setAlphaEquationParameters(32775, 32775, targetIndex);
break;
case 5:
this._alphaState.setAlphaEquationParameters(32775, 32774, targetIndex);
break;
}
this._alphaEquation[targetIndex] = equation;
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.states.js
var init_abstractEngine_states = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.states.js"() {
init_abstractEngine();
init_abstractEngine_alpha();
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.setAlphaConstants = function(r, g, b, a) {
this._alphaState.setAlphaBlendConstants(r, g, b, a);
};
AbstractEngine.prototype.getAlphaMode = function(targetIndex = 0) {
return this._alphaMode[targetIndex];
};
AbstractEngine.prototype.getAlphaEquation = function(targetIndex = 0) {
return this._alphaEquation[targetIndex];
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.stencil.js
var init_abstractEngine_stencil = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.stencil.js"() {
init_abstractEngine();
init_abstractEngine_alpha();
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.getStencilBackFunction = function() {
return this._stencilState.stencilBackFunc;
};
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.setStencilBackFunction = function(stencilFunc) {
this._stencilState.stencilBackFunc = 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.getStencilBackOperationFail = function() {
return this._stencilState.stencilBackOpStencilFail;
};
AbstractEngine.prototype.getStencilOperationDepthFail = function() {
return this._stencilState.stencilOpDepthFail;
};
AbstractEngine.prototype.getStencilBackOperationDepthFail = function() {
return this._stencilState.stencilBackOpDepthFail;
};
AbstractEngine.prototype.getStencilOperationPass = function() {
return this._stencilState.stencilOpStencilDepthPass;
};
AbstractEngine.prototype.getStencilBackOperationPass = function() {
return this._stencilState.stencilBackOpStencilDepthPass;
};
AbstractEngine.prototype.setStencilOperationFail = function(operation) {
this._stencilState.stencilOpStencilFail = operation;
};
AbstractEngine.prototype.setStencilBackOperationFail = function(operation) {
this._stencilState.stencilBackOpStencilFail = operation;
};
AbstractEngine.prototype.setStencilOperationDepthFail = function(operation) {
this._stencilState.stencilOpDepthFail = operation;
};
AbstractEngine.prototype.setStencilBackOperationDepthFail = function(operation) {
this._stencilState.stencilBackOpDepthFail = operation;
};
AbstractEngine.prototype.setStencilOperationPass = function(operation) {
this._stencilState.stencilOpStencilDepthPass = operation;
};
AbstractEngine.prototype.setStencilBackOperationPass = function(operation) {
this._stencilState.stencilBackOpStencilDepthPass = 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);
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.renderPass.js
var init_abstractEngine_renderPass = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.renderPass.js"() {
init_abstractEngine();
AbstractEngine.prototype.getRenderPassNames = function() {
return this._renderPassNames;
};
AbstractEngine.prototype.getCurrentRenderPassName = function() {
return this._renderPassNames[this.currentRenderPassId];
};
AbstractEngine.prototype.createRenderPassId = function(name260) {
const id = ++AbstractEngine._RenderPassIdCounter;
this._renderPassNames[id] = name260 ?? "NONAME";
return id;
};
AbstractEngine.prototype.releaseRenderPassId = function(id) {
this._renderPassNames[id] = void 0;
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);
}
}
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engine.common.js
function DisableTouchAction(canvas) {
if (!canvas || !canvas.setAttribute) {
return;
}
canvas.setAttribute("touch-action", "none");
canvas.style.touchAction = "none";
canvas.style.webkitTapHighlightColor = "transparent";
}
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) => {
if (document.elementFromPoint(ev.clientX, ev.clientY) !== canvas) {
commonEngine.onCanvasPointerOutObservable.notifyObservers(ev);
}
};
const hostWindow = commonEngine.getHostWindow();
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);
}
if (!AbstractEngine.audioEngine && creationOptions.audioEngine && AbstractEngine.AudioEngineFactory) {
AbstractEngine.audioEngine = AbstractEngine.AudioEngineFactory(commonEngine.getRenderingCanvas(), commonEngine.getAudioContext(), commonEngine.getAudioDestination());
}
if (IsDocumentAvailable()) {
commonEngine._onFullscreenChange = () => {
commonEngine.isFullscreen = !!document.fullscreenElement;
if (commonEngine.isFullscreen && commonEngine._pointerLockRequested && canvas) {
RequestPointerlock(canvas);
}
};
document.addEventListener("fullscreenchange", commonEngine._onFullscreenChange, false);
document.addEventListener("webkitfullscreenchange", commonEngine._onFullscreenChange, false);
commonEngine._onPointerLockChange = () => {
commonEngine.isPointerLock = document.pointerLockElement === canvas;
};
document.addEventListener("pointerlockchange", commonEngine._onPointerLockChange, false);
document.addEventListener("webkitpointerlockchange", commonEngine._onPointerLockChange, false);
}
commonEngine.enableOfflineSupport = AbstractEngine.OfflineProviderFactory !== void 0;
commonEngine._deterministicLockstep = !!creationOptions.deterministicLockstep;
commonEngine._lockstepMaxSteps = creationOptions.lockstepMaxSteps || 0;
commonEngine._timeStep = creationOptions.timeStep || 1 / 60;
}
function _CommonDispose(commonEngine, canvas) {
if (EngineStore.Instances.length === 1 && AbstractEngine.audioEngine) {
AbstractEngine.audioEngine.dispose();
AbstractEngine.audioEngine = null;
}
const hostWindow = commonEngine.getHostWindow();
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);
}
}
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 };
}
async function CreateImageBitmapFromSource(engine, imageSource, options) {
return await 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;
});
}
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);
const buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
return buffer;
}
function RequestFullscreen(element) {
const requestFunction = element.requestFullscreen || element.webkitRequestFullscreen;
if (!requestFunction) {
return;
}
requestFunction.call(element);
}
function ExitFullscreen() {
const anyDoc = document;
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (anyDoc.webkitCancelFullScreen) {
anyDoc.webkitCancelFullScreen();
}
}
function RequestPointerlock(element) {
if (element.requestPointerLock) {
const promise = element.requestPointerLock();
if (promise instanceof Promise) {
promise.then(() => {
element.focus();
}).catch(() => {
});
} else {
element.focus();
}
}
}
function ExitPointerlock() {
if (document.exitPointerLock) {
document.exitPointerLock();
}
}
var init_engine_common = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engine.common.js"() {
init_domManagement();
init_abstractEngine();
init_engineStore();
__name(DisableTouchAction, "DisableTouchAction");
__name(_CommonInit, "_CommonInit");
__name(_CommonDispose, "_CommonDispose");
__name(GetFontOffset, "GetFontOffset");
__name(CreateImageBitmapFromSource, "CreateImageBitmapFromSource");
__name(ResizeImageBitmap, "ResizeImageBitmap");
__name(RequestFullscreen, "RequestFullscreen");
__name(ExitFullscreen, "ExitFullscreen");
__name(RequestPointerlock, "RequestPointerlock");
__name(ExitPointerlock, "ExitPointerlock");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/perfCounter.js
var PerfCounter;
var init_perfCounter = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/perfCounter.js"() {
init_precisionDate();
PerfCounter = class _PerfCounter {
static {
__name(this, "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;
this._min = Math.min(this._min, this._current);
this._max = Math.max(this._max, this._current);
this._average = this._totalAccumulated / this._totalValueCount;
const now = PrecisionDate.Now;
if (now - this._lastSecTime > 1e3) {
this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
this._lastSecTime = now;
this._lastSecAccumulated = 0;
this._lastSecValueCount = 0;
}
}
};
PerfCounter.Enabled = true;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engine.js
var Engine;
var init_engine = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engine.js"() {
init_internalTexture();
init_engineStore();
init_thinEngine();
init_performanceMonitor();
init_webGLDataBuffer();
init_logger();
init_webGLHardwareTexture();
init_engine_alpha();
init_engine_rawTexture();
init_engine_readTexture();
init_engine_dynamicBuffer();
init_engine_cubeTexture();
init_engine_renderTarget();
init_engine_renderTargetTexture();
init_engine_renderTargetCube();
init_engine_prefilteredCubeTexture();
init_engine_uniformBuffer();
init_abstractEngine_loadingScreen();
init_abstractEngine_dom();
init_abstractEngine_states();
init_abstractEngine_stencil();
init_abstractEngine_renderPass();
init_abstractEngine_texture();
init_abstractEngine();
init_engine_common();
init_perfCounter();
init_timingTools();
Engine = class _Engine extends ThinEngine {
static {
__name(this, "Engine");
}
/**
* 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);
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
async _createImageBitmapFromSource(imageSource, options) {
return await 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;
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
*/
async _loadFileAsync(url, offlineProvider, useArrayBuffer) {
return await new Promise((resolve, reject) => {
this._loadFile(url, (data) => {
resolve(data);
}, void 0, 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() {
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: cancelAnimationFrame2 } = this.customAnimationFrameRequester;
if (cancelAnimationFrame2) {
cancelAnimationFrame2(this.customAnimationFrameRequester.requestID);
}
}
} else {
super._cancelFrame();
}
}
_renderLoop(timestamp) {
this._processFrame(timestamp);
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);
for (const scene of this.scenes) {
for (const postProcess of scene.postProcesses) {
if (postProcess._outputTexture === rtWrapper) {
postProcess._outputTexture = null;
}
}
for (const camera of scene.cameras) {
for (const postProcess of camera._postProcesses) {
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 = /* @__PURE__ */ __name(() => {
this._rescalePostProcess.onApply = function(effect2) {
effect2._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();
}
}, "onCompiled");
const effect = this._rescalePostProcess.getEffect();
if (effect) {
effect.executeWhenCompiled(onCompiled);
} else {
this._rescalePostProcess.onEffectCreatedObservable.addOnce((effect2) => {
effect2.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, 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);
}
async _clientWaitAsync(sync, flags = 0, intervalms = 10) {
const gl = this._gl;
return await 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);
});
}
/**
* This function might return null synchronously, so it is technically not async.
* @internal
*/
// eslint-disable-next-line no-restricted-syntax
_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();
if (this._rescalePostProcess) {
this._rescalePostProcess.dispose();
}
_CommonDispose(this, this._renderingCanvas);
super.dispose();
}
};
Engine.ALPHA_DISABLE = 0;
Engine.ALPHA_ADD = 1;
Engine.ALPHA_COMBINE = 2;
Engine.ALPHA_SUBTRACT = 3;
Engine.ALPHA_MULTIPLY = 4;
Engine.ALPHA_MAXIMIZED = 5;
Engine.ALPHA_ONEONE = 6;
Engine.ALPHA_PREMULTIPLIED = 7;
Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
Engine.ALPHA_INTERPOLATE = 9;
Engine.ALPHA_SCREENMODE = 10;
Engine.DELAYLOADSTATE_NONE = 0;
Engine.DELAYLOADSTATE_LOADED = 1;
Engine.DELAYLOADSTATE_LOADING = 2;
Engine.DELAYLOADSTATE_NOTLOADED = 4;
Engine.NEVER = 512;
Engine.ALWAYS = 519;
Engine.LESS = 513;
Engine.EQUAL = 514;
Engine.LEQUAL = 515;
Engine.GREATER = 516;
Engine.GEQUAL = 518;
Engine.NOTEQUAL = 517;
Engine.KEEP = 7680;
Engine.REPLACE = 7681;
Engine.INCR = 7682;
Engine.DECR = 7683;
Engine.INVERT = 5386;
Engine.INCR_WRAP = 34055;
Engine.DECR_WRAP = 34056;
Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
Engine.TEXTUREFORMAT_ALPHA = 0;
Engine.TEXTUREFORMAT_LUMINANCE = 1;
Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
Engine.TEXTUREFORMAT_RGB = 4;
Engine.TEXTUREFORMAT_RGBA = 5;
Engine.TEXTUREFORMAT_RED = 6;
Engine.TEXTUREFORMAT_R = 6;
Engine.TEXTUREFORMAT_R16_UNORM = 33322;
Engine.TEXTUREFORMAT_RG16_UNORM = 33324;
Engine.TEXTUREFORMAT_RGB16_UNORM = 32852;
Engine.TEXTUREFORMAT_RGBA16_UNORM = 32859;
Engine.TEXTUREFORMAT_R16_SNORM = 36760;
Engine.TEXTUREFORMAT_RG16_SNORM = 36761;
Engine.TEXTUREFORMAT_RGB16_SNORM = 36762;
Engine.TEXTUREFORMAT_RGBA16_SNORM = 36763;
Engine.TEXTUREFORMAT_RG = 7;
Engine.TEXTUREFORMAT_RED_INTEGER = 8;
Engine.TEXTUREFORMAT_R_INTEGER = 8;
Engine.TEXTUREFORMAT_RG_INTEGER = 9;
Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
Engine.TEXTURETYPE_UNSIGNED_INT = 0;
Engine.TEXTURETYPE_FLOAT = 1;
Engine.TEXTURETYPE_HALF_FLOAT = 2;
Engine.TEXTURETYPE_BYTE = 3;
Engine.TEXTURETYPE_SHORT = 4;
Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
Engine.TEXTURETYPE_INT = 6;
Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;
Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;
Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
Engine.TEXTURE_NEAREST_LINEAR = 7;
Engine.TEXTURE_NEAREST_NEAREST = 1;
Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
Engine.TEXTURE_LINEAR_LINEAR = 2;
Engine.TEXTURE_LINEAR_NEAREST = 12;
Engine.TEXTURE_EXPLICIT_MODE = 0;
Engine.TEXTURE_SPHERICAL_MODE = 1;
Engine.TEXTURE_PLANAR_MODE = 2;
Engine.TEXTURE_CUBIC_MODE = 3;
Engine.TEXTURE_PROJECTION_MODE = 4;
Engine.TEXTURE_SKYBOX_MODE = 5;
Engine.TEXTURE_INVCUBIC_MODE = 6;
Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
Engine.SCALEMODE_FLOOR = 1;
Engine.SCALEMODE_NEAREST = 2;
Engine.SCALEMODE_CEILING = 3;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinPassPostProcess.js
var ThinPassPostProcess, ThinPassCubePostProcess;
var init_thinPassPostProcess = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinPassPostProcess.js"() {
init_effectRenderer();
init_engine();
ThinPassPostProcess = class _ThinPassPostProcess extends EffectWrapper {
static {
__name(this, "ThinPassPostProcess");
}
_gatherImports(useWebGPU, list) {
if (useWebGPU) {
this._webGPUReady = true;
list.push(Promise.all([Promise.resolve().then(() => (init_pass_fragment2(), pass_fragment_exports2))]));
} else {
list.push(Promise.all([Promise.resolve().then(() => (init_pass_fragment(), pass_fragment_exports))]));
}
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(name260, engine = null, options) {
const localOptions = {
name: name260,
engine: engine || Engine.LastCreatedEngine,
useShaderStore: true,
useAsPostProcess: true,
fragmentShader: _ThinPassPostProcess.FragmentUrl,
...options
};
if (!localOptions.engine) {
localOptions.engine = Engine.LastCreatedEngine;
}
super(localOptions);
}
};
ThinPassPostProcess.FragmentUrl = "pass";
ThinPassCubePostProcess = class _ThinPassCubePostProcess extends EffectWrapper {
static {
__name(this, "ThinPassCubePostProcess");
}
_gatherImports(useWebGPU, list) {
if (useWebGPU) {
this._webGPUReady = true;
list.push(Promise.all([Promise.resolve().then(() => (init_passCube_fragment(), passCube_fragment_exports))]));
} else {
list.push(Promise.all([Promise.resolve().then(() => (init_passCube_fragment2(), passCube_fragment_exports2))]));
}
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(name260, engine = null, options) {
super({
...options,
name: name260,
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;
}
}
};
ThinPassCubePostProcess.FragmentUrl = "passCube";
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/passPostProcess.js
var PassPostProcess, PassCubePostProcess;
var init_passPostProcess = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/passPostProcess.js"() {
init_tslib_es6();
init_postProcess();
init_abstractEngine();
init_typeStore();
init_decorators_serialization();
init_thinPassPostProcess();
init_decorators();
PassPostProcess = class _PassPostProcess extends PostProcess {
static {
__name(this, "PassPostProcess");
}
/**
* 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(name260, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {
const localOptions = {
size: typeof options === "number" ? options : void 0,
camera,
samplingMode,
engine,
reusable,
textureType,
blockCompilation,
...options
};
super(name260, ThinPassPostProcess.FragmentUrl, {
effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassPostProcess(name260, engine, localOptions) : void 0,
...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 = class _PassCubePostProcess extends PostProcess {
static {
__name(this, "PassCubePostProcess");
}
/**
* 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(name260, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {
const localOptions = {
size: typeof options === "number" ? options : void 0,
camera,
samplingMode,
engine,
reusable,
textureType,
blockCompilation,
...options
};
super(name260, ThinPassPostProcess.FragmentUrl, {
effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassCubePostProcess(name260, engine, localOptions) : void 0,
...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);
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/textureTools.js
function CreateResizedCopy(texture, width, height, useBilinearMode = true) {
const scene = texture.getScene();
const engine = scene.getEngine();
const rtt = new RenderTargetTexture("resized" + texture.name, { width, 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;
}
function ApplyPostProcess(postProcessName, internalTexture, scene, type, samplingMode, format, width, height) {
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) => {
const postProcess = new PostProcess("postprocess", postProcessName, null, null, 1, null, samplingMode, engine, false, void 0, type, void 0, null, false, format);
postProcess.externalTextureSamplerBinding = true;
const encodedTexture = engine.createRenderTargetTexture({ width, height }, {
generateDepthBuffer: false,
generateMipMaps: false,
generateStencilBuffer: false,
samplingMode,
type,
format
});
postProcess.onEffectCreatedObservable.addOnce((e) => {
e.executeWhenCompiled(() => {
postProcess.onApply = (effect) => {
effect._bindTexture("textureSampler", internalTexture);
effect.setFloat2("scale", 1, 1);
};
scene.postProcessManager.directRender([postProcess], encodedTexture, true);
engine.restoreDefaultFramebuffer();
engine._releaseTexture(internalTexture);
if (postProcess) {
postProcess.dispose();
}
encodedTexture._swapAndDie(internalTexture);
internalTexture.type = type;
internalTexture.format = 5;
internalTexture.isReady = true;
resolve(internalTexture);
});
});
});
}
function ToHalfFloat(value) {
if (!floatView) {
floatView = new Float32Array(1);
int32View = new Int32Array(floatView.buffer);
}
floatView[0] = value;
const x = int32View[0];
let bits = x >> 16 & 32768;
let m = x >> 12 & 2047;
const e = x >> 23 & 255;
if (e < 103) {
return bits;
}
if (e > 142) {
bits |= 31744;
bits |= (e == 255 ? 0 : 1) && x & 8388607;
return bits;
}
if (e < 113) {
m |= 2048;
bits |= (m >> 114 - e) + (m >> 113 - e & 1);
return bits;
}
bits |= e - 112 << 10 | m >> 1;
bits += m & 1;
return bits;
}
function FromHalfFloat(value) {
const s = (value & 32768) >> 15;
const e = (value & 31744) >> 10;
const f = value & 1023;
if (e === 0) {
return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
} else if (e == 31) {
return f ? NaN : (s ? -1 : 1) * Infinity;
}
return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + f / Math.pow(2, 10));
}
function IsCompressedTextureFormat(format) {
switch (format) {
case 36492:
case 36493:
case 36495:
case 36494:
case 33779:
case 35919:
case 33778:
case 35918:
case 33777:
case 33776:
case 35917:
case 35916:
case 37808:
case 37840:
case 36196:
case 37492:
case 37493:
case 37494:
case 37495:
case 37496:
case 37497:
return true;
default:
return false;
}
}
async function WhenTextureReadyAsync(texture) {
if (texture.isReady()) {
return;
}
if (texture.loadingError) {
throw new Error(texture.errorObject?.message || `Texture ${texture.name} errored while loading.`);
}
const onLoadObservable = texture.onLoadObservable;
if (onLoadObservable) {
return await new Promise((res) => onLoadObservable.addOnce(() => res()));
}
const onLoadedObservable = texture._texture?.onLoadedObservable;
if (onLoadedObservable) {
return await new Promise((res) => onLoadedObservable.addOnce(() => res()));
}
throw new Error(`Cannot determine readiness of texture ${texture.name}.`);
}
async function ReadPixelsUsingRTT(texture, width, height, face, lod) {
const scene = texture.getScene();
const engine = scene.getEngine();
if (!engine.isWebGPU) {
if (texture.isCube) {
await Promise.resolve().then(() => (init_lodCube_fragment(), lodCube_fragment_exports));
} else {
await Promise.resolve().then(() => (init_lod_fragment(), lod_fragment_exports));
}
} else {
if (texture.isCube) {
await Promise.resolve().then(() => (init_lodCube_fragment2(), lodCube_fragment_exports2));
} else {
await Promise.resolve().then(() => (init_lod_fragment2(), lod_fragment_exports2));
}
}
let lodPostProcess;
if (!texture.isCube) {
lodPostProcess = new PostProcess("lod", "lod", {
uniforms: ["lod", "gamma"],
samplingMode: Texture.NEAREST_NEAREST_MIPNEAREST,
engine,
shaderLanguage: engine.isWebGPU ? 1 : 0
});
} 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 : 0
});
}
await new Promise((resolve) => {
lodPostProcess.onEffectCreatedObservable.addOnce((e) => {
e.executeWhenCompiled(() => {
resolve(0);
});
});
});
const rtt = new RenderTargetTexture("temp", { width, 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);
const bufferView = await engine.readPixels(0, 0, width, height);
const data = new Uint8Array(bufferView.buffer, 0, bufferView.byteLength);
engine.unBindFramebuffer(rtt.renderTarget);
return data;
} else {
throw Error("Render to texture failed.");
}
} finally {
rtt.dispose();
lodPostProcess.dispose();
}
}
async function GetTextureDataAsync(texture, width, height, face = 0, lod = 0) {
await WhenTextureReadyAsync(texture);
const { width: textureWidth, height: textureHeight } = texture.getSize();
const targetWidth = width ?? textureWidth;
const targetHeight = height ?? textureHeight;
if (IsCompressedTextureFormat(texture.textureFormat) || targetWidth !== textureWidth || targetHeight !== textureHeight) {
return await ReadPixelsUsingRTT(texture, targetWidth, targetHeight, face, lod);
}
let data = await texture.readPixels(face, lod);
if (!data) {
throw new Error(`Failed to read pixels from texture ${texture.name}.`);
}
if (data instanceof Float32Array) {
const data2 = new Uint8Array(data.length);
let n = data.length;
while (n--) {
const v = data[n];
data2[n] = Math.round(Clamp(v) * 255);
}
data = data2;
}
return data;
}
var floatView, int32View, TextureTools;
var init_textureTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/textureTools.js"() {
init_texture();
init_renderTargetTexture();
init_passPostProcess();
init_postProcess();
init_math_scalar_functions();
__name(CreateResizedCopy, "CreateResizedCopy");
__name(ApplyPostProcess, "ApplyPostProcess");
__name(ToHalfFloat, "ToHalfFloat");
__name(FromHalfFloat, "FromHalfFloat");
__name(IsCompressedTextureFormat, "IsCompressedTextureFormat");
__name(WhenTextureReadyAsync, "WhenTextureReadyAsync");
__name(ReadPixelsUsingRTT, "ReadPixelsUsingRTT");
__name(GetTextureDataAsync, "GetTextureDataAsync");
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,
/**
* 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 lod if the texture has multiple LODs, the lod index to use for the source
* @returns the 8-bit texture data
*/
GetTextureDataAsync
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/urlTools.js
function GetExtensionFromUrl(url) {
const urlWithoutUriParams = url.split("?")[0];
const lastDot = urlWithoutUriParams.lastIndexOf(".");
const extension = lastDot > -1 ? urlWithoutUriParams.substring(lastDot).toLowerCase() : "";
return extension;
}
var init_urlTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/urlTools.js"() {
__name(GetExtensionFromUrl, "GetExtensionFromUrl");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.cubeTexture.js
var init_abstractEngine_cubeTexture = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.cubeTexture.js"() {
init_internalTexture();
init_logger();
init_fileTools();
init_guid();
init_abstractEngine();
init_textureLoaderManager();
init_urlTools();
AbstractEngine.prototype._partialLoadFile = function(url, index, loadedFiles, onfinish, onErrorCallBack = null) {
const onload = /* @__PURE__ */ __name((data) => {
loadedFiles[index] = data;
loadedFiles._internalCount++;
if (loadedFiles._internalCount === 6) {
onfinish(loadedFiles);
}
}, "onload");
const onerror = /* @__PURE__ */ __name((request, exception) => {
if (onErrorCallBack && request) {
onErrorCallBack(request.status + " " + request.statusText, exception);
}
}, "onerror");
this._loadFile(url, onload, void 0, void 0, 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 = /* @__PURE__ */ __name((img) => {
loadedImages[index] = img;
loadedImages._internalCount++;
if (scene) {
scene.removePendingData(tokenPendingData);
}
if (loadedImages._internalCount === 6 && onfinish) {
onfinish(texture, loadedImages);
}
}, "onload");
const onerror = /* @__PURE__ */ __name((message, exception) => {
if (scene) {
scene.removePendingData(tokenPendingData);
}
if (onErrorCallBack) {
onErrorCallBack(message, exception);
}
}, "onerror");
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);
}
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 localOnError = /* @__PURE__ */ __name((message, exception) => {
texture.dispose();
if (onError) {
onError(message, exception);
} else if (message) {
Logger.Warn(message);
}
}, "localOnError");
const onInternalError = /* @__PURE__ */ __name((request, exception) => {
if (rootUrl === originalRootUrl) {
if (request) {
localOnError(request.status + " " + request.statusText, exception);
}
} else {
Logger.Warn(`Failed to load ${rootUrl}, falling back to the ${originalRootUrl}`);
this.createCubeTextureBase(originalRootUrl, scene, files, !!noMipmap, onLoad, localOnError, format, forcedExtension, createPolynomials, lodScale, lodOffset, texture, beforeLoadCubeDataCallback, imageHandler, useSRGBBuffer, buffer);
}
}, "onInternalError");
if (loaderPromise) {
loaderPromise.then((loader) => {
const onLoadData = /* @__PURE__ */ __name((data) => {
if (beforeLoadCubeDataCallback) {
beforeLoadCubeDataCallback(texture, data);
}
loader.loadCubeData(data, texture, createPolynomials, onLoad, (message, exception) => {
localOnError(message, exception);
});
}, "onLoadData");
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, localOnError);
} else {
localOnError("Textures type does not support cascades.");
}
} else {
this._loadFile(rootUrl, (data) => onLoadData(new Uint8Array(data)), void 0, scene ? scene.offlineProvider || null : void 0, 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, (texture2, imgs) => {
if (imageHandler) {
imageHandler(texture2, imgs);
}
}, files, localOnError);
}
this._internalTexturesCache.push(texture);
return texture;
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/dds.js
var dds_exports = {};
__export(dds_exports, {
DDSTools: () => DDSTools
});
function FourCCToInt32(value) {
return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
}
function Int32ToFourCC(value) {
return String.fromCharCode(value & 255, value >> 8 & 255, value >> 16 & 255, value >> 24 & 255);
}
var DDS_MAGIC, DDSD_MIPMAPCOUNT, DDSCAPS2_CUBEMAP, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, FOURCC_DXT1, FOURCC_DXT3, FOURCC_DXT5, FOURCC_DX10, FOURCC_D3DFMT_R16G16B16A16F, FOURCC_D3DFMT_R32G32B32A32F, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_B8G8R8X8_UNORM, headerLengthInt, off_magic, off_size, off_flags, off_height, off_width, off_mipmapCount, off_pfFlags, off_pfFourCC, off_RGBbpp, off_RMask, off_GMask, off_BMask, off_AMask, off_caps2, off_dxgiFormat, DDSTools;
var init_dds = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/dds.js"() {
init_math_scalar_functions();
init_logger();
init_cubemapToSphericalPolynomial();
init_textureTools();
init_abstractEngine_cubeTexture();
DDS_MAGIC = 542327876;
DDSD_MIPMAPCOUNT = 131072;
DDSCAPS2_CUBEMAP = 512;
DDPF_FOURCC = 4, DDPF_RGB = 64, DDPF_LUMINANCE = 131072;
__name(FourCCToInt32, "FourCCToInt32");
__name(Int32ToFourCC, "Int32ToFourCC");
FOURCC_DXT1 = FourCCToInt32("DXT1");
FOURCC_DXT3 = FourCCToInt32("DXT3");
FOURCC_DXT5 = FourCCToInt32("DXT5");
FOURCC_DX10 = FourCCToInt32("DX10");
FOURCC_D3DFMT_R16G16B16A16F = 113;
FOURCC_D3DFMT_R32G32B32A32F = 116;
DXGI_FORMAT_R32G32B32A32_FLOAT = 2;
DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
DXGI_FORMAT_B8G8R8X8_UNORM = 88;
headerLengthInt = 31;
off_magic = 0;
off_size = 1;
off_flags = 2;
off_height = 3;
off_width = 4;
off_mipmapCount = 7;
off_pfFlags = 20;
off_pfFourCC = 21;
off_RGBbpp = 22;
off_RMask = 23;
off_GMask = 24;
off_BMask = 25;
off_AMask = 26;
off_caps2 = 28;
off_dxgiFormat = 32;
DDSTools = class _DDSTools {
static {
__name(this, "DDSTools");
}
/**
* Gets DDS information from an array buffer
* @param data defines the array buffer view to read data from
* @returns the DDS information
*/
static GetDDSInfo(data) {
const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt);
const extendedHeader = new Int32Array(data.buffer, data.byteOffset, headerLengthInt + 4);
let mipmapCount = 1;
if (header[off_flags] & DDSD_MIPMAPCOUNT) {
mipmapCount = Math.max(1, header[off_mipmapCount]);
}
const fourCC = header[off_pfFourCC];
const dxgiFormat = fourCC === FOURCC_DX10 ? extendedHeader[off_dxgiFormat] : 0;
let textureType = 0;
switch (fourCC) {
case FOURCC_D3DFMT_R16G16B16A16F:
textureType = 2;
break;
case FOURCC_D3DFMT_R32G32B32A32F:
textureType = 1;
break;
case FOURCC_DX10:
if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
textureType = 2;
break;
}
if (dxgiFormat === DXGI_FORMAT_R32G32B32A32_FLOAT) {
textureType = 1;
break;
}
}
return {
width: header[off_width],
height: header[off_height],
mipmapCount,
isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
isCompressed: fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5,
dxgiFormat,
textureType
};
}
static _GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {
const destArray = new Float32Array(dataLength);
const srcData = new Uint16Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcPos = (x + y * width) * 4;
destArray[index] = FromHalfFloat(srcData[srcPos]);
destArray[index + 1] = FromHalfFloat(srcData[srcPos + 1]);
destArray[index + 2] = FromHalfFloat(srcData[srcPos + 2]);
if (_DDSTools.StoreLODInAlphaChannel) {
destArray[index + 3] = lod;
} else {
destArray[index + 3] = FromHalfFloat(srcData[srcPos + 3]);
}
index += 4;
}
}
return destArray;
}
static _GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {
if (_DDSTools.StoreLODInAlphaChannel) {
const destArray = new Uint16Array(dataLength);
const srcData = new Uint16Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcPos = (x + y * width) * 4;
destArray[index] = srcData[srcPos];
destArray[index + 1] = srcData[srcPos + 1];
destArray[index + 2] = srcData[srcPos + 2];
destArray[index + 3] = ToHalfFloat(lod);
index += 4;
}
}
return destArray;
}
return new Uint16Array(arrayBuffer, dataOffset, dataLength);
}
static _GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {
if (_DDSTools.StoreLODInAlphaChannel) {
const destArray = new Float32Array(dataLength);
const srcData = new Float32Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcPos = (x + y * width) * 4;
destArray[index] = srcData[srcPos];
destArray[index + 1] = srcData[srcPos + 1];
destArray[index + 2] = srcData[srcPos + 2];
destArray[index + 3] = lod;
index += 4;
}
}
return destArray;
}
return new Float32Array(arrayBuffer, dataOffset, dataLength);
}
static _GetFloatAsHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {
const destArray = new Uint16Array(dataLength);
const srcData = new Float32Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
destArray[index] = ToHalfFloat(srcData[index]);
destArray[index + 1] = ToHalfFloat(srcData[index + 1]);
destArray[index + 2] = ToHalfFloat(srcData[index + 2]);
if (_DDSTools.StoreLODInAlphaChannel) {
destArray[index + 3] = ToHalfFloat(lod);
} else {
destArray[index + 3] = ToHalfFloat(srcData[index + 3]);
}
index += 4;
}
}
return destArray;
}
static _GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {
const destArray = new Uint8Array(dataLength);
const srcData = new Float32Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcPos = (x + y * width) * 4;
destArray[index] = Clamp(srcData[srcPos]) * 255;
destArray[index + 1] = Clamp(srcData[srcPos + 1]) * 255;
destArray[index + 2] = Clamp(srcData[srcPos + 2]) * 255;
if (_DDSTools.StoreLODInAlphaChannel) {
destArray[index + 3] = lod;
} else {
destArray[index + 3] = Clamp(srcData[srcPos + 3]) * 255;
}
index += 4;
}
}
return destArray;
}
static _GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {
const destArray = new Uint8Array(dataLength);
const srcData = new Uint16Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcPos = (x + y * width) * 4;
destArray[index] = Clamp(FromHalfFloat(srcData[srcPos])) * 255;
destArray[index + 1] = Clamp(FromHalfFloat(srcData[srcPos + 1])) * 255;
destArray[index + 2] = Clamp(FromHalfFloat(srcData[srcPos + 2])) * 255;
if (_DDSTools.StoreLODInAlphaChannel) {
destArray[index + 3] = lod;
} else {
destArray[index + 3] = Clamp(FromHalfFloat(srcData[srcPos + 3])) * 255;
}
index += 4;
}
}
return destArray;
}
static _GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
const byteArray = new Uint8Array(dataLength);
const srcData = new Uint8Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcPos = (x + y * width) * 4;
byteArray[index] = srcData[srcPos + rOffset];
byteArray[index + 1] = srcData[srcPos + gOffset];
byteArray[index + 2] = srcData[srcPos + bOffset];
byteArray[index + 3] = srcData[srcPos + aOffset];
index += 4;
}
}
return byteArray;
}
static _ExtractLongWordOrder(value) {
if (value === 0 || value === 255 || value === -16777216) {
return 0;
}
return 1 + _DDSTools._ExtractLongWordOrder(value >> 8);
}
static _GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
const byteArray = new Uint8Array(dataLength);
const srcData = new Uint8Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcPos = (x + y * width) * 3;
byteArray[index] = srcData[srcPos + rOffset];
byteArray[index + 1] = srcData[srcPos + gOffset];
byteArray[index + 2] = srcData[srcPos + bOffset];
index += 3;
}
}
return byteArray;
}
static _GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer) {
const byteArray = new Uint8Array(dataLength);
const srcData = new Uint8Array(arrayBuffer, dataOffset);
let index = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcPos = x + y * width;
byteArray[index] = srcData[srcPos];
index++;
}
}
return byteArray;
}
/**
* Uploads DDS Levels to a Babylon Texture
* @internal
*/
static UploadDDSLevels(engine, texture, data, info, loadMipmaps, faces, lodIndex = -1, currentFace, destTypeMustBeFilterable = true) {
let sphericalPolynomialFaces = null;
if (info.sphericalPolynomial) {
sphericalPolynomialFaces = [];
}
const ext = !!engine.getCaps().s3tc;
texture.generateMipMaps = loadMipmaps;
const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt);
let fourCC, width, height, dataLength = 0, dataOffset;
let byteArray, mipmapCount, mip;
let internalCompressedFormat = 0;
let blockBytes = 1;
if (header[off_magic] !== DDS_MAGIC) {
Logger.Error("Invalid magic number in DDS header");
return;
}
if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
Logger.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
return;
}
if (info.isCompressed && !ext) {
Logger.Error("Compressed textures are not supported on this platform.");
return;
}
let bpp = header[off_RGBbpp];
dataOffset = header[off_size] + 4;
let computeFormats = false;
if (info.isFourCC) {
fourCC = header[off_pfFourCC];
switch (fourCC) {
case FOURCC_DXT1:
blockBytes = 8;
internalCompressedFormat = 33777;
break;
case FOURCC_DXT3:
blockBytes = 16;
internalCompressedFormat = 33778;
break;
case FOURCC_DXT5:
blockBytes = 16;
internalCompressedFormat = 33779;
break;
case FOURCC_D3DFMT_R16G16B16A16F:
computeFormats = true;
bpp = 64;
break;
case FOURCC_D3DFMT_R32G32B32A32F:
computeFormats = true;
bpp = 128;
break;
case FOURCC_DX10: {
dataOffset += 5 * 4;
let supported = false;
switch (info.dxgiFormat) {
case DXGI_FORMAT_R16G16B16A16_FLOAT:
computeFormats = true;
bpp = 64;
supported = true;
break;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
computeFormats = true;
bpp = 128;
supported = true;
break;
case DXGI_FORMAT_B8G8R8X8_UNORM:
info.isRGB = true;
info.isFourCC = false;
bpp = 32;
supported = true;
break;
}
if (supported) {
break;
}
}
// eslint-disable-next-line no-fallthrough
default:
Logger.Error(["Unsupported FourCC code:", Int32ToFourCC(fourCC)]);
return;
}
}
const rOffset = _DDSTools._ExtractLongWordOrder(header[off_RMask]);
const gOffset = _DDSTools._ExtractLongWordOrder(header[off_GMask]);
const bOffset = _DDSTools._ExtractLongWordOrder(header[off_BMask]);
const aOffset = _DDSTools._ExtractLongWordOrder(header[off_AMask]);
if (computeFormats) {
internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
}
mipmapCount = 1;
if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
mipmapCount = Math.max(1, header[off_mipmapCount]);
}
const startFace = currentFace || 0;
const caps = engine.getCaps();
for (let face = startFace; face < faces; face++) {
width = header[off_width];
height = header[off_height];
for (mip = 0; mip < mipmapCount; ++mip) {
if (lodIndex === -1 || lodIndex === mip) {
const i = lodIndex === -1 ? mip : 0;
if (!info.isCompressed && info.isFourCC) {
texture.format = 5;
dataLength = width * height * 4;
let floatArray = null;
if (engine._badOS || engine._badDesktopOS || !caps.textureHalfFloat && !caps.textureFloat) {
if (bpp === 128) {
floatArray = _DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);
if (sphericalPolynomialFaces && i == 0) {
sphericalPolynomialFaces.push(_DDSTools._GetFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i));
}
} else if (bpp === 64) {
floatArray = _DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);
if (sphericalPolynomialFaces && i == 0) {
sphericalPolynomialFaces.push(_DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i));
}
}
texture.type = 0;
} else {
const floatAvailable = caps.textureFloat && (destTypeMustBeFilterable && caps.textureFloatLinearFiltering || !destTypeMustBeFilterable);
const halfFloatAvailable = caps.textureHalfFloat && (destTypeMustBeFilterable && caps.textureHalfFloatLinearFiltering || !destTypeMustBeFilterable);
const destType = (bpp === 128 || bpp === 64 && !halfFloatAvailable) && floatAvailable ? 1 : (bpp === 64 || bpp === 128 && !floatAvailable) && halfFloatAvailable ? 2 : 0;
let dataGetter;
let dataGetterPolynomial = null;
switch (bpp) {
case 128: {
switch (destType) {
case 1:
dataGetter = _DDSTools._GetFloatRGBAArrayBuffer;
dataGetterPolynomial = null;
break;
case 2:
dataGetter = _DDSTools._GetFloatAsHalfFloatRGBAArrayBuffer;
dataGetterPolynomial = _DDSTools._GetFloatRGBAArrayBuffer;
break;
case 0:
dataGetter = _DDSTools._GetFloatAsUIntRGBAArrayBuffer;
dataGetterPolynomial = _DDSTools._GetFloatRGBAArrayBuffer;
break;
}
break;
}
default: {
switch (destType) {
case 1:
dataGetter = _DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;
dataGetterPolynomial = null;
break;
case 2:
dataGetter = _DDSTools._GetHalfFloatRGBAArrayBuffer;
dataGetterPolynomial = _DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;
break;
case 0:
dataGetter = _DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer;
dataGetterPolynomial = _DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;
break;
}
break;
}
}
texture.type = destType;
floatArray = dataGetter(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);
if (sphericalPolynomialFaces && i == 0) {
sphericalPolynomialFaces.push(dataGetterPolynomial ? dataGetterPolynomial(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i) : floatArray);
}
}
if (floatArray) {
engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
}
} else if (info.isRGB) {
texture.type = 0;
if (bpp === 24) {
texture.format = 4;
dataLength = width * height * 3;
byteArray = _DDSTools._GetRGBArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset);
engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
} else {
texture.format = 5;
dataLength = width * height * 4;
byteArray = _DDSTools._GetRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset, aOffset);
engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
}
} else if (info.isLuminance) {
const unpackAlignment = engine._getUnpackAlignement();
const unpaddedRowSize = width;
const paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
byteArray = _DDSTools._GetLuminanceArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer);
texture.format = 1;
texture.type = 0;
engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
} else {
dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
byteArray = new Uint8Array(data.buffer, data.byteOffset + dataOffset, dataLength);
texture.type = 0;
engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
}
}
dataOffset += bpp ? width * height * (bpp / 8) : dataLength;
width *= 0.5;
height *= 0.5;
width = Math.max(1, width);
height = Math.max(1, height);
}
if (currentFace !== void 0) {
break;
}
}
if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
info.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
size: header[off_width],
right: sphericalPolynomialFaces[0],
left: sphericalPolynomialFaces[1],
up: sphericalPolynomialFaces[2],
down: sphericalPolynomialFaces[3],
front: sphericalPolynomialFaces[4],
back: sphericalPolynomialFaces[5],
format: 5,
type: 1,
gammaSpace: false
});
} else {
info.sphericalPolynomial = void 0;
}
}
};
DDSTools.StoreLODInAlphaChannel = false;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader.js
var ddsTextureLoader_exports = {};
__export(ddsTextureLoader_exports, {
_DDSTextureLoader: () => _DDSTextureLoader
});
var _DDSTextureLoader;
var init_ddsTextureLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader.js"() {
init_sphericalPolynomial();
init_dds();
_DDSTextureLoader = class {
static {
__name(this, "_DDSTextureLoader");
}
constructor() {
this.supportCascades = true;
}
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param imgs contains the cube maps
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
*/
loadCubeData(imgs, texture, createPolynomials, onLoad) {
const engine = texture.getEngine();
let info;
let loadMipmap = false;
let maxLevel = 1e3;
if (Array.isArray(imgs)) {
for (let index = 0; index < imgs.length; index++) {
const data = imgs[index];
info = DDSTools.GetDDSInfo(data);
texture.width = info.width;
texture.height = info.height;
loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
engine._unpackFlipY(info.isCompressed);
DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6, -1, index);
if (!info.isFourCC && info.mipmapCount === 1) {
engine.generateMipMapsForCubemap(texture);
} else {
maxLevel = info.mipmapCount - 1;
}
}
} else {
const data = imgs;
info = DDSTools.GetDDSInfo(data);
texture.width = info.width;
texture.height = info.height;
if (createPolynomials) {
info.sphericalPolynomial = new SphericalPolynomial();
}
loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
engine._unpackFlipY(info.isCompressed);
DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
if (!info.isFourCC && info.mipmapCount === 1) {
engine.generateMipMapsForCubemap(texture, false);
} else {
maxLevel = info.mipmapCount - 1;
}
}
engine._setCubeMapTextureParams(texture, loadMipmap, maxLevel);
texture.isReady = true;
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad({ isDDS: true, width: texture.width, info, data: imgs, texture });
}
}
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
loadData(data, texture, callback) {
const info = DDSTools.GetDDSInfo(data);
const loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && Math.max(info.width, info.height) >> info.mipmapCount - 1 === 1;
callback(info.width, info.height, loadMipmap, info.isFourCC, () => {
DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
});
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/basisWorker.js
function workerFunction() {
const _BASIS_FORMAT = {
cTFETC1: 0,
cTFETC2: 1,
cTFBC1: 2,
cTFBC3: 3,
cTFBC4: 4,
cTFBC5: 5,
cTFBC7: 6,
cTFPVRTC1_4_RGB: 8,
cTFPVRTC1_4_RGBA: 9,
cTFASTC_4x4: 10,
cTFATC_RGB: 11,
cTFATC_RGBA_INTERPOLATED_ALPHA: 12,
cTFRGBA32: 13,
cTFRGB565: 14,
cTFBGR565: 15,
cTFRGBA4444: 16,
cTFFXT1_RGB: 17,
cTFPVRTC2_4_RGB: 18,
cTFPVRTC2_4_RGBA: 19,
cTFETC2_EAC_R11: 20,
cTFETC2_EAC_RG11: 21
};
let transcoderModulePromise = null;
onmessage = /* @__PURE__ */ __name((event) => {
if (event.data.action === "init") {
if (event.data.url) {
try {
importScripts(event.data.url);
} catch (e) {
postMessage({ action: "error", error: e });
}
}
if (!transcoderModulePromise) {
transcoderModulePromise = BASIS({
// Override wasm binary
wasmBinary: event.data.wasmBinary
});
}
if (transcoderModulePromise !== null) {
transcoderModulePromise.then((m) => {
BASIS = m;
m.initializeBasis();
postMessage({ action: "init" });
});
}
} else if (event.data.action === "transcode") {
const config = event.data.config;
const imgData = event.data.imageData;
const loadedFile = new BASIS.BasisFile(imgData);
const fileInfo = GetFileInfo2(loadedFile);
let format = event.data.ignoreSupportedFormats ? null : GetSupportedTranscodeFormat(event.data.config, fileInfo);
let needsConversion = false;
if (format === null) {
needsConversion = true;
format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1;
}
let success = true;
if (!loadedFile.startTranscoding()) {
success = false;
}
const buffers = [];
for (let imageIndex = 0; imageIndex < fileInfo.images.length; imageIndex++) {
if (!success) {
break;
}
const image = fileInfo.images[imageIndex];
if (config.loadSingleImage === void 0 || config.loadSingleImage === imageIndex) {
let mipCount = image.levels.length;
if (config.loadMipmapLevels === false) {
mipCount = 1;
}
for (let levelIndex = 0; levelIndex < mipCount; levelIndex++) {
const levelInfo = image.levels[levelIndex];
const pixels = TranscodeLevel(loadedFile, imageIndex, levelIndex, format, needsConversion);
if (!pixels) {
success = false;
break;
}
levelInfo.transcodedPixels = pixels;
buffers.push(levelInfo.transcodedPixels.buffer);
}
}
}
loadedFile.close();
loadedFile.delete();
if (needsConversion) {
format = -1;
}
if (!success) {
postMessage({ action: "transcode", success, id: event.data.id });
} else {
postMessage({ action: "transcode", success, id: event.data.id, fileInfo, format }, buffers);
}
}
}, "onmessage");
function GetSupportedTranscodeFormat(config, fileInfo) {
let format = null;
if (config.supportedCompressionFormats) {
if (config.supportedCompressionFormats.astc) {
format = _BASIS_FORMAT.cTFASTC_4x4;
} else if (config.supportedCompressionFormats.bc7) {
format = _BASIS_FORMAT.cTFBC7;
} else if (config.supportedCompressionFormats.s3tc) {
format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1;
} else if (config.supportedCompressionFormats.pvrtc) {
format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFPVRTC1_4_RGBA : _BASIS_FORMAT.cTFPVRTC1_4_RGB;
} else if (config.supportedCompressionFormats.etc2) {
format = _BASIS_FORMAT.cTFETC2;
} else if (config.supportedCompressionFormats.etc1) {
format = _BASIS_FORMAT.cTFETC1;
} else {
format = _BASIS_FORMAT.cTFRGB565;
}
}
return format;
}
__name(GetSupportedTranscodeFormat, "GetSupportedTranscodeFormat");
function GetFileInfo2(basisFile) {
const hasAlpha = basisFile.getHasAlpha();
const imageCount = basisFile.getNumImages();
const images = [];
for (let i = 0; i < imageCount; i++) {
const imageInfo = {
levels: []
};
const levelCount = basisFile.getNumLevels(i);
for (let level = 0; level < levelCount; level++) {
const levelInfo = {
width: basisFile.getImageWidth(i, level),
height: basisFile.getImageHeight(i, level)
};
imageInfo.levels.push(levelInfo);
}
images.push(imageInfo);
}
const info = { hasAlpha, images };
return info;
}
__name(GetFileInfo2, "GetFileInfo");
function TranscodeLevel(loadedFile, imageIndex, levelIndex, format, convertToRgb565) {
const dstSize = loadedFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, format);
let dst = new Uint8Array(dstSize);
if (!loadedFile.transcodeImage(dst, imageIndex, levelIndex, format, 1, 0)) {
return null;
}
if (convertToRgb565) {
const alignedWidth = loadedFile.getImageWidth(imageIndex, levelIndex) + 3 & ~3;
const alignedHeight = loadedFile.getImageHeight(imageIndex, levelIndex) + 3 & ~3;
dst = ConvertDxtToRgb565(dst, 0, alignedWidth, alignedHeight);
}
return dst;
}
__name(TranscodeLevel, "TranscodeLevel");
function ConvertDxtToRgb565(src, srcByteOffset, width, height) {
const c = new Uint16Array(4);
const dst = new Uint16Array(width * height);
const blockWidth = width / 4;
const blockHeight = height / 4;
for (let blockY = 0; blockY < blockHeight; blockY++) {
for (let blockX = 0; blockX < blockWidth; blockX++) {
const i = srcByteOffset + 8 * (blockY * blockWidth + blockX);
c[0] = src[i] | src[i + 1] << 8;
c[1] = src[i + 2] | src[i + 3] << 8;
c[2] = (2 * (c[0] & 31) + 1 * (c[1] & 31)) / 3 | (2 * (c[0] & 2016) + 1 * (c[1] & 2016)) / 3 & 2016 | (2 * (c[0] & 63488) + 1 * (c[1] & 63488)) / 3 & 63488;
c[3] = (2 * (c[1] & 31) + 1 * (c[0] & 31)) / 3 | (2 * (c[1] & 2016) + 1 * (c[0] & 2016)) / 3 & 2016 | (2 * (c[1] & 63488) + 1 * (c[0] & 63488)) / 3 & 63488;
for (let row = 0; row < 4; row++) {
const m = src[i + 4 + row];
let dstI = (blockY * 4 + row) * width + blockX * 4;
dst[dstI++] = c[m & 3];
dst[dstI++] = c[m >> 2 & 3];
dst[dstI++] = c[m >> 4 & 3];
dst[dstI++] = c[m >> 6 & 3];
}
}
}
return dst;
}
__name(ConvertDxtToRgb565, "ConvertDxtToRgb565");
}
async function initializeWebWorker(worker, wasmBinary, moduleUrl) {
return await new Promise((res, reject) => {
const initHandler = /* @__PURE__ */ __name((msg) => {
if (msg.data.action === "init") {
worker.removeEventListener("message", initHandler);
res(worker);
} else if (msg.data.action === "error") {
reject(msg.data.error || "error initializing worker");
}
}, "initHandler");
worker.addEventListener("message", initHandler);
worker.postMessage({ action: "init", url: moduleUrl ? Tools.GetBabylonScriptURL(moduleUrl) : void 0, wasmBinary }, [wasmBinary]);
});
}
var init_basisWorker = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/basisWorker.js"() {
init_tools();
__name(workerFunction, "workerFunction");
__name(initializeWebWorker, "initializeWebWorker");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/basis.js
var BasisFileInfo, TranscodeResult, BasisTranscodeConfiguration, BASIS_FORMATS, BasisToolsOptions, GetInternalFormatFromBasisFormat, WorkerPromise, LocalWorker, ActionId, IgnoreSupportedFormats, CreateWorkerAsync, SetBasisTranscoderWorker, TranscodeAsync, BindTexture, LoadTextureFromTranscodeResult, BasisTools;
var init_basis = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/basis.js"() {
init_tools();
init_texture();
init_internalTexture();
init_basisWorker();
BasisFileInfo = class {
static {
__name(this, "BasisFileInfo");
}
};
TranscodeResult = class {
static {
__name(this, "TranscodeResult");
}
};
BasisTranscodeConfiguration = class {
static {
__name(this, "BasisTranscodeConfiguration");
}
};
(function(BASIS_FORMATS2) {
BASIS_FORMATS2[BASIS_FORMATS2["cTFETC1"] = 0] = "cTFETC1";
BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2"] = 1] = "cTFETC2";
BASIS_FORMATS2[BASIS_FORMATS2["cTFBC1"] = 2] = "cTFBC1";
BASIS_FORMATS2[BASIS_FORMATS2["cTFBC3"] = 3] = "cTFBC3";
BASIS_FORMATS2[BASIS_FORMATS2["cTFBC4"] = 4] = "cTFBC4";
BASIS_FORMATS2[BASIS_FORMATS2["cTFBC5"] = 5] = "cTFBC5";
BASIS_FORMATS2[BASIS_FORMATS2["cTFBC7"] = 6] = "cTFBC7";
BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC1_4_RGB"] = 8] = "cTFPVRTC1_4_RGB";
BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC1_4_RGBA"] = 9] = "cTFPVRTC1_4_RGBA";
BASIS_FORMATS2[BASIS_FORMATS2["cTFASTC_4x4"] = 10] = "cTFASTC_4x4";
BASIS_FORMATS2[BASIS_FORMATS2["cTFATC_RGB"] = 11] = "cTFATC_RGB";
BASIS_FORMATS2[BASIS_FORMATS2["cTFATC_RGBA_INTERPOLATED_ALPHA"] = 12] = "cTFATC_RGBA_INTERPOLATED_ALPHA";
BASIS_FORMATS2[BASIS_FORMATS2["cTFRGBA32"] = 13] = "cTFRGBA32";
BASIS_FORMATS2[BASIS_FORMATS2["cTFRGB565"] = 14] = "cTFRGB565";
BASIS_FORMATS2[BASIS_FORMATS2["cTFBGR565"] = 15] = "cTFBGR565";
BASIS_FORMATS2[BASIS_FORMATS2["cTFRGBA4444"] = 16] = "cTFRGBA4444";
BASIS_FORMATS2[BASIS_FORMATS2["cTFFXT1_RGB"] = 17] = "cTFFXT1_RGB";
BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC2_4_RGB"] = 18] = "cTFPVRTC2_4_RGB";
BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC2_4_RGBA"] = 19] = "cTFPVRTC2_4_RGBA";
BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2_EAC_R11"] = 20] = "cTFETC2_EAC_R11";
BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2_EAC_RG11"] = 21] = "cTFETC2_EAC_RG11";
})(BASIS_FORMATS || (BASIS_FORMATS = {}));
BasisToolsOptions = {
/**
* URL to use when loading the basis transcoder
*/
JSModuleURL: `${Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,
/**
* URL to use when loading the wasm module for the transcoder
*/
WasmModuleURL: `${Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`
};
GetInternalFormatFromBasisFormat = /* @__PURE__ */ __name((basisFormat, engine) => {
let format;
switch (basisFormat) {
case BASIS_FORMATS.cTFETC1:
format = 36196;
break;
case BASIS_FORMATS.cTFBC1:
format = 33776;
break;
case BASIS_FORMATS.cTFBC4:
format = 33779;
break;
case BASIS_FORMATS.cTFASTC_4x4:
format = 37808;
break;
case BASIS_FORMATS.cTFETC2:
format = 37496;
break;
case BASIS_FORMATS.cTFBC7:
format = 36492;
break;
}
if (format === void 0) {
throw "The chosen Basis transcoder format is not currently supported";
}
return format;
}, "GetInternalFormatFromBasisFormat");
WorkerPromise = null;
LocalWorker = null;
ActionId = 0;
IgnoreSupportedFormats = false;
CreateWorkerAsync = /* @__PURE__ */ __name(async () => {
if (!WorkerPromise) {
WorkerPromise = new Promise((res, reject) => {
if (LocalWorker) {
res(LocalWorker);
} else {
Tools.LoadFileAsync(Tools.GetBabylonScriptURL(BasisToolsOptions.WasmModuleURL)).then((wasmBinary) => {
if (typeof URL !== "function") {
return reject("Basis transcoder requires an environment with a URL constructor");
}
const workerBlobUrl = URL.createObjectURL(new Blob([`(${workerFunction})()`], { type: "application/javascript" }));
LocalWorker = new Worker(workerBlobUrl);
initializeWebWorker(LocalWorker, wasmBinary, BasisToolsOptions.JSModuleURL).then(res, reject);
}).catch(reject);
}
});
}
return await WorkerPromise;
}, "CreateWorkerAsync");
SetBasisTranscoderWorker = /* @__PURE__ */ __name((worker) => {
LocalWorker = worker;
}, "SetBasisTranscoderWorker");
TranscodeAsync = /* @__PURE__ */ __name(async (data, config) => {
const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
return await new Promise((res, rej) => {
CreateWorkerAsync().then(() => {
const actionId = ActionId++;
const messageHandler = /* @__PURE__ */ __name((msg) => {
if (msg.data.action === "transcode" && msg.data.id === actionId) {
LocalWorker.removeEventListener("message", messageHandler);
if (!msg.data.success) {
rej("Transcode is not supported on this device");
} else {
res(msg.data);
}
}
}, "messageHandler");
LocalWorker.addEventListener("message", messageHandler);
const dataViewCopy = new Uint8Array(dataView.byteLength);
dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength));
LocalWorker.postMessage({ action: "transcode", id: actionId, imageData: dataViewCopy, config, ignoreSupportedFormats: IgnoreSupportedFormats }, [
dataViewCopy.buffer
]);
}, (error) => {
rej(error);
});
});
}, "TranscodeAsync");
BindTexture = /* @__PURE__ */ __name((texture, engine) => {
let target = engine._gl?.TEXTURE_2D;
if (texture.isCube) {
target = engine._gl?.TEXTURE_CUBE_MAP;
}
engine._bindTextureDirectly(target, texture, true);
}, "BindTexture");
LoadTextureFromTranscodeResult = /* @__PURE__ */ __name((texture, transcodeResult) => {
const engine = texture.getEngine();
for (let i = 0; i < transcodeResult.fileInfo.images.length; i++) {
const rootImage = transcodeResult.fileInfo.images[i].levels[0];
texture._invertVScale = texture.invertY;
if (transcodeResult.format === -1 || transcodeResult.format === BASIS_FORMATS.cTFRGB565) {
texture.type = 10;
texture.format = 4;
if (engine._features.basisNeedsPOT && (Math.log2(rootImage.width) % 1 !== 0 || Math.log2(rootImage.height) % 1 !== 0)) {
const source = new InternalTexture(
engine,
2
/* InternalTextureSource.Temp */
);
texture._invertVScale = texture.invertY;
source.type = 10;
source.format = 4;
source.width = rootImage.width + 3 & ~3;
source.height = rootImage.height + 3 & ~3;
BindTexture(source, engine);
engine._uploadDataToTextureDirectly(source, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true);
engine._rescaleTexture(source, texture, engine.scenes[0], engine._getInternalFormat(4), () => {
engine._releaseTexture(source);
BindTexture(texture, engine);
});
} else {
texture._invertVScale = !texture.invertY;
texture.width = rootImage.width + 3 & ~3;
texture.height = rootImage.height + 3 & ~3;
texture.samplingMode = 2;
BindTexture(texture, engine);
engine._uploadDataToTextureDirectly(texture, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true);
}
} else {
texture.width = rootImage.width;
texture.height = rootImage.height;
texture.generateMipMaps = transcodeResult.fileInfo.images[i].levels.length > 1;
const format = BasisTools.GetInternalFormatFromBasisFormat(transcodeResult.format, engine);
texture.format = format;
BindTexture(texture, engine);
const levels = transcodeResult.fileInfo.images[i].levels;
for (let index = 0; index < levels.length; index++) {
const level = levels[index];
engine._uploadCompressedDataToTextureDirectly(texture, format, level.width, level.height, level.transcodedPixels, i, index);
}
if (engine._features.basisNeedsPOT && (Math.log2(texture.width) % 1 !== 0 || Math.log2(texture.height) % 1 !== 0)) {
Tools.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1.");
texture._cachedWrapU = Texture.CLAMP_ADDRESSMODE;
texture._cachedWrapV = Texture.CLAMP_ADDRESSMODE;
}
}
}
}, "LoadTextureFromTranscodeResult");
BasisTools = {
/**
* URL to use when loading the basis transcoder
*/
JSModuleURL: BasisToolsOptions.JSModuleURL,
/**
* URL to use when loading the wasm module for the transcoder
*/
WasmModuleURL: BasisToolsOptions.WasmModuleURL,
/**
* Get the internal format to be passed to texImage2D corresponding to the .basis format value
* @param basisFormat format chosen from GetSupportedTranscodeFormat
* @returns internal format corresponding to the Basis format
*/
GetInternalFormatFromBasisFormat,
/**
* Transcodes a loaded image file to compressed pixel data
* @param data image data to transcode
* @param config configuration options for the transcoding
* @returns a promise resulting in the transcoded image
*/
TranscodeAsync,
/**
* Loads a texture from the transcode result
* @param texture texture load to
* @param transcodeResult the result of transcoding the basis file to load from
*/
LoadTextureFromTranscodeResult
};
Object.defineProperty(BasisTools, "JSModuleURL", {
get: /* @__PURE__ */ __name(function() {
return BasisToolsOptions.JSModuleURL;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
BasisToolsOptions.JSModuleURL = value;
}, "set")
});
Object.defineProperty(BasisTools, "WasmModuleURL", {
get: /* @__PURE__ */ __name(function() {
return BasisToolsOptions.WasmModuleURL;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
BasisToolsOptions.WasmModuleURL = value;
}, "set")
});
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/basisTextureLoader.js
var basisTextureLoader_exports = {};
__export(basisTextureLoader_exports, {
_BasisTextureLoader: () => _BasisTextureLoader
});
var _BasisTextureLoader;
var init_basisTextureLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/basisTextureLoader.js"() {
init_basis();
init_tools();
_BasisTextureLoader = class {
static {
__name(this, "_BasisTextureLoader");
}
constructor() {
this.supportCascades = false;
}
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
* @param onError defines the callback to trigger in case of error
*/
loadCubeData(data, texture, createPolynomials, onLoad, onError) {
if (Array.isArray(data)) {
return;
}
const caps = texture.getEngine().getCaps();
const transcodeConfig = {
supportedCompressionFormats: {
etc1: caps.etc1 ? true : false,
s3tc: caps.s3tc ? true : false,
pvrtc: caps.pvrtc ? true : false,
etc2: caps.etc2 ? true : false,
astc: caps.astc ? true : false,
bc7: caps.bptc ? true : false
}
};
TranscodeAsync(data, transcodeConfig).then((result) => {
const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps;
LoadTextureFromTranscodeResult(texture, result);
texture.getEngine()._setCubeMapTextureParams(texture, hasMipmap);
texture.isReady = true;
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
}).catch((err) => {
const errorMessage = "Failed to transcode Basis file, transcoding may not be supported on this device";
Tools.Warn(errorMessage);
texture.isReady = true;
if (onError) {
onError(err);
}
});
}
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
loadData(data, texture, callback) {
const caps = texture.getEngine().getCaps();
const transcodeConfig = {
supportedCompressionFormats: {
etc1: caps.etc1 ? true : false,
s3tc: caps.s3tc ? true : false,
pvrtc: caps.pvrtc ? true : false,
etc2: caps.etc2 ? true : false,
astc: caps.astc ? true : false,
bc7: caps.bptc ? true : false
}
};
TranscodeAsync(data, transcodeConfig).then((result) => {
const rootImage = result.fileInfo.images[0].levels[0];
const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps;
callback(rootImage.width, rootImage.height, hasMipmap, result.format !== -1, () => {
LoadTextureFromTranscodeResult(texture, result);
});
}).catch((err) => {
Tools.Warn("Failed to transcode Basis file, transcoding may not be supported on this device");
Tools.Warn(`Failed to transcode Basis file: ${err}`);
callback(0, 0, false, false, () => {
}, true);
});
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/helperFunctions.js
var name11, shader11, helperFunctionsWGSL;
var init_helperFunctions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/helperFunctions.js"() {
init_shaderStore();
name11 = "helperFunctions";
shader11 = `const PI: f32=3.1415926535897932384626433832795;const TWO_PI: f32=6.283185307179586;const HALF_PI: f32=1.5707963267948966;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const RECIPROCAL_PI4: f32=0.07957747154594767;const HALF_MIN: f32=5.96046448e-08;
const LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3f=vec3f(0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;}
fn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);}
fn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(),vec3f(1.0));}
fn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);}
fn maxEps(x: f32)->f32 {return max(x,Epsilon);}
fn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));}
fn absEps(x: f32)->f32 {return abs(x)+Epsilon;}
fn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3f=inMatrix[0];let i1: vec3f=inMatrix[1];let i2: vec3f=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(
vec3(i0.x,i1.x,i2.x),
vec3(i0.y,i1.y,i2.y),
vec3(i0.z,i1.z,i2.z)
);return outMatrix;}
fn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,
b11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,
b21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}
#if USE_EXACT_SRGB_CONVERSIONS
fn toLinearSpaceExact(color: vec3f)->vec3f
{let nearZeroSection: vec3f=0.0773993808*color;let remainingSection: vec3f=pow(0.947867299*(color+vec3f(0.055)),vec3f(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.04045)));}
fn toGammaSpaceExact(color: vec3f)->vec3f
{let nearZeroSection: vec3f=12.92*color;let remainingSection: vec3f=1.055*pow(color,vec3f(0.41666))-vec3f(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.0031308)));}
#endif
fn toLinearSpace(color: f32)->f32
{
#if USE_EXACT_SRGB_CONVERSIONS
var nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045);
#else
return pow(color,LinearEncodePowerApprox);
#endif
}
fn toLinearSpaceVec3(color: vec3f)->vec3f
{
#if USE_EXACT_SRGB_CONVERSIONS
return toLinearSpaceExact(color);
#else
return pow(color,vec3f(LinearEncodePowerApprox));
#endif
}
fn toLinearSpaceVec4(color: vec4)->vec4
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4f(toLinearSpaceExact(color.rgb),color.a);
#else
return vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a);
#endif
}
fn toGammaSpace(color: vec4)->vec4
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4(toGammaSpaceExact(color.rgb),color.a);
#else
return vec4(pow(color.rgb,vec3f(GammaEncodePowerApprox)),color.a);
#endif
}
fn toGammaSpaceVec3(color: vec3f)->vec3f
{
#if USE_EXACT_SRGB_CONVERSIONS
return toGammaSpaceExact(color);
#else
return pow(color,vec3f(GammaEncodePowerApprox));
#endif
}
fn squareVec3(value: vec3f)->vec3f
{return value*value;}
fn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}
fn getLuminance(color: vec3f)->f32
{return saturate(dot(color,LuminanceEncodeApprox));}
fn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}
fn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}
const rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3f)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3f =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(saturateVec3(rgb),D);}
fn fromRGBD(rgbd: vec4)->vec3f {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}
fn parallaxCorrectNormal(vertexPos: vec3f,origVec: vec3f,cubeSize: vec3f,cubePos: vec3f)->vec3f {let invOrigVec: vec3f=vec3f(1.)/origVec;let halfSize: vec3f=cubeSize*0.5;let intersecAtMaxPlane: vec3f=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3f=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3f=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3f=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}
fn equirectangularToCubemapDirection(uv : vec2f)->vec3f {var longitude : f32=uv.x*TWO_PI-PI;var latitude : f32=HALF_PI-uv.y*PI;var direction : vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}
fn sqrtClamped(value: f32)->f32 {return sqrt(max(value,0.));}
fn avg(value: vec3f)->f32 {return dot(value,vec3f(0.333333333));}
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name11]) {
ShaderStore.IncludesShadersStoreWGSL[name11] = shader11;
}
helperFunctionsWGSL = { name: name11, shader: shader11 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/rgbdDecode.fragment.js
var rgbdDecode_fragment_exports = {};
__export(rgbdDecode_fragment_exports, {
rgbdDecodePixelShaderWGSL: () => rgbdDecodePixelShaderWGSL
});
var name12, shader12, rgbdDecodePixelShaderWGSL;
var init_rgbdDecode_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/rgbdDecode.fragment.js"() {
init_shaderStore();
init_helperFunctions();
name12 = "rgbdDecodePixelShader";
shader12 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;
#include
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}`;
if (!ShaderStore.ShadersStoreWGSL[name12]) {
ShaderStore.ShadersStoreWGSL[name12] = shader12;
}
rgbdDecodePixelShaderWGSL = { name: name12, shader: shader12 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/helperFunctions.js
var name13, shader13, helperFunctions;
var init_helperFunctions2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/helperFunctions.js"() {
init_shaderStore();
name13 = "helperFunctions";
shader13 = `const float PI=3.1415926535897932384626433832795;const float TWO_PI=6.283185307179586;const float HALF_PI=1.5707963267948966;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float RECIPROCAL_PI4=0.07957747154594767;const float HALF_MIN=5.96046448e-08;
const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;
#define saturate(x) clamp(x,0.0,1.0)
#define absEps(x) abs(x)+Epsilon
#define maxEps(x) max(x,Epsilon)
#define saturateEps(x) clamp(x,Epsilon,1.0)
mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(
vec3(i0.x,i1.x,i2.x),
vec3(i0.y,i1.y,i2.y),
vec3(i0.z,i1.z,i2.z)
);return outMatrix;}
mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),
b11,(a22*a00-a02*a20),(-a12*a00+a02*a10),
b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}
#if USE_EXACT_SRGB_CONVERSIONS
vec3 toLinearSpaceExact(vec3 color)
{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));
#else
return
vec3(
color.r<=0.04045 ? nearZeroSection.r : remainingSection.r,
color.g<=0.04045 ? nearZeroSection.g : remainingSection.g,
color.b<=0.04045 ? nearZeroSection.b : remainingSection.b);
#endif
}
vec3 toGammaSpaceExact(vec3 color)
{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));
#else
return
vec3(
color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,
color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,
color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);
#endif
}
#endif
float toLinearSpace(float color)
{
#if USE_EXACT_SRGB_CONVERSIONS
float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;
#else
return pow(color,LinearEncodePowerApprox);
#endif
}
vec3 toLinearSpace(vec3 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return toLinearSpaceExact(color);
#else
return pow(color,vec3(LinearEncodePowerApprox));
#endif
}
vec4 toLinearSpace(vec4 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4(toLinearSpaceExact(color.rgb),color.a);
#else
return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);
#endif
}
float toGammaSpace(float color)
{
#if USE_EXACT_SRGB_CONVERSIONS
float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;
#else
return pow(color,GammaEncodePowerApprox);
#endif
}
vec3 toGammaSpace(vec3 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return toGammaSpaceExact(color);
#else
return pow(color,vec3(GammaEncodePowerApprox));
#endif
}
vec4 toGammaSpace(vec4 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4(toGammaSpaceExact(color.rgb),color.a);
#else
return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);
#endif
}
float square(float value)
{return value*value;}
vec3 square(vec3 value)
{return value*value;}
float pow5(float value) {float sq=value*value;return sq*sq*value;}
float getLuminance(vec3 color)
{return saturate(dot(color,LuminanceEncodeApprox));}
float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}
float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}
const float rgbdMaxRange=255.;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =saturate(floor(D)/255.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(saturate(rgb),D);}
vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}
vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}
vec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*TWO_PI-PI;float latitude=HALF_PI-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}
float sqrtClamped(float value) {return sqrt(max(value,0.));}
float avg(vec3 value) {return dot(value,vec3(0.333333333));}
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
uint extractBits(uint value,int offset,int width) {return (value>>offset) & ((1u<>23)-0x7f;}
#endif
`;
if (!ShaderStore.IncludesShadersStore[name13]) {
ShaderStore.IncludesShadersStore[name13] = shader13;
}
helperFunctions = { name: name13, shader: shader13 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/rgbdDecode.fragment.js
var rgbdDecode_fragment_exports2 = {};
__export(rgbdDecode_fragment_exports2, {
rgbdDecodePixelShader: () => rgbdDecodePixelShader
});
var name14, shader14, rgbdDecodePixelShader;
var init_rgbdDecode_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/rgbdDecode.fragment.js"() {
init_shaderStore();
init_helperFunctions2();
name14 = "rgbdDecodePixelShader";
shader14 = `varying vec2 vUV;uniform sampler2D textureSampler;
#include
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;
if (!ShaderStore.ShadersStore[name14]) {
ShaderStore.ShadersStore[name14] = shader14;
}
rgbdDecodePixelShader = { name: name14, shader: shader14 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/stringDictionary.js
var StringDictionary;
var init_stringDictionary = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/stringDictionary.js"() {
StringDictionary = class {
static {
__name(this, "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 !== void 0) {
return val;
}
return void 0;
}
/**
* 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 !== void 0) {
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 !== void 0) {
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] !== void 0;
}
/**
* 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] !== void 0) {
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] === void 0) {
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 !== void 0) {
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
first(callback) {
for (const cur in this._data) {
const val = this._data[cur];
const res = callback(cur, val);
if (res) {
return res;
}
}
return null;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/colorCurves.functions.js
function PrepareUniformsForColorCurves(uniformsList) {
uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
}
var init_colorCurves_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/colorCurves.functions.js"() {
__name(PrepareUniformsForColorCurves, "PrepareUniformsForColorCurves");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/colorCurves.js
var ColorCurves;
var init_colorCurves = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/colorCurves.js"() {
init_tslib_es6();
init_decorators();
init_math_color();
init_decorators_serialization();
init_colorCurves_functions();
ColorCurves = class _ColorCurves {
static {
__name(this, "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;
colorCurves._getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
colorCurves._getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
colorCurves._getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
colorCurves._getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
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);
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 An RGBA color represented as Vector4.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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 {
h /= 60;
const i = Math.floor(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:
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);
}
};
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);
SerializationHelper._ColorCurvesParser = ColorCurves.Parse;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.functions.js
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");
}
}
function PrepareSamplersForImageProcessing(samplersList, defines) {
if (defines.COLORGRADING) {
samplersList.push("txColorTransform");
}
}
var init_imageProcessingConfiguration_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.functions.js"() {
init_colorCurves_functions();
__name(PrepareUniformsForImageProcessing, "PrepareUniformsForImageProcessing");
__name(PrepareSamplersForImageProcessing, "PrepareSamplersForImageProcessing");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.js
var ImageProcessingConfiguration;
var init_imageProcessingConfiguration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.js"() {
init_tslib_es6();
init_decorators();
init_observable();
init_math_color();
init_colorCurves();
init_tools_functions();
init_decorators_serialization();
init_imageProcessingConfiguration_functions();
init_typeStore();
ImageProcessingConfiguration = class _ImageProcessingConfiguration {
static {
__name(this, "ImageProcessingConfiguration");
}
constructor() {
this.colorCurves = new ColorCurves();
this._colorCurvesEnabled = false;
this._colorGradingEnabled = false;
this._colorGradingWithGreenDepth = true;
this._colorGradingBGR = true;
this._exposure = 1;
this._toneMappingEnabled = false;
this._toneMappingType = _ImageProcessingConfiguration.TONEMAPPING_STANDARD;
this._contrast = 1;
this.vignetteStretch = 0;
this.vignetteCenterX = 0;
this.vignetteCenterY = 0;
this.vignetteWeight = 1.5;
this.vignetteColor = new Color4(0, 0, 0, 0);
this.vignetteCameraFov = 0.5;
this._vignetteBlendMode = _ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
this._vignetteEnabled = false;
this._ditheringEnabled = false;
this._ditheringIntensity = 1 / 255;
this._skipFinalColorClamp = false;
this._applyByPostProcess = false;
this._isEnabled = true;
this.outputTextureWidth = 0;
this.outputTextureHeight = 0;
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;
defines.EXPOSURE = this.exposure !== 1;
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() {
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) {
if (this._colorCurvesEnabled && this.colorCurves) {
ColorCurves.Bind(this.colorCurves, effect);
}
if (this._vignetteEnabled || this._ditheringEnabled) {
const inverseWidth = 1 / (this.outputTextureWidth || effect.getEngine().getRenderWidth());
const inverseHeight = 1 / (this.outputTextureHeight || 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);
}
}
effect.setFloat("exposureLinear", this.exposure);
effect.setFloat("contrast", this.contrast);
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);
if (source.vignetteCentreX !== void 0) {
parsed.vignetteCenterX = source.vignetteCentreX;
}
if (source.vignetteCentreY !== void 0) {
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;
}
};
ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL = 2;
ImageProcessingConfiguration.PrepareUniforms = PrepareUniformsForImageProcessing;
ImageProcessingConfiguration.PrepareSamplers = PrepareSamplersForImageProcessing;
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);
__decorate([
serialize()
], ImageProcessingConfiguration.prototype, "outputTextureWidth", void 0);
__decorate([
serialize()
], ImageProcessingConfiguration.prototype, "outputTextureHeight", void 0);
SerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse;
RegisterClass("BABYLON.ImageProcessingConfiguration", ImageProcessingConfiguration);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/uniformBuffer.js
var UniformBuffer;
var init_uniformBuffer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/uniformBuffer.js"() {
init_logger();
init_tools();
UniformBuffer = class _UniformBuffer {
static {
__name(this, "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
* @param trackUBOsInFrame define if the UBOs should be tracked in the frame (default: undefined - will use the value from Engine._features.trackUbosInFrame)
*/
constructor(engine, data, dynamic = false, name260, forceNoUniformBuffer = false, trackUBOsInFrame) {
this._uniformNames = [];
this._valueCache = {};
this._engine = engine;
this._noUBO = !engine.supportsUniformBuffers || forceNoUniformBuffer;
this._dynamic = dynamic;
this._name = name260 ?? "no-name";
this._data = data || [];
this._uniformLocations = {};
this._uniformSizes = {};
this._uniformArraySizes = {};
this._uniformLocationPointer = 0;
this._needSync = false;
this._trackUBOsInFrame = false;
if (trackUBOsInFrame === void 0 && this._engine._features.trackUbosInFrame || trackUBOsInFrame === true) {
this._buffers = [];
this._bufferIndex = -1;
this._createBufferOnWrite = false;
this._currentFrameId = 0;
this._trackUBOsInFrame = true;
}
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;
}
/**
* 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;
}
/**
* The names of the uniforms in the buffer.
* @returns an array of uniform names
*/
getUniformNames() {
return this._uniformNames;
}
/**
* 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) {
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(name260, size, arraySize = 0) {
if (arraySize > 0 && typeof size === "number") {
this._uniformArraySizes[name260] = { strideSize: size, arraySize };
}
if (this._uniformLocations[name260] !== void 0) {
return;
}
this._uniformNames.push(name260);
if (this._noUBO) {
return;
}
let data;
if (arraySize > 0) {
if (size instanceof Array) {
throw "addUniform should not be use with Array in UBO: " + name260;
}
this._fillAlignment(4);
if (size == 16) {
size = size * arraySize;
} else {
const perElementPadding = 4 - size;
const totalPadding = perElementPadding * arraySize;
size = size * arraySize + totalPadding;
}
data = [];
for (let i = 0; i < size; i++) {
data.push(0);
}
} else {
if (size instanceof Array) {
data = size;
size = data.length;
} else {
data = [];
for (let i = 0; i < size; i++) {
data.push(0);
}
}
this._fillAlignment(size);
}
this._uniformSizes[name260] = size;
this._uniformLocations[name260] = 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(name260, mat) {
this.addUniform(name260, 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(name260, x, y) {
const temp = [x, y];
this.addUniform(name260, 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(name260, x, y, z) {
const temp = [x, y, z];
this.addUniform(name260, 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(name260, color) {
const temp = [color.r, color.g, color.b];
this.addUniform(name260, 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(name260, color, alpha) {
const temp = [color.r, color.g, color.b, alpha];
this.addUniform(name260, 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(name260, vector) {
const temp = [vector.x, vector.y, vector.z];
this.addUniform(name260, 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(name260) {
this.addUniform(name260, 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(name260) {
this.addUniform(name260, 8);
}
/**
* Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
*/
create() {
if (this._noUBO) {
return;
}
if (this._buffer) {
return;
}
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)
_getNamesDebug() {
const names = [];
let i = 0;
for (const name260 in this._uniformLocations) {
names.push(name260);
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._getNamesDebug());
} else {
this._buffer = this._engine.createUniformBuffer(this._bufferData, this._name + "_UniformList:" + this._getNamesDebug());
}
if (this._trackUBOsInFrame) {
this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : void 0]);
this._bufferIndex = this._buffers.length - 1;
this._createBufferOnWrite = false;
}
}
/** @internal */
_rebuildAfterContextLost() {
if (this._trackUBOsInFrame) {
this._buffers = [];
this._currentFrameId = 0;
}
this._rebuild();
}
/** @internal */
get _numBuffers() {
return this._buffers.length;
}
/** @internal */
get _indexBuffer() {
return this._bufferIndex;
}
/** Gets or sets the name of this buffer */
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
/** 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._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._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._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._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 location2 = this._uniformLocations[uniformName];
if (location2 === void 0) {
if (this._buffer) {
Logger.Error("Cannot add an uniform after UBO has been created. uniformName=" + uniformName);
return;
}
this.addUniform(uniformName, size);
location2 = this._uniformLocations[uniformName];
}
if (!this._buffer) {
this.create();
}
if (!this._dynamic) {
let changed = false;
for (let i = 0; i < size; i++) {
if (size === 16 && !this._engine._features.uniformBufferHardCheckMatrix || this._bufferData[location2 + i] !== Math.fround(data[i])) {
changed = true;
if (this._createBufferOnWrite) {
this._createNewBuffer();
}
this._bufferData[location2 + i] = data[i];
}
}
this._needSync = this._needSync || changed;
} else {
for (let i = 0; i < size; i++) {
this._bufferData[location2 + 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 location2 = this._uniformLocations[uniformName];
if (location2 === void 0) {
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) {
let changed = false;
let countToFour = 0;
let baseStride = 0;
for (let i = 0; i < size; i++) {
if (this._bufferData[location2 + baseStride * 4 + countToFour] !== Tools.FloatRound(data[i])) {
changed = true;
if (this._createBufferOnWrite) {
this._createNewBuffer();
}
this._bufferData[location2 + baseStride * 4 + countToFour] = data[i];
}
countToFour++;
if (countToFour === arraySizes.strideSize) {
for (; countToFour < 4; countToFour++) {
this._bufferData[location2 + baseStride * 4 + countToFour] = 0;
}
countToFour = 0;
baseStride++;
}
}
this._needSync = this._needSync || changed;
} else {
for (let i = 0; i < size; i++) {
this._bufferData[location2 + i] = data[i];
}
}
}
_cacheMatrix(name260, matrix) {
this._checkNewFrame();
const cache = this._valueCache[name260];
const flag = matrix.updateFlag;
if (cache !== void 0 && cache === flag) {
return false;
}
this._valueCache[name260] = flag;
return true;
}
// Update methods
_updateMatrix3x3ForUniform(name260, matrix) {
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;
}
this.updateUniform(name260, _UniformBuffer._TempBuffer, 12);
}
_updateMatrix3x3ForEffect(name260, matrix) {
this._currentEffect.setMatrix3x3(name260, matrix);
}
_updateMatrix2x2ForEffect(name260, matrix) {
this._currentEffect.setMatrix2x2(name260, matrix);
}
_updateMatrix2x2ForUniform(name260, matrix) {
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;
_UniformBuffer._TempBuffer[i * 4 + 3] = 0;
}
this.updateUniform(name260, _UniformBuffer._TempBuffer, 8);
}
_updateFloatForEffect(name260, x, suffix = "") {
this._currentEffect.setFloat(name260 + suffix, x);
}
_updateFloatForUniform(name260, x) {
_UniformBuffer._TempBuffer[0] = x;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 1);
}
_updateFloat2ForEffect(name260, x, y, suffix = "") {
this._currentEffect.setFloat2(name260 + suffix, x, y);
}
_updateFloat2ForUniform(name260, x, y) {
_UniformBuffer._TempBuffer[0] = x;
_UniformBuffer._TempBuffer[1] = y;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 2);
}
_updateFloat3ForEffect(name260, x, y, z, suffix = "") {
this._currentEffect.setFloat3(name260 + suffix, x, y, z);
}
_updateFloat3ForUniform(name260, x, y, z) {
_UniformBuffer._TempBuffer[0] = x;
_UniformBuffer._TempBuffer[1] = y;
_UniformBuffer._TempBuffer[2] = z;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 3);
}
_updateFloat4ForEffect(name260, x, y, z, w, suffix = "") {
this._currentEffect.setFloat4(name260 + suffix, x, y, z, w);
}
_updateFloat4ForUniform(name260, x, y, z, w) {
_UniformBuffer._TempBuffer[0] = x;
_UniformBuffer._TempBuffer[1] = y;
_UniformBuffer._TempBuffer[2] = z;
_UniformBuffer._TempBuffer[3] = w;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 4);
}
_updateFloatArrayForEffect(name260, array, suffix = "") {
switch (this._uniformArraySizes[name260]?.strideSize) {
case 2:
this._currentEffect.setFloatArray2(name260 + suffix, array);
break;
case 3:
this._currentEffect.setFloatArray3(name260 + suffix, array);
break;
case 4:
this._currentEffect.setFloatArray4(name260 + suffix, array);
break;
default:
this._currentEffect.setFloatArray(name260 + suffix, array);
break;
}
}
_updateFloatArrayForUniform(name260, array) {
this.updateUniformArray(name260, array, array.length);
}
_updateArrayForEffect(name260, array) {
this._currentEffect.setArray(name260, array);
}
_updateArrayForUniform(name260, array) {
this.updateUniformArray(name260, array, array.length);
}
_updateIntArrayForEffect(name260, array) {
this._currentEffect.setIntArray(name260, array);
}
_updateIntArrayForUniform(name260, array) {
_UniformBuffer._TempBufferInt32View.set(array);
this.updateUniformArray(name260, _UniformBuffer._TempBuffer, array.length);
}
_updateUIntArrayForEffect(name260, array) {
this._currentEffect.setUIntArray(name260, array);
}
_updateUIntArrayForUniform(name260, array) {
_UniformBuffer._TempBufferUInt32View.set(array);
this.updateUniformArray(name260, _UniformBuffer._TempBuffer, array.length);
}
_updateMatrixForEffect(name260, mat) {
this._currentEffect.setMatrix(name260, mat);
}
_updateMatrixForUniform(name260, mat) {
if (this._cacheMatrix(name260, mat)) {
this.updateUniform(name260, mat.asArray(), 16);
}
}
_updateMatricesForEffect(name260, mat) {
this._currentEffect.setMatrices(name260, mat);
}
_updateMatricesForUniform(name260, mat) {
this.updateUniform(name260, mat, mat.length);
}
_updateVector3ForEffect(name260, vector) {
this._currentEffect.setVector3(name260, vector);
}
_updateVector3ForUniform(name260, vector) {
_UniformBuffer._TempBuffer[0] = vector.x;
_UniformBuffer._TempBuffer[1] = vector.y;
_UniformBuffer._TempBuffer[2] = vector.z;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 3);
}
_updateVector4ForEffect(name260, vector) {
this._currentEffect.setVector4(name260, vector);
}
_updateVector4ForUniform(name260, vector) {
_UniformBuffer._TempBuffer[0] = vector.x;
_UniformBuffer._TempBuffer[1] = vector.y;
_UniformBuffer._TempBuffer[2] = vector.z;
_UniformBuffer._TempBuffer[3] = vector.w;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 4);
}
_updateColor3ForEffect(name260, color, suffix = "") {
this._currentEffect.setColor3(name260 + suffix, color);
}
_updateColor3ForUniform(name260, color) {
_UniformBuffer._TempBuffer[0] = color.r;
_UniformBuffer._TempBuffer[1] = color.g;
_UniformBuffer._TempBuffer[2] = color.b;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 3);
}
_updateColor4ForEffect(name260, color, alpha, suffix = "") {
this._currentEffect.setColor4(name260 + suffix, color, alpha);
}
_updateDirectColor4ForEffect(name260, color, suffix = "") {
this._currentEffect.setDirectColor4(name260 + suffix, color);
}
_updateColor4ForUniform(name260, color, alpha) {
_UniformBuffer._TempBuffer[0] = color.r;
_UniformBuffer._TempBuffer[1] = color.g;
_UniformBuffer._TempBuffer[2] = color.b;
_UniformBuffer._TempBuffer[3] = alpha;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 4);
}
_updateDirectColor4ForUniform(name260, color) {
_UniformBuffer._TempBuffer[0] = color.r;
_UniformBuffer._TempBuffer[1] = color.g;
_UniformBuffer._TempBuffer[2] = color.b;
_UniformBuffer._TempBuffer[3] = color.a;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 4);
}
_updateIntForEffect(name260, x, suffix = "") {
this._currentEffect.setInt(name260 + suffix, x);
}
_updateIntForUniform(name260, x) {
_UniformBuffer._TempBufferInt32View[0] = x;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 1);
}
_updateInt2ForEffect(name260, x, y, suffix = "") {
this._currentEffect.setInt2(name260 + suffix, x, y);
}
_updateInt2ForUniform(name260, x, y) {
_UniformBuffer._TempBufferInt32View[0] = x;
_UniformBuffer._TempBufferInt32View[1] = y;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 2);
}
_updateInt3ForEffect(name260, x, y, z, suffix = "") {
this._currentEffect.setInt3(name260 + suffix, x, y, z);
}
_updateInt3ForUniform(name260, x, y, z) {
_UniformBuffer._TempBufferInt32View[0] = x;
_UniformBuffer._TempBufferInt32View[1] = y;
_UniformBuffer._TempBufferInt32View[2] = z;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 3);
}
_updateInt4ForEffect(name260, x, y, z, w, suffix = "") {
this._currentEffect.setInt4(name260 + suffix, x, y, z, w);
}
_updateInt4ForUniform(name260, x, y, z, w) {
_UniformBuffer._TempBufferInt32View[0] = x;
_UniformBuffer._TempBufferInt32View[1] = y;
_UniformBuffer._TempBufferInt32View[2] = z;
_UniformBuffer._TempBufferInt32View[3] = w;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 4);
}
_updateUIntForEffect(name260, x, suffix = "") {
this._currentEffect.setUInt(name260 + suffix, x);
}
_updateUIntForUniform(name260, x) {
_UniformBuffer._TempBufferUInt32View[0] = x;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 1);
}
_updateUInt2ForEffect(name260, x, y, suffix = "") {
this._currentEffect.setUInt2(name260 + suffix, x, y);
}
_updateUInt2ForUniform(name260, x, y) {
_UniformBuffer._TempBufferUInt32View[0] = x;
_UniformBuffer._TempBufferUInt32View[1] = y;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 2);
}
_updateUInt3ForEffect(name260, x, y, z, suffix = "") {
this._currentEffect.setUInt3(name260 + suffix, x, y, z);
}
_updateUInt3ForUniform(name260, x, y, z) {
_UniformBuffer._TempBufferUInt32View[0] = x;
_UniformBuffer._TempBufferUInt32View[1] = y;
_UniformBuffer._TempBufferUInt32View[2] = z;
this.updateUniform(name260, _UniformBuffer._TempBuffer, 3);
}
_updateUInt4ForEffect(name260, x, y, z, w, suffix = "") {
this._currentEffect.setUInt4(name260 + suffix, x, y, z, w);
}
_updateUInt4ForUniform(name260, x, y, z, w) {
_UniformBuffer._TempBufferUInt32View[0] = x;
_UniformBuffer._TempBufferUInt32View[1] = y;
_UniformBuffer._TempBufferUInt32View[2] = z;
_UniformBuffer._TempBufferUInt32View[3] = w;
this.updateUniform(name260, _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(name260, texture) {
this._currentEffect.setTexture(name260, 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(name260, textures) {
this._currentEffect.setTextureArray(name260, 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(name260, texture) {
this._currentEffect._bindTexture(name260, 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, name260) {
this._currentEffect = effect;
this._currentEffectName = name260;
}
/**
* 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 = void 0;
this._currentEffectName = void 0;
}
/**
* 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 = void 0;
if (this._buffers.length > 1 && this._buffers[b][1]) {
this._bufferData.set(this._buffers[b][1]);
}
this._valueCache = {};
this._currentFrameId = this._engine.frameId;
return true;
}
}
return false;
}
/**
* Checks if the uniform buffer has a uniform with the given name.
* @param name Name of the uniform to check
* @returns True if the uniform exists, false otherwise.
*/
has(name260) {
return this._uniformLocations[name260] !== void 0;
}
/**
* 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._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;
}
}
};
UniformBuffer._UpdatedUbosInFrame = {};
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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Collisions/pickingInfo.js
var PickingInfo;
var init_pickingInfo = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Collisions/pickingInfo.js"() {
init_math_vector();
init_buffer();
PickingInfo = class {
static {
__name(this, "PickingInfo");
}
constructor() {
this.hit = false;
this.distance = 0;
this.pickedPoint = null;
this.pickedMesh = null;
this.bu = 0;
this.bv = 0;
this.faceId = -1;
this.subMeshFaceId = -1;
this.subMeshId = 0;
this.pickedSprite = null;
this.thinInstanceIndex = -1;
this.ray = null;
this.originMesh = null;
this.aimTransform = null;
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 - 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 = /* @__PURE__ */ __name((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);
}, "transformNormalToWorld");
if (useWorldCoordinates) {
transformNormalToWorld(this.pickedMesh, result);
}
if (this.ray) {
const normalForDirectionChecking = TmpVectors.Vector3[0].copyFrom(result);
if (!useWorldCoordinates) {
transformNormalToWorld(this.pickedMesh, normalForDirectionChecking);
}
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 - this.bu - this.bv);
return new Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Actions/actionEvent.js
var ActionEvent;
var init_actionEvent = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Actions/actionEvent.js"() {
ActionEvent = class _ActionEvent {
static {
__name(this, "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(source, pointerX, pointerY, meshUnderPointer, sourceEvent, 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);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/floatingOriginMatrixOverrides.js
function OffsetWorldToRef(offset, world, ref) {
const refArray = ref.asArray();
const worldArray = world.asArray();
for (let i = 0; i < 16; i++) {
refArray[i] = worldArray[i];
}
refArray[12] -= offset.x;
refArray[13] -= offset.y;
refArray[14] -= offset.z;
Matrix.FromArrayToRef(refArray, 0, ref);
return ref;
}
function OffsetViewToRef(view, ref) {
const refArray = ref.asArray();
const viewArray = view.asArray();
for (let i = 0; i < 16; i++) {
refArray[i] = viewArray[i];
}
refArray[12] = 0;
refArray[13] = 0;
refArray[14] = 0;
Matrix.FromArrayToRef(refArray, 0, ref);
return ref;
}
function OffsetViewProjectionToRef(view, projection, ref) {
MultiplyMatricesToRef(OffsetViewToRef(view, ref), projection, ref);
return ref;
}
function OffsetWorldViewToRef(offset, worldView, view, ref) {
InvertMatrixToRef(view, TempMat1);
MultiplyMatricesToRef(worldView, TempMat1, TempMat2);
OffsetWorldToRef(offset, TempMat2, TempMat1);
OffsetViewToRef(view, TempMat2);
MultiplyMatricesToRef(TempMat1, TempMat2, ref);
return ref;
}
function OffsetWorldViewProjectionToRef(offset, worldViewProjection, viewProjection, view, projection, ref) {
InvertMatrixToRef(viewProjection, TempMat1);
MultiplyMatricesToRef(worldViewProjection, TempMat1, TempMat2);
OffsetWorldToRef(offset, TempMat2, TempMat1);
OffsetViewProjectionToRef(view, projection, TempMat2);
MultiplyMatricesToRef(TempMat1, TempMat2, ref);
return ref;
}
function GetOffsetMatrix(uniformName, mat) {
TempFinalMat.updateFlag = mat.updateFlag;
const scene = FloatingOriginCurrentScene.getScene();
if (!scene) {
return mat;
}
const offset = scene.floatingOriginOffset;
switch (uniformName) {
case "world":
return OffsetWorldToRef(offset, mat, TempFinalMat);
case "view":
return OffsetViewToRef(mat, TempFinalMat);
case "worldView":
return OffsetWorldViewToRef(offset, mat, scene.getViewMatrix(), TempFinalMat);
case "viewProjection":
return OffsetViewProjectionToRef(scene.getViewMatrix(), scene.getProjectionMatrix(), TempFinalMat);
case "worldViewProjection":
return OffsetWorldViewProjectionToRef(offset, mat, scene.getTransformMatrix(), scene.getViewMatrix(), scene.getProjectionMatrix(), TempFinalMat);
default:
return mat;
}
}
function ResetMatrixFunctions() {
Effect.prototype.setMatrix = OriginalSetMatrix;
EffectInternal._setMatrixOverride = void 0;
UniformBufferInternal.prototype._updateMatrixForUniform = OriginalUpdateMatrixForUniform;
UniformBufferInternal.prototype._updateMatrixForUniformOverride = void 0;
}
function OverrideMatrixFunctions() {
EffectInternal.prototype._setMatrixOverride = OriginalSetMatrix;
EffectInternal.prototype.setMatrix = function(uniformName, matrix) {
this._setMatrixOverride(uniformName, GetOffsetMatrix(uniformName, matrix));
return this;
};
UniformBufferInternal.prototype._updateMatrixForUniformOverride = OriginalUpdateMatrixForUniform;
UniformBufferInternal.prototype._updateMatrixForUniform = function(uniformName, matrix) {
this._updateMatrixForUniformOverride(uniformName, GetOffsetMatrix(uniformName, matrix));
};
}
var TempFinalMat, TempMat1, TempMat2, FloatingOriginCurrentScene, UniformBufferInternal, EffectInternal, OriginalUpdateMatrixForUniform, OriginalSetMatrix;
var init_floatingOriginMatrixOverrides = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/floatingOriginMatrixOverrides.js"() {
init_effect();
init_math_vector();
init_thinMath_matrix_functions();
init_uniformBuffer();
TempFinalMat = new Matrix();
TempMat1 = new Matrix();
TempMat2 = new Matrix();
FloatingOriginCurrentScene = {
getScene: /* @__PURE__ */ __name(() => void 0, "getScene")
};
__name(OffsetWorldToRef, "OffsetWorldToRef");
__name(OffsetViewToRef, "OffsetViewToRef");
__name(OffsetViewProjectionToRef, "OffsetViewProjectionToRef");
__name(OffsetWorldViewToRef, "OffsetWorldViewToRef");
__name(OffsetWorldViewProjectionToRef, "OffsetWorldViewProjectionToRef");
__name(GetOffsetMatrix, "GetOffsetMatrix");
UniformBufferInternal = UniformBuffer;
EffectInternal = Effect;
OriginalUpdateMatrixForUniform = UniformBufferInternal.prototype._updateMatrixForUniform;
OriginalSetMatrix = Effect.prototype.setMatrix;
__name(ResetMatrixFunctions, "ResetMatrixFunctions");
__name(OverrideMatrixFunctions, "OverrideMatrixFunctions");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/sceneComponent.js
var SceneComponentConstants, Stage;
var init_sceneComponent = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/sceneComponent.js"() {
SceneComponentConstants = class {
static {
__name(this, "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.NAME_CLUSTEREDLIGHTING = "ClusteredLighting";
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_GATHERACTIVECAMERARENDERTARGETS_CLUSTEREDLIGHTING = 2;
SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
Stage = class _Stage extends Array {
static {
__name(this, "Stage");
}
/**
* 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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/pointerEvents.js
var PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo;
var init_pointerEvents = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/pointerEvents.js"() {
init_math_vector();
PointerEventTypes = class {
static {
__name(this, "PointerEventTypes");
}
};
PointerEventTypes.POINTERDOWN = 1;
PointerEventTypes.POINTERUP = 2;
PointerEventTypes.POINTERMOVE = 4;
PointerEventTypes.POINTERWHEEL = 8;
PointerEventTypes.POINTERPICK = 16;
PointerEventTypes.POINTERTAP = 32;
PointerEventTypes.POINTERDOUBLETAP = 64;
PointerInfoBase = class {
static {
__name(this, "PointerInfoBase");
}
/**
* Instantiates the base class of pointers info.
* @param type Defines the type of event (PointerEventTypes)
* @param event Defines the related dom event
*/
constructor(type, event) {
this.type = type;
this.event = event;
}
};
PointerInfoPre = class extends PointerInfoBase {
static {
__name(this, "PointerInfoPre");
}
/**
* 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);
this.ray = null;
this.originalPickingInfo = null;
this.skipOnPointerObservable = false;
this.localPosition = new Vector2(localX, localY);
}
};
PointerInfo = class extends PointerInfoBase {
static {
__name(this, "PointerInfo");
}
/**
* 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;
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Actions/abstractActionManager.js
var AbstractActionManager;
var init_abstractActionManager = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Actions/abstractActionManager.js"() {
AbstractActionManager = class _AbstractActionManager {
static {
__name(this, "AbstractActionManager");
}
constructor() {
this.hoverCursor = "";
this.actions = [];
this.isRecursive = false;
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;
}
};
AbstractActionManager.Triggers = {};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/keyboardEvents.js
var KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre;
var init_keyboardEvents = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/keyboardEvents.js"() {
KeyboardEventTypes = class {
static {
__name(this, "KeyboardEventTypes");
}
};
KeyboardEventTypes.KEYDOWN = 1;
KeyboardEventTypes.KEYUP = 2;
KeyboardInfo = class {
static {
__name(this, "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(type, event) {
this.type = type;
this.event = event;
}
};
KeyboardInfoPre = class extends KeyboardInfo {
static {
__name(this, "KeyboardInfoPre");
}
/**
* 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(type, event) {
super(type, event);
this.type = type;
this.event = event;
this.skipOnKeyboardObservable = false;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceEnums.js
var DeviceType, PointerInput, NativePointerInput, DualShockInput, DualSenseInput, XboxInput, SwitchInput;
var init_deviceEnums = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceEnums.js"() {
(function(DeviceType2) {
DeviceType2[DeviceType2["Generic"] = 0] = "Generic";
DeviceType2[DeviceType2["Keyboard"] = 1] = "Keyboard";
DeviceType2[DeviceType2["Mouse"] = 2] = "Mouse";
DeviceType2[DeviceType2["Touch"] = 3] = "Touch";
DeviceType2[DeviceType2["DualShock"] = 4] = "DualShock";
DeviceType2[DeviceType2["Xbox"] = 5] = "Xbox";
DeviceType2[DeviceType2["Switch"] = 6] = "Switch";
DeviceType2[DeviceType2["DualSense"] = 7] = "DualSense";
})(DeviceType || (DeviceType = {}));
(function(PointerInput2) {
PointerInput2[PointerInput2["Horizontal"] = 0] = "Horizontal";
PointerInput2[PointerInput2["Vertical"] = 1] = "Vertical";
PointerInput2[PointerInput2["LeftClick"] = 2] = "LeftClick";
PointerInput2[PointerInput2["MiddleClick"] = 3] = "MiddleClick";
PointerInput2[PointerInput2["RightClick"] = 4] = "RightClick";
PointerInput2[PointerInput2["BrowserBack"] = 5] = "BrowserBack";
PointerInput2[PointerInput2["BrowserForward"] = 6] = "BrowserForward";
PointerInput2[PointerInput2["MouseWheelX"] = 7] = "MouseWheelX";
PointerInput2[PointerInput2["MouseWheelY"] = 8] = "MouseWheelY";
PointerInput2[PointerInput2["MouseWheelZ"] = 9] = "MouseWheelZ";
PointerInput2[PointerInput2["Move"] = 12] = "Move";
})(PointerInput || (PointerInput = {}));
(function(NativePointerInput2) {
NativePointerInput2[NativePointerInput2["Horizontal"] = 0] = "Horizontal";
NativePointerInput2[NativePointerInput2["Vertical"] = 1] = "Vertical";
NativePointerInput2[NativePointerInput2["LeftClick"] = 2] = "LeftClick";
NativePointerInput2[NativePointerInput2["MiddleClick"] = 3] = "MiddleClick";
NativePointerInput2[NativePointerInput2["RightClick"] = 4] = "RightClick";
NativePointerInput2[NativePointerInput2["BrowserBack"] = 5] = "BrowserBack";
NativePointerInput2[NativePointerInput2["BrowserForward"] = 6] = "BrowserForward";
NativePointerInput2[NativePointerInput2["MouseWheelX"] = 7] = "MouseWheelX";
NativePointerInput2[NativePointerInput2["MouseWheelY"] = 8] = "MouseWheelY";
NativePointerInput2[NativePointerInput2["MouseWheelZ"] = 9] = "MouseWheelZ";
NativePointerInput2[NativePointerInput2["DeltaHorizontal"] = 10] = "DeltaHorizontal";
NativePointerInput2[NativePointerInput2["DeltaVertical"] = 11] = "DeltaVertical";
})(NativePointerInput || (NativePointerInput = {}));
(function(DualShockInput2) {
DualShockInput2[DualShockInput2["Cross"] = 0] = "Cross";
DualShockInput2[DualShockInput2["Circle"] = 1] = "Circle";
DualShockInput2[DualShockInput2["Square"] = 2] = "Square";
DualShockInput2[DualShockInput2["Triangle"] = 3] = "Triangle";
DualShockInput2[DualShockInput2["L1"] = 4] = "L1";
DualShockInput2[DualShockInput2["R1"] = 5] = "R1";
DualShockInput2[DualShockInput2["L2"] = 6] = "L2";
DualShockInput2[DualShockInput2["R2"] = 7] = "R2";
DualShockInput2[DualShockInput2["Share"] = 8] = "Share";
DualShockInput2[DualShockInput2["Options"] = 9] = "Options";
DualShockInput2[DualShockInput2["L3"] = 10] = "L3";
DualShockInput2[DualShockInput2["R3"] = 11] = "R3";
DualShockInput2[DualShockInput2["DPadUp"] = 12] = "DPadUp";
DualShockInput2[DualShockInput2["DPadDown"] = 13] = "DPadDown";
DualShockInput2[DualShockInput2["DPadLeft"] = 14] = "DPadLeft";
DualShockInput2[DualShockInput2["DPadRight"] = 15] = "DPadRight";
DualShockInput2[DualShockInput2["Home"] = 16] = "Home";
DualShockInput2[DualShockInput2["TouchPad"] = 17] = "TouchPad";
DualShockInput2[DualShockInput2["LStickXAxis"] = 18] = "LStickXAxis";
DualShockInput2[DualShockInput2["LStickYAxis"] = 19] = "LStickYAxis";
DualShockInput2[DualShockInput2["RStickXAxis"] = 20] = "RStickXAxis";
DualShockInput2[DualShockInput2["RStickYAxis"] = 21] = "RStickYAxis";
})(DualShockInput || (DualShockInput = {}));
(function(DualSenseInput2) {
DualSenseInput2[DualSenseInput2["Cross"] = 0] = "Cross";
DualSenseInput2[DualSenseInput2["Circle"] = 1] = "Circle";
DualSenseInput2[DualSenseInput2["Square"] = 2] = "Square";
DualSenseInput2[DualSenseInput2["Triangle"] = 3] = "Triangle";
DualSenseInput2[DualSenseInput2["L1"] = 4] = "L1";
DualSenseInput2[DualSenseInput2["R1"] = 5] = "R1";
DualSenseInput2[DualSenseInput2["L2"] = 6] = "L2";
DualSenseInput2[DualSenseInput2["R2"] = 7] = "R2";
DualSenseInput2[DualSenseInput2["Create"] = 8] = "Create";
DualSenseInput2[DualSenseInput2["Options"] = 9] = "Options";
DualSenseInput2[DualSenseInput2["L3"] = 10] = "L3";
DualSenseInput2[DualSenseInput2["R3"] = 11] = "R3";
DualSenseInput2[DualSenseInput2["DPadUp"] = 12] = "DPadUp";
DualSenseInput2[DualSenseInput2["DPadDown"] = 13] = "DPadDown";
DualSenseInput2[DualSenseInput2["DPadLeft"] = 14] = "DPadLeft";
DualSenseInput2[DualSenseInput2["DPadRight"] = 15] = "DPadRight";
DualSenseInput2[DualSenseInput2["Home"] = 16] = "Home";
DualSenseInput2[DualSenseInput2["TouchPad"] = 17] = "TouchPad";
DualSenseInput2[DualSenseInput2["LStickXAxis"] = 18] = "LStickXAxis";
DualSenseInput2[DualSenseInput2["LStickYAxis"] = 19] = "LStickYAxis";
DualSenseInput2[DualSenseInput2["RStickXAxis"] = 20] = "RStickXAxis";
DualSenseInput2[DualSenseInput2["RStickYAxis"] = 21] = "RStickYAxis";
})(DualSenseInput || (DualSenseInput = {}));
(function(XboxInput2) {
XboxInput2[XboxInput2["A"] = 0] = "A";
XboxInput2[XboxInput2["B"] = 1] = "B";
XboxInput2[XboxInput2["X"] = 2] = "X";
XboxInput2[XboxInput2["Y"] = 3] = "Y";
XboxInput2[XboxInput2["LB"] = 4] = "LB";
XboxInput2[XboxInput2["RB"] = 5] = "RB";
XboxInput2[XboxInput2["LT"] = 6] = "LT";
XboxInput2[XboxInput2["RT"] = 7] = "RT";
XboxInput2[XboxInput2["Back"] = 8] = "Back";
XboxInput2[XboxInput2["Start"] = 9] = "Start";
XboxInput2[XboxInput2["LS"] = 10] = "LS";
XboxInput2[XboxInput2["RS"] = 11] = "RS";
XboxInput2[XboxInput2["DPadUp"] = 12] = "DPadUp";
XboxInput2[XboxInput2["DPadDown"] = 13] = "DPadDown";
XboxInput2[XboxInput2["DPadLeft"] = 14] = "DPadLeft";
XboxInput2[XboxInput2["DPadRight"] = 15] = "DPadRight";
XboxInput2[XboxInput2["Home"] = 16] = "Home";
XboxInput2[XboxInput2["LStickXAxis"] = 17] = "LStickXAxis";
XboxInput2[XboxInput2["LStickYAxis"] = 18] = "LStickYAxis";
XboxInput2[XboxInput2["RStickXAxis"] = 19] = "RStickXAxis";
XboxInput2[XboxInput2["RStickYAxis"] = 20] = "RStickYAxis";
})(XboxInput || (XboxInput = {}));
(function(SwitchInput2) {
SwitchInput2[SwitchInput2["B"] = 0] = "B";
SwitchInput2[SwitchInput2["A"] = 1] = "A";
SwitchInput2[SwitchInput2["Y"] = 2] = "Y";
SwitchInput2[SwitchInput2["X"] = 3] = "X";
SwitchInput2[SwitchInput2["L"] = 4] = "L";
SwitchInput2[SwitchInput2["R"] = 5] = "R";
SwitchInput2[SwitchInput2["ZL"] = 6] = "ZL";
SwitchInput2[SwitchInput2["ZR"] = 7] = "ZR";
SwitchInput2[SwitchInput2["Minus"] = 8] = "Minus";
SwitchInput2[SwitchInput2["Plus"] = 9] = "Plus";
SwitchInput2[SwitchInput2["LS"] = 10] = "LS";
SwitchInput2[SwitchInput2["RS"] = 11] = "RS";
SwitchInput2[SwitchInput2["DPadUp"] = 12] = "DPadUp";
SwitchInput2[SwitchInput2["DPadDown"] = 13] = "DPadDown";
SwitchInput2[SwitchInput2["DPadLeft"] = 14] = "DPadLeft";
SwitchInput2[SwitchInput2["DPadRight"] = 15] = "DPadRight";
SwitchInput2[SwitchInput2["Home"] = 16] = "Home";
SwitchInput2[SwitchInput2["Capture"] = 17] = "Capture";
SwitchInput2[SwitchInput2["LStickXAxis"] = 18] = "LStickXAxis";
SwitchInput2[SwitchInput2["LStickYAxis"] = 19] = "LStickYAxis";
SwitchInput2[SwitchInput2["RStickXAxis"] = 20] = "RStickXAxis";
SwitchInput2[SwitchInput2["RStickYAxis"] = 21] = "RStickYAxis";
})(SwitchInput || (SwitchInput = {}));
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/deviceInputEvents.js
var DeviceInputEventType, EventConstants;
var init_deviceInputEvents = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/deviceInputEvents.js"() {
(function(DeviceInputEventType2) {
DeviceInputEventType2[DeviceInputEventType2["PointerMove"] = 0] = "PointerMove";
DeviceInputEventType2[DeviceInputEventType2["PointerDown"] = 1] = "PointerDown";
DeviceInputEventType2[DeviceInputEventType2["PointerUp"] = 2] = "PointerUp";
})(DeviceInputEventType || (DeviceInputEventType = {}));
EventConstants = class {
static {
__name(this, "EventConstants");
}
};
EventConstants.DOM_DELTA_PIXEL = 0;
EventConstants.DOM_DELTA_LINE = 1;
EventConstants.DOM_DELTA_PAGE = 2;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/eventFactory.js
var DeviceEventFactory;
var init_eventFactory = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/eventFactory.js"() {
init_deviceInputEvents();
init_deviceEnums();
DeviceEventFactory = class {
static {
__name(this, "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:
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;
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);
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);
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 */
);
evt.movementY = deviceInputSystem.pollInput(
deviceType,
deviceSlot,
11
/* NativePointerInput.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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/nativeDeviceInputSystem.js
var NativeDeviceInputSystem;
var init_nativeDeviceInputSystem = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/nativeDeviceInputSystem.js"() {
init_eventFactory();
init_deviceEnums();
NativeDeviceInputSystem = class {
static {
__name(this, "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) {
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: /* @__PURE__ */ __name(() => {
return 0;
}, "pollInput"),
isDeviceAvailable: /* @__PURE__ */ __name(() => {
return false;
}, "isDeviceAvailable"),
dispose: /* @__PURE__ */ __name(() => {
}, "dispose")
};
return nativeInput;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/webDeviceInputSystem.js
var MAX_KEYCODES, MAX_POINTER_INPUTS, WebDeviceInputSystem;
var init_webDeviceInputSystem = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/webDeviceInputSystem.js"() {
init_domManagement();
init_tools();
init_eventFactory();
init_deviceEnums();
MAX_KEYCODES = 255;
MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2;
WebDeviceInputSystem = class {
static {
__name(this, "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) {
this._inputs = [];
this._keyboardActive = false;
this._pointerActive = false;
this._usingSafari = Tools.IsSafari();
this._usingMacOs = IsNavigatorAvailable() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
this._keyboardDownEvent = (evt) => {
};
this._keyboardUpEvent = (evt) => {
};
this._keyboardBlurEvent = (evt) => {
};
this._pointerMoveEvent = (evt) => {
};
this._pointerDownEvent = (evt) => {
};
this._pointerUpEvent = (evt) => {
};
this._pointerCancelEvent = (evt) => {
};
this._pointerCancelTouch = (pointerId) => {
};
this._pointerLeaveEvent = (evt) => {
};
this._pointerWheelEvent = (evt) => {
};
this._pointerBlurEvent = (evt) => {
};
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;
this._gamepadConnectedEvent = (evt) => {
};
this._gamepadDisconnectedEvent = (evt) => {
};
this._eventPrefix = Tools.GetPointerPrefix(engine);
this._engine = engine;
this._onDeviceConnected = onDeviceConnected;
this._onDeviceDisconnected = onDeviceDisconnected;
this._onInputChanged = onInputChanged;
this._mouseId = this._isUsingFirefox ? 0 : 1;
this._enableEvents();
if (this._usingMacOs) {
this._metaKeys = [];
}
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) {
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 === void 0) {
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] !== void 0;
}
/**
* Dispose of all the eventlisteners
*/
dispose() {
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)) {
this._disableEvents();
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;
this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex;
this._handleKeyActions();
this._handlePointerActions();
this._handleGamepadActions();
this._eventsAttached = true;
this._checkForConnectedDevices();
}
}
/**
* Disable listening for user input events
*/
_disableEvents() {
if (this._elementToAttachTo) {
this._elementToAttachTo.removeEventListener("blur", this._keyboardBlurEvent);
this._elementToAttachTo.removeEventListener("blur", this._pointerBlurEvent);
this._elementToAttachTo.removeEventListener("keydown", this._keyboardDownEvent);
this._elementToAttachTo.removeEventListener("keyup", this._keyboardUpEvent);
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);
}
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 (typeof matchMedia === "function" && matchMedia("(pointer:fine)").matches) {
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];
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 === void 0) {
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 deviceEvent2 = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, keyCode, 0, this, this._elementToAttachTo);
kbKey[keyCode] = 0;
this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent2);
}
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() {
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);
if (deviceType === DeviceType.Touch && deviceSlot === -1) {
const idx = this._activeTouchIds.indexOf(-1);
if (idx >= 0) {
deviceSlot = idx;
this._activeTouchIds[idx] = evt.pointerId;
this._onDeviceConnected(deviceType, deviceSlot);
} else {
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;
if (deviceType === DeviceType.Touch && pointer[PointerInput.LeftClick] === 0) {
pointer[PointerInput.LeftClick] = 1;
}
if (evt.pointerId === void 0) {
evt.pointerId = this._mouseId;
}
this._onInputChanged(deviceType, deviceSlot, deviceEvent);
if (!this._usingSafari && evt.button !== -1) {
deviceEvent.inputIndex = evt.button + 2;
pointer[evt.button + 2] = pointer[evt.button + 2] ? 0 : 1;
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) {
let idx = this._activeTouchIds.indexOf(evt.pointerId);
if (idx === -1) {
idx = this._activeTouchIds.indexOf(-1);
}
if (idx >= 0) {
deviceSlot = idx;
this._activeTouchIds[idx] = evt.pointerId;
} else {
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) {
if (evt.pointerId === void 0) {
evt.pointerId = this._mouseId;
}
if (!document.pointerLockElement) {
try {
this._elementToAttachTo.setPointerCapture(this._mouseId);
} catch (e) {
}
}
} else {
if (evt.pointerId && !document.pointerLockElement) {
try {
this._elementToAttachTo.setPointerCapture(evt.pointerId);
} catch (e) {
}
}
}
pointer[PointerInput.Horizontal] = evt.clientX;
pointer[PointerInput.Vertical] = evt.clientY;
pointer[evt.button + 2] = 1;
const deviceEvent = evt;
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 (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;
if (!shouldProcessPointerUp && this._isUsingFirefox && this._usingMacOs && pointer) {
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 === void 0) {
evt.pointerId = this._mouseId;
}
if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) {
deviceEvent.inputIndex = PointerInput.Move;
this._onInputChanged(deviceType, deviceSlot, deviceEvent);
}
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 (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") {
this._pointerCancelTouch(evt.pointerId);
}
};
this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : document.onmousewheel !== void 0 ? "mousewheel" : "DOMMouseScroll";
let passiveSupported = false;
const noop = /* @__PURE__ */ __name(function() {
}, "noop");
try {
const options = Object.defineProperty({}, "passive", {
get: /* @__PURE__ */ __name(function() {
passiveSupported = true;
}, "get")
});
this._elementToAttachTo.addEventListener("test", noop, options);
this._elementToAttachTo.removeEventListener("test", noop, options);
} catch (e) {
}
this._pointerBlurEvent = () => {
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);
}
}
}
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;
if (evt.pointerId === void 0) {
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);
}
}
};
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);
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) {
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) {
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) {
return DeviceType.Xbox;
} else if (deviceName.indexOf("057e") !== -1) {
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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSource.js
var DeviceSource;
var init_deviceSource = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSource.js"() {
init_observable();
DeviceSource = class {
static {
__name(this, "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, deviceType, deviceSlot = 0) {
this.deviceType = deviceType;
this.deviceSlot = deviceSlot;
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);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/internalDeviceSourceManager.js
var InternalDeviceSourceManager;
var init_internalDeviceSourceManager = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/internalDeviceSourceManager.js"() {
init_deviceEnums();
init_nativeDeviceInputSystem();
init_webDeviceInputSystem();
init_deviceSource();
InternalDeviceSourceManager = class {
static {
__name(this, "InternalDeviceSourceManager");
}
constructor(engine) {
this._registeredManagers = new Array();
this._refCount = 0;
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 = /* @__PURE__ */ __name((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);
}
}, "onDeviceConnected");
const onDeviceDisconnected = /* @__PURE__ */ __name((deviceType, deviceSlot) => {
if (this._devices[deviceType]?.[deviceSlot]) {
delete this._devices[deviceType][deviceSlot];
}
for (const manager of this._registeredManagers) {
manager._removeDevice(deviceType, deviceSlot);
}
}, "onDeviceDisconnected");
const onInputChanged = /* @__PURE__ */ __name((deviceType, deviceSlot, eventData) => {
if (eventData) {
for (const manager of this._registeredManagers) {
manager._onInputChanged(deviceType, deviceSlot, eventData);
}
}
}, "onInputChanged");
if (typeof _native !== "undefined") {
this._deviceInputSystem = new NativeDeviceInputSystem(onDeviceConnected, onDeviceDisconnected, onInputChanged);
} else {
this._deviceInputSystem = new WebDeviceInputSystem(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged);
}
}
dispose() {
this._deviceInputSystem.dispose();
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSourceManager.js
var DeviceSourceManager;
var init_deviceSourceManager = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSourceManager.js"() {
init_deviceEnums();
init_observable();
init_internalDeviceSourceManager();
DeviceSourceManager = class {
static {
__name(this, "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 === void 0) {
if (this._firstDevice[deviceType] === void 0) {
return null;
}
deviceSlot = this._firstDevice[deviceType];
}
if (!this._devices[deviceType] || this._devices[deviceType][deviceSlot] === void 0) {
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 (!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++;
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() {
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] = [];
}
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];
this.onDeviceDisconnectedObservable.notifyObservers(deviceSource);
if (this._devices[deviceType]?.[deviceSlot]) {
delete this._devices[deviceType][deviceSlot];
}
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];
const devices = this._devices[type];
if (devices) {
for (let i = 0; i < devices.length; i++) {
if (devices[i]) {
this._firstDevice[type] = i;
break;
}
}
}
break;
}
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/import.helper.js
var _ImportHelper;
var init_import_helper = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/import.helper.js"() {
_ImportHelper = class {
static {
__name(this, "_ImportHelper");
}
};
_ImportHelper._IsPickingAvailable = false;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Inputs/scene.inputManager.js
var _ClickInfo, InputManager;
var init_scene_inputManager = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Inputs/scene.inputManager.js"() {
init_pointerEvents();
init_abstractActionManager();
init_pickingInfo();
init_math_vector();
init_actionEvent();
init_keyboardEvents();
init_deviceEnums();
init_deviceSourceManager();
init_engineStore();
init_import_helper();
_ClickInfo = class {
static {
__name(this, "_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;
}
};
InputManager = class _InputManager {
static {
__name(this, "InputManager");
}
/**
* Creates a new InputManager
* @param scene - defines the hosting scene
*/
constructor(scene) {
this._alreadyAttached = false;
this._meshPickProceed = false;
this._currentPickResult = null;
this._previousPickResult = null;
this._activePointerIds = new Array();
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) {
this._movePointerInfo._generatePickInfo();
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;
if (!scene.doNotHandleCursors) {
canvas.style.cursor = scene.defaultCursor;
}
}
this._setCursorAndPointerOverMesh(pickResult, evt, scene);
for (const step of scene._pointerMoveStage) {
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) {
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 pickResult2 = 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 (pickResult2?.pickedMesh && actionManager) {
if (this._activePointerIdsCount !== 0 && Date.now() - this._startingPointerTime > _InputManager.LongPressDelay && !this._isPointerSwiping()) {
this._startingPointerTime = 0;
actionManager.processTrigger(8, ActionEvent.CreateNew(pickResult2.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);
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 pi2 = new PointerInfo(type, evt, pickResult);
if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {
scene.onPointerObservable.notifyObservers(pi2, 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);
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) => {
if (Date.now() - this._previousStartingPointerTime > _InputManager.DoubleClickDelay && !this._doubleClickOccured || btn !== this._previousButtonPressed) {
this._doubleClickOccured = false;
clickInfo.singleClick = true;
clickInfo.ignore = false;
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);
}
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;
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) {
if (Date.now() - this._previousStartingPointerTime > _InputManager.DoubleClickDelay || btn !== this._previousButtonPressed) {
clickInfo.singleClick = true;
cb(clickInfo, this._currentPickResult);
needToIgnoreNext = true;
}
} else {
const delayedClick = {
evt,
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) {
if (btn === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < _InputManager.DoubleClickDelay && !this._doubleClickOccured) {
if (!clickInfo.hasSwiped && !this._isPointerSwiping()) {
this._previousStartingPointerTime = 0;
this._doubleClickOccured = true;
clickInfo.doubleClick = true;
clickInfo.ignore = false;
if (_InputManager.ExclusiveDoubleClickMode && this._delayedClicks[btn]) {
clearTimeout(this._delayedClicks[btn]?.timeoutId);
this._delayedClicks[btn] = null;
}
cb(clickInfo, this._currentPickResult);
} 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 (this._delayedClicks[btn]) {
clearTimeout(this._delayedClicks[btn]?.timeoutId);
this._delayedClicks[btn] = null;
}
cb(clickInfo, this._previousPickResult);
} else {
cb(clickInfo, this._currentPickResult);
}
}
needToIgnoreNext = true;
} else {
this._doubleClickOccured = false;
this._previousStartingPointerTime = this._startingPointerTime;
this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
this._previousButtonPressed = btn;
}
}
}
}
if (!needToIgnoreNext) {
cb(clickInfo, this._currentPickResult);
}
};
this._onPointerMove = (evt) => {
this._updatePointerPosition(evt);
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;
}
if (engine.isPointerLock) {
engine._verifyPointerLock();
}
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 (_InputManager.ExclusiveDoubleClickMode) {
for (let i = 0; i < this._delayedClicks.length; i++) {
if (this._delayedClicks[i]) {
if (evt.button === i) {
clearTimeout(this._delayedClicks[i]?.timeoutId);
} else {
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);
}
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();
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);
};
}
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) {
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) => {
if (scene.onPrePointerObservable.hasObservers()) {
this._skipPointerTap = false;
if (!clickInfo.ignore) {
if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) {
if (this._swipeButtonPressed === evt.button) {
this._isSwiping = false;
this._swipeButtonPressed = -1;
}
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;
}
}
}
}
}
if (!this._pointerCaptures[evt.pointerId]) {
if (this._swipeButtonPressed === evt.button) {
this._isSwiping = false;
this._swipeButtonPressed = -1;
}
return;
}
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);
};
}
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));
}
};
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;
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 (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];
}
}
}
};
InputManager.DragMovementThreshold = 10;
InputManager.LongPressDelay = 500;
InputManager.DoubleClickDelay = 300;
InputManager.ExclusiveDoubleClickMode = false;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/uniqueIdGenerator.js
var UniqueIdGenerator;
var init_uniqueIdGenerator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/uniqueIdGenerator.js"() {
UniqueIdGenerator = class {
static {
__name(this, "UniqueIdGenerator");
}
/**
* Gets an unique (relatively to the current scene) Id
*/
static get UniqueId() {
const result = this._UniqueIdCounter;
this._UniqueIdCounter++;
return result;
}
};
UniqueIdGenerator._UniqueIdCounter = 1;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Inputs/pointerPickingConfiguration.js
var PointerPickingConfiguration;
var init_pointerPickingConfiguration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Inputs/pointerPickingConfiguration.js"() {
PointerPickingConfiguration = class {
static {
__name(this, "PointerPickingConfiguration");
}
constructor() {
this.pointerDownFastCheck = false;
this.pointerUpFastCheck = false;
this.pointerMoveFastCheck = false;
this.skipPointerMovePicking = false;
this.skipPointerDownPicking = false;
this.skipPointerUpPicking = false;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/frameGraphTypes.js
var backbufferColorTextureHandle, backbufferDepthStencilTextureHandle;
var init_frameGraphTypes = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/frameGraphTypes.js"() {
backbufferColorTextureHandle = 0;
backbufferDepthStencilTextureHandle = 1;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/pass.js
var FrameGraphPass;
var init_pass = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/pass.js"() {
FrameGraphPass = class {
static {
__name(this, "FrameGraphPass");
}
constructor(name260, _parentTask, _context) {
this.name = name260;
this._parentTask = _parentTask;
this._context = _context;
this.disabled = false;
}
setExecuteFunc(func) {
this._executeFunc = func;
}
_execute() {
if (!this.disabled) {
this._executeFunc(this._context);
}
}
_isValid() {
return this._executeFunc !== void 0 ? null : "Execute function is not set (call setExecuteFunc to set it)";
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/cullPass.js
var FrameGraphCullPass;
var init_cullPass = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/cullPass.js"() {
init_pass();
FrameGraphCullPass = class extends FrameGraphPass {
static {
__name(this, "FrameGraphCullPass");
}
/**
* Checks if a pass is a cull pass.
* @param pass The pass to check.
* @returns True if the pass is a cull pass, else false.
*/
static IsCullPass(pass) {
return pass.setObjectList !== void 0;
}
/**
* Gets the object list used by the cull pass.
*/
get objectList() {
return this._objectList;
}
/**
* Sets the object list to use for culling.
* @param objectList The object list to use for culling.
*/
setObjectList(objectList) {
this._objectList = objectList;
}
/** @internal */
constructor(name260, parentTask, context, engine) {
super(name260, parentTask, context);
this._engine = engine;
}
/** @internal */
_isValid() {
const errMsg = super._isValid();
return errMsg ? errMsg : this._objectList !== void 0 ? null : "Object list is not set (call setObjectList to set it)";
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/renderPass.js
var FrameGraphRenderPass;
var init_renderPass = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/renderPass.js"() {
init_pass();
FrameGraphRenderPass = class extends FrameGraphPass {
static {
__name(this, "FrameGraphRenderPass");
}
/**
* Checks if a pass is a render pass.
* @param pass The pass to check.
* @returns True if the pass is a render pass, else false.
*/
static IsRenderPass(pass) {
return pass.setRenderTarget !== void 0;
}
/**
* Gets the render target(s) used by the render pass.
*/
get renderTarget() {
return this._renderTarget;
}
/**
* Gets the render target depth used by the render pass.
*/
get renderTargetDepth() {
return this._renderTargetDepth;
}
/** @internal */
constructor(name260, parentTask, context, engine) {
super(name260, parentTask, context);
this._dependencies = /* @__PURE__ */ new Set();
this.depthReadOnly = false;
this.stencilReadOnly = false;
this._engine = engine;
}
/**
* Sets the render target(s) to use for rendering.
* @param renderTargetHandle The render target to use for rendering, or an array of render targets to use for multi render target rendering.
*/
setRenderTarget(renderTargetHandle) {
this._renderTarget = renderTargetHandle;
}
/**
* Sets the render target depth to use for rendering.
* @param renderTargetHandle The render target depth to use for rendering.
*/
setRenderTargetDepth(renderTargetHandle) {
this._renderTargetDepth = renderTargetHandle;
}
/**
* Adds dependencies to the render pass.
* @param dependencies The dependencies to add.
*/
addDependencies(dependencies) {
if (dependencies === void 0) {
return;
}
if (Array.isArray(dependencies)) {
for (const dependency of dependencies) {
this._dependencies.add(dependency);
}
} else {
this._dependencies.add(dependencies);
}
}
/**
* Collects the dependencies of the render pass.
* @param dependencies The set of dependencies to update.
*/
collectDependencies(dependencies) {
const iterator = this._dependencies.keys();
for (let key = iterator.next(); key.done !== true; key = iterator.next()) {
dependencies.add(key.value);
}
if (this._renderTarget !== void 0) {
if (Array.isArray(this._renderTarget)) {
for (const handle of this._renderTarget) {
if (handle !== void 0) {
dependencies.add(handle);
}
}
} else {
dependencies.add(this._renderTarget);
}
}
if (this._renderTargetDepth !== void 0) {
dependencies.add(this._renderTargetDepth);
}
}
/** @internal */
_execute() {
this._frameGraphRenderTarget = this._frameGraphRenderTarget || this._context.createRenderTarget(this.name, this._renderTarget, this._renderTargetDepth, this.depthReadOnly, this.stencilReadOnly);
this._context.bindRenderTarget(this._frameGraphRenderTarget, `frame graph render pass - ${this.name}`);
super._execute();
this._context._flushDebugMessages();
}
/** @internal */
_isValid() {
const errMsg = super._isValid();
return errMsg ? errMsg : this._renderTarget !== void 0 || this.renderTargetDepth !== void 0 ? null : "Render target and render target depth cannot both be undefined.";
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/frameGraphTask.js
var FrameGraphTask;
var init_frameGraphTask = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/frameGraphTask.js"() {
init_cullPass();
init_renderPass();
init_observable();
FrameGraphTask = class {
static {
__name(this, "FrameGraphTask");
}
/**
* The name of the task.
*/
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
/**
* Whether the task is disabled.
*/
get disabled() {
return this._disabled;
}
set disabled(value) {
this._disabled = value;
}
/**
* Gets the render passes of the task.
*/
get passes() {
return this._passes;
}
/**
* Gets the disabled render passes of the task.
*/
get passesDisabled() {
return this._passesDisabled;
}
/**
* Checks if the task is ready to be executed.
* @returns True if the task is ready to be executed, else false.
*/
isReady() {
return true;
}
/**
* Disposes of the task.
*/
dispose() {
this._reset();
this.onTexturesAllocatedObservable.clear();
}
/**
* Constructs a new frame graph task.
* @param name The name of the task.
* @param frameGraph The frame graph this task is associated with.
*/
constructor(name260, frameGraph) {
this._passes = [];
this._passesDisabled = [];
this._disabled = false;
this.onTexturesAllocatedObservable = new Observable();
this.name = name260;
this._frameGraph = frameGraph;
this._reset();
}
/** @internal */
_reset() {
this._passes.length = 0;
this._passesDisabled.length = 0;
}
/** @internal */
_addPass(pass, disabled) {
if (disabled) {
this._passesDisabled.push(pass);
} else {
this._passes.push(pass);
}
}
/** @internal */
_checkTask() {
let outputTexture = null;
let outputDepthTexture = null;
let outputObjectList;
for (const pass of this._passes) {
const errMsg = pass._isValid();
if (errMsg) {
throw new Error(`Pass "${pass.name}" is not valid. ${errMsg}`);
}
if (FrameGraphRenderPass.IsRenderPass(pass)) {
const handles = Array.isArray(pass.renderTarget) ? pass.renderTarget : [pass.renderTarget];
outputTexture = [];
for (const handle of handles) {
if (handle !== void 0) {
outputTexture.push(this._frameGraph.textureManager.getTextureFromHandle(handle));
}
}
outputDepthTexture = pass.renderTargetDepth !== void 0 ? this._frameGraph.textureManager.getTextureFromHandle(pass.renderTargetDepth) : null;
} else if (FrameGraphCullPass.IsCullPass(pass)) {
outputObjectList = pass.objectList;
}
}
let disabledOutputTexture = null;
let disabledOutputTextureHandle = [];
let disabledOutputDepthTexture = null;
let disabledOutputObjectList;
for (const pass of this._passesDisabled) {
const errMsg = pass._isValid();
if (errMsg) {
throw new Error(`Pass "${pass.name}" is not valid. ${errMsg}`);
}
if (FrameGraphRenderPass.IsRenderPass(pass)) {
const handles = Array.isArray(pass.renderTarget) ? pass.renderTarget : [pass.renderTarget];
disabledOutputTexture = [];
for (const handle of handles) {
if (handle !== void 0) {
disabledOutputTexture.push(this._frameGraph.textureManager.getTextureFromHandle(handle));
}
}
disabledOutputTextureHandle = handles;
disabledOutputDepthTexture = pass.renderTargetDepth !== void 0 ? this._frameGraph.textureManager.getTextureFromHandle(pass.renderTargetDepth) : null;
} else if (FrameGraphCullPass.IsCullPass(pass)) {
disabledOutputObjectList = pass.objectList;
}
}
if (this._passesDisabled.length > 0) {
if (!this._checkSameRenderTarget(outputTexture, disabledOutputTexture)) {
let ok = true;
for (const handle of disabledOutputTextureHandle) {
if (handle !== void 0 && !this._frameGraph.textureManager.isHistoryTexture(handle)) {
ok = false;
break;
}
}
if (!ok) {
throw new Error(`The output texture of the task "${this.name}" is different when it is enabled or disabled.`);
}
}
if (outputDepthTexture !== disabledOutputDepthTexture) {
throw new Error(`The output depth texture of the task "${this.name}" is different when it is enabled or disabled.`);
}
if (outputObjectList !== disabledOutputObjectList) {
throw new Error(`The output object list of the task "${this.name}" is different when it is enabled or disabled.`);
}
}
}
/** @internal */
_getPasses() {
return this.disabled && this._passesDisabled.length > 0 ? this._passesDisabled : this._passes;
}
_checkSameRenderTarget(src, dst) {
if (src === null || dst === null) {
return src === dst;
}
if (src.length !== dst.length) {
return false;
}
for (let i = 0; i < src.length; i++) {
if (src[i] !== dst[i]) {
return false;
}
}
return true;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/packingFunctions.js
var name15, shader15, packingFunctionsWGSL;
var init_packingFunctions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/packingFunctions.js"() {
init_shaderStore();
name15 = "packingFunctions";
shader15 = `fn pack(depth: f32)->vec4f
{const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
fn unpack(color: vec4f)->f32
{const bit_shift: vec4f= vec4f(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);}`;
if (!ShaderStore.IncludesShadersStoreWGSL[name15]) {
ShaderStore.IncludesShadersStoreWGSL[name15] = shader15;
}
packingFunctionsWGSL = { name: name15, shader: shader15 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bayerDitherFunctions.js
var name16, shader16, bayerDitherFunctionsWGSL;
var init_bayerDitherFunctions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bayerDitherFunctions.js"() {
init_shaderStore();
name16 = "bayerDitherFunctions";
shader16 = `fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));}
fn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0));
var P2: vec2f=floor(0.5*((_P)%(4.0)));
return 4.0*bayerDither2(P1)+bayerDither2(P2);}
fn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0));
var P2: vec2f=floor(0.5 *((_P)%(4.0)));
var P4: vec2f=floor(0.25*((_P)%(8.0)));
return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name16]) {
ShaderStore.IncludesShadersStoreWGSL[name16] = shader16;
}
bayerDitherFunctionsWGSL = { name: name16, shader: shader16 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentExtraDeclaration.js
var name17, shader17, shadowMapFragmentExtraDeclarationWGSL;
var init_shadowMapFragmentExtraDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentExtraDeclaration.js"() {
init_shaderStore();
init_packingFunctions();
init_bayerDitherFunctions();
name17 = "shadowMapFragmentExtraDeclaration";
shader17 = `#if SM_FLOAT==0
#include
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#include
uniform softTransparentShadowSM: vec2f;
#endif
varying vDepthMetricSM: f32;
#if SM_USEDISTANCE==1
uniform lightDataSM: vec3f;varying vPositionWSM: vec3f;
#endif
uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying zSM: f32;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name17]) {
ShaderStore.IncludesShadersStoreWGSL[name17] = shader17;
}
shadowMapFragmentExtraDeclarationWGSL = { name: name17, shader: shader17 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js
var name18, shader18, clipPlaneFragmentDeclarationWGSL;
var init_clipPlaneFragmentDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js"() {
init_shaderStore();
name18 = "clipPlaneFragmentDeclaration";
shader18 = `#ifdef CLIPPLANE
varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
varying fClipDistance6: f32;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name18]) {
ShaderStore.IncludesShadersStoreWGSL[name18] = shader18;
}
clipPlaneFragmentDeclarationWGSL = { name: name18, shader: shader18 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragment.js
var name19, shader19, clipPlaneFragmentWGSL;
var init_clipPlaneFragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragment.js"() {
init_shaderStore();
name19 = "clipPlaneFragment";
shader19 = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
if (false) {}
#endif
#ifdef CLIPPLANE
else if (fragmentInputs.fClipDistance>0.0)
{discard;}
#endif
#ifdef CLIPPLANE2
else if (fragmentInputs.fClipDistance2>0.0)
{discard;}
#endif
#ifdef CLIPPLANE3
else if (fragmentInputs.fClipDistance3>0.0)
{discard;}
#endif
#ifdef CLIPPLANE4
else if (fragmentInputs.fClipDistance4>0.0)
{discard;}
#endif
#ifdef CLIPPLANE5
else if (fragmentInputs.fClipDistance5>0.0)
{discard;}
#endif
#ifdef CLIPPLANE6
else if (fragmentInputs.fClipDistance6>0.0)
{discard;}
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name19]) {
ShaderStore.IncludesShadersStoreWGSL[name19] = shader19;
}
clipPlaneFragmentWGSL = { name: name19, shader: shader19 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragment.js
var name20, shader20, shadowMapFragmentWGSL;
var init_shadowMapFragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragment.js"() {
init_shaderStore();
name20 = "shadowMapFragment";
shader20 = `var depthSM: f32=fragmentInputs.vDepthMetricSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
#if SM_USEDISTANCE==1
depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
depthSM=(-fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
depthSM=(fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#endif
depthSM=clamp(depthSM,0.0,1.0);
#ifdef USE_REVERSE_DEPTHBUFFER
fragmentOutputs.fragDepth=clamp(1.0-depthSM,0.0,1.0);
#else
fragmentOutputs.fragDepth=clamp(depthSM,0.0,1.0);
#endif
#elif SM_USEDISTANCE==1
depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#if SM_ESM==1
depthSM=clamp(exp(-min(87.,uniforms.biasAndScaleSM.z*depthSM)),0.,1.);
#endif
#if SM_FLOAT==1
fragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0);
#else
fragmentOutputs.color=pack(depthSM);
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name20]) {
ShaderStore.IncludesShadersStoreWGSL[name20] = shader20;
}
shadowMapFragmentWGSL = { name: name20, shader: shader20 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/shadowMap.fragment.js
var shadowMap_fragment_exports = {};
__export(shadowMap_fragment_exports, {
shadowMapPixelShaderWGSL: () => shadowMapPixelShaderWGSL
});
var name21, shader21, shadowMapPixelShaderWGSL;
var init_shadowMap_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/shadowMap.fragment.js"() {
init_shaderStore();
init_shadowMapFragmentExtraDeclaration();
init_clipPlaneFragmentDeclaration();
init_clipPlaneFragment();
init_shadowMapFragment();
name21 = "shadowMapPixelShader";
shader21 = `#include
#ifdef ALPHATEXTURE
varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;
#endif
#include
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include
#ifdef ALPHATEXTURE
var opacityMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV);var alphaFromAlphaTexture: f32=opacityMap.a;
#if SM_SOFTTRANSPARENTSHADOW==1
if (uniforms.softTransparentShadowSM.y==1.0) {opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}
#endif
#ifdef ALPHATESTVALUE
if (alphaFromAlphaTexture=uniforms.softTransparentShadowSM.x*alphaFromAlphaTexture) {discard;}
#else
if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x) {discard;}
#endif
#endif
#include
}`;
if (!ShaderStore.ShadersStoreWGSL[name21]) {
ShaderStore.ShadersStoreWGSL[name21] = shader21;
}
shadowMapPixelShaderWGSL = { name: name21, shader: shader21 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesDeclaration.js
var name22, shader22, bonesDeclarationWGSL;
var init_bonesDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesDeclaration.js"() {
init_shaderStore();
name22 = "bonesDeclaration";
shader22 = `#if NUM_BONE_INFLUENCERS>0
attribute matricesIndices : vec4;attribute matricesWeights : vec4;
#if NUM_BONE_INFLUENCERS>4
attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
var boneSampler : texture_2d;uniform boneTextureWidth : f32;
#else
uniform mBones : array;
#endif
#ifdef BONES_VELOCITY_ENABLED
uniform mPreviousBones : array;
#endif
#ifdef BONETEXTURE
fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4f
{let offset=i32(index) *4;
let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4f(m0,m1,m2,m3);}
#endif
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name22]) {
ShaderStore.IncludesShadersStoreWGSL[name22] = shader22;
}
bonesDeclarationWGSL = { name: name22, shader: shader22 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js
var name23, shader23, bakedVertexAnimationDeclarationWGSL;
var init_bakedVertexAnimationDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js"() {
init_shaderStore();
name23 = "bakedVertexAnimationDeclaration";
shader23 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;
#ifdef INSTANCES
attribute bakedVertexAnimationSettingsInstanced : vec4;
#endif
fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4
{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name23]) {
ShaderStore.IncludesShadersStoreWGSL[name23] = shader23;
}
bakedVertexAnimationDeclarationWGSL = { name: name23, shader: shader23 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js
var name24, shader24, morphTargetsVertexGlobalDeclarationWGSL;
var init_morphTargetsVertexGlobalDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js"() {
init_shaderStore();
name24 = "morphTargetsVertexGlobalDeclaration";
shader24 = `#ifdef MORPHTARGETS
uniform morphTargetInfluences : array;
#ifdef MORPHTARGETS_TEXTURE
uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3
{
let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}
fn readVector4FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec4
{
let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0);}
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name24]) {
ShaderStore.IncludesShadersStoreWGSL[name24] = shader24;
}
morphTargetsVertexGlobalDeclarationWGSL = { name: name24, shader: shader24 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js
var name25, shader25, morphTargetsVertexDeclarationWGSL;
var init_morphTargetsVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js"() {
init_shaderStore();
name25 = "morphTargetsVertexDeclaration";
shader25 = `#ifdef MORPHTARGETS
#ifndef MORPHTARGETS_TEXTURE
#ifdef MORPHTARGETS_POSITION
attribute position{X} : vec3;
#endif
#ifdef MORPHTARGETS_NORMAL
attribute normal{X} : vec3;
#endif
#ifdef MORPHTARGETS_TANGENT
attribute tangent{X} : vec3;
#endif
#ifdef MORPHTARGETS_UV
attribute uv_{X} : vec2;
#endif
#ifdef MORPHTARGETS_UV2
attribute uv2_{X} : vec2;
#endif
#ifdef MORPHTARGETS_COLOR
attribute color{X} : vec4;
#endif
#elif {X}==0
uniform morphTargetCount: f32;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name25]) {
ShaderStore.IncludesShadersStoreWGSL[name25] = shader25;
}
morphTargetsVertexDeclarationWGSL = { name: name25, shader: shader25 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/sceneUboDeclaration.js
var name26, shader26, sceneUboDeclarationWGSL;
var init_sceneUboDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/sceneUboDeclaration.js"() {
init_shaderStore();
name26 = "sceneUboDeclaration";
shader26 = `struct Scene {viewProjection : mat4x4,
#ifdef MULTIVIEW
viewProjectionR : mat4x4,
#endif
view : mat4x4,
projection : mat4x4,
vEyePosition : vec4,};
#define SCENE_UBO
var scene : Scene;
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name26]) {
ShaderStore.IncludesShadersStoreWGSL[name26] = shader26;
}
sceneUboDeclarationWGSL = { name: name26, shader: shader26 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/meshUboDeclaration.js
var name27, shader27, meshUboDeclarationWGSL;
var init_meshUboDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/meshUboDeclaration.js"() {
init_shaderStore();
name27 = "meshUboDeclaration";
shader27 = `struct Mesh {world : mat4x4,
visibility : f32,};var mesh : Mesh;
#define WORLD_UBO
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name27]) {
ShaderStore.IncludesShadersStoreWGSL[name27] = shader27;
}
meshUboDeclarationWGSL = { name: name27, shader: shader27 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexExtraDeclaration.js
var name28, shader28, shadowMapVertexExtraDeclarationWGSL;
var init_shadowMapVertexExtraDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexExtraDeclaration.js"() {
init_shaderStore();
name28 = "shadowMapVertexExtraDeclaration";
shader28 = `#if SM_NORMALBIAS==1
uniform lightDataSM: vec3f;
#endif
uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32;
#if SM_USEDISTANCE==1
varying vPositionWSM: vec3f;
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying zSM: f32;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name28]) {
ShaderStore.IncludesShadersStoreWGSL[name28] = shader28;
}
shadowMapVertexExtraDeclarationWGSL = { name: name28, shader: shader28 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js
var name29, shader29, clipPlaneVertexDeclarationWGSL;
var init_clipPlaneVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js"() {
init_shaderStore();
name29 = "clipPlaneVertexDeclaration";
shader29 = `#ifdef CLIPPLANE
uniform vClipPlane: vec4;varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
uniform vClipPlane2: vec4;varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
uniform vClipPlane3: vec4;varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
uniform vClipPlane4: vec4;varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
uniform vClipPlane5: vec4;varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
uniform vClipPlane6: vec4;varying fClipDistance6: f32;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name29]) {
ShaderStore.IncludesShadersStoreWGSL[name29] = shader29;
}
clipPlaneVertexDeclarationWGSL = { name: name29, shader: shader29 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js
var name30, shader30, morphTargetsVertexGlobalWGSL;
var init_morphTargetsVertexGlobal = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js"() {
init_shaderStore();
name30 = "morphTargetsVertexGlobal";
shader30 = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
var vertexID : f32;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name30]) {
ShaderStore.IncludesShadersStoreWGSL[name30] = shader30;
}
morphTargetsVertexGlobalWGSL = { name: name30, shader: shader30 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertex.js
var name31, shader31, morphTargetsVertexWGSL;
var init_morphTargetsVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertex.js"() {
init_shaderStore();
name31 = "morphTargetsVertex";
shader31 = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
#if {X}==0
for (var i=0; i=uniforms.morphTargetCount) {break;}
vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;
#ifdef MORPHTARGETS_POSITION
positionUpdated=positionUpdated+(readVector3FromRawSampler(i,vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASPOSITIONS
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_NORMAL
normalUpdated=normalUpdated+(readVector3FromRawSampler(i,vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASNORMALS
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_UV
uvUpdated=uvUpdated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASUVS
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated=vec4f(tangentUpdated.xyz+(readVector3FromRawSampler(i,vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[i],tangentUpdated.a);
#endif
#ifdef MORPHTARGETTEXTURE_HASTANGENTS
vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_UV2
uv2Updated=uv2Updated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv2)*uniforms.morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETS_COLOR
colorUpdated=colorUpdated+(readVector4FromRawSampler(i,vertexID)-vertexInputs.color)*uniforms.morphTargetInfluences[i];
#endif
}
#endif
#else
#ifdef MORPHTARGETS_POSITION
positionUpdated=positionUpdated+(vertexInputs.position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_NORMAL
normalUpdated=normalUpdated+(vertexInputs.normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated=vec4f(tangentUpdated.xyz+(vertexInputs.tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}],tangentUpdated.a);
#endif
#ifdef MORPHTARGETS_UV
uvUpdated=uvUpdated+(vertexInputs.uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV2
uv2Updated=uv2Updated+(vertexInputs.uv2_{X}-vertexInputs.uv2)*uniforms.morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_COLOR
colorUpdated=colorUpdated+(vertexInputs.color{X}-vertexInputs.color)*uniforms.morphTargetInfluences[{X}];
#endif
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name31]) {
ShaderStore.IncludesShadersStoreWGSL[name31] = shader31;
}
morphTargetsVertexWGSL = { name: name31, shader: shader31 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesVertex.js
var name32, shader32, instancesVertexWGSL;
var init_instancesVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesVertex.js"() {
init_shaderStore();
name32 = "instancesVertex";
shader32 = `#ifdef INSTANCES
var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
var finalPreviousWorld=mat4x4(
vertexInputs.previousWorld0,vertexInputs.previousWorld1,
vertexInputs.previousWorld2,vertexInputs.previousWorld3);
#endif
#ifdef THIN_INSTANCES
#if !defined(WORLD_UBO)
finalWorld=uniforms.world*finalWorld;
#else
finalWorld=mesh.world*finalWorld;
#endif
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
finalPreviousWorld=uniforms.previousWorld*finalPreviousWorld;
#endif
#endif
#else
#if !defined(WORLD_UBO)
var finalWorld=uniforms.world;
#else
var finalWorld=mesh.world;
#endif
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
var finalPreviousWorld=uniforms.previousWorld;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name32]) {
ShaderStore.IncludesShadersStoreWGSL[name32] = shader32;
}
instancesVertexWGSL = { name: name32, shader: shader32 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesVertex.js
var name33, shader33, bonesVertexWGSL;
var init_bonesVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesVertex.js"() {
init_shaderStore();
name33 = "bonesVertex";
shader33 = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#if NUM_BONE_INFLUENCERS>0
var influence : mat4x4;
#ifdef BONETEXTURE
influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];
#endif
#else
influence=uniforms.mBones[i32(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];
#endif
#endif
finalWorld=finalWorld*influence;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name33]) {
ShaderStore.IncludesShadersStoreWGSL[name33] = shader33;
}
bonesVertexWGSL = { name: name33, shader: shader33 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimation.js
var name34, shader34, bakedVertexAnimationWGSL;
var init_bakedVertexAnimation = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimation.js"() {
init_shaderStore();
name34 = "bakedVertexAnimation";
shader34 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
{
#ifdef INSTANCES
let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;
#else
let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;
#endif
let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];
#endif
finalWorld=finalWorld*VATInfluence;}
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name34]) {
ShaderStore.IncludesShadersStoreWGSL[name34] = shader34;
}
bakedVertexAnimationWGSL = { name: name34, shader: shader34 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexNormalBias.js
var name35, shader35, shadowMapVertexNormalBiasWGSL;
var init_shadowMapVertexNormalBias = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexNormalBias.js"() {
init_shaderStore();
name35 = "shadowMapVertexNormalBias";
shader35 = `#if SM_NORMALBIAS==1
#if SM_DIRECTIONINLIGHTDATA==1
var worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz);
#else
var directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLightDirSM: vec3f=normalize(directionToLightSM);
#endif
var ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w);
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name35]) {
ShaderStore.IncludesShadersStoreWGSL[name35] = shader35;
}
shadowMapVertexNormalBiasWGSL = { name: name35, shader: shader35 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexMetric.js
var name36, shader36, shadowMapVertexMetricWGSL;
var init_shadowMapVertexMetric = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexMetric.js"() {
init_shaderStore();
name36 = "shadowMapVertexMetric";
shader36 = `#if SM_USEDISTANCE==1
vertexOutputs.vPositionWSM=worldPos.xyz;
#endif
#if SM_DEPTHTEXTURE==1
#ifdef IS_NDC_HALF_ZRANGE
#define BIASFACTOR 0.5
#else
#define BIASFACTOR 1.0
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.position.z-=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;
#else
vertexOutputs.position.z+=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;
#endif
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
vertexOutputs.zSM=vertexOutputs.position.z;vertexOutputs.position.z=0.0;
#elif SM_USEDISTANCE==0
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
vertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name36]) {
ShaderStore.IncludesShadersStoreWGSL[name36] = shader36;
}
shadowMapVertexMetricWGSL = { name: name36, shader: shader36 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertex.js
var name37, shader37, clipPlaneVertexWGSL;
var init_clipPlaneVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertex.js"() {
init_shaderStore();
name37 = "clipPlaneVertex";
shader37 = `#ifdef CLIPPLANE
vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);
#endif
#ifdef CLIPPLANE2
vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);
#endif
#ifdef CLIPPLANE3
vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);
#endif
#ifdef CLIPPLANE4
vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);
#endif
#ifdef CLIPPLANE5
vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);
#endif
#ifdef CLIPPLANE6
vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name37]) {
ShaderStore.IncludesShadersStoreWGSL[name37] = shader37;
}
clipPlaneVertexWGSL = { name: name37, shader: shader37 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/shadowMap.vertex.js
var shadowMap_vertex_exports = {};
__export(shadowMap_vertex_exports, {
shadowMapVertexShaderWGSL: () => shadowMapVertexShaderWGSL
});
var name38, shader38, shadowMapVertexShaderWGSL;
var init_shadowMap_vertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/shadowMap.vertex.js"() {
init_shaderStore();
init_bonesDeclaration();
init_bakedVertexAnimationDeclaration();
init_morphTargetsVertexGlobalDeclaration();
init_morphTargetsVertexDeclaration();
init_helperFunctions();
init_sceneUboDeclaration();
init_meshUboDeclaration();
init_shadowMapVertexExtraDeclaration();
init_clipPlaneVertexDeclaration();
init_morphTargetsVertexGlobal();
init_morphTargetsVertex();
init_instancesVertex();
init_bonesVertex();
init_bakedVertexAnimation();
init_shadowMapVertexNormalBias();
init_shadowMapVertexMetric();
init_clipPlaneVertex();
name38 = "shadowMapVertexShader";
shader38 = `attribute position: vec3f;
#ifdef NORMAL
attribute normal: vec3f;
#endif
#include
#include
#include
#include[0..maxSimultaneousMorphTargets]
#ifdef INSTANCES
attribute world0: vec4f;attribute world1: vec4f;attribute world2: vec4f;attribute world3: vec4f;
#endif
#include
#include
#include
#ifdef ALPHATEXTURE
varying vUV: vec2f;uniform diffuseMatrix: mat4x4f;
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#include
#include
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;
#ifdef UV1
var uvUpdated: vec2f=input.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=input.uv2;
#endif
#ifdef NORMAL
var normalUpdated: vec3f=input.normal;
#endif
#include
#include[0..maxSimultaneousMorphTargets]
#include
#include
#include
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);
#ifdef NORMAL
var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
var vNormalW: vec3f=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
var vNormalW: vec3f=normalize(normWorldSM*normalUpdated);
#endif
#endif
#include
vertexOutputs.position=scene.viewProjection*worldPos;
#include
#ifdef ALPHATEXTURE
#ifdef UV1
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef UV2
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#include
}`;
if (!ShaderStore.ShadersStoreWGSL[name38]) {
ShaderStore.ShadersStoreWGSL[name38] = shader38;
}
shadowMapVertexShaderWGSL = { name: name38, shader: shader38 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depthBoxBlur.fragment.js
var depthBoxBlur_fragment_exports = {};
__export(depthBoxBlur_fragment_exports, {
depthBoxBlurPixelShaderWGSL: () => depthBoxBlurPixelShaderWGSL
});
var name39, shader39, depthBoxBlurPixelShaderWGSL;
var init_depthBoxBlur_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depthBoxBlur.fragment.js"() {
init_shaderStore();
name39 = "depthBoxBlurPixelShader";
shader39 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}}
fragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}`;
if (!ShaderStore.ShadersStoreWGSL[name39]) {
ShaderStore.ShadersStoreWGSL[name39] = shader39;
}
depthBoxBlurPixelShaderWGSL = { name: name39, shader: shader39 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js
var shadowMapFragmentSoftTransparentShadow_exports = {};
__export(shadowMapFragmentSoftTransparentShadow_exports, {
shadowMapFragmentSoftTransparentShadowWGSL: () => shadowMapFragmentSoftTransparentShadowWGSL
});
var name40, shader40, shadowMapFragmentSoftTransparentShadowWGSL;
var init_shadowMapFragmentSoftTransparentShadow = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js"() {
init_shaderStore();
name40 = "shadowMapFragmentSoftTransparentShadow";
shader40 = `#if SM_SOFTTRANSPARENTSHADOW==1
if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;}
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name40]) {
ShaderStore.IncludesShadersStoreWGSL[name40] = shader40;
}
shadowMapFragmentSoftTransparentShadowWGSL = { name: name40, shader: shader40 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/packingFunctions.js
var name41, shader41, packingFunctions;
var init_packingFunctions2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/packingFunctions.js"() {
init_shaderStore();
name41 = "packingFunctions";
shader41 = `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);}`;
if (!ShaderStore.IncludesShadersStore[name41]) {
ShaderStore.IncludesShadersStore[name41] = shader41;
}
packingFunctions = { name: name41, shader: shader41 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bayerDitherFunctions.js
var name42, shader42, bayerDitherFunctions;
var init_bayerDitherFunctions2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bayerDitherFunctions.js"() {
init_shaderStore();
name42 = "bayerDitherFunctions";
shader42 = `float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}
float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0);
vec2 P2=floor(0.5*mod(_P,4.0));
return 4.0*bayerDither2(P1)+bayerDither2(P2);}
float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0);
vec2 P2=floor(0.5 *mod(_P,4.0));
vec2 P4=floor(0.25*mod(_P,8.0));
return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}
`;
if (!ShaderStore.IncludesShadersStore[name42]) {
ShaderStore.IncludesShadersStore[name42] = shader42;
}
bayerDitherFunctions = { name: name42, shader: shader42 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentExtraDeclaration.js
var name43, shader43, shadowMapFragmentExtraDeclaration;
var init_shadowMapFragmentExtraDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentExtraDeclaration.js"() {
init_shaderStore();
init_packingFunctions2();
init_bayerDitherFunctions2();
name43 = "shadowMapFragmentExtraDeclaration";
shader43 = `#if SM_FLOAT==0
#include
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#include
uniform vec2 softTransparentShadowSM;
#endif
varying float vDepthMetricSM;
#if SM_USEDISTANCE==1
uniform vec3 lightDataSM;varying vec3 vPositionWSM;
#endif
uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying float zSM;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name43]) {
ShaderStore.IncludesShadersStore[name43] = shader43;
}
shadowMapFragmentExtraDeclaration = { name: name43, shader: shader43 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration.js
var name44, shader44, clipPlaneFragmentDeclaration;
var init_clipPlaneFragmentDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration.js"() {
init_shaderStore();
name44 = "clipPlaneFragmentDeclaration";
shader44 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name44]) {
ShaderStore.IncludesShadersStore[name44] = shader44;
}
clipPlaneFragmentDeclaration = { name: name44, shader: shader44 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragment.js
var name45, shader45, clipPlaneFragment;
var init_clipPlaneFragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragment.js"() {
init_shaderStore();
name45 = "clipPlaneFragment";
shader45 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name45]) {
ShaderStore.IncludesShadersStore[name45] = shader45;
}
clipPlaneFragment = { name: name45, shader: shader45 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragment.js
var name46, shader46, shadowMapFragment;
var init_shadowMapFragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragment.js"() {
init_shaderStore();
name46 = "shadowMapFragment";
shader46 = `float depthSM=vDepthMetricSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
#if SM_USEDISTANCE==1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
depthSM=clamp(depthSM,0.0,1.0);
#ifdef USE_REVERSE_DEPTHBUFFER
gl_FragDepth=clamp(1.0-depthSM,0.0,1.0);
#else
gl_FragDepth=clamp(depthSM,0.0,1.0);
#endif
#elif SM_USEDISTANCE==1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#if SM_ESM==1
depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);
#endif
#if SM_FLOAT==1
gl_FragColor=vec4(depthSM,1.0,1.0,1.0);
#else
gl_FragColor=pack(depthSM);
#endif
return;`;
if (!ShaderStore.IncludesShadersStore[name46]) {
ShaderStore.IncludesShadersStore[name46] = shader46;
}
shadowMapFragment = { name: name46, shader: shader46 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/shadowMap.fragment.js
var shadowMap_fragment_exports2 = {};
__export(shadowMap_fragment_exports2, {
shadowMapPixelShader: () => shadowMapPixelShader
});
var name47, shader47, shadowMapPixelShader;
var init_shadowMap_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/shadowMap.fragment.js"() {
init_shaderStore();
init_shadowMapFragmentExtraDeclaration2();
init_clipPlaneFragmentDeclaration2();
init_clipPlaneFragment2();
init_shadowMapFragment2();
name47 = "shadowMapPixelShader";
shader47 = `#include
#ifdef ALPHATEXTURE
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include
#ifdef ALPHATEXTURE
vec4 opacityMap=texture2D(diffuseSampler,vUV);float alphaFromAlphaTexture=opacityMap.a;
#if SM_SOFTTRANSPARENTSHADOW==1
if (softTransparentShadowSM.y==1.0) {opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}
#endif
#ifdef ALPHATESTVALUE
if (alphaFromAlphaTexture=softTransparentShadowSM.x*alphaFromAlphaTexture) discard;
#else
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x) discard;
#endif
#endif
#include
}`;
if (!ShaderStore.ShadersStore[name47]) {
ShaderStore.ShadersStore[name47] = shader47;
}
shadowMapPixelShader = { name: name47, shader: shader47 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesDeclaration.js
var name48, shader48, bonesDeclaration;
var init_bonesDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesDeclaration.js"() {
init_shaderStore();
name48 = "bonesDeclaration";
shader48 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name48]) {
ShaderStore.IncludesShadersStore[name48] = shader48;
}
bonesDeclaration = { name: name48, shader: shader48 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimationDeclaration.js
var name49, shader49, bakedVertexAnimationDeclaration;
var init_bakedVertexAnimationDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimationDeclaration.js"() {
init_shaderStore();
name49 = "bakedVertexAnimationDeclaration";
shader49 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name49]) {
ShaderStore.IncludesShadersStore[name49] = shader49;
}
bakedVertexAnimationDeclaration = { name: name49, shader: shader49 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js
var name50, shader50, morphTargetsVertexGlobalDeclaration;
var init_morphTargetsVertexGlobalDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js"() {
init_shaderStore();
name50 = "morphTargetsVertexGlobalDeclaration";
shader50 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name50]) {
ShaderStore.IncludesShadersStore[name50] = shader50;
}
morphTargetsVertexGlobalDeclaration = { name: name50, shader: shader50 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexDeclaration.js
var name51, shader51, morphTargetsVertexDeclaration;
var init_morphTargetsVertexDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexDeclaration.js"() {
init_shaderStore();
name51 = "morphTargetsVertexDeclaration";
shader51 = `#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
#ifdef MORPHTARGETS_COLOR
attribute vec4 color{X};
#endif
#elif {X}==0
uniform float morphTargetCount;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStore[name51]) {
ShaderStore.IncludesShadersStore[name51] = shader51;
}
morphTargetsVertexDeclaration = { name: name51, shader: shader51 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneVertexDeclaration.js
var name52, shader52, sceneVertexDeclaration;
var init_sceneVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneVertexDeclaration.js"() {
init_shaderStore();
name52 = "sceneVertexDeclaration";
shader52 = `uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;
`;
if (!ShaderStore.IncludesShadersStore[name52]) {
ShaderStore.IncludesShadersStore[name52] = shader52;
}
sceneVertexDeclaration = { name: name52, shader: shader52 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/meshVertexDeclaration.js
var name53, shader53, meshVertexDeclaration;
var init_meshVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/meshVertexDeclaration.js"() {
init_shaderStore();
name53 = "meshVertexDeclaration";
shader53 = `uniform mat4 world;uniform float visibility;
`;
if (!ShaderStore.IncludesShadersStore[name53]) {
ShaderStore.IncludesShadersStore[name53] = shader53;
}
meshVertexDeclaration = { name: name53, shader: shader53 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexDeclaration.js
var name54, shader54, shadowMapVertexDeclaration;
var init_shadowMapVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexDeclaration.js"() {
init_shaderStore();
init_sceneVertexDeclaration();
init_meshVertexDeclaration();
name54 = "shadowMapVertexDeclaration";
shader54 = `#include
#include
`;
if (!ShaderStore.IncludesShadersStore[name54]) {
ShaderStore.IncludesShadersStore[name54] = shader54;
}
shadowMapVertexDeclaration = { name: name54, shader: shader54 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneUboDeclaration.js
var name55, shader55, sceneUboDeclaration;
var init_sceneUboDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneUboDeclaration.js"() {
init_shaderStore();
name55 = "sceneUboDeclaration";
shader55 = `layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif
mat4 view;mat4 projection;vec4 vEyePosition;};
`;
if (!ShaderStore.IncludesShadersStore[name55]) {
ShaderStore.IncludesShadersStore[name55] = shader55;
}
sceneUboDeclaration = { name: name55, shader: shader55 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/meshUboDeclaration.js
var name56, shader56, meshUboDeclaration;
var init_meshUboDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/meshUboDeclaration.js"() {
init_shaderStore();
name56 = "meshUboDeclaration";
shader56 = `#ifdef WEBGL2
uniform mat4 world;uniform float visibility;
#else
layout(std140,column_major) uniform;uniform Mesh
{mat4 world;float visibility;};
#endif
#define WORLD_UBO
`;
if (!ShaderStore.IncludesShadersStore[name56]) {
ShaderStore.IncludesShadersStore[name56] = shader56;
}
meshUboDeclaration = { name: name56, shader: shader56 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapUboDeclaration.js
var name57, shader57, shadowMapUboDeclaration;
var init_shadowMapUboDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapUboDeclaration.js"() {
init_shaderStore();
init_sceneUboDeclaration2();
init_meshUboDeclaration2();
name57 = "shadowMapUboDeclaration";
shader57 = `layout(std140,column_major) uniform;
#include
#include
`;
if (!ShaderStore.IncludesShadersStore[name57]) {
ShaderStore.IncludesShadersStore[name57] = shader57;
}
shadowMapUboDeclaration = { name: name57, shader: shader57 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexExtraDeclaration.js
var name58, shader58, shadowMapVertexExtraDeclaration;
var init_shadowMapVertexExtraDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexExtraDeclaration.js"() {
init_shaderStore();
name58 = "shadowMapVertexExtraDeclaration";
shader58 = `#if SM_NORMALBIAS==1
uniform vec3 lightDataSM;
#endif
uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;
#if SM_USEDISTANCE==1
varying vec3 vPositionWSM;
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying float zSM;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name58]) {
ShaderStore.IncludesShadersStore[name58] = shader58;
}
shadowMapVertexExtraDeclaration = { name: name58, shader: shader58 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration.js
var name59, shader59, clipPlaneVertexDeclaration;
var init_clipPlaneVertexDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration.js"() {
init_shaderStore();
name59 = "clipPlaneVertexDeclaration";
shader59 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name59]) {
ShaderStore.IncludesShadersStore[name59] = shader59;
}
clipPlaneVertexDeclaration = { name: name59, shader: shader59 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobal.js
var name60, shader60, morphTargetsVertexGlobal;
var init_morphTargetsVertexGlobal2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobal.js"() {
init_shaderStore();
name60 = "morphTargetsVertexGlobal";
shader60 = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
float vertexID;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStore[name60]) {
ShaderStore.IncludesShadersStore[name60] = shader60;
}
morphTargetsVertexGlobal = { name: name60, shader: shader60 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertex.js
var name61, shader61, morphTargetsVertex;
var init_morphTargetsVertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertex.js"() {
init_shaderStore();
name61 = "morphTargetsVertex";
shader61 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name61]) {
ShaderStore.IncludesShadersStore[name61] = shader61;
}
morphTargetsVertex = { name: name61, shader: shader61 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesVertex.js
var name62, shader62, instancesVertex;
var init_instancesVertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesVertex.js"() {
init_shaderStore();
name62 = "instancesVertex";
shader62 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name62]) {
ShaderStore.IncludesShadersStore[name62] = shader62;
}
instancesVertex = { name: name62, shader: shader62 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesVertex.js
var name63, shader63, bonesVertex;
var init_bonesVertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesVertex.js"() {
init_shaderStore();
name63 = "bonesVertex";
shader63 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name63]) {
ShaderStore.IncludesShadersStore[name63] = shader63;
}
bonesVertex = { name: name63, shader: shader63 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimation.js
var name64, shader64, bakedVertexAnimation;
var init_bakedVertexAnimation2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimation.js"() {
init_shaderStore();
name64 = "bakedVertexAnimation";
shader64 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name64]) {
ShaderStore.IncludesShadersStore[name64] = shader64;
}
bakedVertexAnimation = { name: name64, shader: shader64 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexNormalBias.js
var name65, shader65, shadowMapVertexNormalBias;
var init_shadowMapVertexNormalBias2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexNormalBias.js"() {
init_shaderStore();
name65 = "shadowMapVertexNormalBias";
shader65 = `#if SM_NORMALBIAS==1
#if SM_DIRECTIONINLIGHTDATA==1
vec3 worldLightDirSM=normalize(-lightDataSM.xyz);
#else
vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);
#endif
float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name65]) {
ShaderStore.IncludesShadersStore[name65] = shader65;
}
shadowMapVertexNormalBias = { name: name65, shader: shader65 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexMetric.js
var name66, shader66, shadowMapVertexMetric;
var init_shadowMapVertexMetric2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexMetric.js"() {
init_shaderStore();
name66 = "shadowMapVertexMetric";
shader66 = `#if SM_USEDISTANCE==1
vPositionWSM=worldPos.xyz;
#endif
#if SM_DEPTHTEXTURE==1
#ifdef IS_NDC_HALF_ZRANGE
#define BIASFACTOR 0.5
#else
#define BIASFACTOR 1.0
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#else
gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#endif
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
zSM=gl_Position.z;gl_Position.z=0.0;
#elif SM_USEDISTANCE==0
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStore[name66]) {
ShaderStore.IncludesShadersStore[name66] = shader66;
}
shadowMapVertexMetric = { name: name66, shader: shader66 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertex.js
var name67, shader67, clipPlaneVertex;
var init_clipPlaneVertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertex.js"() {
init_shaderStore();
name67 = "clipPlaneVertex";
shader67 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name67]) {
ShaderStore.IncludesShadersStore[name67] = shader67;
}
clipPlaneVertex = { name: name67, shader: shader67 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/shadowMap.vertex.js
var shadowMap_vertex_exports2 = {};
__export(shadowMap_vertex_exports2, {
shadowMapVertexShader: () => shadowMapVertexShader
});
var name68, shader68, shadowMapVertexShader;
var init_shadowMap_vertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/shadowMap.vertex.js"() {
init_shaderStore();
init_bonesDeclaration2();
init_bakedVertexAnimationDeclaration2();
init_morphTargetsVertexGlobalDeclaration2();
init_morphTargetsVertexDeclaration2();
init_helperFunctions2();
init_shadowMapVertexDeclaration();
init_shadowMapUboDeclaration();
init_shadowMapVertexExtraDeclaration2();
init_clipPlaneVertexDeclaration2();
init_morphTargetsVertexGlobal2();
init_morphTargetsVertex2();
init_instancesVertex2();
init_bonesVertex2();
init_bakedVertexAnimation2();
init_shadowMapVertexNormalBias2();
init_shadowMapVertexMetric2();
init_clipPlaneVertex2();
name68 = "shadowMapVertexShader";
shader68 = `attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#include
#include
#include
#include[0..maxSimultaneousMorphTargets]
#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#endif
#include
#include<__decl__shadowMapVertex>
#ifdef ALPHATEXTURE
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#include
#include
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#include
#include[0..maxSimultaneousMorphTargets]
#include
#include
#include
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normWorldSM=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
vec3 vNormalW=normalize(normWorldSM*normalUpdated);
#endif
#endif
#include
gl_Position=viewProjection*worldPos;
#include
#ifdef ALPHATEXTURE
#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
}`;
if (!ShaderStore.ShadersStore[name68]) {
ShaderStore.ShadersStore[name68] = shader68;
}
shadowMapVertexShader = { name: name68, shader: shader68 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depthBoxBlur.fragment.js
var depthBoxBlur_fragment_exports2 = {};
__export(depthBoxBlur_fragment_exports2, {
depthBoxBlurPixelShader: () => depthBoxBlurPixelShader
});
var name69, shader69, depthBoxBlurPixelShader;
var init_depthBoxBlur_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depthBoxBlur.fragment.js"() {
init_shaderStore();
name69 = "depthBoxBlurPixelShader";
shader69 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)
for (int y=-OFFSET; y<=OFFSET; y++)
colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;
if (!ShaderStore.ShadersStore[name69]) {
ShaderStore.ShadersStore[name69] = shader69;
}
depthBoxBlurPixelShader = { name: name69, shader: shader69 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js
var shadowMapFragmentSoftTransparentShadow_exports2 = {};
__export(shadowMapFragmentSoftTransparentShadow_exports2, {
shadowMapFragmentSoftTransparentShadow: () => shadowMapFragmentSoftTransparentShadow
});
var name70, shader70, shadowMapFragmentSoftTransparentShadow;
var init_shadowMapFragmentSoftTransparentShadow2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js"() {
init_shaderStore();
name70 = "shadowMapFragmentSoftTransparentShadow";
shader70 = `#if SM_SOFTTRANSPARENTSHADOW==1
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name70]) {
ShaderStore.IncludesShadersStore[name70] = shader70;
}
shadowMapFragmentSoftTransparentShadow = { name: name70, shader: shader70 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/node.js
var _InternalNodeDataInfo, Node;
var init_node = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/node.js"() {
init_tslib_es6();
init_math_vector();
init_decorators();
init_observable();
init_engineStore();
init_devTools();
init_decorators_serialization();
_InternalNodeDataInfo = class {
static {
__name(this, "_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();
this._inheritVisibility = false;
this._isVisible = true;
}
};
Node = class _Node {
static {
__name(this, "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, name260, scene, options) {
const constructorFunc = this._NodeConstructors[type];
if (!constructorFunc) {
return null;
}
return constructorFunc(name260, 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;
if (this._parentNode && this._parentNode._children !== void 0 && 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();
}
}
this._parentNode = parent;
this._isDirty = true;
if (this._parentNode) {
if (this._parentNode._children === void 0 || this._parentNode._children === null) {
this._parentNode._children = new Array();
}
this._parentNode._children.push(this);
if (!previousParentNode) {
this._removeFromSceneRootNodes();
}
}
this._syncParentEnabledState();
}
get parent() {
return this._parentNode;
}
/**
* If set to true, this node, when renderable, will only be visible if its parent(s) are also visible.
* @default false
*/
get inheritVisibility() {
return this._nodeDataStorage._inheritVisibility;
}
set inheritVisibility(value) {
this._nodeDataStorage._inheritVisibility = value;
}
/**
* Gets or sets a boolean indicating whether this node is visible, either this node itself when it is renderable or its renderable child nodes when `inheritVisibility` is true.
* @default true
*/
get isVisible() {
if (this.inheritVisibility && this._parentNode && !this._parentNode.isVisible) {
return false;
}
return this._nodeDataStorage._isVisible;
}
set isVisible(value) {
this._nodeDataStorage._isVisible = value;
}
/**
* @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(name260, scene = null, isPure = true) {
this._isDirty = false;
this._nodeDataStorage = new _InternalNodeDataInfo();
this.state = "";
this.metadata = null;
this.reservedDataStore = null;
this._accessibilityTag = null;
this.onAccessibilityTagChangedObservable = new Observable();
this._parentContainer = null;
this.animations = [];
this._ranges = {};
this.onReady = null;
this._currentRenderId = -1;
this._parentUpdateId = -1;
this._childUpdateId = -1;
this._waitingParentId = null;
this._waitingParentInstanceIndex = null;
this._waitingParsedUniqueId = null;
this._cache = {};
this._parentNode = null;
this._children = null;
this._worldMatrix = Matrix.Identity();
this._worldMatrixDeterminant = 0;
this._worldMatrixDeterminantIsDirty = true;
this._animationPropertiesOverride = null;
this._isNode = true;
this.onDisposeObservable = new Observable();
this._onDisposeObserver = null;
this._behaviors = new Array();
this.name = name260;
this.id = name260;
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) {
this._scene.onDataLoadedObservable.addOnce(() => {
if (this._behaviors.includes(behavior)) {
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(name260) {
for (const behavior of this._behaviors) {
if (behavior.name === name260) {
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) {
for (const c of this._children) {
c._syncParentEnabledState();
}
}
}
/**
* 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 !== void 0;
});
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(name260) {
for (let i = 0; i < this.animations.length; i++) {
const animation = this.animations[i];
if (animation.name === name260) {
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(name260, from, to) {
if (!this._ranges[name260]) {
this._ranges[name260] = _Node._AnimationRangeFactory(name260, from, to);
for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
if (this.animations[i]) {
this.animations[i].createRange(name260, 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(name260, deleteFrames = true) {
for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
if (this.animations[i]) {
this.animations[i].deleteRange(name260, deleteFrames);
}
}
this._ranges[name260] = null;
}
/**
* 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(name260) {
return this._ranges[name260] || 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(name260, newParent, doNotCloneChildren) {
const result = SerializationHelper.Clone(() => new _Node(name260, this.getScene()), this);
if (newParent) {
result.parent = newParent;
}
if (!doNotCloneChildren) {
const directDescendants = this.getDescendants(true);
for (let index = 0; index < directDescendants.length; index++) {
const child = directDescendants[index];
child.clone(name260 + "." + child.name, result);
}
}
return result;
}
/**
* Gets the list of all animation ranges defined on this node
* @returns an array
*/
getAnimationRanges() {
const animationRanges = [];
let name260;
for (name260 in this._ranges) {
animationRanges.push(this._ranges[name260]);
}
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(name260, loop, speedRatio, onAnimationEnd) {
const range = this.getAnimationRange(name260);
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 name260 in this._ranges) {
const localRange = this._ranges[name260];
if (!localRange) {
continue;
}
const range = {};
range.name = name260;
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;
}
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onEnabledStateChangedObservable.clear();
this.onClonedObservable.clear();
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) {
this.getScene().incrementRenderId();
this.computeWorldMatrix(true);
let min;
let max;
const thisAbstractMesh = this;
if (thisAbstractMesh.getBoundingInfo && thisAbstractMesh.subMeshes) {
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);
if (predicate && !predicate(childMesh)) {
continue;
}
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,
max
};
}
};
Node._AnimationRangeFactory = (_name, _from, _to) => {
throw _WarnImport("AnimationRange");
};
Node._NodeConstructors = {};
__decorate([
serialize()
], Node.prototype, "name", void 0);
__decorate([
serialize()
], Node.prototype, "id", void 0);
__decorate([
serialize()
], Node.prototype, "uniqueId", void 0);
__decorate([
serialize()
], Node.prototype, "state", void 0);
__decorate([
serialize()
], Node.prototype, "metadata", void 0);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/light.js
var Light;
var init_light = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/light.js"() {
init_tslib_es6();
init_decorators();
init_math_vector();
init_math_color();
init_node();
init_uniformBuffer();
init_typeStore();
init_lightConstants();
init_decorators_serialization();
Light = class _Light extends Node {
static {
__name(this, "Light");
}
/**
* 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 / (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(name260, scene) {
super(name260, scene, false);
this.diffuse = new Color3(1, 1, 1);
this.specular = new Color3(1, 1, 1);
this.falloffType = _Light.FALLOFF_DEFAULT;
this.intensity = 1;
this._range = Number.MAX_VALUE;
this._inverseSquaredRange = 0;
this._photometricScale = 1;
this._intensityMode = _Light.INTENSITYMODE_AUTOMATIC;
this._radius = 1e-5;
this.renderPriority = 0;
this._shadowEnabled = true;
this._excludeWithLayerMask = 0;
this._includeOnlyWithLayerMask = 0;
this._lightmapMode = 0;
this._shadowGenerators = null;
this._excludedMeshesIds = new Array();
this._includedOnlyMeshesIds = new Array();
this._currentViewDepth = 0;
this._isLight = true;
this.getScene().addLight(this);
this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), void 0, void 0, name260);
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) {
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;
}
this.transferTexturesToEffect(effect, iAsString);
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", "Clustered"][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;
}
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;
}
for (const mesh of this.getScene().meshes) {
mesh._removeLightSource(this, true);
}
this._uniformBuffer.dispose();
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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(name260, newParent = null) {
const constructor = _Light.GetConstructorFromName(this.getTypeID(), name260, this.getScene());
if (!constructor) {
return null;
}
const clonedLight = SerializationHelper.Clone(constructor, this);
if (name260) {
clonedLight.name = name260;
}
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;
serializationObject.type = this.getTypeID();
if (this.parent) {
this.parent._serializeAsParent(serializationObject);
}
if (this.excludedMeshes.length > 0) {
serializationObject.excludedMeshesIds = [];
for (const mesh of this.excludedMeshes) {
serializationObject.excludedMeshesIds.push(mesh.id);
}
}
if (this.includedOnlyMeshes.length > 0) {
serializationObject.includedOnlyMeshesIds = [];
for (const mesh of this.includedOnlyMeshes) {
serializationObject.includedOnlyMeshesIds.push(mesh.id);
}
}
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, name260, scene) {
const constructorFunc = Node.Construct("Light_Type_" + type, name260, scene);
if (constructorFunc) {
return constructorFunc;
}
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);
if (parsedLight.excludedMeshesIds) {
light._excludedMeshesIds = parsedLight.excludedMeshesIds;
}
if (parsedLight.includedOnlyMeshesIds) {
light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
}
if (parsedLight.parentId !== void 0) {
light._waitingParentId = parsedLight.parentId;
}
if (parsedLight.parentInstanceIndex !== void 0) {
light._waitingParentInstanceIndex = parsedLight.parentInstanceIndex;
}
if (parsedLight.falloffType !== void 0) {
light.falloffType = parsedLight.falloffType;
}
if (parsedLight.lightmapMode !== void 0) {
light.lightmapMode = parsedLight.lightmapMode;
}
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.ParseAnimationRanges(light, parsedLight, scene);
}
if (parsedLight.autoAnimate) {
scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1);
}
if (parsedLight.isEnabled !== void 0) {
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;
const lightTypeID = this.getTypeID();
let photometricMode = this.intensityMode;
if (photometricMode === _Light.INTENSITYMODE_AUTOMATIC) {
if (lightTypeID === _Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
photometricMode = _Light.INTENSITYMODE_ILLUMINANCE;
} else {
photometricMode = _Light.INTENSITYMODE_LUMINOUSINTENSITY;
}
}
switch (lightTypeID) {
case _Light.LIGHTTYPEID_POINTLIGHT:
case _Light.LIGHTTYPEID_SPOTLIGHT:
switch (photometricMode) {
case _Light.INTENSITYMODE_LUMINOUSPOWER:
photometricScale = 1 / (4 * Math.PI);
break;
case _Light.INTENSITYMODE_LUMINOUSINTENSITY:
photometricScale = 1;
break;
case _Light.INTENSITYMODE_LUMINANCE:
photometricScale = this.radius * this.radius;
break;
}
break;
case _Light.LIGHTTYPEID_DIRECTIONALLIGHT:
switch (photometricMode) {
case _Light.INTENSITYMODE_ILLUMINANCE:
photometricScale = 1;
break;
case _Light.INTENSITYMODE_LUMINANCE: {
let apexAngleRadians = this.radius;
apexAngleRadians = Math.max(apexAngleRadians, 1e-3);
const solidAngle = 2 * Math.PI * (1 - Math.cos(apexAngleRadians));
photometricScale = solidAngle;
break;
}
}
break;
case _Light.LIGHTTYPEID_HEMISPHERICLIGHT:
photometricScale = 1;
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;
}
};
Light.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT;
Light.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL;
Light.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF;
Light.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD;
Light.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT;
Light.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR;
Light.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY;
Light.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC;
Light.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER;
Light.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY;
Light.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE;
Light.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE;
Light.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT;
Light.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT;
Light.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT;
Light.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT;
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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVaryingDeclaration.js
var name71, shader71, kernelBlurVaryingDeclarationWGSL;
var init_kernelBlurVaryingDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVaryingDeclaration.js"() {
init_shaderStore();
name71 = "kernelBlurVaryingDeclaration";
shader71 = `varying sampleCoord{X}: vec2f;`;
if (!ShaderStore.IncludesShadersStoreWGSL[name71]) {
ShaderStore.IncludesShadersStoreWGSL[name71] = shader71;
}
kernelBlurVaryingDeclarationWGSL = { name: name71, shader: shader71 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment.js
var name72, shader72, kernelBlurFragmentWGSL;
var init_kernelBlurFragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment.js"() {
init_shaderStore();
name72 = "kernelBlurFragment";
shader72 = `#ifdef DOF
factor=sampleCoC(fragmentInputs.sampleCoord{X});
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name72]) {
ShaderStore.IncludesShadersStoreWGSL[name72] = shader72;
}
kernelBlurFragmentWGSL = { name: name72, shader: shader72 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment2.js
var name73, shader73, kernelBlurFragment2WGSL;
var init_kernelBlurFragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment2.js"() {
init_shaderStore();
name73 = "kernelBlurFragment2";
shader73 = `#ifdef DOF
factor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_DEP_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name73]) {
ShaderStore.IncludesShadersStoreWGSL[name73] = shader73;
}
kernelBlurFragment2WGSL = { name: name73, shader: shader73 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.fragment.js
var kernelBlur_fragment_exports = {};
__export(kernelBlur_fragment_exports, {
kernelBlurPixelShaderWGSL: () => kernelBlurPixelShaderWGSL
});
var name74, shader74, kernelBlurPixelShaderWGSL;
var init_kernelBlur_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.fragment.js"() {
init_shaderStore();
init_kernelBlurVaryingDeclaration();
init_packingFunctions();
init_kernelBlurFragment();
init_kernelBlurFragment2();
name74 = "kernelBlurPixelShader";
shader74 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform delta: vec2f;varying sampleCenter: vec2f;
#ifdef DOF
var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; }
#endif
#include[0..varyingCount]
#ifdef PACKEDFLOAT
#include
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0;
#ifdef PACKEDFLOAT
var blend: f32=0.;
#else
var blend: vec4f= vec4f(0.);
#endif
#ifdef DOF
var sumOfWeights: f32=CENTER_WEIGHT;
var factor: f32=0.0;
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT;
#endif
#endif
#include[0..varyingCount]
#include[0..depCount]
#ifdef PACKEDFLOAT
fragmentOutputs.color=pack(blend);
#else
fragmentOutputs.color=blend;
#endif
#ifdef DOF
fragmentOutputs.color/=sumOfWeights;
#endif
}`;
if (!ShaderStore.ShadersStoreWGSL[name74]) {
ShaderStore.ShadersStoreWGSL[name74] = shader74;
}
kernelBlurPixelShaderWGSL = { name: name74, shader: shader74 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVertex.js
var name75, shader75, kernelBlurVertexWGSL;
var init_kernelBlurVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVertex.js"() {
init_shaderStore();
name75 = "kernelBlurVertex";
shader75 = `vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};`;
if (!ShaderStore.IncludesShadersStoreWGSL[name75]) {
ShaderStore.IncludesShadersStoreWGSL[name75] = shader75;
}
kernelBlurVertexWGSL = { name: name75, shader: shader75 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.vertex.js
var kernelBlur_vertex_exports = {};
__export(kernelBlur_vertex_exports, {
kernelBlurVertexShaderWGSL: () => kernelBlurVertexShaderWGSL
});
var name76, shader76, kernelBlurVertexShaderWGSL;
var init_kernelBlur_vertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.vertex.js"() {
init_shaderStore();
init_kernelBlurVaryingDeclaration();
init_kernelBlurVertex();
name76 = "kernelBlurVertexShader";
shader76 = `attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f;
#include[0..varyingCount]
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.sampleCenter=(input.position*madd+madd);
#include[0..varyingCount]
vertexOutputs.position= vec4f(input.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;
if (!ShaderStore.ShadersStoreWGSL[name76]) {
ShaderStore.ShadersStoreWGSL[name76] = shader76;
}
kernelBlurVertexShaderWGSL = { name: name76, shader: shader76 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVaryingDeclaration.js
var name77, shader77, kernelBlurVaryingDeclaration;
var init_kernelBlurVaryingDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVaryingDeclaration.js"() {
init_shaderStore();
name77 = "kernelBlurVaryingDeclaration";
shader77 = `varying vec2 sampleCoord{X};`;
if (!ShaderStore.IncludesShadersStore[name77]) {
ShaderStore.IncludesShadersStore[name77] = shader77;
}
kernelBlurVaryingDeclaration = { name: name77, shader: shader77 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment.js
var name78, shader78, kernelBlurFragment;
var init_kernelBlurFragment3 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment.js"() {
init_shaderStore();
name78 = "kernelBlurFragment";
shader78 = `#ifdef DOF
factor=sampleCoC(sampleCoord{X});
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name78]) {
ShaderStore.IncludesShadersStore[name78] = shader78;
}
kernelBlurFragment = { name: name78, shader: shader78 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment2.js
var name79, shader79, kernelBlurFragment2;
var init_kernelBlurFragment22 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment2.js"() {
init_shaderStore();
name79 = "kernelBlurFragment2";
shader79 = `#ifdef DOF
factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_DEP_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name79]) {
ShaderStore.IncludesShadersStore[name79] = shader79;
}
kernelBlurFragment2 = { name: name79, shader: shader79 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/kernelBlur.fragment.js
var kernelBlur_fragment_exports2 = {};
__export(kernelBlur_fragment_exports2, {
kernelBlurPixelShader: () => kernelBlurPixelShader
});
var name80, shader80, kernelBlurPixelShader;
var init_kernelBlur_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/kernelBlur.fragment.js"() {
init_shaderStore();
init_kernelBlurVaryingDeclaration2();
init_packingFunctions2();
init_kernelBlurFragment3();
init_kernelBlurFragment22();
name80 = "kernelBlurPixelShader";
shader80 = `uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;
#ifdef DOF
uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }
#endif
#include[0..varyingCount]
#ifdef PACKEDFLOAT
#include
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float computedWeight=0.0;
#ifdef PACKEDFLOAT
float blend=0.;
#else
vec4 blend=vec4(0.);
#endif
#ifdef DOF
float sumOfWeights=CENTER_WEIGHT;
float factor=0.0;
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;
#else
blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;
#endif
#endif
#include[0..varyingCount]
#include[0..depCount]
#ifdef PACKEDFLOAT
gl_FragColor=pack(blend);
#else
gl_FragColor=blend;
#endif
#ifdef DOF
gl_FragColor/=sumOfWeights;
#endif
}`;
if (!ShaderStore.ShadersStore[name80]) {
ShaderStore.ShadersStore[name80] = shader80;
}
kernelBlurPixelShader = { name: name80, shader: shader80 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVertex.js
var name81, shader81, kernelBlurVertex;
var init_kernelBlurVertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVertex.js"() {
init_shaderStore();
name81 = "kernelBlurVertex";
shader81 = `sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};`;
if (!ShaderStore.IncludesShadersStore[name81]) {
ShaderStore.IncludesShadersStore[name81] = shader81;
}
kernelBlurVertex = { name: name81, shader: shader81 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/kernelBlur.vertex.js
var kernelBlur_vertex_exports2 = {};
__export(kernelBlur_vertex_exports2, {
kernelBlurVertexShader: () => kernelBlurVertexShader
});
var name82, shader82, kernelBlurVertexShader;
var init_kernelBlur_vertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/kernelBlur.vertex.js"() {
init_shaderStore();
init_kernelBlurVaryingDeclaration2();
init_kernelBlurVertex2();
name82 = "kernelBlurVertexShader";
shader82 = `attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;
#include[0..varyingCount]
const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
sampleCenter=(position*madd+madd);
#include[0..varyingCount]
gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;
if (!ShaderStore.ShadersStore[name82]) {
ShaderStore.ShadersStore[name82] = shader82;
}
kernelBlurVertexShader = { name: name82, shader: shader82 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinBlurPostProcess.js
var ThinBlurPostProcess;
var init_thinBlurPostProcess = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinBlurPostProcess.js"() {
init_effectRenderer();
init_engine();
ThinBlurPostProcess = class _ThinBlurPostProcess extends EffectWrapper {
static {
__name(this, "ThinBlurPostProcess");
}
_gatherImports(useWebGPU, list) {
if (useWebGPU) {
this._webGPUReady = true;
list.push(Promise.all([Promise.resolve().then(() => (init_kernelBlur_fragment(), kernelBlur_fragment_exports)), Promise.resolve().then(() => (init_kernelBlur_vertex(), kernelBlur_vertex_exports))]));
} else {
list.push(Promise.all([Promise.resolve().then(() => (init_kernelBlur_fragment2(), kernelBlur_fragment_exports2)), Promise.resolve().then(() => (init_kernelBlur_vertex2(), kernelBlur_vertex_exports2))]));
}
}
/**
* 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(name260, engine = null, direction, kernel, options) {
const blockCompilationFinal = !!options?.blockCompilation;
super({
...options,
name: name260,
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 = "";
this.textureWidth = 0;
this.textureHeight = 0;
this._staticDefines = options ? Array.isArray(options.defines) ? options.defines.join("\n") : options.defines || "" : "";
this.options.blockCompilation = blockCompilationFinal;
if (direction !== void 0) {
this.direction = direction;
}
if (kernel !== void 0) {
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(noDefaultBindings = false) {
super.bind(noDefaultBindings);
this._drawWrapper.effect.setFloat2("delta", 1 / this.textureWidth * this.direction.x, 1 / this.textureHeight * this.direction.y);
}
/** @internal */
_updateParameters(onCompiled, onError) {
const n = this._kernel;
const centerIndex = (n - 1) / 2;
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 - 1);
offsets[i] = i - centerIndex;
weights[i] = w;
totalWeight += w;
}
for (let i = 0; i < weights.length; i++) {
weights[i] /= totalWeight;
}
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;
}
offsets = linearSamplingOffsets;
weights = linearSamplingWeights;
const maxVaryingRows = this.options.engine.getCaps().maxVaryingVectors - (this.options.shaderLanguage === 1 ? 1 : 0);
const freeVaryingVec2 = Math.max(maxVaryingRows, 0) - 1;
let varyingCount = Math.min(offsets.length, freeVaryingVec2);
let defines = "";
defines += this._staticDefines;
if (this._staticDefines.indexOf("DOF") != -1) {
defines += `#define CENTER_WEIGHT ${this._glslFloat(weights[varyingCount - 1])}
`;
varyingCount--;
}
for (let i = 0; i < varyingCount; i++) {
defines += `#define KERNEL_OFFSET${i} ${this._glslFloat(offsets[i])}
`;
defines += `#define KERNEL_WEIGHT${i} ${this._glslFloat(weights[i])}
`;
}
let depCount = 0;
for (let i = freeVaryingVec2; i < offsets.length; i++) {
defines += `#define KERNEL_DEP_OFFSET${depCount} ${this._glslFloat(offsets[i])}
`;
defines += `#define KERNEL_DEP_WEIGHT${depCount} ${this._glslFloat(weights[i])}
`;
depCount++;
}
if (this.packedFloat) {
defines += `#define PACKEDFLOAT 1`;
}
this.options.blockCompilation = false;
this.updateEffect(defines, null, null, {
varyingCount,
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) {
const sigma = 1 / 3;
const denominator = Math.sqrt(2 * Math.PI) * sigma;
const exponent = -(x * x / (2 * sigma * sigma));
const weight = 1 / 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+$/, "");
}
};
ThinBlurPostProcess.VertexUrl = "kernelBlur";
ThinBlurPostProcess.FragmentUrl = "kernelBlur";
ThinBlurPostProcess.Uniforms = ["delta", "direction"];
ThinBlurPostProcess.Samplers = ["circleOfConfusionSampler"];
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/blurPostProcess.js
var BlurPostProcess;
var init_blurPostProcess = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/blurPostProcess.js"() {
init_tslib_es6();
init_postProcess();
init_texture();
init_typeStore();
init_decorators();
init_decorators_serialization();
init_thinBlurPostProcess();
BlurPostProcess = class _BlurPostProcess extends PostProcess {
static {
__name(this, "BlurPostProcess");
}
/** 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(name260, 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 : void 0,
camera,
samplingMode,
engine,
reusable,
textureType,
vertexUrl: ThinBlurPostProcess.VertexUrl,
indexParameters: { varyingCount: 0, depCount: 0 },
textureFormat,
defines,
...options,
blockCompilation: true
};
super(name260, ThinBlurPostProcess.FragmentUrl, {
effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBlurPostProcess(name260, engine, void 0, void 0, localOptions) : void 0,
...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, void 0, 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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effectFallbacks.js
var EffectFallbacks;
var init_effectFallbacks = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effectFallbacks.js"() {
EffectFallbacks = class {
static {
__name(this, "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) {
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;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/clipPlaneMaterialHelper.js
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");
}
}
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");
}
}
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);
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;
}
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);
}
}
var init_clipPlaneMaterialHelper = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/clipPlaneMaterialHelper.js"() {
__name(AddClipPlaneUniforms, "AddClipPlaneUniforms");
__name(PrepareStringDefinesForClipPlanes, "PrepareStringDefinesForClipPlanes");
__name(PrepareDefinesForClipPlanes, "PrepareDefinesForClipPlanes");
__name(BindClipPlane, "BindClipPlane");
__name(SetClipPlane, "SetClipPlane");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialFlags.js
var MaterialFlags;
var init_materialFlags = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialFlags.js"() {
init_abstractEngine();
MaterialFlags = class {
static {
__name(this, "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);
}
/**
* Is the OpenPBR Base Diffuse Roughness texture enabled in the application.
*/
static get BaseDiffuseRoughnessTextureEnabled() {
return this._BaseDiffuseRoughnessTextureEnabled;
}
static set BaseDiffuseRoughnessTextureEnabled(value) {
if (this._BaseDiffuseRoughnessTextureEnabled === value) {
return;
}
this._BaseDiffuseRoughnessTextureEnabled = 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);
}
};
MaterialFlags._DiffuseTextureEnabled = true;
MaterialFlags._BaseWeightTextureEnabled = true;
MaterialFlags._BaseDiffuseRoughnessTextureEnabled = 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;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.functions.pure.js
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 / (Math.log(camera.maxZ + 1) / Math.LN2));
}
}
var init_materialHelper_functions_pure = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.functions.pure.js"() {
init_logger();
__name(BindLogDepth, "BindLogDepth");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.functions.js
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);
if (linearSpace) {
scene.fogColor.toLinearSpaceToRef(TempFogColor, scene.getEngine().useExactSrgbConversions);
effect.setColor3("vFogColor", TempFogColor);
} else {
effect.setColor3("vFogColor", scene.fogColor);
}
}
}
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;
}
function PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, influencers) {
TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;
TmpMorphInfluencers.NORMAL = false;
TmpMorphInfluencers.TANGENT = false;
TmpMorphInfluencers.UV = false;
TmpMorphInfluencers.UV2 = false;
TmpMorphInfluencers.COLOR = false;
PrepareAttributesForMorphTargets(attribs, mesh, TmpMorphInfluencers, true);
}
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["VERTEXCOLOR"];
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);
}
}
}
}
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");
}
}
function BindMorphTargetParameters(abstractMesh, effect) {
const manager = abstractMesh.morphTargetManager;
if (!abstractMesh || !manager) {
return;
}
effect.setFloatArray("morphTargetInfluences", manager.influences);
}
function BindSceneUniformBuffer(effect, sceneUbo) {
sceneUbo.bindToEffect(effect, "Scene");
}
function BindIBLParameters(scene, defines, ubo, reflectionColor, reflectionTexture = null, realTimeFiltering = false, supportTextureInfo = false, supportLocalProjection = false, usePBR = false, supportSH = false, useColor = false, reflectionBlur = 0) {
if (scene.texturesEnabled) {
if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
ubo.updateFloat2("vReflectionInfos", reflectionTexture.level * scene.iblIntensity, reflectionBlur);
if (supportLocalProjection && reflectionTexture.boundingBoxSize) {
const cubeTexture = reflectionTexture;
ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
}
if (realTimeFiltering) {
const width = reflectionTexture.getSize().width;
ubo.updateFloat2("vReflectionFilteringInfo", width, Math.log2(width));
}
if (supportSH && !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);
}
}
} else if (usePBR) {
if (defines.USEIRRADIANCEMAP && defines.USE_IRRADIANCE_DOMINANT_DIRECTION) {
ubo.updateVector3("vReflectionDominantDirection", reflectionTexture.irradianceTexture._dominantDirection);
}
}
if (supportTextureInfo) {
ubo.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
}
}
}
if (useColor) {
ubo.updateColor3("vReflectionColor", reflectionColor);
}
}
function BindIBLSamplers(scene, defines, ubo, reflectionTexture = null, realTimeFiltering = false) {
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);
}
const cdfGenerator = scene.iblCdfGenerator;
if (realTimeFiltering && cdfGenerator) {
ubo.setTexture("icdfSampler", cdfGenerator.getIcdfTexture());
}
}
}
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;
}
}
function BindTextureMatrix(texture, uniformBuffer, key) {
const matrix = texture.getTextureMatrix();
uniformBuffer.updateMatrix(key + "Matrix", matrix);
}
function PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) {
const enabled = defines["BAKED_VERTEX_ANIMATION_TEXTURE"] && defines["INSTANCES"];
if (enabled) {
attribs.push("bakedVertexAnimationSettingsInstanced");
}
}
function CopyBonesTransformationMatrices(source, target) {
target.set(source);
return target;
}
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 * (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]);
}
}
}
}
}
function BindLightProperties(light, effect, lightIndex) {
light.transferToEffect(effect, lightIndex + "");
}
function BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) {
light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows);
}
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);
}
}
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`);
}
}
}
function PrepareAttributesForInstances(attribs, defines) {
if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) {
PushAttributesForInstances(attribs, !!defines["PREPASS_VELOCITY"]);
}
if (defines.INSTANCESCOLOR) {
attribs.push(`instanceColor`);
}
}
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++;
}
function GetFogState(mesh, scene) {
return scene.fogEnabled && mesh.applyFog && scene.fogMode !== 0;
}
function PrepareDefinesForMisc(mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines, applyDecalAfterDetail = false, useVertexPulling = false, renderingMesh, setVertexOutputInvariant) {
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;
defines["USE_VERTEX_PULLING"] = useVertexPulling;
const indexBuffer = renderingMesh?.geometry?.getIndexBuffer();
defines["VERTEX_PULLING_USE_INDEX_BUFFER"] = !!indexBuffer;
defines["VERTEX_PULLING_INDEX_BUFFER_32BITS"] = indexBuffer ? indexBuffer.is32Bits : false;
defines["VERTEXOUTPUT_INVARIANT"] = !!setVertexOutputInvariant;
}
}
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;
const maxLightCount = Math.max(maxSimultaneousLights, defines["MAXLIGHTCOUNT"] || 0);
for (let index = lightIndex; index < maxLightCount; index++) {
if (defines["LIGHT" + index] !== void 0) {
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["CLUSTLIGHT" + 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;
}
}
defines["MAXLIGHTCOUNT"] = maxSimultaneousLights;
const caps = scene.getEngine().getCaps();
if (defines["SHADOWFLOAT"] === void 0) {
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;
}
function PrepareDefinesForIBL(scene, reflectionTexture, defines, realTimeFiltering = false, realTimeFilteringQuality = 8, forceSHInVertex = false) {
if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
if (!reflectionTexture.isReadyOrNotBlocking()) {
return false;
}
defines._needNormals = true;
defines.REFLECTION = true;
defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
defines.RGBDREFLECTION = reflectionTexture.isRGBD;
defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD;
defines.USEIRRADIANCEMAP = false;
const engine = scene.getEngine();
if (realTimeFiltering && realTimeFilteringQuality > 0) {
defines.NUM_SAMPLES = "" + realTimeFilteringQuality;
if (engine._features.needTypeSuffixInShaderConstants) {
defines.NUM_SAMPLES = defines.NUM_SAMPLES + "u";
}
defines.REALTIME_FILTERING = true;
if (scene.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 && scene.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;
if (reflectionTexture.irradianceTexture._dominantDirection) {
defines.USE_IRRADIANCE_DOMINANT_DIRECTION = true;
}
} else if (reflectionTexture.isCube) {
defines.USESPHERICALFROMREFLECTIONMAP = true;
defines.USEIRRADIANCEMAP = false;
defines.USE_IRRADIANCE_DOMINANT_DIRECTION = false;
defines.USESPHERICALINVERTEX = forceSHInVertex;
}
}
} 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.USE_IRRADIANCE_DOMINANT_DIRECTION = false;
defines.USESPHERICALINVERTEX = false;
defines.REFLECTIONMAP_OPPOSITEZ = false;
defines.LODINREFLECTIONALPHA = false;
defines.GAMMAREFLECTION = false;
defines.RGBDREFLECTION = false;
defines.LINEARSPECULARREFLECTION = false;
}
return true;
}
function PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state) {
state.needNormals = true;
if (defines["LIGHT" + lightIndex] === void 0) {
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;
defines["CLUSTLIGHT" + lightIndex] = false;
light.prepareLightSpecificDefines(defines, lightIndex);
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;
}
if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
state.specularEnabled = true;
}
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;
}
}
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();
}
}
function PrepareDefinesForBones(mesh, defines) {
if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
const materialSupportsBoneTexture = defines["BONETEXTURE"] !== void 0;
if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
defines["BONETEXTURE"] = true;
} else {
defines["BonesPerMesh"] = mesh.skeleton.bones.length + 1;
defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : void 0;
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"] !== void 0) {
defines["BONETEXTURE"] = false;
}
}
}
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;
}
}
function PrepareDefinesForBakedVertexAnimation(mesh, defines) {
const manager = mesh.bakedVertexAnimationManager;
defines["BAKED_VERTEX_ANIMATION_TEXTURE"] = manager && manager.isEnabled ? true : false;
}
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;
}
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();
}
}
}
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();
}
}
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();
}
}
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;
}
function PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, projectedLightTexture, uniformBuffersList = null, updateOnlyBuffersList = false, iesLightTexture = false, clusteredLightTextures = 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, "vSliceData" + lightIndex, "vSliceRanges" + 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);
}
if (clusteredLightTextures) {
samplersList.push("lightDataTexture" + lightIndex);
samplersList.push("tileMaskTexture" + lightIndex);
}
}
function PrepareUniformsAndSamplersForIBL(uniformsList, samplersList, useSH) {
const iblUniforms = [
"vReflectionMicrosurfaceInfos",
"vReflectionDominantDirection",
"reflectionMatrix",
"vReflectionInfos",
"vReflectionPosition",
"vReflectionSize",
"vReflectionColor",
"vReflectionFilteringInfo"
];
if (useSH) {
iblUniforms.push("vSphericalX", "vSphericalY", "vSphericalZ", "vSphericalXX_ZZ", "vSphericalYY_ZZ", "vSphericalZZ", "vSphericalXY", "vSphericalYZ", "vSphericalZX", "vSphericalL00", "vSphericalL1_1", "vSphericalL10", "vSphericalL11", "vSphericalL2_2", "vSphericalL2_1", "vSphericalL20", "vSphericalL21", "vSphericalL22");
}
uniformsList.push(...iblUniforms);
const iblSamplers = ["reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh", "irradianceSampler", "icdfSampler"];
samplersList.push(...iblSamplers);
}
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], defines["CLUSTLIGHT" + 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");
}
}
function PrepareUniformLayoutForIBL(ubo, supportTextureInfo = false, supportLocalProjection = false, usePBR = false, supportSH = false, useColor = false) {
ubo.addUniform("vReflectionInfos", 2);
ubo.addUniform("reflectionMatrix", 16);
if (supportTextureInfo) {
ubo.addUniform("vReflectionMicrosurfaceInfos", 3);
}
if (supportLocalProjection) {
ubo.addUniform("vReflectionPosition", 3);
ubo.addUniform("vReflectionSize", 3);
}
if (usePBR) {
ubo.addUniform("vReflectionFilteringInfo", 2);
ubo.addUniform("vReflectionDominantDirection", 3);
}
if (useColor) {
ubo.addUniform("vReflectionColor", 3);
}
if (supportSH) {
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);
}
}
var TempFogColor, TmpMorphInfluencers;
var init_materialHelper_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.functions.js"() {
init_logger();
init_engineStore();
init_lightConstants();
init_clipPlaneMaterialHelper();
init_materialFlags();
init_texture();
init_materialHelper_functions_pure();
TempFogColor = { r: 0, g: 0, b: 0 };
TmpMorphInfluencers = {
NUM_MORPH_INFLUENCERS: 0,
NORMAL: false,
TANGENT: false,
UV: false,
UV2: false,
COLOR: false
};
__name(BindFogParameters, "BindFogParameters");
__name(PrepareDefinesAndAttributesForMorphTargets, "PrepareDefinesAndAttributesForMorphTargets");
__name(PrepareAttributesForMorphTargetsInfluencers, "PrepareAttributesForMorphTargetsInfluencers");
__name(PrepareAttributesForMorphTargets, "PrepareAttributesForMorphTargets");
__name(PushAttributesForInstances, "PushAttributesForInstances");
__name(BindMorphTargetParameters, "BindMorphTargetParameters");
__name(BindSceneUniformBuffer, "BindSceneUniformBuffer");
__name(BindIBLParameters, "BindIBLParameters");
__name(BindIBLSamplers, "BindIBLSamplers");
__name(PrepareDefinesForMergedUV, "PrepareDefinesForMergedUV");
__name(BindTextureMatrix, "BindTextureMatrix");
__name(PrepareAttributesForBakedVertexAnimation, "PrepareAttributesForBakedVertexAnimation");
__name(CopyBonesTransformationMatrices, "CopyBonesTransformationMatrices");
__name(BindBonesParameters, "BindBonesParameters");
__name(BindLightProperties, "BindLightProperties");
__name(BindLight, "BindLight");
__name(BindLights, "BindLights");
__name(PrepareAttributesForBones, "PrepareAttributesForBones");
__name(PrepareAttributesForInstances, "PrepareAttributesForInstances");
__name(HandleFallbacksForShadows, "HandleFallbacksForShadows");
__name(GetFogState, "GetFogState");
__name(PrepareDefinesForMisc, "PrepareDefinesForMisc");
__name(PrepareDefinesForLights, "PrepareDefinesForLights");
__name(PrepareDefinesForIBL, "PrepareDefinesForIBL");
__name(PrepareDefinesForLight, "PrepareDefinesForLight");
__name(PrepareDefinesForFrameBoundValues, "PrepareDefinesForFrameBoundValues");
__name(PrepareDefinesForBones, "PrepareDefinesForBones");
__name(PrepareDefinesForMorphTargets, "PrepareDefinesForMorphTargets");
__name(PrepareDefinesForBakedVertexAnimation, "PrepareDefinesForBakedVertexAnimation");
__name(PrepareDefinesForAttributes, "PrepareDefinesForAttributes");
__name(PrepareDefinesForMultiview, "PrepareDefinesForMultiview");
__name(PrepareDefinesForOIT, "PrepareDefinesForOIT");
__name(PrepareDefinesForPrePass, "PrepareDefinesForPrePass");
__name(PrepareDefinesForCamera, "PrepareDefinesForCamera");
__name(PrepareUniformsAndSamplersForLight, "PrepareUniformsAndSamplersForLight");
__name(PrepareUniformsAndSamplersForIBL, "PrepareUniformsAndSamplersForIBL");
__name(PrepareUniformsAndSamplersList, "PrepareUniformsAndSamplersList");
__name(PrepareUniformLayoutForIBL, "PrepareUniformLayoutForIBL");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js
var ShadowGenerator;
var init_shadowGenerator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js"() {
init_math_vector();
init_math_color();
init_buffer();
init_light();
init_texture();
init_renderTargetTexture();
init_postProcess();
init_blurPostProcess();
init_observable();
init_devTools();
init_effectFallbacks();
init_renderingManager();
init_drawWrapper();
init_clipPlaneMaterialHelper();
init_materialHelper_functions();
ShadowGenerator = class _ShadowGenerator {
static {
__name(this, "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 !== void 0 ? 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);
if (this._light.needCube()) {
if (value === _ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
this.useExponentialShadowMap = true;
return;
} else if (value === _ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
this.useCloseExponentialShadowMap = true;
return;
} else if (value === _ShadowGenerator.FILTER_PCF || value === _ShadowGenerator.FILTER_PCSS) {
this.usePoissonSampling = true;
return;
}
}
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) {
this._darkness = 1;
} else if (darkness <= 0) {
this._darkness = 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) {
this.onBeforeShadowMapRenderObservable = new Observable();
this.onAfterShadowMapRenderObservable = new Observable();
this.onBeforeShadowMapRenderMeshObservable = new Observable();
this.onAfterShadowMapRenderMeshObservable = new Observable();
this.doNotSerialize = false;
this._bias = 5e-5;
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;
this.enableSoftTransparentShadow = false;
this.useOpacityTextureForTransparentShadow = false;
this.frustumEdgeFalloff = 0;
this._shaderLanguage = 0;
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 = /* @__PURE__ */ 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);
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();
this._shadowMap?.dispose();
if (engine._features.supportDepthStencilTexture) {
this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), void 0, false, false, void 0, this._useRedTextureType ? 6 : 5);
this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true, void 0, void 0, void 0, `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;
}
this._shadowMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => this._renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes);
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 engine2 = 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 = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0 || 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);
});
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();
this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix);
if (this._useUBO) {
this._scene.getSceneUniformBuffer().unbindEffect();
this._scene.finalizeSceneUbo();
}
});
this._shadowMap.onAfterUnbindObservable.add(() => {
if (this._sceneUBOs) {
this._scene.setSceneUniformBuffer(this._currentSceneUBO);
}
this._scene.updateTransformMatrix();
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);
});
const clearZero = new Color4(0, 0, 0, 0);
const clearOne = new Color4(1, 1, 1, 1);
this._shadowMap.onClearObservable.add((engine2) => {
if (this._filter === _ShadowGenerator.FILTER_PCF) {
engine2.clear(clearOne, false, true, false);
} else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
engine2.clear(clearZero, true, true, false);
} else {
engine2.clear(clearOne, true, true, false);
}
});
this._shadowMap.onResizeObservable.add((rtt) => {
this._storedUniqueId = this._shadowMap.uniqueId;
this._mapSize = rtt.getRenderSize();
this._light._markMeshesAsLightDirty();
this.recreateShadowMap();
});
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;
await Promise.all([
Promise.resolve().then(() => (init_shadowMap_fragment(), shadowMap_fragment_exports)),
Promise.resolve().then(() => (init_shadowMap_vertex(), shadowMap_vertex_exports)),
Promise.resolve().then(() => (init_depthBoxBlur_fragment(), depthBoxBlur_fragment_exports)),
Promise.resolve().then(() => (init_shadowMapFragmentSoftTransparentShadow(), shadowMapFragmentSoftTransparentShadow_exports))
]);
} else {
await Promise.all([
Promise.resolve().then(() => (init_shadowMap_fragment2(), shadowMap_fragment_exports2)),
Promise.resolve().then(() => (init_shadowMap_vertex2(), shadowMap_vertex_exports2)),
Promise.resolve().then(() => (init_depthBoxBlur_fragment2(), depthBoxBlur_fragment_exports2)),
Promise.resolve().then(() => (init_shadowMapFragmentSoftTransparentShadow2(), shadowMapFragmentSoftTransparentShadow_exports2))
]);
}
this._shadersLoaded = true;
}
_initializeBlurRTTAndPostProcesses() {
const engine = this._scene.getEngine();
const targetSize = this._mapSize / this.blurScale;
if (!this.useKernelBlur || this.blurScale !== 1) {
this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType, void 0, void 0, 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, 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, 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, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType, void 0, void 0, void 0, void 0, 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;
}
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, void 0, void 0, reverseSideOrientation, material.cullBackFaces);
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] !== void 0 || 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();
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 {
if (this._opacityTexture) {
effect.setTexture("diffuseSampler", this._opacityTexture);
effect.setMatrix("diffuseMatrix", this._opacityTexture.getTextureMatrix() || this._defaultTextureMatrix);
}
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 * (skeleton.bones.length + 1));
} else {
effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh));
}
}
BindMorphTargetParameters(renderingMesh, effect);
if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
renderingMesh.morphTargetManager._bind(effect);
}
const bvaManager = subMesh.getMesh().bakedVertexAnimationManager;
if (bvaManager && bvaManager.isEnabled) {
bvaManager.bind(effect, hardwareInstancedRendering);
}
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();
if (hardwareInstancedRendering) {
effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
effectiveMesh.transferToEffect(world);
}
if (this.forceBackFacesOnly) {
engine.setState(true, 0, false, true, material.cullBackFaces);
}
this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
this.onBeforeShadowMapRenderObservable.notifyObservers(effect);
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);
}
this.onAfterShadowMapRenderObservable.notifyObservers(effect);
this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
} else {
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 = /* @__PURE__ */ __name(() => {
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");
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
*/
async forceCompilationAsync(options) {
return await 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();
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"));
defines.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0"));
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(void 0, 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;
if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
attribs.push(VertexBuffer.NormalKind);
defines.push("#define NORMAL");
useNormal = true;
if (mesh.nonUniformScaling) {
defines.push("#define NONUNIFORMSCALING");
}
}
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;
}
}
}
}
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");
}
const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(
mesh.morphTargetManager,
defines,
attribs,
mesh,
true,
// usePositionMorph
useNormal,
// useNormalMorph
false,
// useTangentMorph
uv1,
// useUVMorph
uv2,
// useUV2Morph
color
// useColorMorph
) : 0;
PrepareStringDefinesForClipPlanes(material, this._scene, defines);
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);
}
}
}
}
const bvaManager = mesh.bakedVertexAnimationManager;
if (bvaManager && bvaManager.isEnabled) {
defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
if (useInstances) {
attribs.push("bakedVertexAnimationSettingsInstanced");
}
}
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);
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,
defines: join,
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 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 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());
}
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) {
this._lightDirection.z = 1e-13;
}
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;
}
const renderList = shadowMap.renderList;
this._disposeRTTandPostProcesses();
this._initializeGenerator();
this.filter = this._filter;
this._applyFilterValues();
if (renderList) {
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 !== void 0 ? scene.getCameraById(parsedShadowGenerator.cameraId) : null;
const shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light, camera) : new _ShadowGenerator(parsedShadowGenerator.mapSize, light, void 0, camera);
const shadowMap = shadowGenerator.getShadowMap();
if (parsedShadowGenerator.renderList.length && shadowMap) {
const renderSet = new Set(parsedShadowGenerator.renderList);
let renderList = shadowMap.renderList;
if (!renderList) {
renderList = shadowMap.renderList = [];
}
const meshes = scene.meshes;
for (const mesh of meshes) {
if (renderSet.has(mesh.id)) {
renderList.push(mesh);
}
}
}
if (parsedShadowGenerator.id !== void 0) {
shadowGenerator.id = parsedShadowGenerator.id;
}
shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly;
if (parsedShadowGenerator.darkness !== void 0) {
shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
}
if (parsedShadowGenerator.transparencyShadow) {
shadowGenerator.setTransparencyShadow(true);
}
if (parsedShadowGenerator.frustumEdgeFalloff !== void 0) {
shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
}
if (parsedShadowGenerator.bias !== void 0) {
shadowGenerator.bias = parsedShadowGenerator.bias;
}
if (parsedShadowGenerator.normalBias !== void 0) {
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;
} else if (parsedShadowGenerator.useVarianceShadowMap) {
shadowGenerator.useExponentialShadowMap = true;
} else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
shadowGenerator.useBlurExponentialShadowMap = true;
}
if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== void 0) {
shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
}
if (parsedShadowGenerator.filteringQuality !== void 0) {
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;
}
};
ShadowGenerator.CLASSNAME = "ShadowGenerator";
ShadowGenerator.ForceGLSL = false;
ShadowGenerator.FILTER_NONE = 0;
ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
ShadowGenerator.FILTER_POISSONSAMPLING = 2;
ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
ShadowGenerator.FILTER_PCF = 6;
ShadowGenerator.FILTER_PCSS = 7;
ShadowGenerator.QUALITY_HIGH = 0;
ShadowGenerator.QUALITY_MEDIUM = 1;
ShadowGenerator.QUALITY_LOW = 2;
ShadowGenerator.DEFAULT_ALPHA_CUTOFF = 0.5;
ShadowGenerator._SceneComponentInitialization = (_) => {
throw _WarnImport("ShadowGeneratorSceneComponent");
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingBox.js
var BoundingBox;
var init_boundingBox = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingBox.js"() {
init_arrayTools();
init_math_vector();
init_math_constants();
BoundingBox = class _BoundingBox {
static {
__name(this, "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) {
this.vectors = BuildArray(8, Vector3.Zero);
this.center = Vector3.Zero();
this.centerWorld = Vector3.Zero();
this.extendSize = Vector3.Zero();
this.extendSizeWorld = Vector3.Zero();
this.directions = BuildArray(3, Vector3.Zero);
this.vectorsWorld = BuildArray(8, Vector3.Zero);
this.minimumWorld = Vector3.Zero();
this.maximumWorld = Vector3.Zero();
this.minimum = Vector3.Zero();
this.maximum = Vector3.Zero();
this._drawWrapperFront = null;
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);
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);
}
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]);
}
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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingSphere.js
var BoundingSphere;
var init_boundingSphere = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingSphere.js"() {
init_arrayTools();
init_math_vector();
BoundingSphere = class _BoundingSphere {
static {
__name(this, "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) {
this.center = Vector3.Zero();
this.centerWorld = Vector3.Zero();
this.minimum = Vector3.Zero();
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, 1, 1, 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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingInfo.js
var _Result0, _Result1, ComputeBoxExtents, AxisOverlap, BoundingInfo;
var init_boundingInfo = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingInfo.js"() {
init_arrayTools();
init_math_vector();
init_boundingBox();
init_boundingSphere();
_Result0 = { min: 0, max: 0 };
_Result1 = { min: 0, max: 0 };
ComputeBoxExtents = /* @__PURE__ */ __name((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;
}, "ComputeBoxExtents");
AxisOverlap = /* @__PURE__ */ __name((axis, box0, box1) => {
ComputeBoxExtents(axis, box0, _Result0);
ComputeBoxExtents(axis, box1, _Result1);
return !(_Result0.min > _Result1.max || _Result1.min > _Result0.max);
}, "AxisOverlap");
BoundingInfo = class _BoundingInfo {
static {
__name(this, "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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesDeclaration.js
var name83, shader83, instancesDeclarationWGSL;
var init_instancesDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesDeclaration.js"() {
init_shaderStore();
name83 = "instancesDeclaration";
shader83 = `#ifdef INSTANCES
attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;
#ifdef INSTANCESCOLOR
attribute instanceColor : vec4;
#endif
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform world : mat4x4;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;
#ifdef THIN_INSTANCES
uniform previousWorld : mat4x4;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform world : mat4x4;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
uniform previousWorld : mat4x4;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name83]) {
ShaderStore.IncludesShadersStoreWGSL[name83] = shader83;
}
instancesDeclarationWGSL = { name: name83, shader: shader83 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depth.vertex.js
var depth_vertex_exports = {};
__export(depth_vertex_exports, {
depthVertexShaderWGSL: () => depthVertexShaderWGSL
});
var name84, shader84, depthVertexShaderWGSL;
var init_depth_vertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depth.vertex.js"() {
init_shaderStore();
init_bonesDeclaration();
init_bakedVertexAnimationDeclaration();
init_morphTargetsVertexGlobalDeclaration();
init_morphTargetsVertexDeclaration();
init_clipPlaneVertexDeclaration();
init_instancesDeclaration();
init_morphTargetsVertexGlobal();
init_morphTargetsVertex();
init_instancesVertex();
init_bonesVertex();
init_bakedVertexAnimation();
init_clipPlaneVertex();
name84 = "depthVertexShader";
shader84 = `attribute position: vec3f;
#include
#include
#include
#include[0..maxSimultaneousMorphTargets]
#include
#include
uniform viewProjection: mat4x4f;uniform depthValues: vec2f;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vUV: vec2f;uniform diffuseMatrix: mat4x4f;
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#ifdef STORE_CAMERASPACE_Z
uniform view: mat4x4f;varying vViewPos: vec4f;
#endif
varying vDepthMetric: f32;
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;
#ifdef UV1
var uvUpdated: vec2f=input.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=input.uv2;
#endif
#include
#include[0..maxSimultaneousMorphTargets]
#include
#include
#include
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);
#include
vertexOutputs.position=uniforms.viewProjection*worldPos;
#ifdef STORE_CAMERASPACE_Z
vertexOutputs.vViewPos=uniforms.view*worldPos;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric=((-vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));
#else
vertexOutputs.vDepthMetric=((vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));
#endif
#endif
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef UV2
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
}
`;
if (!ShaderStore.ShadersStoreWGSL[name84]) {
ShaderStore.ShadersStoreWGSL[name84] = shader84;
}
depthVertexShaderWGSL = { name: name84, shader: shader84 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depth.fragment.js
var depth_fragment_exports = {};
__export(depth_fragment_exports, {
depthPixelShaderWGSL: () => depthPixelShaderWGSL
});
var name85, shader85, depthPixelShaderWGSL;
var init_depth_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depth.fragment.js"() {
init_shaderStore();
init_clipPlaneFragmentDeclaration();
init_packingFunctions();
init_clipPlaneFragment();
name85 = "depthPixelShader";
shader85 = `#ifdef ALPHATEST
varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;
#endif
#include
varying vDepthMetric: f32;
#ifdef PACKED
#include
#endif
#ifdef STORE_CAMERASPACE_Z
varying vViewPos: vec4f;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include
#ifdef ALPHATEST
if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}
#endif
#ifdef STORE_CAMERASPACE_Z
#ifdef PACKED
fragmentOutputs.color=pack(input.vViewPos.z);
#else
fragmentOutputs.color= vec4f(input.vViewPos.z,0.0,0.0,1.0);
#endif
#else
#ifdef NONLINEARDEPTH
#ifdef PACKED
fragmentOutputs.color=pack(input.position.z);
#else
fragmentOutputs.color= vec4f(input.position.z,0.0,0.0,0.0);
#endif
#else
#ifdef PACKED
fragmentOutputs.color=pack(input.vDepthMetric);
#else
fragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0);
#endif
#endif
#endif
}`;
if (!ShaderStore.ShadersStoreWGSL[name85]) {
ShaderStore.ShadersStoreWGSL[name85] = shader85;
}
depthPixelShaderWGSL = { name: name85, shader: shader85 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesDeclaration.js
var name86, shader86, instancesDeclaration;
var init_instancesDeclaration2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesDeclaration.js"() {
init_shaderStore();
name86 = "instancesDeclaration";
shader86 = `#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
`;
if (!ShaderStore.IncludesShadersStore[name86]) {
ShaderStore.IncludesShadersStore[name86] = shader86;
}
instancesDeclaration = { name: name86, shader: shader86 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertexDeclaration.js
var name87, shader87, pointCloudVertexDeclaration;
var init_pointCloudVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertexDeclaration.js"() {
init_shaderStore();
name87 = "pointCloudVertexDeclaration";
shader87 = `#ifdef POINTSIZE
uniform float pointSize;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name87]) {
ShaderStore.IncludesShadersStore[name87] = shader87;
}
pointCloudVertexDeclaration = { name: name87, shader: shader87 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertex.js
var name88, shader88, pointCloudVertex;
var init_pointCloudVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertex.js"() {
init_shaderStore();
name88 = "pointCloudVertex";
shader88 = `#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name88]) {
ShaderStore.IncludesShadersStore[name88] = shader88;
}
pointCloudVertex = { name: name88, shader: shader88 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depth.vertex.js
var depth_vertex_exports2 = {};
__export(depth_vertex_exports2, {
depthVertexShader: () => depthVertexShader
});
var name89, shader89, depthVertexShader;
var init_depth_vertex2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depth.vertex.js"() {
init_shaderStore();
init_bonesDeclaration2();
init_bakedVertexAnimationDeclaration2();
init_morphTargetsVertexGlobalDeclaration2();
init_morphTargetsVertexDeclaration2();
init_clipPlaneVertexDeclaration2();
init_instancesDeclaration2();
init_pointCloudVertexDeclaration();
init_morphTargetsVertexGlobal2();
init_morphTargetsVertex2();
init_instancesVertex2();
init_bonesVertex2();
init_bakedVertexAnimation2();
init_clipPlaneVertex2();
init_pointCloudVertex();
name89 = "depthVertexShader";
shader89 = `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
}
`;
if (!ShaderStore.ShadersStore[name89]) {
ShaderStore.ShadersStore[name89] = shader89;
}
depthVertexShader = { name: name89, shader: shader89 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depth.fragment.js
var depth_fragment_exports2 = {};
__export(depth_fragment_exports2, {
depthPixelShader: () => depthPixelShader
});
var name90, shader90, depthPixelShader;
var init_depth_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depth.fragment.js"() {
init_shaderStore();
init_clipPlaneFragmentDeclaration2();
init_packingFunctions2();
init_clipPlaneFragment2();
name90 = "depthPixelShader";
shader90 = `#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
}`;
if (!ShaderStore.ShadersStore[name90]) {
ShaderStore.ShadersStore[name90] = shader90;
}
depthPixelShader = { name: name90, shader: shader90 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Cameras/camera.js
var Camera;
var init_camera = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Cameras/camera.js"() {
init_tslib_es6();
init_decorators();
init_smartArray();
init_tools();
init_observable();
init_math_vector();
init_node();
init_logger();
init_typeStore();
init_devTools();
init_math_viewport();
init_math_frustum();
init_decorators_serialization();
Camera = class _Camera extends Node {
static {
__name(this, "Camera");
}
/**
* 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;
const halfHeight = this.getEngine().getRenderHeight() / 2;
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;
}
/**
* Sets the camera's field of view in radians based on the focal length and sensor size.
* @param value the focal length of the camera in mm.
* @param sensorSize the sensor width size of the camera in mm. (default is 36mm, which is a full frame sensor)
*/
setFocalLength(value, sensorSize = 36) {
this.fov = 2 * Math.atan(sensorSize / (2 * value));
}
/**
* Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA)
*/
set mode(mode) {
this._mode = mode;
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(name260, position, scene, setActiveOnSceneIfNoneActive = true) {
super(name260, scene, false);
this._position = Vector3.Zero();
this._upVector = Vector3.Up();
this.oblique = null;
this._orthoLeft = null;
this._orthoRight = null;
this._orthoBottom = null;
this._orthoTop = null;
this.fov = 0.8;
this.projectionPlaneTilt = 0;
this.minZ = 1;
this.maxZ = 1e4;
this.inertia = 0.9;
this._mode = _Camera.PERSPECTIVE_CAMERA;
this.isIntermediate = false;
this.viewport = new Viewport(0, 0, 1, 1);
this.layerMask = 268435455;
this.fovMode = _Camera.FOVMODE_VERTICAL_FIXED;
this.cameraRigMode = _Camera.RIG_MODE_NONE;
this.customRenderTargets = [];
this.outputRenderTarget = null;
this.onViewMatrixChangedObservable = new Observable();
this.onProjectionMatrixChangedObservable = new Observable();
this.onAfterCheckInputsObservable = new Observable();
this.onRestoreStateObservable = new Observable();
this.isRigCamera = false;
this._hasMoved = false;
this._rigCameras = new Array();
this._skipRendering = false;
this._projectionMatrix = new Matrix();
this._postProcesses = new Array();
this._activeMeshes = new SmartArray(256);
this._globalPosition = Vector3.Zero();
this._computedViewMatrix = Matrix.Identity();
this._doNotComputeProjectionMatrix = false;
this._transformMatrix = Matrix.Zero();
this._refreshFrustumPlanes = true;
this._absoluteRotation = Quaternion.Identity();
this._isCamera = true;
this._isLeftCamera = false;
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 ${name260}`);
}
/**
* 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 = void 0;
this._cache.minZ = void 0;
this._cache.maxZ = void 0;
this._cache.fov = void 0;
this._cache.fovMode = void 0;
this._cache.aspectRatio = void 0;
this._cache.orthoLeft = void 0;
this._cache.orthoRight = void 0;
this._cache.orthoBottom = void 0;
this._cache.orthoTop = void 0;
this._cache.obliqueAngle = void 0;
this._cache.obliqueLength = void 0;
this._cache.obliqueOffset = void 0;
this._cache.renderWidth = void 0;
this._cache.renderHeight = void 0;
}
/**
* @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();
}
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() {
const firstPostProcess = this._getFirstPostProcess();
if (firstPostProcess) {
firstPostProcess.markTextureDirty();
}
for (let i = 0, len = this._rigCameras.length; i < len; i++) {
const cam = this._rigCameras[i];
const rigPostProcess = cam._rigPostProcess;
if (rigPostProcess) {
const isPass = rigPostProcess.getEffectName() === "pass";
if (isPass) {
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();
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;
}
if (this._scene.prePassRenderer) {
this._scene.prePassRenderer.markAsDirty();
}
this._cascadePostProcessesToRigCams();
}
/**
* Gets the current world matrix of the camera
* @returns the world matrix
*/
getWorldMatrix() {
if (this._isSynchronizedViewMatrix()) {
return this._worldMatrix;
}
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);
}
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 !== void 0) {
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;
}
this._cache.mode = this.mode;
this._cache.minZ = this.minZ;
this._cache.maxZ = this.maxZ;
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;
const halfHeight = engine.getRenderHeight() / 2;
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;
for (const cam of this.rigCameras) {
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 world 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 matrix is used to create a world 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) {
this.onViewMatrixChangedObservable.clear();
this.onProjectionMatrixChangedObservable.clear();
this.onAfterCheckInputsObservable.clear();
this.onRestoreStateObservable.clear();
if (this.inputs) {
this.inputs.clear();
}
this.getScene().stopAnimation(this);
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;
}
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 i2 = this._postProcesses.length;
while (--i2 >= 0) {
const postProcess = this._postProcesses[i2];
if (postProcess) {
postProcess.dispose(this);
}
}
}
let i = this.customRenderTargets.length;
while (--i >= 0) {
this.customRenderTargets[i].dispose();
}
this.customRenderTargets.length = 0;
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 = {};
this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
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) {
}
/** @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(name260, value) {
if (!this._cameraRigParams) {
this._cameraRigParams = {};
}
this._cameraRigParams[name260] = value;
if (name260 === "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(name260, 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);
}
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;
serializationObject.type = this.getClassName();
if (this.parent) {
this.parent._serializeAsParent(serializationObject);
}
if (this.inputs) {
this.inputs.serialize(serializationObject);
}
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(name260, newParent = null) {
const camera = SerializationHelper.Clone(_Camera.GetConstructorFromName(this.getClassName(), name260, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
camera.name = name260;
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(void 0, 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, name260, scene, interaxial_distance = 0, isStereoscopicSideBySide = true) {
const constructorFunc = Node.Construct(type, name260, scene, {
// eslint-disable-next-line @typescript-eslint/naming-convention
interaxial_distance,
isStereoscopicSideBySide
});
if (constructorFunc) {
return constructorFunc;
}
return () => _Camera._CreateDefaultParsedCamera(name260, 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);
if (parsedCamera.parentId !== void 0) {
camera._waitingParentId = parsedCamera.parentId;
}
if (parsedCamera.parentInstanceIndex !== void 0) {
camera._waitingParentInstanceIndex = parsedCamera.parentInstanceIndex;
}
if (camera.inputs) {
camera.inputs.parse(parsedCamera);
camera._setupInputs();
}
if (parsedCamera.upVector) {
camera.upVector = Vector3.FromArray(parsedCamera.upVector);
}
if (camera.setPosition) {
camera.position.copyFromFloats(0, 0, 0);
camera.setPosition(Vector3.FromArray(parsedCamera.position));
}
if (parsedCamera.target) {
if (camera.setTarget) {
camera.setTarget(Vector3.FromArray(parsedCamera.target));
}
}
if (parsedCamera.cameraRigMode) {
const rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
}
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.ParseAnimationRanges(camera, parsedCamera, scene);
}
if (parsedCamera.autoAnimate) {
scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1);
}
if (parsedCamera.isEnabled !== void 0) {
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;
}
};
Camera._CreateDefaultParsedCamera = (name260, scene) => {
throw _WarnImport("UniversalCamera");
};
Camera.PERSPECTIVE_CAMERA = 0;
Camera.ORTHOGRAPHIC_CAMERA = 1;
Camera.FOVMODE_VERTICAL_FIXED = 0;
Camera.FOVMODE_HORIZONTAL_FIXED = 1;
Camera.RIG_MODE_NONE = 0;
Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
Camera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;
Camera.RIG_MODE_VR = 20;
Camera.RIG_MODE_CUSTOM = 22;
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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/depthRenderer.js
var DepthRenderer;
var init_depthRenderer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/depthRenderer.js"() {
init_math_color();
init_buffer();
init_texture();
init_renderTargetTexture();
init_camera();
init_depth_fragment2();
init_depth_vertex2();
init_devTools();
init_clipPlaneMaterialHelper();
init_materialHelper_functions();
init_effectFallbacks();
DepthRenderer = class _DepthRenderer {
static {
__name(this, "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)
* @param existingRenderTargetTexture An existing render target texture to use (default: undefined). If not provided, a new render target texture will be created.
*/
constructor(scene, type = 1, camera = null, storeNonLinearDepth = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, storeCameraSpaceZ = false, name260, existingRenderTargetTexture) {
this._shaderLanguage = 0;
this.enabled = true;
this.forceDepthWriteTransparentMeshes = false;
this.useOnlyInActiveCamera = false;
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, 1, 1, 1);
} else {
this.clearColor = new Color4(storeCameraSpaceZ ? 0 : 1, 0, 0, 1);
}
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;
}
}
const format = this.isPacked || !engine._features.supportExtendedTextureFormats ? 5 : 6;
this._depthMap = existingRenderTargetTexture ?? new RenderTargetTexture(name260 ?? "DepthRenderer", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type, false, samplingMode, void 0, void 0, void 0, 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;
this._depthMap.activeCamera = this._camera;
this._depthMap.ignoreCameraViewport = true;
this._depthMap.useCameraPostProcesses = false;
this._depthMap.onClearObservable.add((engine2) => {
engine2.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] !== void 0 || renderingMesh.hasThinInstances);
if (!this.isReady(subMesh, hardwareInstancedRendering)) {
return false;
}
}
}
return true;
};
const renderSubMesh = /* @__PURE__ */ __name((subMesh) => {
const renderingMesh = subMesh.getRenderingMesh();
const effectiveMesh = subMesh.getEffectiveMesh();
const scene2 = this._scene;
const engine2 = scene2.getEngine();
const material = subMesh.getMaterial();
effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
if (!material || effectiveMesh.infiniteDistance || material.disableDepthWrite || subMesh.verticesCount === 0 || subMesh._renderId === scene2.getRenderId()) {
return;
}
const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;
let sideOrientation = material._getEffectiveOrientation(renderingMesh);
if (detNeg) {
sideOrientation = sideOrientation === 0 ? 1 : 0;
}
const reverseSideOrientation = sideOrientation === 0;
engine2.setState(material.backFaceCulling, 0, false, reverseSideOrientation, this.reverseCulling ? !material.cullBackFaces : material.cullBackFaces);
const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
if (batch.mustReturn) {
return;
}
const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0 || renderingMesh.hasThinInstances);
const camera2 = this._camera || scene2.activeCamera;
if (this.isReady(subMesh, hardwareInstancedRendering) && camera2) {
subMesh._renderId = scene2.getRenderId();
const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine2.currentRenderPassId];
let drawWrapper = subMesh._getDrawWrapper();
if (!drawWrapper && renderingMaterial) {
drawWrapper = renderingMaterial._getDrawWrapper();
}
const cameraIsOrtho = camera2.mode === Camera.ORTHOGRAPHIC_CAMERA;
if (!drawWrapper) {
return;
}
const effect = drawWrapper.effect;
engine2.enableEffect(drawWrapper);
if (!hardwareInstancedRendering) {
renderingMesh._bind(subMesh, effect, material.fillMode);
}
if (!renderingMaterial) {
effect.setMatrix("viewProjection", scene2.getTransformMatrix());
effect.setMatrix("world", effectiveMesh.getWorldMatrix());
if (this._storeCameraSpaceZ) {
effect.setMatrix("view", scene2.getViewMatrix());
}
} else {
renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);
}
let minZ, maxZ;
if (cameraIsOrtho) {
minZ = !engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : 1;
maxZ = engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : 1;
} else {
minZ = engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? camera2.minZ : engine2.isNDCHalfZRange ? 0 : camera2.minZ;
maxZ = engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : camera2.maxZ;
}
effect.setFloat2("depthValues", minZ, minZ + maxZ);
if (!renderingMaterial) {
if (material.needAlphaTestingForMesh(effectiveMesh)) {
const alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
effect.setTexture("diffuseSampler", alphaTexture);
effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
}
}
BindBonesParameters(renderingMesh, effect);
BindClipPlane(effect, material, scene2);
BindMorphTargetParameters(renderingMesh, effect);
if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
renderingMesh.morphTargetManager._bind(effect);
}
const bvaManager = subMesh.getMesh().bakedVertexAnimationManager;
if (bvaManager && bvaManager.isEnabled) {
bvaManager.bind(effect, hardwareInstancedRendering);
}
if (material.pointsCloud) {
effect.setFloat("pointSize", material.pointSize);
}
}
renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world));
}
}, "renderSubMesh");
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;
await Promise.all([Promise.resolve().then(() => (init_depth_vertex(), depth_vertex_exports)), Promise.resolve().then(() => (init_depth_fragment(), depth_fragment_exports))]);
} else {
await Promise.all([Promise.resolve().then(() => (init_depth_vertex2(), depth_vertex_exports2)), Promise.resolve().then(() => (init_depth_fragment2(), depth_fragment_exports2))]);
}
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;
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;
}
}
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");
}
const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(
mesh.morphTargetManager,
defines,
attribs,
mesh,
true,
// usePositionMorph
false,
// useNormalMorph
false,
// useTangentMorph
uv1,
// useUVMorph
uv2,
// useUV2Morph
color
// useColorMorph
) : 0;
if (material.pointsCloud) {
defines.push("#define POINTSIZE");
}
if (useInstances) {
defines.push("#define INSTANCES");
PushAttributesForInstances(attribs);
if (subMesh.getRenderingMesh().hasThinInstances) {
defines.push("#define THIN_INSTANCES");
}
}
const bvaManager = mesh.bakedVertexAnimationManager;
if (bvaManager && bvaManager.isEnabled) {
defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
if (useInstances) {
attribs.push("bakedVertexAnimationSettingsInstanced");
}
}
if (this._storeNonLinearDepth) {
defines.push("#define NONLINEARDEPTH");
}
if (this._storeCameraSpaceZ) {
defines.push("#define STORE_CAMERASPACE_Z");
}
if (this.isPacked) {
defines.push("#define PACKED");
}
PrepareStringDefinesForClipPlanes(material, scene, defines);
const drawWrapper = subMesh._getDrawWrapper(void 0, 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,
defines: join,
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];
}
}
}
};
DepthRenderer.ForceGLSL = false;
DepthRenderer._SceneComponentInitialization = (_) => {
throw _WarnImport("DepthRendererSceneComponent");
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/minmaxRedux.fragment.js
var minmaxRedux_fragment_exports = {};
__export(minmaxRedux_fragment_exports, {
minmaxReduxPixelShaderWGSL: () => minmaxReduxPixelShaderWGSL
});
var name91, shader91, minmaxReduxPixelShaderWGSL;
var init_minmaxRedux_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/minmaxRedux.fragment.js"() {
init_shaderStore();
name91 = "minmaxReduxPixelShader";
shader91 = `varying vUV: vec2f;var textureSampler: texture_2d;
#if defined(INITIAL)
uniform texSize: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).r;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).r;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).r;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).r;
#ifdef DEPTH_REDUX
#ifdef VIEW_DEPTH
var minz=3.4e38;if (f1 != 0.0) { minz=f1; }
if (f2 != 0.0) { minz=min(minz,f2); }
if (f3 != 0.0) { minz=min(minz,f3); }
if (f4 != 0.0) { minz=min(minz,f4); }
let maxz=max(max(max(f1,f2),f3),f4);
#else
let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
#endif
#else
let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(f1,f2),f3),f4);
#endif
fragmentOutputs.color=vec4f(minz,maxz,0.,0.);}
#elif defined(MAIN)
uniform texSize: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).rg;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).rg;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).rg;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);}
#elif defined(ONEBEFORELAST)
uniform texSize: vec2i;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*vec2f(uniforms.texSize-1));let f1=textureLoad(textureSampler,coord % uniforms.texSize,0).rg;let f2=textureLoad(textureSampler,(coord+vec2i(1,0)) % uniforms.texSize,0).rg;let f3=textureLoad(textureSampler,(coord+vec2i(1,1)) % uniforms.texSize,0).rg;let f4=textureLoad(textureSampler,(coord+vec2i(0,1)) % uniforms.texSize,0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);}
#elif defined(LAST)
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(0.);if (true) {
discard;}}
#endif
`;
if (!ShaderStore.ShadersStoreWGSL[name91]) {
ShaderStore.ShadersStoreWGSL[name91] = shader91;
}
minmaxReduxPixelShaderWGSL = { name: name91, shader: shader91 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/minmaxRedux.fragment.js
var minmaxRedux_fragment_exports2 = {};
__export(minmaxRedux_fragment_exports2, {
minmaxReduxPixelShader: () => minmaxReduxPixelShader
});
var name92, shader92, minmaxReduxPixelShader;
var init_minmaxRedux_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/minmaxRedux.fragment.js"() {
init_shaderStore();
name92 = "minmaxReduxPixelShader";
shader92 = `varying vec2 vUV;uniform sampler2D textureSampler;
#if defined(INITIAL)
uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(textureSampler,coord,0).r;float f2=texelFetch(textureSampler,coord+ivec2(1,0),0).r;float f3=texelFetch(textureSampler,coord+ivec2(1,1),0).r;float f4=texelFetch(textureSampler,coord+ivec2(0,1),0).r;
#ifdef DEPTH_REDUX
#ifdef VIEW_DEPTH
float minz=3.4e38;if (f1 != 0.0) { minz=f1; }
if (f2 != 0.0) { minz=min(minz,f2); }
if (f3 != 0.0) { minz=min(minz,f3); }
if (f4 != 0.0) { minz=min(minz,f4); }
float maxz=max(max(max(f1,f2),f3),f4);
#else
float minz=min(min(min(f1,f2),f3),f4);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);
#endif
#else
float minz=min(min(min(f1,f2),f3),f4);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(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(LAST)
void main(void)
{glFragColor=vec4(0.);if (true) {
discard;}}
#endif
`;
if (!ShaderStore.ShadersStore[name92]) {
ShaderStore.ShadersStore[name92] = shader92;
}
minmaxReduxPixelShader = { name: name92, shader: shader92 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/thinMinMaxReducer.js
var DepthTextureType, ThinMinMaxReducerPostProcess, BufferFloat, BufferUint8, MinMax, ThinMinMaxReducer;
var init_thinMinMaxReducer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/thinMinMaxReducer.js"() {
init_observable();
init_effectRenderer();
init_engine();
(function(DepthTextureType2) {
DepthTextureType2[DepthTextureType2["NormalizedViewDepth"] = 0] = "NormalizedViewDepth";
DepthTextureType2[DepthTextureType2["ViewDepth"] = 1] = "ViewDepth";
DepthTextureType2[DepthTextureType2["ScreenDepth"] = 2] = "ScreenDepth";
})(DepthTextureType || (DepthTextureType = {}));
ThinMinMaxReducerPostProcess = class _ThinMinMaxReducerPostProcess extends EffectWrapper {
static {
__name(this, "ThinMinMaxReducerPostProcess");
}
_gatherImports(useWebGPU, list) {
if (useWebGPU) {
this._webGPUReady = true;
list.push(Promise.resolve().then(() => (init_minmaxRedux_fragment(), minmaxRedux_fragment_exports)));
} else {
list.push(Promise.resolve().then(() => (init_minmaxRedux_fragment2(), minmaxRedux_fragment_exports2)));
}
}
constructor(name260, engine = null, defines = "", options) {
super({
...options,
name: name260,
engine: engine || Engine.LastCreatedEngine,
useShaderStore: true,
useAsPostProcess: true,
fragmentShader: _ThinMinMaxReducerPostProcess.FragmentUrl,
uniforms: _ThinMinMaxReducerPostProcess.Uniforms,
defines
});
this.textureWidth = 0;
this.textureHeight = 0;
}
bind(noDefaultBindings = false) {
super.bind(noDefaultBindings);
const effect = this.drawWrapper.effect;
if (this.textureWidth === 1 || this.textureHeight === 1) {
effect.setInt2("texSize", this.textureWidth, this.textureHeight);
} else {
effect.setFloat2("texSize", this.textureWidth, this.textureHeight);
}
}
};
ThinMinMaxReducerPostProcess.FragmentUrl = "minmaxRedux";
ThinMinMaxReducerPostProcess.Uniforms = ["texSize"];
BufferFloat = new Float32Array(4 * 1 * 1);
BufferUint8 = new Uint8Array(4 * 1 * 1);
MinMax = { min: 0, max: 0 };
ThinMinMaxReducer = class {
static {
__name(this, "ThinMinMaxReducer");
}
get depthRedux() {
return this._depthRedux;
}
set depthRedux(value) {
if (this._depthRedux === value) {
return;
}
this._depthRedux = value;
this._recreatePostProcesses();
}
get textureWidth() {
return this._textureWidth;
}
get textureHeight() {
return this._textureHeight;
}
constructor(scene, depthRedux = true) {
this.onAfterReductionPerformed = new Observable();
this._textureWidth = 0;
this._textureHeight = 0;
this._scene = scene;
this._depthRedux = depthRedux;
this.reductionSteps = [];
}
setTextureDimensions(width, height, depthTextureType = 0) {
if (width === this._textureWidth && height === this._textureHeight && depthTextureType === this._depthTextureType) {
return false;
}
this._textureWidth = width;
this._textureHeight = height;
this._depthTextureType = depthTextureType;
this._recreatePostProcesses();
return true;
}
readMinMax(texture) {
const isFloat = texture.type === Engine.TEXTURETYPE_FLOAT || texture.type === Engine.TEXTURETYPE_HALF_FLOAT;
const buffer = isFloat ? BufferFloat : BufferUint8;
this._scene.getEngine()._readTexturePixels(texture, 1, 1, -1, 0, buffer, false);
MinMax.min = buffer[0];
MinMax.max = buffer[1];
if (!isFloat) {
MinMax.min = MinMax.min / 255;
MinMax.max = MinMax.max / 255;
}
if (MinMax.min >= MinMax.max) {
MinMax.min = 0;
MinMax.max = 1;
}
this.onAfterReductionPerformed.notifyObservers(MinMax);
}
dispose(disposeAll = true) {
if (disposeAll) {
this.onAfterReductionPerformed.clear();
this._textureWidth = 0;
this._textureHeight = 0;
}
for (let i = 0; i < this.reductionSteps.length; ++i) {
this.reductionSteps[i].dispose();
}
this.reductionSteps.length = 0;
}
_recreatePostProcesses() {
this.dispose(false);
const scene = this._scene;
let w = this.textureWidth, h = this.textureHeight;
const reductionInitial = new ThinMinMaxReducerPostProcess("Initial reduction phase", scene.getEngine(), "#define INITIAL" + (this._depthRedux ? "\n#define DEPTH_REDUX" : "") + (this._depthTextureType === 1 ? "\n#define VIEW_DEPTH" : ""));
reductionInitial.textureWidth = w;
reductionInitial.textureHeight = h;
this.reductionSteps.push(reductionInitial);
let index = 1;
while (w > 1 || h > 1) {
w = Math.max(Math.round(w / 2), 1);
h = Math.max(Math.round(h / 2), 1);
const reduction = new ThinMinMaxReducerPostProcess("Reduction phase " + index, scene.getEngine(), "#define " + (w == 1 && h == 1 ? "LAST" : w == 1 || h == 1 ? "ONEBEFORELAST" : "MAIN"));
reduction.textureWidth = w;
reduction.textureHeight = h;
this.reductionSteps.push(reduction);
index++;
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/minMaxReducer.js
var MinMaxReducer;
var init_minMaxReducer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/minMaxReducer.js"() {
init_postProcess();
init_postProcessManager();
init_thinMinMaxReducer();
init_minmaxRedux_fragment2();
init_minmaxRedux_fragment();
MinMaxReducer = class {
static {
__name(this, "MinMaxReducer");
}
/**
* Observable triggered when the computation has been performed
*/
get onAfterReductionPerformed() {
return this._thinMinMaxReducer.onAfterReductionPerformed;
}
/**
* Creates a min/max reducer
* @param camera The camera to use for the post processes
*/
constructor(camera) {
this._onAfterUnbindObserver = null;
this._forceFullscreenViewport = true;
this._activated = false;
this._camera = camera;
this._postProcessManager = new PostProcessManager(camera.getScene());
this._thinMinMaxReducer = new ThinMinMaxReducer(camera.getScene());
this._reductionSteps = [];
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._thinMinMaxReducer.depthRedux = depthRedux;
this.deactivate();
this._sourceTexture = sourceTexture;
this._forceFullscreenViewport = forceFullscreenViewport;
if (this._thinMinMaxReducer.setTextureDimensions(sourceTexture.getRenderWidth(), sourceTexture.getRenderHeight())) {
this._disposePostProcesses();
const reductionSteps = this._thinMinMaxReducer.reductionSteps;
for (let i = 0; i < reductionSteps.length; ++i) {
const reductionStep = reductionSteps[i];
const postProcess = new PostProcess(reductionStep.name, ThinMinMaxReducerPostProcess.FragmentUrl, {
effectWrapper: reductionStep,
samplingMode: 1,
engine: this._camera.getScene().getEngine(),
textureType: type,
textureFormat: 7,
size: { width: reductionStep.textureWidth, height: reductionStep.textureHeight }
});
this._reductionSteps.push(postProcess);
postProcess.autoClear = false;
postProcess.forceFullscreenViewport = forceFullscreenViewport;
if (i === 0) {
postProcess.externalTextureSamplerBinding = true;
postProcess.onApplyObservable.add((effect) => {
effect.setTexture("textureSampler", this._sourceTexture);
});
}
if (i === reductionSteps.length - 1) {
this._reductionSteps[i - 1].onAfterRenderObservable.add(() => {
this._thinMinMaxReducer.readMinMax(postProcess.inputTexture.texture);
});
}
}
}
}
/**
* 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, 0, 0, true, this._reductionSteps.length - 1);
engine.unBindFramebuffer(this._reductionSteps[this._reductionSteps.length - 1].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) {
return;
}
this.onAfterReductionPerformed.clear();
this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
this._onContextRestoredObserver = void 0;
this._disposePostProcesses();
this._postProcessManager.dispose();
this._postProcessManager = void 0;
this._thinMinMaxReducer.dispose();
this._thinMinMaxReducer = void 0;
this._sourceTexture = null;
}
_disposePostProcesses() {
for (let i = 0; i < this._reductionSteps.length; ++i) {
this._reductionSteps[i].dispose();
}
this._reductionSteps.length = 0;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/depthReducer.js
var DepthReducer;
var init_depthReducer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/depthReducer.js"() {
init_depthRenderer();
init_minMaxReducer();
DepthReducer = class extends MinMaxReducer {
static {
__name(this, "DepthReducer");
}
/**
* 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 = {};
}
this._depthRendererId = "minmax_" + this._camera.id;
depthRenderer = this._depthRenderer = new DepthRenderer(scene, type, this._camera, false, 1, false, `DepthRenderer ${this._depthRendererId}`);
depthRenderer.enabled = false;
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) {
this._depthRenderer.dispose();
this._depthRenderer = null;
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js
var UpDir, ZeroVec, Tmpv1, Tmpv2, TmpMatrix, CascadedShadowGenerator;
var init_cascadedShadowGenerator = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js"() {
init_math_vector();
init_renderTargetTexture();
init_devTools();
init_shadowGenerator();
init_boundingInfo();
init_depthReducer();
init_logger();
init_engineStore();
UpDir = Vector3.Up();
ZeroVec = Vector3.Zero();
Tmpv1 = new Vector3();
Tmpv2 = new Vector3();
TmpMatrix = new Matrix();
CascadedShadowGenerator = class _CascadedShadowGenerator extends ShadowGenerator {
static {
__name(this, "CascadedShadowGenerator");
}
_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, 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) {
this._lightDirection.z = 1e-13;
}
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);
this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]);
Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]);
let viewMinZ = 0, viewMaxZ = Tmpv1.z;
const boundingInfo = this._shadowCastersBoundingInfo;
boundingInfo.update(this._viewMatrices[cascadeIndex]);
const castersViewMinZ = boundingInfo.boundingBox.minimumWorld.z;
const castersViewMaxZ = boundingInfo.boundingBox.maximumWorld.z;
if (castersViewMinZ > viewMaxZ) {
} else {
if (!this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS) {
viewMinZ = Math.min(viewMinZ, castersViewMinZ);
if (this.filter !== ShadowGenerator.FILTER_PCSS) {
viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ);
}
} else {
viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ);
viewMinZ = Math.max(viewMinZ, castersViewMinZ);
viewMaxZ = Math.max(viewMinZ + 1, 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]);
Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], Tmpv1);
Tmpv1.scaleInPlace(this._mapSize / 2);
Tmpv2.copyFromFloats(Math.round(Tmpv1.x), Math.round(Tmpv1.y), Math.round(Tmpv1.z));
Tmpv2.subtractInPlace(Tmpv1).scaleInPlace(2 / this._mapSize);
Matrix.TranslationToRef(Tmpv2.x, Tmpv2.y, 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();
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]);
}
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);
Tmpv1.scaleInPlace(splitDist);
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;
}
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) {
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 {
const lightCameraPos = this._frustumCenter[cascadeIndex];
this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, Tmpv1);
Matrix.LookAtLHToRef(lightCameraPos, Tmpv1, UpDir, TmpMatrix);
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;
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 ?? 1e4;
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();
this._shadowMap?.dispose();
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, void 0, false, false, void 0, this._useRedTextureType ? 6 : 5);
this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true, void 0, void 0, void 0, `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 ? 1e4 : 1 / this.cascadeBlendPercentage);
effect.setArray("frustumLengths" + lightIndex, this._frustumLengths);
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);
this._lightSizeUVCorrection[cascadeIndex * 2 + 1] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y);
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, void 0, camera));
if (parsedShadowGenerator.numCascades !== void 0) {
shadowGenerator.numCascades = parsedShadowGenerator.numCascades;
}
if (parsedShadowGenerator.debug !== void 0) {
shadowGenerator.debug = parsedShadowGenerator.debug;
}
if (parsedShadowGenerator.stabilizeCascades !== void 0) {
shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades;
}
if (parsedShadowGenerator.lambda !== void 0) {
shadowGenerator.lambda = parsedShadowGenerator.lambda;
}
if (parsedShadowGenerator.cascadeBlendPercentage !== void 0) {
shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage;
}
if (parsedShadowGenerator.depthClamp !== void 0) {
shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp;
}
if (parsedShadowGenerator.autoCalcDepthBounds !== void 0) {
shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds;
}
if (parsedShadowGenerator.shadowMaxZ !== void 0) {
shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ;
}
if (parsedShadowGenerator.penumbraDarkness !== void 0) {
shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness;
}
if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== void 0) {
shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo;
}
if (parsedShadowGenerator.minDistance !== void 0 && parsedShadowGenerator.maxDistance !== void 0) {
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)
];
CascadedShadowGenerator.CLASSNAME = "CascadedShadowGenerator";
CascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4;
CascadedShadowGenerator.MIN_CASCADES_COUNT = 2;
CascadedShadowGenerator.MAX_CASCADES_COUNT = 4;
CascadedShadowGenerator._SceneComponentInitialization = (_) => {
throw _WarnImport("ShadowGeneratorSceneComponent");
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/shadowGeneratorTask.js
var FrameGraphShadowGeneratorTask;
var init_shadowGeneratorTask = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/shadowGeneratorTask.js"() {
init_frameGraphTask();
init_shadowGenerator();
FrameGraphShadowGeneratorTask = class extends FrameGraphTask {
static {
__name(this, "FrameGraphShadowGeneratorTask");
}
/**
* The light to generate shadows from.
*/
get light() {
return this._light;
}
set light(value) {
if (value === this._light) {
return;
}
this._light = value;
this._setupShadowGenerator();
}
/**
* Gets or sets the camera used to generate the shadow generator.
*/
get camera() {
return this._camera;
}
set camera(camera) {
this._camera = camera;
this._setupShadowGenerator();
}
/**
* The size of the shadow map.
*/
get mapSize() {
return this._mapSize;
}
set mapSize(value) {
if (value === this._mapSize) {
return;
}
this._mapSize = value;
this._setupShadowGenerator();
}
/**
* If true, the shadow map will use a 32 bits float texture type (else, 16 bits float is used if supported).
*/
get useFloat32TextureType() {
return this._useFloat32TextureType;
}
set useFloat32TextureType(value) {
if (value === this._useFloat32TextureType) {
return;
}
this._useFloat32TextureType = value;
this._setupShadowGenerator();
}
/**
* If true, the shadow map will use a red texture format (else, a RGBA format is used).
*/
get useRedTextureFormat() {
return this._useRedTextureFormat;
}
set useRedTextureFormat(value) {
if (value === this._useRedTextureFormat) {
return;
}
this._useRedTextureFormat = value;
this._setupShadowGenerator();
}
/**
* The bias to apply to the shadow map.
*/
get bias() {
return this._bias;
}
set bias(value) {
if (value === this._bias) {
return;
}
this._bias = value;
if (this._shadowGenerator) {
this._shadowGenerator.bias = value;
}
}
/**
* The normal bias to apply to the shadow map.
*/
get normalBias() {
return this._normalBias;
}
set normalBias(value) {
if (value === this._normalBias) {
return;
}
this._normalBias = value;
if (this._shadowGenerator) {
this._shadowGenerator.normalBias = value;
}
}
/**
* The darkness of the shadows.
*/
get darkness() {
return this._darkness;
}
set darkness(value) {
if (value === this._darkness) {
return;
}
this._darkness = value;
if (this._shadowGenerator) {
this._shadowGenerator.darkness = value;
}
}
/**
* Gets or sets the ability to have transparent shadow
*/
get transparencyShadow() {
return this._transparencyShadow;
}
set transparencyShadow(value) {
if (value === this._transparencyShadow) {
return;
}
this._transparencyShadow = value;
if (this._shadowGenerator) {
this._shadowGenerator.transparencyShadow = value;
}
}
/**
* Enables or disables shadows with varying strength based on the transparency
*/
get enableSoftTransparentShadow() {
return this._enableSoftTransparentShadow;
}
set enableSoftTransparentShadow(value) {
if (value === this._enableSoftTransparentShadow) {
return;
}
this._enableSoftTransparentShadow = value;
if (this._shadowGenerator) {
this._shadowGenerator.enableSoftTransparentShadow = value;
}
}
/**
* If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one
*/
get useOpacityTextureForTransparentShadow() {
return this._useOpacityTextureForTransparentShadow;
}
set useOpacityTextureForTransparentShadow(value) {
if (value === this._useOpacityTextureForTransparentShadow) {
return;
}
this._useOpacityTextureForTransparentShadow = value;
if (this._shadowGenerator) {
this._shadowGenerator.useOpacityTextureForTransparentShadow = value;
}
}
/**
* The filter to apply to the shadow map.
*/
get filter() {
return this._filter;
}
set filter(value) {
if (value === this._filter) {
return;
}
this._filter = value;
if (this._shadowGenerator) {
this._shadowGenerator.filter = value;
}
}
/**
* The filtering quality to apply to the filter.
*/
get filteringQuality() {
return this._filteringQuality;
}
set filteringQuality(value) {
if (value === this._filteringQuality) {
return;
}
this._filteringQuality = value;
if (this._shadowGenerator) {
this._shadowGenerator.filteringQuality = value;
}
}
_createShadowGenerator() {
this._shadowGenerator = new ShadowGenerator(this._mapSize, this._light, this._useFloat32TextureType, void 0, this._useRedTextureFormat);
}
_setupShadowGenerator() {
this._shadowGenerator?.dispose();
this._shadowGenerator = void 0;
if (this._light !== void 0) {
this._createShadowGenerator();
const shadowGenerator = this._shadowGenerator;
if (shadowGenerator === void 0) {
return;
}
shadowGenerator.bias = this._bias;
shadowGenerator.normalBias = this._normalBias;
shadowGenerator.darkness = this._darkness;
shadowGenerator.transparencyShadow = this._transparencyShadow;
shadowGenerator.enableSoftTransparentShadow = this._enableSoftTransparentShadow;
shadowGenerator.useOpacityTextureForTransparentShadow = this._useOpacityTextureForTransparentShadow;
shadowGenerator.filter = this._filter;
shadowGenerator.filteringQuality = this._filteringQuality;
const shadowMap = shadowGenerator.getShadowMap();
shadowMap._disableEngineStages = true;
shadowMap.cameraForLOD = this._camera;
this.shadowGenerator = shadowGenerator;
}
}
isReady() {
return !!this._shadowGenerator && !!this._shadowGenerator.getShadowMap()?.isReadyForRendering();
}
/**
* Creates a new shadow generator task.
* @param name The name of the task.
* @param frameGraph The frame graph the task belongs to.
* @param _scene The scene to create the shadow generator for.
*/
constructor(name260, frameGraph, _scene) {
super(name260, frameGraph);
this._mapSize = 1024;
this._useFloat32TextureType = false;
this._useRedTextureFormat = true;
this._bias = 0.01;
this._normalBias = 0;
this._darkness = 0;
this._transparencyShadow = false;
this._enableSoftTransparentShadow = false;
this._useOpacityTextureForTransparentShadow = false;
this._filter = ShadowGenerator.FILTER_PCF;
this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
}
record() {
if (this.light === void 0 || this.objectList === void 0 || this.camera === void 0) {
throw new Error(`FrameGraphShadowGeneratorTask ${this.name}: light, objectList and camera are required`);
}
const shadowMap = this._shadowGenerator.getShadowMap();
shadowMap.renderList = this.objectList.meshes;
shadowMap.particleSystemList = this.objectList.particleSystems;
const shadowTextureHandle = this._frameGraph.textureManager.importTexture(`${this.name} shadowmap`, this._shadowGenerator.getShadowMap().getInternalTexture());
this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, shadowTextureHandle);
const pass = this._frameGraph.addPass(this.name);
pass.setExecuteFunc((context) => {
if (!this.light.isEnabled() || !this.light.shadowEnabled) {
return;
}
const shadowMap2 = this._shadowGenerator.getShadowMap();
shadowMap2.renderList = this.objectList.meshes;
shadowMap2.particleSystemList = this.objectList.particleSystems;
context.saveDepthStates();
context.setDepthStates(true, true);
context.renderUnmanaged(shadowMap2);
context.restoreDepthStates();
});
const passDisabled = this._frameGraph.addPass(this.name + "_disabled", true);
passDisabled.setExecuteFunc((_context) => {
});
}
dispose() {
this._shadowGenerator?.dispose();
this._shadowGenerator = void 0;
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/shadowLight.js
var ShadowLight;
var init_shadowLight = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/shadowLight.js"() {
init_tslib_es6();
init_decorators();
init_math_vector();
init_light();
init_math_axis();
ShadowLight = class extends Light {
static {
__name(this, "ShadowLight");
}
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);
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;
}
/**
* 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();
}
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 !== void 0 ? 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 !== void 0 ? this.shadowMaxZ : activeCamera?.maxZ || 1e4;
}
/**
* 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) {
lightDirection.z = 1e-13;
}
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);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/directionalLight.js
var DirectionalLight;
var init_directionalLight = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/directionalLight.js"() {
init_tslib_es6();
init_decorators();
init_math_vector();
init_node();
init_light();
init_shadowLight();
init_typeStore();
Node.AddNodeConstructor("Light_Type_1", (name260, scene) => {
return () => new DirectionalLight(name260, Vector3.Zero(), scene);
});
DirectionalLight = class extends ShadowLight {
static {
__name(this, "DirectionalLight");
}
/**
* 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(name260, direction, scene) {
super(name260, scene);
this._shadowFrustumSize = 0;
this._shadowOrthoScale = 0.1;
this.autoUpdateExtends = true;
this.autoCalcShadowZBounds = false;
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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 !== void 0 ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== void 0 ? 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;
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 !== void 0 ? this.shadowMinZ : activeCamera?.minZ || 0;
const maxZ = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : activeCamera?.maxZ || 1e4;
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);
RegisterClass("BABYLON.DirectionalLight", DirectionalLight);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/postProcessTask.js
var FrameGraphPostProcessTask;
var init_postProcessTask = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/postProcessTask.js"() {
init_frameGraphTask();
FrameGraphPostProcessTask = class extends FrameGraphTask {
static {
__name(this, "FrameGraphPostProcessTask");
}
/**
* The draw wrapper used by the post process
*/
get drawWrapper() {
return this._postProcessDrawWrapper;
}
/**
* Constructs a new post process task.
* @param name Name of the task.
* @param frameGraph The frame graph this task is associated with.
* @param postProcess The post process to apply.
*/
constructor(name260, frameGraph, postProcess) {
super(name260, frameGraph);
this.sourceSamplingMode = 2;
this.depthReadOnly = false;
this.stencilReadOnly = false;
this.disableColorWrite = false;
this.drawBackFace = false;
this.depthTest = true;
this.postProcess = postProcess;
this._postProcessDrawWrapper = this.postProcess.drawWrapper;
this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
this.outputDepthAttachmentTexture = this._frameGraph.textureManager.createDanglingHandle();
}
isReady() {
return this.postProcess.isReady();
}
record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) {
if (this.sourceTexture === void 0 && this.targetTexture === void 0) {
throw new Error(`FrameGraphPostProcessTask "${this.name}": sourceTexture or targetTexture is required`);
}
const sourceTextureCreationOptions = this.sourceTexture !== void 0 ? this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture) : void 0;
if (sourceTextureCreationOptions) {
sourceTextureCreationOptions.options.samples = 1;
}
this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this.name, sourceTextureCreationOptions);
if (this.depthAttachmentTexture !== void 0) {
this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthAttachmentTexture, this.depthAttachmentTexture);
}
if (sourceTextureCreationOptions) {
const sourceSize = this._frameGraph.textureManager.getTextureAbsoluteDimensions(sourceTextureCreationOptions);
this._sourceWidth = sourceSize.width;
this._sourceHeight = sourceSize.height;
}
const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.outputTexture);
this._outputWidth = outputTextureDescription.size.width;
this._outputHeight = outputTextureDescription.size.height;
const pass = this._frameGraph.addRenderPass(this.name);
pass.depthReadOnly = this.depthReadOnly;
pass.stencilReadOnly = this.stencilReadOnly;
pass.addDependencies(this.sourceTexture);
pass.setRenderTarget(this.outputTexture);
pass.setRenderTargetDepth(this.depthAttachmentTexture);
pass.setExecuteFunc((context) => {
if (this.sourceTexture !== void 0) {
context.setTextureSamplingMode(this.sourceTexture, this.sourceSamplingMode);
}
additionalExecute?.(context);
context.applyFullScreenEffect(this._postProcessDrawWrapper, () => {
if (this.sourceTexture !== void 0) {
context.bindTextureHandle(this._postProcessDrawWrapper.effect, "textureSampler", this.sourceTexture);
}
additionalBindings?.(context);
this.postProcess.bind();
}, this.stencilState, this.disableColorWrite, this.drawBackFace, this.depthTest);
});
if (!skipCreationOfDisabledPasses) {
const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
passDisabled.depthReadOnly = this.depthReadOnly;
passDisabled.stencilReadOnly = this.stencilReadOnly;
passDisabled.addDependencies(this.sourceTexture);
passDisabled.setRenderTarget(this.outputTexture);
passDisabled.setRenderTargetDepth(this.depthAttachmentTexture);
passDisabled.setExecuteFunc((context) => {
if (this.sourceTexture !== void 0) {
context.copyTexture(this.sourceTexture);
}
});
}
return pass;
}
dispose() {
this.postProcess.dispose();
super.dispose();
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureCreationOptions.js
function textureSizeIsObject(size) {
return size.width !== void 0;
}
function getDimensionsFromTextureSize(size) {
if (textureSizeIsObject(size)) {
return { width: size.width, height: size.height };
}
return { width: size, height: size };
}
var init_textureCreationOptions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureCreationOptions.js"() {
__name(textureSizeIsObject, "textureSizeIsObject");
__name(getDimensionsFromTextureSize, "getDimensionsFromTextureSize");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/csmShadowGeneratorTask.js
var FrameGraphCascadedShadowGeneratorTask;
var init_csmShadowGeneratorTask = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/csmShadowGeneratorTask.js"() {
init_cascadedShadowGenerator();
init_shadowGeneratorTask();
init_directionalLight();
init_thinMinMaxReducer();
init_postProcessTask();
init_textureCreationOptions();
FrameGraphCascadedShadowGeneratorTask = class extends FrameGraphShadowGeneratorTask {
static {
__name(this, "FrameGraphCascadedShadowGeneratorTask");
}
/**
* Checks if a shadow generator task is a cascaded shadow generator task.
* @param task The task to check.
* @returns True if the task is a cascaded shadow generator task, else false.
*/
static IsCascadedShadowGenerator(task) {
return task.numCascades !== void 0;
}
/**
* The number of cascades.
*/
get numCascades() {
return this._numCascades;
}
set numCascades(value) {
if (value === this._numCascades) {
return;
}
this._numCascades = value;
this._setupShadowGenerator();
}
/**
* Gets or sets a value indicating whether the shadow generator should display the cascades.
*/
get debug() {
return this._debug;
}
set debug(value) {
if (value === this._debug) {
return;
}
this._debug = value;
if (this._shadowGenerator) {
this._shadowGenerator.debug = value;
}
}
/**
* Gets or sets a value indicating whether the shadow generator should stabilize the cascades.
*/
get stabilizeCascades() {
return this._stabilizeCascades;
}
set stabilizeCascades(value) {
if (value === this._stabilizeCascades) {
return;
}
this._stabilizeCascades = value;
if (this._shadowGenerator) {
this._shadowGenerator.stabilizeCascades = value;
}
}
/**
* Gets or sets the lambda parameter of the shadow generator.
*/
get lambda() {
return this._lambda;
}
set lambda(value) {
if (value === this._lambda) {
return;
}
this._lambda = value;
if (this._shadowGenerator) {
this._shadowGenerator.lambda = value;
}
}
/**
* Gets or sets the cascade blend percentage.
*/
get cascadeBlendPercentage() {
return this._cascadeBlendPercentage;
}
set cascadeBlendPercentage(value) {
if (value === this._cascadeBlendPercentage) {
return;
}
this._cascadeBlendPercentage = value;
if (this._shadowGenerator) {
this._shadowGenerator.cascadeBlendPercentage = value;
}
}
/**
* Gets or sets a value indicating whether the shadow generator should use depth clamping.
*/
get depthClamp() {
return this._depthClamp;
}
set depthClamp(value) {
if (value === this._depthClamp) {
return;
}
this._depthClamp = value;
if (this._shadowGenerator) {
this._shadowGenerator.depthClamp = value;
}
}
/**
* Gets or sets a value indicating whether the shadow generator should automatically calculate the depth bounds.
*/
get autoCalcDepthBounds() {
return this._autoCalcDepthBounds;
}
set autoCalcDepthBounds(value) {
if (value === this._autoCalcDepthBounds) {
return;
}
this._autoCalcDepthBounds = value;
this._currentAutoCalcDepthBoundsCounter = this._autoCalcDepthBoundsRefreshRate;
if (!value) {
this._shadowGenerator?.setMinMaxDistance(0, 1);
}
const passes = this.passes;
for (let i = 0; i < passes.length - 1; ++i) {
passes[i].disabled = !value;
}
}
/**
* 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...
*/
get autoCalcDepthBoundsRefreshRate() {
return this._autoCalcDepthBoundsRefreshRate;
}
set autoCalcDepthBoundsRefreshRate(value) {
this._autoCalcDepthBoundsRefreshRate = value;
this._currentAutoCalcDepthBoundsCounter = this._autoCalcDepthBoundsRefreshRate;
}
/**
* Gets or sets the maximum shadow Z value.
*/
get shadowMaxZ() {
return this._shadowMaxZ;
}
set shadowMaxZ(value) {
if (value === this._shadowMaxZ) {
return;
}
this._shadowMaxZ = value;
if (this._shadowGenerator) {
this._shadowGenerator.shadowMaxZ = value;
}
}
/**
* Creates a new shadow generator task.
* @param name The name of the task.
* @param frameGraph The frame graph the task belongs to.
* @param scene The scene to create the shadow generator for.
*/
constructor(name260, frameGraph, scene) {
super(name260, frameGraph, scene);
this.depthTextureType = 0;
this._numCascades = CascadedShadowGenerator.DEFAULT_CASCADES_COUNT;
this._debug = false;
this._stabilizeCascades = false;
this._lambda = 0.5;
this._cascadeBlendPercentage = 0.1;
this._depthClamp = true;
this._autoCalcDepthBounds = false;
this._currentAutoCalcDepthBoundsCounter = 0;
this._autoCalcDepthBoundsRefreshRate = 1;
this._shadowMaxZ = 1e4;
this._thinMinMaxReducer = new ThinMinMaxReducer(scene);
this._thinMinMaxReducer.onAfterReductionPerformed.add((minmax) => {
if (!this._shadowGenerator) {
return;
}
const camera = this.camera;
let min = minmax.min, max = minmax.max;
if (min >= max) {
min = 0;
max = 1;
} else if (camera && this.depthTextureType !== 0) {
if (this.depthTextureType === 2) {
const engine = this._frameGraph.engine;
const projectionMatrix = camera.getProjectionMatrix();
const p2z = projectionMatrix.m[10];
const p3z = projectionMatrix.m[14];
if (!engine.isNDCHalfZRange) {
min = min * 2 - 1;
max = max * 2 - 1;
}
min = p3z / (min - p2z);
max = p3z / (max - p2z);
}
const zNear = camera.minZ;
const zFar = camera.maxZ;
min = (min - zNear) / (zFar - zNear);
max = (max - zNear) / (zFar - zNear);
}
if (min !== this._shadowGenerator.minDistance || max !== this._shadowGenerator.maxDistance) {
this._shadowGenerator.setMinMaxDistance(min, max);
}
});
}
_createShadowGenerator() {
if (!(this.light instanceof DirectionalLight)) {
throw new Error(`FrameGraphCascadedShadowGeneratorTask ${this.name}: the CSM shadow generator only supports directional lights.`);
}
this._shadowGenerator = new CascadedShadowGenerator(this.mapSize, this.light, this.useFloat32TextureType, this.camera, this.useRedTextureFormat);
this._shadowGenerator.numCascades = this._numCascades;
}
_setupShadowGenerator() {
super._setupShadowGenerator();
const shadowGenerator = this._shadowGenerator;
if (shadowGenerator === void 0) {
return;
}
shadowGenerator.debug = this._debug;
shadowGenerator.stabilizeCascades = this._stabilizeCascades;
shadowGenerator.lambda = this._lambda;
shadowGenerator.cascadeBlendPercentage = this._cascadeBlendPercentage;
shadowGenerator.depthClamp = this._depthClamp;
shadowGenerator.shadowMaxZ = this._shadowMaxZ;
}
record() {
if (this.light === void 0 || this.objectList === void 0 || this.camera === void 0) {
throw new Error(`FrameGraphCascadedShadowGeneratorTask ${this.name}: light, objectList and camera are required`);
}
if (this.depthTexture !== void 0) {
const depthTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.depthTexture);
const size = !depthTextureCreationOptions.sizeIsPercentage ? textureSizeIsObject(depthTextureCreationOptions.size) ? depthTextureCreationOptions.size : { width: depthTextureCreationOptions.size, height: depthTextureCreationOptions.size } : this._frameGraph.textureManager.getAbsoluteDimensions(depthTextureCreationOptions.size);
const width = size.width;
const height = size.height;
depthTextureCreationOptions.sizeIsPercentage = false;
depthTextureCreationOptions.options.formats = [7];
depthTextureCreationOptions.options.samples = 1;
this._thinMinMaxReducer.setTextureDimensions(width, height, this.depthTextureType);
const reductionSteps = this._thinMinMaxReducer.reductionSteps;
let targetTexture;
this._frameGraph.addPass(`${this.name} Before Min Max Reduction`).setExecuteFunc((context) => {
context.pushDebugGroup(`Min Max Reduction`);
});
for (let i = 0; i < reductionSteps.length - 1; ++i) {
const reductionStep = reductionSteps[i];
depthTextureCreationOptions.size = { width: reductionSteps[i + 1].textureWidth, height: reductionSteps[i + 1].textureHeight };
const postProcess = new FrameGraphPostProcessTask(reductionStep.name, this._frameGraph, reductionStep);
postProcess.sourceTexture = i == 0 ? this.depthTexture : targetTexture;
postProcess.sourceSamplingMode = 1;
postProcess.targetTexture = this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} ${reductionStep.name}`, depthTextureCreationOptions);
postProcess.record(true);
targetTexture = postProcess.outputTexture;
}
this._frameGraph.addPass(`${this.name} After Min Max Reduction`).setExecuteFunc((context) => {
context.popDebugGroup();
if (this._autoCalcDepthBounds && this._currentAutoCalcDepthBoundsCounter >= 0) {
if (++this._currentAutoCalcDepthBoundsCounter >= this._autoCalcDepthBoundsRefreshRate) {
const minMaxTexture = context.getTextureFromHandle(targetTexture);
if (minMaxTexture) {
this._thinMinMaxReducer.readMinMax(minMaxTexture);
}
}
this._currentAutoCalcDepthBoundsCounter %= this._autoCalcDepthBoundsRefreshRate;
if (this._autoCalcDepthBoundsRefreshRate === 0) {
this._currentAutoCalcDepthBoundsCounter = -1;
}
}
});
}
super.record();
}
dispose() {
super.dispose();
this._thinMinMaxReducer.dispose();
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/objectRendererTask.js
var FrameGraphObjectRendererTask;
var init_objectRendererTask = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/objectRendererTask.js"() {
init_frameGraphTypes();
init_frameGraphTask();
init_objectRenderer();
init_csmShadowGeneratorTask();
FrameGraphObjectRendererTask = class extends FrameGraphTask {
static {
__name(this, "FrameGraphObjectRendererTask");
}
/**
* Gets or sets the camera used to render the objects.
*/
get camera() {
return this._camera;
}
set camera(camera) {
this._camera = camera;
this._renderer.activeCamera = this.camera;
}
/**
* If image processing should be disabled (default is false).
* false means that the default image processing configuration will be applied (the one from the scene)
*/
get disableImageProcessing() {
return this._disableImageProcessing;
}
set disableImageProcessing(value) {
if (value === this._disableImageProcessing) {
return;
}
this._disableImageProcessing = value;
this._renderer.disableImageProcessing = value;
}
/**
* Define if particles should be rendered (default is true).
*/
get renderParticles() {
return this._renderParticles;
}
set renderParticles(value) {
if (value === this._renderParticles) {
return;
}
this._renderParticles = value;
this._renderer.renderParticles = value;
}
/**
* Define if sprites should be rendered (default is true).
*/
get renderSprites() {
return this._renderSprites;
}
set renderSprites(value) {
if (value === this._renderSprites) {
return;
}
this._renderSprites = value;
this._renderer.renderSprites = value;
}
/**
* Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined). Default is true.
*/
get forceLayerMaskCheck() {
return this._forceLayerMaskCheck;
}
set forceLayerMaskCheck(value) {
if (value === this._forceLayerMaskCheck) {
return;
}
this._forceLayerMaskCheck = value;
this._renderer.forceLayerMaskCheck = value;
}
/**
* Enables the rendering of bounding boxes for meshes (still subject to Mesh.showBoundingBox or scene.forceShowBoundingBoxes). Default is true.
*/
get enableBoundingBoxRendering() {
return this._enableBoundingBoxRendering;
}
set enableBoundingBoxRendering(value) {
if (value === this._enableBoundingBoxRendering) {
return;
}
this._enableBoundingBoxRendering = value;
this._renderer.enableBoundingBoxRendering = value;
}
/**
* Enables the rendering of outlines/overlays for meshes (still subject to Mesh.renderOutline/Mesh.renderOverlay). Default is true.
*/
get enableOutlineRendering() {
return this._enableOutlineRendering;
}
set enableOutlineRendering(value) {
if (value === this._enableOutlineRendering) {
return;
}
this._enableOutlineRendering = value;
this._renderer.enableOutlineRendering = value;
}
/**
* The object renderer used to render the objects.
*/
get objectRenderer() {
return this._renderer;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
if (this._renderer) {
this._renderer.name = value;
}
}
/**
* Constructs a new object renderer task.
* @param name The name of the task.
* @param frameGraph The frame graph the task belongs to.
* @param scene The scene the frame graph is associated with.
* @param options The options of the object renderer.
* @param existingObjectRenderer An existing object renderer to use (optional). If provided, the options parameter will be ignored.
*/
constructor(name260, frameGraph, scene, options, existingObjectRenderer) {
super(name260, frameGraph);
this.shadowGenerators = [];
this.depthTest = true;
this.depthWrite = true;
this.disableShadows = false;
this._disableImageProcessing = false;
this.isMainObjectRenderer = false;
this._renderParticles = true;
this._renderSprites = true;
this._forceLayerMaskCheck = true;
this._enableBoundingBoxRendering = true;
this._enableOutlineRendering = true;
this._onBeforeRenderObservable = null;
this._onAfterRenderObservable = null;
this._externalObjectRenderer = false;
this._scene = scene;
this._engine = scene.getEngine();
this._externalObjectRenderer = !!existingObjectRenderer;
this._renderer = existingObjectRenderer ?? new ObjectRenderer(name260, scene, options);
this.name = name260;
this._renderer.disableImageProcessing = this._disableImageProcessing;
this._renderer.renderParticles = this._renderParticles;
this._renderer.renderSprites = this._renderSprites;
this._renderer.enableBoundingBoxRendering = this._enableBoundingBoxRendering;
this._renderer.forceLayerMaskCheck = this._forceLayerMaskCheck;
if (!this._externalObjectRenderer) {
this._renderer.onBeforeRenderingManagerRenderObservable.add(() => {
if (!this._renderer.options.doNotChangeAspectRatio) {
scene.updateTransformMatrix(true);
}
});
}
this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
this.outputDepthTexture = this._frameGraph.textureManager.createDanglingHandle();
}
isReady() {
return this._renderer.isReadyForRendering(this._textureWidth, this._textureHeight);
}
record(skipCreationOfDisabledPasses = false, additionalExecute) {
if (this.targetTexture === void 0 || this.objectList === void 0) {
throw new Error(`FrameGraphObjectRendererTask ${this.name}: targetTexture and objectList are required`);
}
this._renderer.renderList = this.objectList.meshes;
this._renderer.particleSystemList = this.objectList.particleSystems;
const targetTextures = Array.isArray(this.targetTexture) ? this.targetTexture : [this.targetTexture];
const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(targetTextures[0]);
let depthEnabled = false;
if (this.depthTexture !== void 0) {
if (this.depthTexture === backbufferDepthStencilTextureHandle && (targetTextures[0] !== backbufferColorTextureHandle || targetTextures.length > 1)) {
throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer color texture is the only color texture allowed when the depth is the back buffer depth/stencil`);
}
if (this.depthTexture !== backbufferDepthStencilTextureHandle && targetTextures[0] === backbufferColorTextureHandle) {
throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer depth/stencil texture is the only depth texture allowed when the target is the back buffer color`);
}
const depthTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.depthTexture);
if (depthTextureDescription.options.samples !== outputTextureDescription.options.samples) {
throw new Error(`FrameGraphObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);
}
depthEnabled = true;
}
this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, targetTextures[0]);
if (this.depthTexture !== void 0) {
this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture);
}
this._textureWidth = outputTextureDescription.size.width;
this._textureHeight = outputTextureDescription.size.height;
this._setLightsForShadow();
const pass = this._frameGraph.addRenderPass(this.name);
pass.setRenderTarget(targetTextures);
pass.setRenderTargetDepth(this.depthTexture);
pass.setExecuteFunc((context) => {
this._renderer.renderList = this.objectList.meshes;
this._renderer.particleSystemList = this.objectList.particleSystems;
const boundingBoxRenderer = this.getBoundingBoxRenderer?.();
const currentBoundingBoxMeshList = boundingBoxRenderer && boundingBoxRenderer.renderList.length > 0 ? boundingBoxRenderer.renderList.data.slice() : [];
if (boundingBoxRenderer) {
currentBoundingBoxMeshList.length = boundingBoxRenderer.renderList.length;
}
context.setDepthStates(this.depthTest && depthEnabled, this.depthWrite && depthEnabled);
const camera = this._renderer.activeCamera;
if (camera && camera.cameraRigMode !== 0 && !camera._renderingMultiview) {
for (let index = 0; index < camera._rigCameras.length; index++) {
const rigCamera = camera._rigCameras[index];
rigCamera.rigParent = void 0;
this._renderer.activeCamera = rigCamera;
context.render(this._renderer, this._textureWidth, this._textureHeight);
rigCamera.rigParent = camera;
}
this._renderer.activeCamera = camera;
} else {
context.render(this._renderer, this._textureWidth, this._textureHeight);
}
additionalExecute?.(context);
if (boundingBoxRenderer) {
boundingBoxRenderer.renderList.data = currentBoundingBoxMeshList;
boundingBoxRenderer.renderList.length = currentBoundingBoxMeshList.length;
}
});
if (!skipCreationOfDisabledPasses) {
const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
passDisabled.setRenderTarget(targetTextures);
passDisabled.setRenderTargetDepth(this.depthTexture);
passDisabled.setExecuteFunc((_context) => {
});
}
return pass;
}
dispose() {
this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable);
this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable);
if (!this._externalObjectRenderer) {
this._renderer.dispose();
}
super.dispose();
}
_setLightsForShadow() {
const lightsForShadow = /* @__PURE__ */ new Set();
const shadowEnabled = /* @__PURE__ */ new Map();
if (this.shadowGenerators) {
for (const shadowGeneratorTask of this.shadowGenerators) {
const shadowGenerator = shadowGeneratorTask.shadowGenerator;
const light = shadowGenerator.getLight();
if (light.isEnabled() && light.shadowEnabled) {
lightsForShadow.add(light);
if (FrameGraphCascadedShadowGeneratorTask.IsCascadedShadowGenerator(shadowGeneratorTask)) {
light._shadowGenerators.set(shadowGeneratorTask.camera, shadowGenerator);
} else {
light._shadowGenerators.set(null, shadowGenerator);
}
}
}
}
this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable);
this._onBeforeRenderObservable = this._renderer.onBeforeRenderObservable.add(() => {
for (let i = 0; i < this._scene.lights.length; i++) {
const light = this._scene.lights[i];
if (!light.setShadowProjectionMatrix) {
continue;
}
shadowEnabled.set(light, light.shadowEnabled);
light.shadowEnabled = !this.disableShadows && lightsForShadow.has(light);
}
});
this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable);
this._onAfterRenderObservable = this._renderer.onAfterRenderObservable.add(() => {
for (let i = 0; i < this._scene.lights.length; i++) {
const light = this._scene.lights[i];
if (!light.setShadowProjectionMatrix) {
continue;
}
light.shadowEnabled = shadowEnabled.get(light);
}
});
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/scene.js
var ScenePerformancePriority, Scene;
var init_scene = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/scene.js"() {
init_tools();
init_precisionDate();
init_observable();
init_smartArray();
init_stringDictionary();
init_tags();
init_math_vector();
init_imageProcessingConfiguration();
init_uniformBuffer();
init_pickingInfo();
init_actionEvent();
init_postProcessManager();
init_floatingOriginMatrixOverrides();
init_renderingManager();
init_sceneComponent();
init_domManagement();
init_engineStore();
init_devTools();
init_scene_inputManager();
init_perfCounter();
init_math_color();
init_math_frustum();
init_uniqueIdGenerator();
init_fileTools();
init_lightConstants();
init_arrayTools();
init_pointerPickingConfiguration();
init_logger();
init_typeStore();
init_objectRendererTask();
init_timingTools();
(function(ScenePerformancePriority2) {
ScenePerformancePriority2[ScenePerformancePriority2["BackwardCompatible"] = 0] = "BackwardCompatible";
ScenePerformancePriority2[ScenePerformancePriority2["Intermediate"] = 1] = "Intermediate";
ScenePerformancePriority2[ScenePerformancePriority2["Aggressive"] = 2] = "Aggressive";
})(ScenePerformancePriority || (ScenePerformancePriority = {}));
Scene = class _Scene {
static {
__name(this, "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:
this.skipFrustumClipping = false;
this._renderingManager.maintainStateBetweenFrames = false;
this.skipPointerMovePicking = false;
this.autoClear = true;
break;
case 1:
this.skipFrustumClipping = false;
this._renderingManager.maintainStateBetweenFrames = false;
this.skipPointerMovePicking = true;
this.autoClear = false;
break;
case 2:
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);
for (const skeleton of this.skeletons) {
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);
const offset = this.floatingOriginOffset;
const eyePos = this._tempVect4.set(eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
const offsetEyePos = eyePos.subtractFromFloatsToRef(offset.x, offset.y, offset.z, 0, TmpVectors.Vector4[1]);
if (effect) {
if (isVector3) {
effect.setFloat3(variableName, offsetEyePos.x, offsetEyePos.y, offsetEyePos.z);
} else {
effect.setVector4(variableName, offsetEyePos);
}
}
return eyePos;
}
/**
* 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);
const offset = this.floatingOriginOffset;
ubo.updateFloat4("vEyePosition", eyePosition.x - offset.x, eyePosition.y - offset.y, eyePosition.z - offset.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;
this.activeCamera = null;
}
}
/**
* 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() {
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(name260) {
for (const component of this._components) {
if (component.name === name260) {
return component;
}
}
return null;
}
/**
* Gets the unique id of the scene
*/
get uniqueId() {
return this._uniqueId;
}
/**
* Creates a new Scene
* @param engine defines the engine to use to render this scene
* @param options defines the scene options
*/
constructor(engine, options) {
this._inputManager = new InputManager(this);
this.cameraToUseForPointers = null;
this._isScene = true;
this._blockEntityCollection = false;
this.autoClear = true;
this.autoClearDepthAndStencil = true;
this._clearColor = new Color4(0.2, 0.2, 0.3, 1);
this._tempVect4 = new Vector4();
this.onClearColorChangedObservable = new Observable();
this.ambientColor = new Color3(0, 0, 0);
this.environmentIntensity = 1;
this.iblIntensity = 1;
this._performancePriority = 0;
this.onScenePerformancePriorityChangedObservable = new Observable();
this._forceWireframe = false;
this._skipFrustumClipping = false;
this._forcePointsCloud = false;
this.rootNodes = [];
this.cameras = [];
this.lights = [];
this.meshes = [];
this.skeletons = [];
this.particleSystems = [];
this.animations = [];
this.animationGroups = [];
this.multiMaterials = [];
this.materials = [];
this.morphTargetManagers = [];
this.geometries = [];
this.transformNodes = [];
this.actionManagers = [];
this.objectRenderers = [];
this.textures = [];
this._environmentTexture = null;
this.postProcesses = [];
this.effectLayers = [];
this.sounds = null;
this.layers = [];
this.lensFlareSystems = [];
this.proceduralTextures = [];
this.animationsEnabled = true;
this._animationPropertiesOverride = null;
this.useConstantAnimationDeltaTime = false;
this.constantlyUpdateMeshUnderPointer = false;
this.hoverCursor = "pointer";
this.defaultCursor = "";
this.doNotHandleCursors = false;
this.preventDefaultOnPointerDown = true;
this.preventDefaultOnPointerUp = true;
this.metadata = null;
this.reservedDataStore = null;
this.disableOfflineSupportExceptionRules = [];
this.onDisposeObservable = new Observable();
this._onDisposeObserver = null;
this.onBeforeRenderObservable = new Observable();
this._onBeforeRenderObserver = null;
this.onAfterRenderObservable = new Observable();
this.onAfterRenderCameraObservable = new Observable();
this._onAfterRenderObserver = null;
this.onBeforeAnimationsObservable = new Observable();
this.onAfterAnimationsObservable = new Observable();
this.onBeforeDrawPhaseObservable = new Observable();
this.onAfterDrawPhaseObservable = new Observable();
this.onReadyObservable = new Observable();
this.onBeforeCameraRenderObservable = new Observable();
this._onBeforeCameraRenderObserver = null;
this.onAfterCameraRenderObservable = new Observable();
this._onAfterCameraRenderObserver = null;
this.onBeforeActiveMeshesEvaluationObservable = new Observable();
this.onAfterActiveMeshesEvaluationObservable = new Observable();
this.onBeforeParticlesRenderingObservable = new Observable();
this.onAfterParticlesRenderingObservable = new Observable();
this.onDataLoadedObservable = new Observable();
this.onNewCameraAddedObservable = new Observable();
this.onCameraRemovedObservable = new Observable();
this.onNewLightAddedObservable = new Observable();
this.onLightRemovedObservable = new Observable();
this.onNewGeometryAddedObservable = new Observable();
this.onGeometryRemovedObservable = new Observable();
this.onNewTransformNodeAddedObservable = new Observable();
this.onTransformNodeRemovedObservable = new Observable();
this.onNewMeshAddedObservable = new Observable();
this.onMeshRemovedObservable = new Observable();
this.onNewSkeletonAddedObservable = new Observable();
this.onSkeletonRemovedObservable = new Observable();
this.onNewParticleSystemAddedObservable = new Observable();
this.onParticleSystemRemovedObservable = new Observable();
this.onNewAnimationGroupAddedObservable = new Observable();
this.onAnimationGroupRemovedObservable = new Observable();
this.onNewMaterialAddedObservable = new Observable();
this.onNewMultiMaterialAddedObservable = new Observable();
this.onMaterialRemovedObservable = new Observable();
this.onMultiMaterialRemovedObservable = new Observable();
this.onNewTextureAddedObservable = new Observable();
this.onTextureRemovedObservable = new Observable();
this.onNewFrameGraphAddedObservable = new Observable();
this.onFrameGraphRemovedObservable = new Observable();
this.onNewObjectRendererAddedObservable = new Observable();
this.onObjectRendererRemovedObservable = new Observable();
this.onNewPostProcessAddedObservable = new Observable();
this.onPostProcessRemovedObservable = new Observable();
this.onNewEffectLayerAddedObservable = new Observable();
this.onEffectLayerRemovedObservable = new Observable();
this.onBeforeRenderTargetsRenderObservable = new Observable();
this.onAfterRenderTargetsRenderObservable = new Observable();
this.onBeforeStepObservable = new Observable();
this.onAfterStepObservable = new Observable();
this.onActiveCameraChanged = new Observable();
this.onActiveCamerasChanged = new Observable();
this.onBeforeRenderingGroupObservable = new Observable();
this.onAfterRenderingGroupObservable = new Observable();
this.onMeshImportedObservable = new Observable();
this.onAnimationFileImportedObservable = new Observable();
this.onEnvironmentTextureChangedObservable = new Observable();
this.onMeshUnderPointerUpdatedObservable = new Observable();
this._registeredForLateAnimationBindings = new SmartArrayNoDuplicate(256);
this._pointerPickingConfiguration = new PointerPickingConfiguration();
this.onPrePointerObservable = new Observable();
this.onPointerObservable = new Observable();
this.onPreKeyboardObservable = new Observable();
this.onKeyboardObservable = new Observable();
this._useRightHandedSystem = false;
this._timeAccumulator = 0;
this._currentStepId = 0;
this._currentInternalStep = 0;
this._fogEnabled = true;
this._fogMode = _Scene.FOGMODE_NONE;
this.fogColor = new Color3(0.2, 0.2, 0.3);
this.fogDensity = 0.1;
this.fogStart = 0;
this.fogEnd = 1e3;
this.needsPreviousWorldMatrices = false;
this._shadowsEnabled = true;
this._lightsEnabled = true;
this._unObserveActiveCameras = null;
this._texturesEnabled = true;
this._frameGraph = null;
this.frameGraphs = [];
this.physicsEnabled = true;
this.particlesEnabled = true;
this.spritesEnabled = true;
this._skeletonsEnabled = true;
this.lensFlaresEnabled = true;
this.collisionsEnabled = true;
this.gravity = new Vector3(0, -9.807, 0);
this.postProcessesEnabled = true;
this.renderTargetsEnabled = true;
this.dumpNextRenderTargets = false;
this.customRenderTargets = [];
this.importedMeshesFiles = [];
this.probesEnabled = true;
this._meshesForIntersections = new SmartArrayNoDuplicate(256);
this.proceduralTexturesEnabled = true;
this._totalVertices = new PerfCounter();
this._activeIndices = new PerfCounter();
this._activeParticles = new PerfCounter();
this._activeBones = new PerfCounter();
this._animationTime = 0;
this.animationTimeScale = 1;
this._renderId = 0;
this._frameId = 0;
this._executeWhenReadyTimeoutId = null;
this._intermediateRendering = false;
this._defaultFrameBufferCleared = false;
this._viewUpdateFlag = -1;
this._projectionUpdateFlag = -1;
this._toBeDisposed = new Array(256);
this._activeRequests = new Array();
this._pendingData = [];
this._isDisposed = false;
this.dispatchAllSubMeshesOfActiveMeshes = false;
this._activeMeshes = new SmartArray(256);
this._processedMaterials = new SmartArray(256);
this._renderTargets = new SmartArrayNoDuplicate(256);
this._materialsRenderTargets = new SmartArrayNoDuplicate(256);
this._activeParticleSystems = new SmartArray(256);
this._activeSkeletons = new SmartArrayNoDuplicate(32);
this._softwareSkinnedMeshes = new SmartArrayNoDuplicate(32);
this._activeAnimatables = new Array();
this._transformMatrix = Matrix.Zero();
this.requireLightSorting = false;
this._components = [];
this._serializableComponents = [];
this._transientComponents = [];
this._beforeCameraUpdateStage = Stage.Create();
this._beforeClearStage = Stage.Create();
this._beforeRenderTargetClearStage = Stage.Create();
this._gatherRenderTargetsStage = Stage.Create();
this._gatherActiveCameraRenderTargetsStage = Stage.Create();
this._isReadyForMeshStage = Stage.Create();
this._beforeEvaluateActiveMeshStage = Stage.Create();
this._evaluateSubMeshStage = Stage.Create();
this._preActiveMeshStage = Stage.Create();
this._cameraDrawRenderTargetStage = Stage.Create();
this._beforeCameraDrawStage = Stage.Create();
this._beforeRenderTargetDrawStage = Stage.Create();
this._beforeRenderingGroupDrawStage = Stage.Create();
this._beforeRenderingMeshStage = Stage.Create();
this._afterRenderingMeshStage = Stage.Create();
this._afterRenderingGroupDrawStage = Stage.Create();
this._afterCameraDrawStage = Stage.Create();
this._afterCameraPostProcessStage = Stage.Create();
this._afterRenderTargetDrawStage = Stage.Create();
this._afterRenderTargetPostProcessStage = Stage.Create();
this._afterRenderStage = Stage.Create();
this._pointerMoveStage = Stage.Create();
this._pointerDownStage = Stage.Create();
this._pointerUpStage = Stage.Create();
this._geometriesByUniqueId = null;
this._uniqueId = 0;
this._defaultMeshCandidates = {
data: [],
length: 0
};
this._defaultSubMeshCandidates = {
data: [],
length: 0
};
this._floatingOriginScene = void 0;
this._floatingOriginOffsetDefault = Vector3.Zero();
this._preventFreeActiveMeshesAndRenderingGroups = false;
this._activeMeshesFrozen = false;
this._activeMeshesFrozenButKeepClipping = false;
this._skipEvaluateActiveMeshesCompletely = false;
this._freezeActiveMeshesCancel = null;
this._useCurrentFrameBuffer = false;
this._allowPostProcessClearColor = true;
this.getDeterministicFrameTime = () => {
return this._engine.getTimeStep();
};
this._getFloatingOriginScene = () => {
return this._floatingOriginScene;
};
this._registeredActions = 0;
this._blockMaterialDirtyMechanism = false;
this._perfCollector = null;
this.activeCameras = [];
this._uniqueId = this.getUniqueId();
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);
}
if (engine.getCreationOptions().useLargeWorldRendering || options?.useFloatingOrigin) {
OverrideMatrixFunctions();
this._floatingOriginScene = this;
}
this._uid = null;
this._renderingManager = new RenderingManager(this);
if (PostProcessManager) {
this.postProcessManager = new PostProcessManager(this);
}
if (IsWindowObjectExist()) {
this.attachControl();
}
this._createUbo();
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 !== void 0 ? 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;
if (this._pendingData.length > 0) {
isReady = false;
}
this.prePassRenderer?.update();
if (this.useOrderIndependentTransparency && this.depthPeelingRenderer) {
isReady && (isReady = this.depthPeelingRenderer.isReady());
}
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;
}
if (!mesh.isReady(true)) {
isReady = false;
continue;
}
const hardwareInstancedRendering = mesh.hasThinInstances || mesh.getClassName() === "InstancedMesh" || mesh.getClassName() === "InstancedLinesMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
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());
}
}
}
}
}
if (checkRenderTargets) {
for (index = 0; index < this._materialsRenderTargets.length; ++index) {
const rtt = this._materialsRenderTargets.data[index];
if (!rtt.isReadyForRendering()) {
isReady = false;
}
}
}
for (index = 0; index < this.geometries.length; index++) {
const geometry = this.geometries[index];
if (geometry.delayLoadState === 2) {
isReady = false;
}
}
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;
}
}
for (const particleSystem of this.particleSystems) {
if (!particleSystem.isReady()) {
isReady = false;
}
}
if (this.layers) {
for (const layer of this.layers) {
if (!layer.isReady()) {
isReady = false;
}
}
}
if (this.effectLayers) {
for (const effectLayer of this.effectLayers) {
if (!effectLayer.isLayerReady()) {
isReady = false;
}
}
}
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 = /* @__PURE__ */ __name(() => {
func();
setTimeout(() => {
this.unregisterBeforeRender(execFunc);
});
}, "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 !== void 0) {
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
*/
async whenReadyAsync(checkRenderTargets = false) {
return await 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(() => {
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) {
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);
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)
* @param trackUBOsInFrame define if the UBOs should be tracked in the frame (default: undefined - will use the value from Engine._features.trackUbosInFrame)
* @returns a new ubo
*/
createSceneUniformBuffer(name260, trackUBOsInFrame) {
const sceneUbo = new UniformBuffer(this._engine, void 0, false, name260 ?? "scene", void 0, trackUBOsInFrame);
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;
}
/**
* @experimental
* True if floatingOriginMode was passed to engine or this scene creation otions.
* This mode avoids floating point imprecision in huge coordinate system by offsetting uniform values before passing to shader, centering camera at origin and displacing rest of scene by camera position
*/
get floatingOriginMode() {
return this._floatingOriginScene !== void 0;
}
/**
* @experimental
* When floatingOriginMode is enabled, offset is equal to the active camera position in world space. If no active camera or floatingOriginMode is disabled, offset is 0.
*/
get floatingOriginOffset() {
return this.floatingOriginMode && this.activeCamera ? this.activeCamera.getWorldMatrix().getTranslation() : this._floatingOriginOffsetDefault;
}
/**
* 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) {
const children = newMesh.getChildMeshes();
for (const m of children) {
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) {
this.meshes.splice(index, 1);
if (!toRemove.parent) {
toRemove._removeFromSceneRootNodes();
}
}
this._inputManager._invalidateMesh(toRemove);
this.onMeshRemovedObservable.notifyObservers(toRemove);
if (recursive) {
const children = toRemove.getChildMeshes();
for (const m of children) {
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) {
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) {
this.skeletons.splice(index, 1);
this.onSkeletonRemovedObservable.notifyObservers(toRemove);
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) {
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) {
for (const mesh of this.meshes) {
mesh._removeLightSource(toRemove, false);
}
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) {
this.cameras.splice(index, 1);
if (!toRemove.parent) {
toRemove._removeFromSceneRootNodes();
}
}
if (this.activeCameras) {
const index2 = this.activeCameras.indexOf(toRemove);
if (index2 !== -1) {
this.activeCameras.splice(index2, 1);
}
}
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);
this._executeActiveContainerCleanup(this._activeParticleSystems);
}
this.onParticleSystemRemovedObservable.notifyObservers(toRemove);
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) {
}
/**
* 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);
}
this.onAnimationGroupRemovedObservable.notifyObservers(toRemove);
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;
}
/**
* Removes the given frame graph from this scene.
* @param toRemove The frame graph to remove
* @returns The index of the removed frame graph
*/
removeFrameGraph(toRemove) {
const index = this.frameGraphs.indexOf(toRemove);
if (index !== -1) {
this.frameGraphs.splice(index, 1);
}
this.onFrameGraphRemovedObservable.notifyObservers(toRemove);
return index;
}
/**
* Removes the given object renderer from this scene.
* @param toRemove The object renderer to remove
* @returns The index of the removed object renderer
*/
removeObjectRenderer(toRemove) {
const index = this.objectRenderers.indexOf(toRemove);
if (index !== -1) {
this.objectRenderers.splice(index, 1);
}
this.onObjectRendererRemovedObservable.notifyObservers(toRemove);
return index;
}
/**
* Removes the given post-process from this scene.
* @param toRemove The post-process to remove
* @returns The index of the removed post-process
*/
removePostProcess(toRemove) {
const index = this.postProcesses.indexOf(toRemove);
if (index !== -1) {
this.postProcesses.splice(index, 1);
}
this.onPostProcessRemovedObservable.notifyObservers(toRemove);
return index;
}
/**
* Removes the given layer from this scene.
* @param toRemove The layer to remove
* @returns The index of the removed layer
*/
removeEffectLayer(toRemove) {
const index = this.effectLayers.indexOf(toRemove);
if (index !== -1) {
this.effectLayers.splice(index, 1);
}
this.onEffectLayerRemovedObservable.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();
}
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);
Tools.SetImmediate(() => {
this.onNewParticleSystemAddedObservable.notifyObservers(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);
Tools.SetImmediate(() => {
this.onNewAnimationGroupAddedObservable.notifyObservers(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) {
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);
}
/**
* Adds the given frame graph to this scene.
* @param newFrameGraph The frame graph to add
*/
addFrameGraph(newFrameGraph) {
this.frameGraphs.push(newFrameGraph);
Tools.SetImmediate(() => {
this.onNewFrameGraphAddedObservable.notifyObservers(newFrameGraph);
});
}
/**
* Adds the given object renderer to this scene.
* @param objectRenderer The object renderer to add
*/
addObjectRenderer(objectRenderer) {
this.objectRenderers.push(objectRenderer);
Tools.SetImmediate(() => {
this.onNewObjectRendererAddedObservable.notifyObservers(objectRenderer);
});
}
/**
* Adds the given post process to this scene.
* @param newPostProcess The post process to add
*/
addPostProcess(newPostProcess) {
if (this._blockEntityCollection) {
return;
}
this.postProcesses.push(newPostProcess);
Tools.SetImmediate(() => {
this.onNewPostProcessAddedObservable.notifyObservers(newPostProcess);
});
}
/**
* Adds the given effect layer to this scene.
* @param newEffectLayer The effect layer to add
*/
addEffectLayer(newEffectLayer) {
if (this._blockEntityCollection) {
return;
}
this.effectLayers.push(newEffectLayer);
Tools.SetImmediate(() => {
this.onNewEffectLayerAddedObservable.notifyObservers(newEffectLayer);
});
}
/**
* 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(name260) {
const camera = this.getCameraByName(name260);
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(name260) {
for (let index = 0; index < this.animationGroups.length; index++) {
if (this.animationGroups[index].name === name260) {
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.
* @deprecated Please use getMaterialByUniqueId instead.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
getMaterialByUniqueID(uniqueId, allowMultiMaterials = false) {
return this.getMaterialByUniqueId(uniqueId, allowMultiMaterials);
}
/**
* 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(name260, allowMultiMaterials = false) {
return this._getMaterial(allowMultiMaterials, (m) => m.name === name260);
}
/**
* 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(name260) {
for (let index = 0; index < this.textures.length; index++) {
if (this.textures[index].name === name260) {
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(name260) {
for (let index = 0; index < this.cameras.length; index++) {
if (this.cameras[index].name === name260) {
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(name260) {
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 === name260) {
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(name260) {
for (let index = 0; index < this.lights.length; index++) {
if (this.lights[index].name === name260) {
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 !== void 0) {
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(name260) {
for (let index = 0; index < this.frameGraphs.length; index++) {
if (this.frameGraphs[index].name === name260) {
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 === void 0) {
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] = void 0;
}
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(name260) {
const mesh = this.getMeshByName(name260);
if (mesh) {
return mesh;
}
const transformNode = this.getTransformNodeByName(name260);
if (transformNode) {
return transformNode;
}
const light = this.getLightByName(name260);
if (light) {
return light;
}
const camera = this.getCameraByName(name260);
if (camera) {
return camera;
}
const bone = this.getBoneByName(name260);
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(name260) {
for (let index = 0; index < this.meshes.length; index++) {
if (this.meshes[index].name === name260) {
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(name260) {
for (let index = 0; index < this.transformNodes.length; index++) {
if (this.transformNodes[index].name === name260) {
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(name260) {
for (let index = 0; index < this.skeletons.length; index++) {
if (this.skeletons[index].name === name260) {
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(name260) {
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 === name260) {
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(name260) {
for (let postProcessIndex = 0; postProcessIndex < this.postProcesses.length; ++postProcessIndex) {
const postProcess = this.postProcesses[postProcessIndex];
if (postProcess.name === name260) {
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 !== void 0) {
if (material.hasRenderTargetTextures && material.getRenderTargetTextures != null) {
if (this._processedMaterials.indexOf(material) === -1) {
this._processedMaterials.push(material);
this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
}
}
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) {
if (this.frameGraph) {
this._renderWithFrameGraph(true, false, true);
const objectRendererTasks = this.frameGraph.getTasksByType(FrameGraphObjectRendererTask);
for (const task of objectRendererTasks) {
task.objectRenderer._freezeActiveMeshes(freezeMeshes);
}
this._freezeActiveMeshesCancel = _RetryWithInterval(() => {
let ok = true;
let notCancelled = true;
for (const task of objectRendererTasks) {
ok && (ok = task.objectRenderer._isFrozen);
notCancelled && (notCancelled = task.objectRenderer._freezeActiveMeshesCancel !== null);
}
if (ok) {
return true;
} else if (!notCancelled) {
throw new Error("Freezing active meshes was cancelled");
}
return false;
}, () => {
this._freezeActiveMeshesCancel = null;
this._activeMeshesFrozen = true;
this._activeMeshesFrozenButKeepClipping = keepFrustumCulling;
this._skipEvaluateActiveMeshesCompletely = skipEvaluateActiveMeshes;
onSuccess?.();
}, (err, isTimeout) => {
this._freezeActiveMeshesCancel = null;
this.unfreezeActiveMeshes();
if (!isTimeout) {
const errMsg = "Scene: An unexpected error occurred while trying to freeze active meshes.";
if (onError) {
onError(errMsg);
} else {
Logger.Error(errMsg);
if (err) {
Logger.Error(err);
if (err.stack) {
Logger.Error(err.stack);
}
}
}
} else {
const errMsg = "Scene: Timeout while waiting for meshes to be frozen.";
if (onError) {
onError(errMsg);
} else {
Logger.Error(errMsg);
if (err) {
Logger.Error(err);
}
}
}
});
return this;
}
this.executeWhenReady(() => {
if (!this.activeCamera) {
if (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();
}
}
if (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;
}
}
this._freezeActiveMeshesCancel?.();
this._freezeActiveMeshesCancel = null;
if (this.frameGraph) {
const objectRendererTasks = this.frameGraph.getTasksByType(FrameGraphObjectRendererTask);
for (const task of objectRendererTasks) {
task.objectRenderer._unfreezeActiveMeshes();
}
} else {
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;
}
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 len2 = this._activeMeshes.length;
for (let i = 0; i < len2; 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();
}
const meshes = this.getActiveMeshCandidates();
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();
if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) {
this._meshesForIntersections.pushNoDuplicate(mesh);
}
let meshToRender = this.customLODSelector ? this.customLODSelector(mesh, this.activeCamera) : mesh.getLOD(this.activeCamera);
currentLOD[0] = meshToRender;
currentLOD[1] = this._frameId;
if (meshToRender === void 0 || meshToRender === null) {
continue;
}
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);
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) {
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;
this._activeCamera = camera;
if (!this.activeCamera) {
throw new Error("Active camera not set");
}
engine.setViewport(this.activeCamera.viewport);
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);
this._evaluateActiveMeshes();
for (let softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
const mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
mesh.applySkeleton(mesh.skeleton);
}
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);
}
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);
const boundingBoxRenderer = this.getBoundingBoxRenderer?.();
let currentBoundingBoxMeshList;
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;
if (boundingBoxRenderer && !currentBoundingBoxMeshList) {
currentBoundingBoxMeshList = boundingBoxRenderer.renderList.length > 0 ? boundingBoxRenderer.renderList.data.slice() : [];
currentBoundingBoxMeshList.length = boundingBoxRenderer.renderList.length;
}
renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
needRebind = true;
}
}
if (boundingBoxRenderer && currentBoundingBoxMeshList) {
boundingBoxRenderer.renderList.data = currentBoundingBoxMeshList;
boundingBoxRenderer.renderList.length = currentBoundingBoxMeshList.length;
}
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;
if (needRebind && !this.prePass) {
this._bindFrameBuffer(this._activeCamera, false);
this.updateTransformMatrix();
}
this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
if (this.postProcessManager && !camera._multiviewTexture && !this.prePass) {
this.postProcessManager._prepareFrame();
}
for (const step of this._beforeCameraDrawStage) {
step.action(this.activeCamera);
}
this.onBeforeDrawPhaseObservable.notifyObservers(this);
const fastSnapshotMode = engine.snapshotRendering && engine.snapshotRenderingMode === 1;
if (fastSnapshotMode) {
this.finalizeSceneUbo();
}
this._renderingManager.render(null, null, true, !fastSnapshotMode);
this.onAfterDrawPhaseObservable.notifyObservers(this);
for (const step of this._afterCameraDrawStage) {
step.action(this.activeCamera);
}
if (this.postProcessManager && !camera._multiviewTexture) {
const texture = camera.outputRenderTarget ? camera.outputRenderTarget.renderTarget : void 0;
this.postProcessManager._finalizeFrame(camera.isIntermediate, texture);
}
for (const step of this._afterCameraPostProcessStage) {
step.action(this.activeCamera);
}
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, void 0, bindFrameBuffer);
this.onAfterRenderCameraObservable.notifyObservers(camera);
return;
}
if (camera._useMultiviewToSingleView) {
this._renderMultiviewToSingleView(camera);
} else {
this.onBeforeCameraRenderObservable.notifyObservers(camera);
for (let index = 0; index < camera._rigCameras.length; index++) {
this._renderForCamera(camera._rigCameras[index], camera);
}
}
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, void 0, otherMesh));
sourceMesh._intersectionsInProgress.push(otherMesh);
} else if (action.trigger === 13) {
sourceMesh._intersectionsInProgress.push(otherMesh);
}
} else if (!areIntersecting && currentIntersectionInProgress > -1) {
if (action.trigger === 13) {
action._executeCurrent(ActionEvent.CreateNew(sourceMesh, void 0, otherMesh));
}
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) {
}
/** @internal */
_animate(customDeltaTime) {
}
/** 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 = 1e3 / defaultFrameTime / 1e3;
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);
this._animationRatio = defaultFrameTime * defaultFPS;
this._animate(defaultFrameTime);
this.onAfterAnimationsObservable.notifyObservers(this);
if (this.physicsEnabled) {
this._advancePhysicsEngineStep(defaultFrameTime);
}
this.onAfterStepObservable.notifyObservers(this);
this._currentStepId++;
stepsTaken++;
deltaTime -= defaultFrameTime;
}
this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
} else {
const deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(_Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), _Scene.MaxDeltaTime));
this._animationRatio = deltaTime * (60 / 1e3);
this._animate();
this.onAfterAnimationsObservable.notifyObservers(this);
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, forceUpdateWorldMatrix = false) {
this.activeCamera = null;
this.activeCameras = null;
if (updateCameras) {
for (const camera of this.cameras) {
camera.update();
if (camera.cameraRigMode !== 0) {
for (let index = 0; index < camera._rigCameras.length; index++) {
camera._rigCameras[index].update();
}
}
}
}
this.onBeforeRenderObservable.notifyObservers(this);
for (const step of this._beforeClearStage) {
step.action();
}
if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) {
this._activeParticleSystems.reset();
this._activeSkeletons.reset();
this._softwareSkinnedMeshes.reset();
} else {
const meshes = this.getActiveMeshCandidates();
const len = meshes.length;
if (!this._activeMeshesFrozen) {
this._activeParticleSystems.reset();
this._activeSkeletons.reset();
this._softwareSkinnedMeshes.reset();
for (let i = 0; i < len; i++) {
const mesh = meshes.data[i];
mesh._internalAbstractMeshDataInfo._wasActiveLastFrame = false;
if (mesh.isBlocked) {
continue;
}
this._totalVertices.addCount(mesh.getTotalVertices(), false);
if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) {
continue;
}
mesh.computeWorldMatrix(forceUpdateWorldMatrix);
if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) {
this._meshesForIntersections.pushNoDuplicate(mesh);
}
}
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();
}
}
}
} else {
if (!this._skipEvaluateActiveMeshesCompletely) {
for (let i = 0; i < len; i++) {
const mesh = meshes.data[i];
if (mesh._internalAbstractMeshDataInfo._wasActiveLastFrame) {
mesh.computeWorldMatrix();
}
}
}
if (this.particlesEnabled) {
const psLength = this._activeParticleSystems.length;
for (let i = 0; i < psLength; i++) {
this._activeParticleSystems.data[i].animate();
}
}
}
}
this.frameGraph?.execute();
}
/**
* @internal
*/
_renderRenderTarget(renderTarget, activeCamera, useCameraPostProcess = false, dumpForDebug = false) {
this._intermediateRendering = true;
if (renderTarget._shouldRender()) {
this._renderId++;
this.activeCamera = activeCamera;
if (!this.activeCamera) {
throw new Error("Active camera not set");
}
this._engine.setViewport(this.activeCamera.viewport);
this.updateTransformMatrix();
renderTarget.render(useCameraPostProcess, dumpForDebug);
}
this._intermediateRendering = false;
}
/**
* 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();
}
FloatingOriginCurrentScene.getScene = this._getFloatingOriginScene;
this._frameId++;
this._defaultFrameBufferCleared = false;
this._checkCameraRenderTarget(this.activeCamera);
if (this.activeCameras?.length) {
for (const c of this.activeCameras) {
this._checkCameraRenderTarget(c);
}
}
this._registerTransientComponents();
this._activeParticles.fetchNewFrame();
this._totalVertices.fetchNewFrame();
this._activeIndices.fetchNewFrame();
this._activeBones.fetchNewFrame();
this._meshesForIntersections.reset();
this.resetCachedMaterial();
this.onBeforeAnimationsObservable.notifyObservers(this);
if (this.actionManager) {
this.actionManager.processTrigger(11);
}
if (!ignoreAnimations) {
this.animate();
}
for (const step of this._beforeCameraUpdateStage) {
step.action();
}
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) {
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) {
for (let index = 0; index < this.activeCamera._rigCameras.length; index++) {
this.activeCamera._rigCameras[index].update();
}
}
}
}
if (this.customRenderFunction) {
this._renderId++;
this._engine.currentRenderPassId = 0;
this.customRenderFunction(updateCameras, ignoreAnimations);
} else {
this.onBeforeRenderObservable.notifyObservers(this);
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);
for (let customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
const renderTarget = this.customRenderTargets[customIndex];
const activeCamera = renderTarget.activeCamera || this.activeCamera;
this._renderRenderTarget(renderTarget, activeCamera, currentActiveCamera !== activeCamera, this.dumpNextRenderTargets);
}
Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
this._renderId++;
}
this._engine.currentRenderPassId = currentActiveCamera?.renderPassId ?? 0;
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();
}
this._clearFrameBuffer(this.activeCamera);
for (const step of this._gatherRenderTargetsStage) {
step.action(this._renderTargets);
}
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);
}
}
this._checkIntersections();
for (const step of this._afterRenderStage) {
step.action();
}
if (this.afterRender) {
this.afterRender();
}
this.onAfterRenderObservable.notifyObservers(this);
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) {
for (const animatable of this._activeAnimatables) {
animatable.onAnimationEndObservable.clear();
animatable.onAnimationEnd = null;
}
this.stopAllAnimations();
}
this.resetCachedMaterial();
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;
const activeRequests = this._activeRequests.slice();
for (const request of activeRequests) {
request.abort();
}
this._activeRequests.length = 0;
try {
this.onDisposeObservable.notifyObservers(this);
} catch (e) {
Logger.Error("An error occurred while calling onDisposeObservable!", e);
}
this.detachControl();
const canvas = this._engine.getInputElement();
if (canvas) {
for (let index2 = 0; index2 < this.cameras.length; index2++) {
this.cameras[index2].detachControl();
}
}
this._disposeList(this.animationGroups);
this._disposeList(this.lights);
if (this._defaultMaterial) {
this._defaultMaterial.dispose();
}
this._disposeList(this.multiMaterials);
this._disposeList(this.materials);
this._disposeList(this.meshes, (item) => item.dispose(true));
this._disposeList(this.transformNodes, (item) => item.dispose(true));
const cameras = this.cameras;
this._disposeList(cameras);
this._disposeList(this.particleSystems);
this._disposeList(this.postProcesses);
this._disposeList(this.textures);
this._disposeList(this.morphTargetManagers);
this._disposeList(this.frameGraphs);
this._sceneUbo.dispose();
if (this._multiviewSceneUbo) {
this._multiviewSceneUbo.dispose();
}
this.postProcessManager.dispose();
this._disposeList(this._components);
let index = this._engine.scenes.indexOf(this);
if (index > -1) {
this._engine.scenes.splice(index, 1);
}
this._floatingOriginScene = void 0;
if (this._engine.scenes.length === 0) {
ResetMatrixFunctions();
}
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.onNewFrameGraphAddedObservable.clear();
this.onFrameGraphRemovedObservable.clear();
this.onNewObjectRendererAddedObservable.clear();
this.onObjectRendererRemovedObservable.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);
const meshes = this.meshes.filter(filterPredicate);
for (const mesh of meshes) {
mesh.computeWorldMatrix(true);
if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
continue;
}
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,
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);
}
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);
}
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 === void 0) {
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) {
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 : void 0, useArrayBuffer, onError, onOpened);
this._activeRequests.push(request);
request.onCompleteObservable.add((request2) => {
this._activeRequests.splice(this._activeRequests.indexOf(request2), 1);
});
return request;
}
/**
* @internal
*/
async _loadFileAsync(fileOrUrl, onProgress, useOfflineSupport, useArrayBuffer, onOpened) {
return await 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 : void 0, useArrayBuffer, onError, onOpened);
this._activeRequests.push(request);
request.onCompleteObservable.add((request2) => {
this._activeRequests.splice(this._activeRequests.indexOf(request2), 1);
});
return request;
}
/**
* @internal
*/
async _requestFileAsync(url, onProgress, useOfflineSupport, useArrayBuffer, onOpened) {
return await 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((request2) => {
this._activeRequests.splice(this._activeRequests.indexOf(request2), 1);
});
return request;
}
/**
* @internal
*/
async _readFileAsync(file, onProgress, useArrayBuffer) {
return await 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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
getLastSkeletonByID(id) {
return this.getLastSkeletonById(id);
}
};
Scene.FOGMODE_NONE = 0;
Scene.FOGMODE_EXP = 1;
Scene.FOGMODE_EXP2 = 2;
Scene.FOGMODE_LINEAR = 3;
Scene.MinDeltaTime = 1;
Scene.MaxDeltaTime = 1e3;
Scene._OriginalDefaultMaterialFactory = Scene.DefaultMaterialFactory;
RegisterClass("BABYLON.Scene", Scene);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/rgbdEncode.fragment.js
var rgbdEncode_fragment_exports = {};
__export(rgbdEncode_fragment_exports, {
rgbdEncodePixelShader: () => rgbdEncodePixelShader
});
var name93, shader93, rgbdEncodePixelShader;
var init_rgbdEncode_fragment = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/rgbdEncode.fragment.js"() {
init_shaderStore();
init_helperFunctions2();
name93 = "rgbdEncodePixelShader";
shader93 = `varying vec2 vUV;uniform sampler2D textureSampler;
#include
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;
if (!ShaderStore.ShadersStore[name93]) {
ShaderStore.ShadersStore[name93] = shader93;
}
rgbdEncodePixelShader = { name: name93, shader: shader93 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/rgbdEncode.fragment.js
var rgbdEncode_fragment_exports2 = {};
__export(rgbdEncode_fragment_exports2, {
rgbdEncodePixelShaderWGSL: () => rgbdEncodePixelShaderWGSL
});
var name94, shader94, rgbdEncodePixelShaderWGSL;
var init_rgbdEncode_fragment2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/rgbdEncode.fragment.js"() {
init_shaderStore();
init_helperFunctions();
name94 = "rgbdEncodePixelShader";
shader94 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;
#include
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}`;
if (!ShaderStore.ShadersStoreWGSL[name94]) {
ShaderStore.ShadersStoreWGSL[name94] = shader94;
}
rgbdEncodePixelShaderWGSL = { name: name94, shader: shader94 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/rgbdTextureTools.js
var RGBDTextureTools;
var init_rgbdTextureTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/rgbdTextureTools.js"() {
init_postProcess();
init_textureTools();
RGBDTextureTools = class {
static {
__name(this, "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;
}
const engine = internalTexture.getEngine();
const caps = engine.getCaps();
const isReady = internalTexture.isReady;
let expandTexture = false;
if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
expandTexture = true;
internalTexture.type = 2;
} else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
expandTexture = true;
internalTexture.type = 1;
}
if (expandTexture) {
internalTexture.isReady = false;
internalTexture._isRGBD = false;
internalTexture.invertY = false;
}
const expandRgbdTextureAsync = /* @__PURE__ */ __name(async () => {
const isWebGpu = engine.isWebGPU;
const shaderLanguage = isWebGpu ? 1 : 0;
internalTexture.isReady = false;
if (isWebGpu) {
await Promise.resolve().then(() => (init_rgbdDecode_fragment(), rgbdDecode_fragment_exports));
} else {
await Promise.resolve().then(() => (init_rgbdDecode_fragment2(), rgbdDecode_fragment_exports2));
}
const rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, void 0, internalTexture.type, void 0, null, false, void 0, shaderLanguage);
rgbdPostProcess.externalTextureSamplerBinding = true;
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(() => {
rgbdPostProcess.onApply = (effect) => {
effect._bindTexture("textureSampler", internalTexture);
effect.setFloat2("scale", 1, 1);
};
texture.getScene().postProcessManager.directRender([rgbdPostProcess], expandedTexture, true);
engine.restoreDefaultFramebuffer();
engine._releaseTexture(internalTexture);
if (rgbdPostProcess) {
rgbdPostProcess.dispose();
}
expandedTexture._swapAndDie(internalTexture);
internalTexture.isReady = true;
});
});
}, "expandRgbdTextureAsync");
if (expandTexture) {
if (isReady) {
expandRgbdTextureAsync();
} else {
texture.onLoadObservable.addOnce(expandRgbdTextureAsync);
}
}
}
/**
* 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
*/
// Should have "Async" in the name but this is a breaking change.
// eslint-disable-next-line no-restricted-syntax
static async EncodeTextureToRGBD(internalTexture, scene, outputTextureType = 0) {
if (!scene.getEngine().isWebGPU) {
await Promise.resolve().then(() => (init_rgbdEncode_fragment(), rgbdEncode_fragment_exports));
} else {
await Promise.resolve().then(() => (init_rgbdEncode_fragment2(), rgbdEncode_fragment_exports2));
}
return await ApplyPostProcess("rgbdEncode", internalTexture, scene, outputTextureType, 1, 5);
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/baseTexture.polynomial.js
var init_baseTexture_polynomial = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/baseTexture.polynomial.js"() {
init_cubemapToSphericalPolynomial();
init_baseTexture();
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: /* @__PURE__ */ __name(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;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
if (this._texture) {
this._texture._sphericalPolynomial = value;
}
}, "set"),
enumerable: true,
configurable: true
});
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/environmentTextureTools.js
function GetEnvInfo(data) {
const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
let pos = 0;
for (let i = 0; i < MagicBytes.length; i++) {
if (dataView.getUint8(pos++) !== MagicBytes[i]) {
Logger.Error("Not a babylon environment map");
return null;
}
}
let manifestString = "";
let charCode = 0;
while (charCode = dataView.getUint8(pos++)) {
manifestString += String.fromCharCode(charCode);
}
let manifest = JSON.parse(manifestString);
manifest = normalizeEnvInfo(manifest);
manifest.binaryDataPosition = pos;
if (manifest.specular) {
manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
}
return manifest;
}
function normalizeEnvInfo(info) {
if (info.version > CurrentVersion) {
throw new Error(`Unsupported babylon environment map version "${info.version}". Latest supported version is "${CurrentVersion}".`);
}
if (info.version === 2) {
return info;
}
info = { ...info, version: 2, imageType: DefaultEnvironmentTextureImageType };
return info;
}
async function CreateEnvTextureAsync(texture, options = {}) {
const internalTexture = texture.getInternalTexture();
if (!internalTexture) {
return await Promise.reject("The cube texture is invalid.");
}
const engine = internalTexture.getEngine();
if (texture.textureType !== 2 && texture.textureType !== 1 && texture.textureType !== 0 && texture.textureType !== 0 && texture.textureType !== 7 && texture.textureType !== -1) {
return await Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
}
let textureType = 1;
if (!engine.getCaps().textureFloatRender) {
textureType = 2;
if (!engine.getCaps().textureHalfFloatRender) {
return await Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
}
}
texture.sphericalPolynomial;
const sphericalPolynomialPromise = texture.getInternalTexture()?._sphericalPolynomialPromise;
const cubeWidth = internalTexture.width;
const hostingScene = new Scene(engine);
const specularTextures = {};
const diffuseTextures = {};
engine.flushFramebuffer();
const imageType = options.imageType ?? DefaultEnvironmentTextureImageType;
const mipmapsCount = ILog2(internalTexture.width);
for (let i = 0; i <= mipmapsCount; i++) {
const faceWidth = Math.pow(2, mipmapsCount - i);
for (let face = 0; face < 6; face++) {
specularTextures[i * 6 + face] = await _GetTextureEncodedDataAsync(hostingScene, texture, textureType, face, i, faceWidth, imageType, options.imageQuality);
}
}
const irradianceTexture = options.disableIrradianceTexture ? null : texture.irradianceTexture;
if (irradianceTexture) {
const faceWidth = irradianceTexture.getSize().width;
for (let face = 0; face < 6; face++) {
diffuseTextures[face] = await _GetTextureEncodedDataAsync(hostingScene, irradianceTexture, textureType, face, 0, faceWidth, imageType, options.imageQuality);
}
}
hostingScene.dispose();
if (sphericalPolynomialPromise) {
await sphericalPolynomialPromise;
}
const info = {
version: CurrentVersion,
width: cubeWidth,
imageType,
irradiance: CreateEnvTextureIrradiance(texture),
specular: {
mipmaps: [],
lodGenerationScale: texture.lodGenerationScale
}
};
let position = 0;
for (let i = 0; i <= mipmapsCount; i++) {
for (let face = 0; face < 6; face++) {
const byteLength = specularTextures[i * 6 + face].byteLength;
info.specular.mipmaps.push({
length: byteLength,
position
});
position += byteLength;
}
}
if (irradianceTexture) {
info.irradiance = info.irradiance || {
x: [0, 0, 0],
xx: [0, 0, 0],
y: [0, 0, 0],
yy: [0, 0, 0],
z: [0, 0, 0],
zz: [0, 0, 0],
yz: [0, 0, 0],
zx: [0, 0, 0],
xy: [0, 0, 0]
};
info.irradiance.irradianceTexture = {
size: irradianceTexture.getSize().width,
faces: [],
dominantDirection: irradianceTexture._dominantDirection?.asArray()
};
for (let face = 0; face < 6; face++) {
const byteLength = diffuseTextures[face].byteLength;
info.irradiance.irradianceTexture.faces.push({
length: byteLength,
position
});
position += byteLength;
}
}
const infoString = JSON.stringify(info);
const infoBuffer = new ArrayBuffer(infoString.length + 1);
const infoView = new Uint8Array(infoBuffer);
for (let i = 0, strLen = infoString.length; i < strLen; i++) {
infoView[i] = infoString.charCodeAt(i);
}
infoView[infoString.length] = 0;
const totalSize = MagicBytes.length + position + infoBuffer.byteLength;
const finalBuffer = new ArrayBuffer(totalSize);
const finalBufferView = new Uint8Array(finalBuffer);
const dataView = new DataView(finalBuffer);
let pos = 0;
for (let i = 0; i < MagicBytes.length; i++) {
dataView.setUint8(pos++, MagicBytes[i]);
}
finalBufferView.set(new Uint8Array(infoBuffer), pos);
pos += infoBuffer.byteLength;
for (let i = 0; i <= mipmapsCount; i++) {
for (let face = 0; face < 6; face++) {
const dataBuffer = specularTextures[i * 6 + face];
finalBufferView.set(new Uint8Array(dataBuffer), pos);
pos += dataBuffer.byteLength;
}
}
if (irradianceTexture) {
for (let face = 0; face < 6; face++) {
const dataBuffer = diffuseTextures[face];
finalBufferView.set(new Uint8Array(dataBuffer), pos);
pos += dataBuffer.byteLength;
}
}
return finalBuffer;
}
async function _GetTextureEncodedDataAsync(hostingScene, texture, textureType, face, i, size, imageType, imageQuality) {
let faceData = await texture.readPixels(face, i, void 0, false);
if (faceData && faceData.byteLength === faceData.length) {
const faceDataFloat = new Float32Array(faceData.byteLength * 4);
for (let i2 = 0; i2 < faceData.byteLength; i2++) {
faceDataFloat[i2] = faceData[i2] / 255;
faceDataFloat[i2] = Math.pow(faceDataFloat[i2], 2.2);
}
faceData = faceDataFloat;
} else if (faceData && texture.gammaSpace) {
const floatData = faceData;
for (let i2 = 0; i2 < floatData.length; i2++) {
floatData[i2] = Math.pow(floatData[i2], 2.2);
}
}
const engine = hostingScene.getEngine();
const tempTexture = engine.createRawTexture(faceData, size, size, 5, false, true, 1, null, textureType);
await RGBDTextureTools.EncodeTextureToRGBD(tempTexture, hostingScene, textureType);
const rgbdEncodedData = await engine._readTexturePixels(tempTexture, size, size);
const imageEncodedData = await DumpDataAsync(size, size, rgbdEncodedData, imageType, void 0, false, true, imageQuality);
tempTexture.dispose();
return imageEncodedData;
}
function CreateEnvTextureIrradiance(texture) {
const polynmials = texture.sphericalPolynomial;
if (polynmials == null) {
return null;
}
return {
x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
};
}
function CreateRadianceImageDataArrayBufferViews(data, info) {
info = normalizeEnvInfo(info);
const specularInfo = info.specular;
let mipmapsCount = Math.log2(info.width);
mipmapsCount = Math.round(mipmapsCount) + 1;
if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
throw new Error(`Unsupported specular mipmaps number "${specularInfo.mipmaps.length}"`);
}
const imageData = new Array(mipmapsCount);
for (let i = 0; i < mipmapsCount; i++) {
imageData[i] = new Array(6);
for (let face = 0; face < 6; face++) {
const imageInfo = specularInfo.mipmaps[i * 6 + face];
imageData[i][face] = new Uint8Array(data.buffer, data.byteOffset + info.binaryDataPosition + imageInfo.position, imageInfo.length);
}
}
return imageData;
}
function CreateIrradianceImageDataArrayBufferViews(data, info) {
info = normalizeEnvInfo(info);
const imageData = new Array(6);
const irradianceTexture = info.irradiance?.irradianceTexture;
if (irradianceTexture) {
if (irradianceTexture.faces.length !== 6) {
throw new Error(`Incorrect irradiance texture faces number "${irradianceTexture.faces.length}"`);
}
for (let face = 0; face < 6; face++) {
const imageInfo = irradianceTexture.faces[face];
imageData[face] = new Uint8Array(data.buffer, data.byteOffset + info.binaryDataPosition + imageInfo.position, imageInfo.length);
}
}
return imageData;
}
function UploadEnvLevelsAsync(texture, data, info) {
info = normalizeEnvInfo(info);
const specularInfo = info.specular;
if (!specularInfo) {
return Promise.resolve([]);
}
texture._lodGenerationScale = specularInfo.lodGenerationScale;
const promises = [];
const radianceImageData = CreateRadianceImageDataArrayBufferViews(data, info);
promises.push(UploadRadianceLevelsAsync(texture, radianceImageData, info.imageType));
const irradianceTexture = info.irradiance?.irradianceTexture;
if (irradianceTexture) {
const irradianceImageData = CreateIrradianceImageDataArrayBufferViews(data, info);
let dominantDirection = null;
if (info.irradiance?.irradianceTexture?.dominantDirection) {
dominantDirection = Vector3.FromArray(info.irradiance.irradianceTexture.dominantDirection);
}
promises.push(UploadIrradianceLevelsAsync(texture, irradianceImageData, irradianceTexture.size, info.imageType, dominantDirection));
}
return Promise.all(promises);
}
async function _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture) {
return await new Promise((resolve, reject) => {
if (expandTexture) {
const tempTexture = engine.createTexture(null, true, true, null, 1, null, (message) => {
reject(message);
}, image);
rgbdPostProcess?.onEffectCreatedObservable.addOnce((effect) => {
effect.executeWhenCompiled(() => {
rgbdPostProcess.externalTextureSamplerBinding = true;
rgbdPostProcess.onApply = (effect2) => {
effect2._bindTexture("textureSampler", tempTexture);
effect2.setFloat2("scale", 1, engine._features.needsInvertingBitmap && image instanceof ImageBitmap ? -1 : 1);
};
if (!engine.scenes.length) {
return;
}
engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
engine.restoreDefaultFramebuffer();
tempTexture.dispose();
URL.revokeObjectURL(url);
resolve();
});
});
} else {
engine._uploadImageToTexture(texture, image, face, i);
if (generateNonLODTextures) {
const lodTexture = lodTextures[i];
if (lodTexture) {
engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
}
}
resolve();
}
});
}
async function UploadRadianceLevelsAsync(texture, imageData, imageType = DefaultEnvironmentTextureImageType) {
const engine = texture.getEngine();
texture.format = 5;
texture.type = 0;
texture.generateMipMaps = true;
texture._cachedAnisotropicFilteringLevel = null;
engine.updateTextureSamplingMode(3, texture);
await _UploadLevelsAsync(texture, imageData, true, imageType);
texture.isReady = true;
}
async function UploadIrradianceLevelsAsync(mainTexture, imageData, size, imageType = DefaultEnvironmentTextureImageType, dominantDirection = null) {
const engine = mainTexture.getEngine();
const texture = new InternalTexture(
engine,
5
/* InternalTextureSource.RenderTarget */
);
const baseTexture = new BaseTexture(engine, texture);
mainTexture._irradianceTexture = baseTexture;
baseTexture._dominantDirection = dominantDirection;
texture.isCube = true;
texture.format = 5;
texture.type = 0;
texture.generateMipMaps = true;
texture._cachedAnisotropicFilteringLevel = null;
texture.generateMipMaps = true;
texture.width = size;
texture.height = size;
engine.updateTextureSamplingMode(3, texture);
await _UploadLevelsAsync(texture, [imageData], false, imageType);
engine.generateMipMapsForCubemap(texture);
texture.isReady = true;
}
async function _UploadLevelsAsync(texture, imageData, canGenerateNonLODTextures, imageType = DefaultEnvironmentTextureImageType) {
if (!Tools.IsExponentOfTwo(texture.width)) {
throw new Error("Texture size must be a power of two");
}
const mipmapsCount = ILog2(texture.width) + 1;
const engine = texture.getEngine();
let expandTexture = false;
let generateNonLODTextures = false;
let rgbdPostProcess = null;
let cubeRtt = null;
let lodTextures = null;
const caps = engine.getCaps();
if (!caps.textureLOD) {
expandTexture = false;
generateNonLODTextures = canGenerateNonLODTextures;
} else if (!engine._features.supportRenderAndCopyToLodForFloatTextures) {
expandTexture = false;
} else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
expandTexture = true;
texture.type = 2;
} else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
expandTexture = true;
texture.type = 1;
}
let shaderLanguage = 0;
if (expandTexture) {
if (engine.isWebGPU) {
shaderLanguage = 1;
await Promise.resolve().then(() => (init_rgbdDecode_fragment(), rgbdDecode_fragment_exports));
} else {
await Promise.resolve().then(() => (init_rgbdDecode_fragment2(), rgbdDecode_fragment_exports2));
}
rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, void 0, texture.type, void 0, null, false, void 0, shaderLanguage);
texture._isRGBD = false;
texture.invertY = false;
cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
generateDepthBuffer: false,
generateMipMaps: true,
generateStencilBuffer: false,
samplingMode: 3,
type: texture.type,
format: 5
});
} else {
texture._isRGBD = true;
texture.invertY = true;
if (generateNonLODTextures) {
const mipSlices = 3;
lodTextures = {};
const scale = texture._lodGenerationScale;
const offset = texture._lodGenerationOffset;
for (let i = 0; i < mipSlices; i++) {
const smoothness = i / (mipSlices - 1);
const roughness = 1 - smoothness;
const minLODIndex = offset;
const maxLODIndex = (mipmapsCount - 1) * scale + offset;
const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
const glTextureFromLod = new InternalTexture(
engine,
2
/* InternalTextureSource.Temp */
);
glTextureFromLod.isCube = true;
glTextureFromLod.invertY = true;
glTextureFromLod.generateMipMaps = false;
engine.updateTextureSamplingMode(2, glTextureFromLod);
const lodTexture = new BaseTexture(null);
lodTexture._isCube = true;
lodTexture._texture = glTextureFromLod;
lodTextures[mipmapIndex] = lodTexture;
switch (i) {
case 0:
texture._lodTextureLow = lodTexture;
break;
case 1:
texture._lodTextureMid = lodTexture;
break;
case 2:
texture._lodTextureHigh = lodTexture;
break;
}
}
}
}
const promises = [];
for (let i = 0; i < imageData.length; i++) {
for (let face = 0; face < 6; face++) {
const bytes = imageData[i][face];
const blob = new Blob([bytes], { type: imageType });
const url = URL.createObjectURL(blob);
let promise;
if (engine._features.forceBitmapOverHTMLImageElement) {
promise = engine.createImageBitmap(blob, { premultiplyAlpha: "none" }).then(async (img) => {
return await _OnImageReadyAsync(img, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture);
});
} else {
const image = new Image();
image.src = url;
promise = new Promise((resolve, reject) => {
image.onload = () => {
_OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture).then(() => resolve()).catch((reason) => {
reject(reason);
});
};
image.onerror = (error) => {
reject(error);
};
});
}
promises.push(promise);
}
}
await Promise.all(promises);
if (imageData.length < mipmapsCount) {
let data;
const size = Math.pow(2, mipmapsCount - 1 - imageData.length);
const dataLength = size * size * 4;
switch (texture.type) {
case 0: {
data = new Uint8Array(dataLength);
break;
}
case 2: {
data = new Uint16Array(dataLength);
break;
}
case 1: {
data = new Float32Array(dataLength);
break;
}
}
for (let i = imageData.length; i < mipmapsCount; i++) {
for (let face = 0; face < 6; face++) {
engine._uploadArrayBufferViewToTexture(cubeRtt?.texture || texture, data, face, i);
}
}
}
if (cubeRtt) {
const irradiance = texture._irradianceTexture;
texture._irradianceTexture = null;
engine._releaseTexture(texture);
cubeRtt._swapAndDie(texture);
texture._irradianceTexture = irradiance;
}
if (rgbdPostProcess) {
rgbdPostProcess.dispose();
}
if (generateNonLODTextures) {
if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
texture._lodTextureHigh._texture.isReady = true;
}
if (texture._lodTextureMid && texture._lodTextureMid._texture) {
texture._lodTextureMid._texture.isReady = true;
}
if (texture._lodTextureLow && texture._lodTextureLow._texture) {
texture._lodTextureLow._texture.isReady = true;
}
}
}
function UploadEnvSpherical(texture, info) {
info = normalizeEnvInfo(info);
const irradianceInfo = info.irradiance;
if (!irradianceInfo) {
return;
}
const sp = new SphericalPolynomial();
Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
texture._sphericalPolynomial = sp;
}
function _UpdateRGBDAsync(internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
const proxy = internalTexture.getEngine().createRawCubeTexture(null, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
const proxyPromise = UploadRadianceLevelsAsync(proxy, data).then(() => internalTexture);
internalTexture.onRebuildCallback = (_internalTexture) => {
return {
proxy: proxyPromise,
isReady: true,
isAsync: true
};
};
internalTexture._source = 13;
internalTexture._bufferViewArrayArray = data;
internalTexture._lodGenerationScale = lodScale;
internalTexture._lodGenerationOffset = lodOffset;
internalTexture._sphericalPolynomial = sphericalPolynomial;
return UploadRadianceLevelsAsync(internalTexture, data).then(() => {
internalTexture.isReady = true;
return internalTexture;
});
}
var DefaultEnvironmentTextureImageType, CurrentVersion, MagicBytes, EnvironmentTextureTools;
var init_environmentTextureTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/environmentTextureTools.js"() {
init_tools();
init_math_vector();
init_math_scalar_functions();
init_sphericalPolynomial();
init_internalTexture();
init_baseTexture();
init_scene();
init_postProcess();
init_logger();
init_rgbdTextureTools();
init_dumpTools();
init_baseTexture_polynomial();
DefaultEnvironmentTextureImageType = "image/png";
CurrentVersion = 2;
MagicBytes = [134, 22, 135, 150, 246, 214, 150, 54];
__name(GetEnvInfo, "GetEnvInfo");
__name(normalizeEnvInfo, "normalizeEnvInfo");
__name(CreateEnvTextureAsync, "CreateEnvTextureAsync");
__name(_GetTextureEncodedDataAsync, "_GetTextureEncodedDataAsync");
__name(CreateEnvTextureIrradiance, "CreateEnvTextureIrradiance");
__name(CreateRadianceImageDataArrayBufferViews, "CreateRadianceImageDataArrayBufferViews");
__name(CreateIrradianceImageDataArrayBufferViews, "CreateIrradianceImageDataArrayBufferViews");
__name(UploadEnvLevelsAsync, "UploadEnvLevelsAsync");
__name(_OnImageReadyAsync, "_OnImageReadyAsync");
__name(UploadRadianceLevelsAsync, "UploadRadianceLevelsAsync");
__name(UploadIrradianceLevelsAsync, "UploadIrradianceLevelsAsync");
__name(_UploadLevelsAsync, "_UploadLevelsAsync");
__name(UploadEnvSpherical, "UploadEnvSpherical");
__name(_UpdateRGBDAsync, "_UpdateRGBDAsync");
EnvironmentTextureTools = {
/**
* Gets the environment info from an env file.
* @param data The array buffer containing the .env bytes.
* @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version.
*/
GetEnvInfo,
/**
* Creates an environment texture from a loaded cube texture.
* @param texture defines the cube texture to convert in env file
* @param options options for the conversion process
* @param options.imageType the mime type for the encoded images, with support for "image/png" (default) and "image/webp"
* @param options.imageQuality the image quality of encoded WebP images.
* @returns a promise containing the environment data if successful.
*/
CreateEnvTextureAsync,
/**
* Creates the ArrayBufferViews used for initializing environment texture image data.
* @param data the image data
* @param info parameters that determine what views will be created for accessing the underlying buffer
* @returns the views described by info providing access to the underlying buffer
*/
CreateRadianceImageDataArrayBufferViews,
/**
* Creates the ArrayBufferViews used for initializing environment texture image data.
* @param data the image data
* @param info parameters that determine what views will be created for accessing the underlying buffer
* @returns the views described by info providing access to the underlying buffer
*/
CreateIrradianceImageDataArrayBufferViews,
/**
* Uploads the texture info contained in the env file to the GPU.
* @param texture defines the internal texture to upload to
* @param data defines the data to load
* @param info defines the texture info retrieved through the GetEnvInfo method
* @returns a promise
*/
UploadEnvLevelsAsync,
/**
* Uploads the levels of image data to the GPU.
* @param texture defines the internal texture to upload to
* @param imageData defines the array buffer views of image data [mipmap][face]
* @param imageType the mime type of the image data
* @returns a promise
*/
UploadRadianceLevelsAsync,
/**
* Uploads the levels of image data to the GPU.
* @param texture defines the internal texture to upload to
* @param imageData defines the array buffer views of image data [mipmap][face]
* @param imageType the mime type of the image data
* @param dominantDirection the dominant direction of light in the environment texture, if available
* @returns a promise
*/
UploadIrradianceLevelsAsync,
/**
* Uploads spherical polynomials information to the texture.
* @param texture defines the texture we are trying to upload the information to
* @param info defines the environment texture info retrieved through the GetEnvInfo method
*/
UploadEnvSpherical
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/envTextureLoader.js
var envTextureLoader_exports = {};
__export(envTextureLoader_exports, {
_ENVTextureLoader: () => _ENVTextureLoader
});
var _ENVTextureLoader;
var init_envTextureLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/envTextureLoader.js"() {
init_environmentTextureTools();
_ENVTextureLoader = class {
static {
__name(this, "_ENVTextureLoader");
}
constructor() {
this.supportCascades = false;
}
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
* @param onError defines the callback to trigger in case of error
*/
loadCubeData(data, texture, createPolynomials, onLoad, onError) {
if (Array.isArray(data)) {
return;
}
const info = GetEnvInfo(data);
if (info) {
texture.width = info.width;
texture.height = info.width;
try {
UploadEnvSpherical(texture, info);
UploadEnvLevelsAsync(texture, data, info).then(() => {
texture.isReady = true;
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
}, (reason) => {
onError?.("Can not upload environment levels", reason);
});
} catch (e) {
onError?.("Can not upload environment file", e);
}
} else if (onError) {
onError("Can not parse the environment file", null);
}
}
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
*/
loadData() {
throw ".env not supported in 2d.";
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/panoramaToCubemap.js
var PanoramaToCubeMapTools;
var init_panoramaToCubemap = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/panoramaToCubemap.js"() {
init_math_vector();
PanoramaToCubeMapTools = class {
static {
__name(this, "PanoramaToCubeMapTools");
}
/**
* Converts a panorama stored in RGB right to left up to down format into a cubemap (6 faces).
*
* @param float32Array The source data.
* @param inputWidth The width of the input panorama.
* @param inputHeight The height of the input panorama.
* @param size The willing size of the generated cubemap (each faces will be size * size pixels)
* @param supersample enable supersampling the cubemap
* @param invertY defines if the Y axis must be inverted
* @returns The cubemap data
*/
static ConvertPanoramaToCubemap(float32Array, inputWidth, inputHeight, size, supersample = false, invertY = true) {
if (!float32Array) {
throw "ConvertPanoramaToCubemap: input cannot be null";
}
let stride = 0;
if (float32Array.length != inputWidth * inputHeight * 3) {
if (float32Array.length != inputWidth * inputHeight * 4) {
throw "ConvertPanoramaToCubemap: input size is wrong";
} else {
stride = 4;
}
} else {
stride = 3;
}
const textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight, supersample, invertY, stride);
const textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight, supersample, invertY, stride);
const textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight, supersample, invertY, stride);
const textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight, supersample, invertY, stride);
const textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight, supersample, invertY, stride);
const textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight, supersample, invertY, stride);
return {
front: textureFront,
back: textureBack,
left: textureLeft,
right: textureRight,
up: textureUp,
down: textureDown,
size,
type: 1,
format: 4,
gammaSpace: false
};
}
static CreateCubemapTexture(texSize, faceData, float32Array, inputWidth, inputHeight, supersample, invertY, stride) {
const buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
const textureArray = new Float32Array(buffer);
const samples = supersample ? Math.max(1, Math.round(inputWidth / 4 / texSize)) : 1;
const sampleFactor = 1 / samples;
const sampleFactorSqr = sampleFactor * sampleFactor;
const rotDX1 = faceData[1].subtract(faceData[0]).scale(sampleFactor / texSize);
const rotDX2 = faceData[3].subtract(faceData[2]).scale(sampleFactor / texSize);
const dy = 1 / texSize;
let fy = 0;
for (let y = 0; y < texSize; y++) {
for (let sy = 0; sy < samples; sy++) {
let xv1 = faceData[0];
let xv2 = faceData[2];
for (let x = 0; x < texSize; x++) {
for (let sx = 0; sx < samples; sx++) {
const v = xv2.subtract(xv1).scale(fy).add(xv1);
v.normalize();
const color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight, stride, invertY);
textureArray[y * texSize * 3 + x * 3 + 0] += color.r * sampleFactorSqr;
textureArray[y * texSize * 3 + x * 3 + 1] += color.g * sampleFactorSqr;
textureArray[y * texSize * 3 + x * 3 + 2] += color.b * sampleFactorSqr;
xv1 = xv1.add(rotDX1);
xv2 = xv2.add(rotDX2);
}
}
fy += dy * sampleFactor;
}
}
return textureArray;
}
static CalcProjectionSpherical(vDir, float32Array, inputWidth, inputHeight, stride, invertY) {
let theta = Math.atan2(vDir.z, vDir.x);
const phi = Math.acos(vDir.y);
while (theta < -Math.PI) {
theta += 2 * Math.PI;
}
while (theta > Math.PI) {
theta -= 2 * Math.PI;
}
let dx = theta / Math.PI;
const dy = phi / Math.PI;
dx = dx * 0.5 + 0.5;
let px = Math.round(dx * inputWidth);
if (px < 0) {
px = 0;
} else if (px >= inputWidth) {
px = inputWidth - 1;
}
let py = Math.round(dy * inputHeight);
if (py < 0) {
py = 0;
} else if (py >= inputHeight) {
py = inputHeight - 1;
}
const inputY = invertY ? inputHeight - py - 1 : py;
const r = float32Array[inputY * inputWidth * stride + px * stride + 0];
const g = float32Array[inputY * inputWidth * stride + px * stride + 1];
const b = float32Array[inputY * inputWidth * stride + px * stride + 2];
return {
r,
g,
b
};
}
};
PanoramaToCubeMapTools.FACE_LEFT = [new Vector3(-1, -1, -1), new Vector3(1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1)];
PanoramaToCubeMapTools.FACE_RIGHT = [new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(1, 1, 1), new Vector3(-1, 1, 1)];
PanoramaToCubeMapTools.FACE_FRONT = [new Vector3(1, -1, -1), new Vector3(1, -1, 1), new Vector3(1, 1, -1), new Vector3(1, 1, 1)];
PanoramaToCubeMapTools.FACE_BACK = [new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(-1, 1, 1), new Vector3(-1, 1, -1)];
PanoramaToCubeMapTools.FACE_DOWN = [new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1)];
PanoramaToCubeMapTools.FACE_UP = [new Vector3(-1, -1, -1), new Vector3(-1, -1, 1), new Vector3(1, -1, -1), new Vector3(1, -1, 1)];
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/hdr.js
function Ldexp(mantissa, exponent) {
if (exponent > 1023) {
return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
}
if (exponent < -1074) {
return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
}
return mantissa * Math.pow(2, exponent);
}
function Rgbe2float(float32array, red, green, blue, exponent, index) {
if (exponent > 0) {
exponent = Ldexp(1, exponent - (128 + 8));
float32array[index + 0] = red * exponent;
float32array[index + 1] = green * exponent;
float32array[index + 2] = blue * exponent;
} else {
float32array[index + 0] = 0;
float32array[index + 1] = 0;
float32array[index + 2] = 0;
}
}
function ReadStringLine(uint8array, startIndex) {
let line = "";
let character = "";
for (let i = startIndex; i < uint8array.length - startIndex; i++) {
character = String.fromCharCode(uint8array[i]);
if (character == "\n") {
break;
}
line += character;
}
return line;
}
function RGBE_ReadHeader(uint8array) {
let height = 0;
let width = 0;
let line = ReadStringLine(uint8array, 0);
if (line[0] != "#" || line[1] != "?") {
throw "Bad HDR Format.";
}
let endOfHeader = false;
let findFormat = false;
let lineIndex = 0;
do {
lineIndex += line.length + 1;
line = ReadStringLine(uint8array, lineIndex);
if (line == "FORMAT=32-bit_rle_rgbe") {
findFormat = true;
} else if (line.length == 0) {
endOfHeader = true;
}
} while (!endOfHeader);
if (!findFormat) {
throw "HDR Bad header format, unsupported FORMAT";
}
lineIndex += line.length + 1;
line = ReadStringLine(uint8array, lineIndex);
const sizeRegexp = /^-Y (.*) \+X (.*)$/g;
const match = sizeRegexp.exec(line);
if (!match || match.length < 3) {
throw "HDR Bad header format, no size";
}
width = parseInt(match[2]);
height = parseInt(match[1]);
if (width < 8 || width > 32767) {
throw "HDR Bad header format, unsupported size";
}
lineIndex += line.length + 1;
return {
height,
width,
dataPosition: lineIndex
};
}
function GetCubeMapTextureData(buffer, size, supersample = false) {
const uint8array = new Uint8Array(buffer);
const hdrInfo = RGBE_ReadHeader(uint8array);
const data = RGBE_ReadPixels(uint8array, hdrInfo);
const cubeMapData = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size, supersample);
return cubeMapData;
}
function RGBE_ReadPixels(uint8array, hdrInfo) {
return ReadRGBEPixelsRLE(uint8array, hdrInfo);
}
function ReadRGBEPixelsRLE(uint8array, hdrInfo) {
let numScanlines = hdrInfo.height;
const scanlineWidth = hdrInfo.width;
let a, b, c, d, count;
let dataIndex = hdrInfo.dataPosition;
let index = 0, endIndex = 0, i = 0;
const scanLineArrayBuffer = new ArrayBuffer(scanlineWidth * 4);
const scanLineArray = new Uint8Array(scanLineArrayBuffer);
const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
const resultArray = new Float32Array(resultBuffer);
while (numScanlines > 0) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
c = uint8array[dataIndex++];
d = uint8array[dataIndex++];
if (a != 2 || b != 2 || c & 128 || hdrInfo.width < 8 || hdrInfo.width > 32767) {
return ReadRGBEPixelsNotRLE(uint8array, hdrInfo);
}
if ((c << 8 | d) != scanlineWidth) {
throw "HDR Bad header format, wrong scan line width";
}
index = 0;
for (i = 0; i < 4; i++) {
endIndex = (i + 1) * scanlineWidth;
while (index < endIndex) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
if (a > 128) {
count = a - 128;
if (count == 0 || count > endIndex - index) {
throw "HDR Bad Format, bad scanline data (run)";
}
while (count-- > 0) {
scanLineArray[index++] = b;
}
} else {
count = a;
if (count == 0 || count > endIndex - index) {
throw "HDR Bad Format, bad scanline data (non-run)";
}
scanLineArray[index++] = b;
if (--count > 0) {
for (let j = 0; j < count; j++) {
scanLineArray[index++] = uint8array[dataIndex++];
}
}
}
}
}
for (i = 0; i < scanlineWidth; i++) {
a = scanLineArray[i];
b = scanLineArray[i + scanlineWidth];
c = scanLineArray[i + 2 * scanlineWidth];
d = scanLineArray[i + 3 * scanlineWidth];
Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - numScanlines) * scanlineWidth * 3 + i * 3);
}
numScanlines--;
}
return resultArray;
}
function ReadRGBEPixelsNotRLE(uint8array, hdrInfo) {
let numScanlines = hdrInfo.height;
const scanlineWidth = hdrInfo.width;
let a, b, c, d, i;
let dataIndex = hdrInfo.dataPosition;
const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
const resultArray = new Float32Array(resultBuffer);
while (numScanlines > 0) {
for (i = 0; i < hdrInfo.width; i++) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
c = uint8array[dataIndex++];
d = uint8array[dataIndex++];
Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - numScanlines) * scanlineWidth * 3 + i * 3);
}
numScanlines--;
}
return resultArray;
}
var HDRTools;
var init_hdr = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/hdr.js"() {
init_panoramaToCubemap();
__name(Ldexp, "Ldexp");
__name(Rgbe2float, "Rgbe2float");
__name(ReadStringLine, "ReadStringLine");
__name(RGBE_ReadHeader, "RGBE_ReadHeader");
__name(GetCubeMapTextureData, "GetCubeMapTextureData");
__name(RGBE_ReadPixels, "RGBE_ReadPixels");
__name(ReadRGBEPixelsRLE, "ReadRGBEPixelsRLE");
__name(ReadRGBEPixelsNotRLE, "ReadRGBEPixelsNotRLE");
HDRTools = {
// eslint-disable-next-line @typescript-eslint/naming-convention
RGBE_ReadHeader,
// eslint-disable-next-line @typescript-eslint/naming-convention
GetCubeMapTextureData,
// eslint-disable-next-line @typescript-eslint/naming-convention
RGBE_ReadPixels
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/hdrTextureLoader.js
var hdrTextureLoader_exports = {};
__export(hdrTextureLoader_exports, {
_HDRTextureLoader: () => _HDRTextureLoader
});
var _HDRTextureLoader;
var init_hdrTextureLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/hdrTextureLoader.js"() {
init_hdr();
_HDRTextureLoader = class {
static {
__name(this, "_HDRTextureLoader");
}
constructor() {
this.supportCascades = false;
}
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* Cube texture are not supported by .hdr files
*/
loadCubeData() {
throw ".hdr not supported in Cube.";
}
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
loadData(data, texture, callback) {
const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
const hdrInfo = RGBE_ReadHeader(uint8array);
const pixelsDataRGB32 = RGBE_ReadPixels(uint8array, hdrInfo);
const pixels = hdrInfo.width * hdrInfo.height;
const pixelsDataRGBA32 = new Float32Array(pixels * 4);
for (let i = 0; i < pixels; i += 1) {
pixelsDataRGBA32[i * 4] = pixelsDataRGB32[i * 3];
pixelsDataRGBA32[i * 4 + 1] = pixelsDataRGB32[i * 3 + 1];
pixelsDataRGBA32[i * 4 + 2] = pixelsDataRGB32[i * 3 + 2];
pixelsDataRGBA32[i * 4 + 3] = 1;
}
callback(hdrInfo.width, hdrInfo.height, texture.generateMipMaps, false, () => {
const engine = texture.getEngine();
texture.type = 1;
texture.format = 5;
texture._gammaSpace = false;
engine._uploadDataToTextureDirectly(texture, pixelsDataRGBA32);
});
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer.js
var KhronosTextureContainer;
var init_khronosTextureContainer = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer.js"() {
init_logger();
KhronosTextureContainer = class _KhronosTextureContainer {
static {
__name(this, "KhronosTextureContainer");
}
/**
* Creates a new KhronosTextureContainer
* @param data contents of the KTX container file
* @param facesExpected should be either 1 or 6, based whether a cube texture or or
*/
constructor(data, facesExpected) {
this.data = data;
this.isInvalid = false;
if (!_KhronosTextureContainer.IsValid(data)) {
this.isInvalid = true;
Logger.Error("texture missing KTX identifier");
return;
}
const dataSize = Uint32Array.BYTES_PER_ELEMENT;
const headerDataView = new DataView(this.data.buffer, this.data.byteOffset + 12, 13 * dataSize);
const endianness = headerDataView.getUint32(0, true);
const littleEndian = endianness === 67305985;
this.glType = headerDataView.getUint32(1 * dataSize, littleEndian);
this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian);
this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian);
this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian);
this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian);
this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian);
this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian);
this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian);
this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian);
this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian);
this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian);
this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian);
if (this.glType !== 0) {
Logger.Error("only compressed formats currently supported");
this.isInvalid = true;
return;
} else {
this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
}
if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
Logger.Error("only 2D textures currently supported");
this.isInvalid = true;
return;
}
if (this.numberOfArrayElements !== 0) {
Logger.Error("texture arrays not currently supported");
this.isInvalid = true;
return;
}
if (this.numberOfFaces !== facesExpected) {
Logger.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
this.isInvalid = true;
return;
}
this.loadType = _KhronosTextureContainer.COMPRESSED_2D;
}
/**
* Uploads KTX content to a Babylon Texture.
* It is assumed that the texture has already been created & is currently bound
* @internal
*/
uploadLevels(texture, loadMipmaps) {
switch (this.loadType) {
case _KhronosTextureContainer.COMPRESSED_2D:
this._upload2DCompressedLevels(texture, loadMipmaps);
break;
case _KhronosTextureContainer.TEX_2D:
case _KhronosTextureContainer.COMPRESSED_3D:
case _KhronosTextureContainer.TEX_3D:
}
}
_upload2DCompressedLevels(texture, loadMipmaps) {
let dataOffset = _KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
let width = this.pixelWidth;
let height = this.pixelHeight;
const mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
for (let level = 0; level < mipmapCount; level++) {
const imageSize = new Int32Array(this.data.buffer, this.data.byteOffset + dataOffset, 1)[0];
dataOffset += 4;
for (let face = 0; face < this.numberOfFaces; face++) {
const byteArray = new Uint8Array(this.data.buffer, this.data.byteOffset + dataOffset, imageSize);
const engine = texture.getEngine();
engine._uploadCompressedDataToTextureDirectly(texture, texture.format, width, height, byteArray, face, level);
dataOffset += imageSize;
dataOffset += 3 - (imageSize + 3) % 4;
}
width = Math.max(1, width * 0.5);
height = Math.max(1, height * 0.5);
}
}
/**
* Checks if the given data starts with a KTX file identifier.
* @param data the data to check
* @returns true if the data is a KTX file or false otherwise
*/
static IsValid(data) {
if (data.byteLength >= 12) {
const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);
if (identifier[0] === 171 && identifier[1] === 75 && identifier[2] === 84 && identifier[3] === 88 && identifier[4] === 32 && identifier[5] === 49 && identifier[6] === 49 && identifier[7] === 187 && identifier[8] === 13 && identifier[9] === 10 && identifier[10] === 26 && identifier[11] === 10) {
return true;
}
}
return false;
}
};
KhronosTextureContainer.HEADER_LEN = 12 + 13 * 4;
KhronosTextureContainer.COMPRESSED_2D = 0;
KhronosTextureContainer.COMPRESSED_3D = 1;
KhronosTextureContainer.TEX_2D = 2;
KhronosTextureContainer.TEX_3D = 3;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/workerPool.js
var WorkerPool, AutoReleaseWorkerPool;
var init_workerPool = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/workerPool.js"() {
WorkerPool = class {
static {
__name(this, "WorkerPool");
}
/**
* Constructor
* @param workers Array of workers to use for actions
*/
constructor(workers) {
this._pendingActions = new Array();
this._workerInfos = workers.map((worker) => ({
workerPromise: Promise.resolve(worker),
idle: true
}));
}
/**
* Terminates all workers and clears any pending actions.
*/
dispose() {
for (const workerInfo of this._workerInfos) {
workerInfo.workerPromise.then((worker) => {
worker.terminate();
});
}
this._workerInfos.length = 0;
this._pendingActions.length = 0;
}
/**
* Pushes an action to the worker pool. If all the workers are active, the action will be
* pended until a worker has completed its action.
* @param action The action to perform. Call onComplete when the action is complete.
*/
push(action) {
if (!this._executeOnIdleWorker(action)) {
this._pendingActions.push(action);
}
}
_executeOnIdleWorker(action) {
for (const workerInfo of this._workerInfos) {
if (workerInfo.idle) {
this._execute(workerInfo, action);
return true;
}
}
return false;
}
_execute(workerInfo, action) {
workerInfo.idle = false;
workerInfo.workerPromise.then((worker) => {
action(worker, () => {
const nextAction = this._pendingActions.shift();
if (nextAction) {
this._execute(workerInfo, nextAction);
} else {
workerInfo.idle = true;
}
});
});
}
};
AutoReleaseWorkerPool = class _AutoReleaseWorkerPool extends WorkerPool {
static {
__name(this, "AutoReleaseWorkerPool");
}
constructor(maxWorkers, createWorkerAsync, options = _AutoReleaseWorkerPool.DefaultOptions) {
super([]);
this._maxWorkers = maxWorkers;
this._createWorkerAsync = createWorkerAsync;
this._options = options;
}
push(action) {
if (!this._executeOnIdleWorker(action)) {
if (this._workerInfos.length < this._maxWorkers) {
const workerInfo = {
workerPromise: this._createWorkerAsync(),
idle: false
};
this._workerInfos.push(workerInfo);
this._execute(workerInfo, action);
} else {
this._pendingActions.push(action);
}
}
}
_execute(workerInfo, action) {
if (workerInfo.timeoutId) {
clearTimeout(workerInfo.timeoutId);
delete workerInfo.timeoutId;
}
super._execute(workerInfo, (worker, onComplete) => {
action(worker, () => {
onComplete();
if (workerInfo.idle) {
workerInfo.timeoutId = setTimeout(() => {
workerInfo.workerPromise.then((worker2) => {
worker2.terminate();
});
const indexOf = this._workerInfos.indexOf(workerInfo);
if (indexOf !== -1) {
this._workerInfos.splice(indexOf, 1);
}
}, this._options.idleTimeElapsedBeforeRelease);
}
});
});
}
};
AutoReleaseWorkerPool.DefaultOptions = {
idleTimeElapsedBeforeRelease: 1e3
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/ktx2decoderTypes.js
var SourceTextureFormat, TranscodeTarget, EngineFormat;
var init_ktx2decoderTypes = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/ktx2decoderTypes.js"() {
(function(SourceTextureFormat2) {
SourceTextureFormat2[SourceTextureFormat2["ETC1S"] = 0] = "ETC1S";
SourceTextureFormat2[SourceTextureFormat2["UASTC4x4"] = 1] = "UASTC4x4";
})(SourceTextureFormat || (SourceTextureFormat = {}));
(function(TranscodeTarget2) {
TranscodeTarget2[TranscodeTarget2["ASTC_4X4_RGBA"] = 0] = "ASTC_4X4_RGBA";
TranscodeTarget2[TranscodeTarget2["ASTC_4x4_RGBA"] = 0] = "ASTC_4x4_RGBA";
TranscodeTarget2[TranscodeTarget2["BC7_RGBA"] = 1] = "BC7_RGBA";
TranscodeTarget2[TranscodeTarget2["BC3_RGBA"] = 2] = "BC3_RGBA";
TranscodeTarget2[TranscodeTarget2["BC1_RGB"] = 3] = "BC1_RGB";
TranscodeTarget2[TranscodeTarget2["PVRTC1_4_RGBA"] = 4] = "PVRTC1_4_RGBA";
TranscodeTarget2[TranscodeTarget2["PVRTC1_4_RGB"] = 5] = "PVRTC1_4_RGB";
TranscodeTarget2[TranscodeTarget2["ETC2_RGBA"] = 6] = "ETC2_RGBA";
TranscodeTarget2[TranscodeTarget2["ETC1_RGB"] = 7] = "ETC1_RGB";
TranscodeTarget2[TranscodeTarget2["RGBA32"] = 8] = "RGBA32";
TranscodeTarget2[TranscodeTarget2["R8"] = 9] = "R8";
TranscodeTarget2[TranscodeTarget2["RG8"] = 10] = "RG8";
})(TranscodeTarget || (TranscodeTarget = {}));
(function(EngineFormat2) {
EngineFormat2[EngineFormat2["COMPRESSED_RGBA_BPTC_UNORM_EXT"] = 36492] = "COMPRESSED_RGBA_BPTC_UNORM_EXT";
EngineFormat2[EngineFormat2["COMPRESSED_RGBA_ASTC_4X4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4X4_KHR";
EngineFormat2[EngineFormat2["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
EngineFormat2[EngineFormat2["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
EngineFormat2[EngineFormat2["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
EngineFormat2[EngineFormat2["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
EngineFormat2[EngineFormat2["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
EngineFormat2[EngineFormat2["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
EngineFormat2[EngineFormat2["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
EngineFormat2[EngineFormat2["RGBA8Format"] = 32856] = "RGBA8Format";
EngineFormat2[EngineFormat2["R8Format"] = 33321] = "R8Format";
EngineFormat2[EngineFormat2["RG8Format"] = 33323] = "RG8Format";
})(EngineFormat || (EngineFormat = {}));
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer2Worker.js
function applyConfig(urls, binariesAndModulesContainer) {
const KTX2DecoderModule = binariesAndModulesContainer?.jsDecoderModule || KTX2DECODER;
if (urls) {
if (urls.wasmBaseUrl) {
KTX2DecoderModule.Transcoder.WasmBaseUrl = urls.wasmBaseUrl;
}
if (urls.wasmUASTCToASTC) {
KTX2DecoderModule.LiteTranscoder_UASTC_ASTC.WasmModuleURL = urls.wasmUASTCToASTC;
}
if (urls.wasmUASTCToBC7) {
KTX2DecoderModule.LiteTranscoder_UASTC_BC7.WasmModuleURL = urls.wasmUASTCToBC7;
}
if (urls.wasmUASTCToRGBA_UNORM) {
KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = urls.wasmUASTCToRGBA_UNORM;
}
if (urls.wasmUASTCToRGBA_SRGB) {
KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = urls.wasmUASTCToRGBA_SRGB;
}
if (urls.wasmUASTCToR8_UNORM) {
KTX2DecoderModule.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL = urls.wasmUASTCToR8_UNORM;
}
if (urls.wasmUASTCToRG8_UNORM) {
KTX2DecoderModule.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL = urls.wasmUASTCToRG8_UNORM;
}
if (urls.jsMSCTranscoder) {
KTX2DecoderModule.MSCTranscoder.JSModuleURL = urls.jsMSCTranscoder;
}
if (urls.wasmMSCTranscoder) {
KTX2DecoderModule.MSCTranscoder.WasmModuleURL = urls.wasmMSCTranscoder;
}
if (urls.wasmZSTDDecoder) {
KTX2DecoderModule.ZSTDDecoder.WasmModuleURL = urls.wasmZSTDDecoder;
}
}
if (binariesAndModulesContainer) {
if (binariesAndModulesContainer.wasmUASTCToASTC) {
KTX2DecoderModule.LiteTranscoder_UASTC_ASTC.WasmBinary = binariesAndModulesContainer.wasmUASTCToASTC;
}
if (binariesAndModulesContainer.wasmUASTCToBC7) {
KTX2DecoderModule.LiteTranscoder_UASTC_BC7.WasmBinary = binariesAndModulesContainer.wasmUASTCToBC7;
}
if (binariesAndModulesContainer.wasmUASTCToRGBA_UNORM) {
KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToRGBA_UNORM;
}
if (binariesAndModulesContainer.wasmUASTCToRGBA_SRGB) {
KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary = binariesAndModulesContainer.wasmUASTCToRGBA_SRGB;
}
if (binariesAndModulesContainer.wasmUASTCToR8_UNORM) {
KTX2DecoderModule.LiteTranscoder_UASTC_R8_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToR8_UNORM;
}
if (binariesAndModulesContainer.wasmUASTCToRG8_UNORM) {
KTX2DecoderModule.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToRG8_UNORM;
}
if (binariesAndModulesContainer.jsMSCTranscoder) {
KTX2DecoderModule.MSCTranscoder.JSModule = binariesAndModulesContainer.jsMSCTranscoder;
}
if (binariesAndModulesContainer.wasmMSCTranscoder) {
KTX2DecoderModule.MSCTranscoder.WasmBinary = binariesAndModulesContainer.wasmMSCTranscoder;
}
if (binariesAndModulesContainer.wasmZSTDDecoder) {
KTX2DecoderModule.ZSTDDecoder.WasmBinary = binariesAndModulesContainer.wasmZSTDDecoder;
}
}
}
function workerFunction2(KTX2DecoderModule) {
if (typeof KTX2DecoderModule === "undefined" && typeof KTX2DECODER !== "undefined") {
KTX2DecoderModule = KTX2DECODER;
}
let ktx2Decoder;
onmessage = /* @__PURE__ */ __name((event) => {
if (!event.data) {
return;
}
switch (event.data.action) {
case "init": {
const urls = event.data.urls;
if (urls) {
if (urls.jsDecoderModule && typeof KTX2DecoderModule === "undefined") {
importScripts(urls.jsDecoderModule);
KTX2DecoderModule = KTX2DECODER;
}
applyConfig(urls);
}
if (event.data.wasmBinaries) {
applyConfig(void 0, { ...event.data.wasmBinaries, jsDecoderModule: KTX2DecoderModule });
}
ktx2Decoder = new KTX2DecoderModule.KTX2Decoder();
postMessage({ action: "init" });
break;
}
case "setDefaultDecoderOptions": {
KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions = event.data.options;
break;
}
case "decode":
ktx2Decoder.decode(event.data.data, event.data.caps, event.data.options).then((data) => {
const buffers = [];
for (let mip = 0; mip < data.mipmaps.length; ++mip) {
const mipmap = data.mipmaps[mip];
if (mipmap && mipmap.data) {
buffers.push(mipmap.data.buffer);
}
}
postMessage({ action: "decoded", success: true, decodedData: data }, buffers);
}).catch((reason) => {
postMessage({ action: "decoded", success: false, msg: reason });
});
break;
}
}, "onmessage");
}
async function initializeWebWorker2(worker, wasmBinaries, urls) {
return await new Promise((resolve, reject) => {
const onError = /* @__PURE__ */ __name((error) => {
worker.removeEventListener("error", onError);
worker.removeEventListener("message", onMessage);
reject(error);
}, "onError");
const onMessage = /* @__PURE__ */ __name((message) => {
if (message.data.action === "init") {
worker.removeEventListener("error", onError);
worker.removeEventListener("message", onMessage);
resolve(worker);
}
}, "onMessage");
worker.addEventListener("error", onError);
worker.addEventListener("message", onMessage);
worker.postMessage({
action: "init",
urls,
wasmBinaries
});
});
}
var init_khronosTextureContainer2Worker = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer2Worker.js"() {
__name(applyConfig, "applyConfig");
__name(workerFunction2, "workerFunction");
__name(initializeWebWorker2, "initializeWebWorker");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer2.js
var DefaultKTX2DecoderOptions, KhronosTextureContainer2;
var init_khronosTextureContainer2 = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer2.js"() {
init_workerPool();
init_tools();
init_ktx2decoderTypes();
init_khronosTextureContainer2Worker();
DefaultKTX2DecoderOptions = class {
static {
__name(this, "DefaultKTX2DecoderOptions");
}
constructor() {
this._isDirty = true;
this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = true;
this._ktx2DecoderOptions = {};
}
/**
* Gets the dirty flag
*/
get isDirty() {
return this._isDirty;
}
/**
* force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and ASTC + BC7 are not available as a compressed transcoded format
*/
get useRGBAIfASTCBC7NotAvailableWhenUASTC() {
return this._useRGBAIfASTCBC7NotAvailableWhenUASTC;
}
set useRGBAIfASTCBC7NotAvailableWhenUASTC(value) {
if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC === value) {
return;
}
this._useRGBAIfASTCBC7NotAvailableWhenUASTC = value;
this._isDirty = true;
}
/**
* force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and only BC1 or BC3 are available as a compressed transcoded format.
* This property is true by default to favor speed over memory, because currently transcoding from UASTC to BC1/3 is slow because the transcoder transcodes
* to uncompressed and then recompresses the texture
*/
get useRGBAIfOnlyBC1BC3AvailableWhenUASTC() {
return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC;
}
set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(value) {
if (this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC === value) {
return;
}
this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = value;
this._isDirty = true;
}
/**
* force to always use (uncompressed) RGBA for transcoded format
*/
get forceRGBA() {
return this._forceRGBA;
}
set forceRGBA(value) {
if (this._forceRGBA === value) {
return;
}
this._forceRGBA = value;
this._isDirty = true;
}
/**
* force to always use (uncompressed) R8 for transcoded format
*/
get forceR8() {
return this._forceR8;
}
set forceR8(value) {
if (this._forceR8 === value) {
return;
}
this._forceR8 = value;
this._isDirty = true;
}
/**
* force to always use (uncompressed) RG8 for transcoded format
*/
get forceRG8() {
return this._forceRG8;
}
set forceRG8(value) {
if (this._forceRG8 === value) {
return;
}
this._forceRG8 = value;
this._isDirty = true;
}
/**
* list of transcoders to bypass when looking for a suitable transcoder. The available transcoders are:
* UniversalTranscoder_UASTC_ASTC
* UniversalTranscoder_UASTC_BC7
* UniversalTranscoder_UASTC_RGBA_UNORM
* UniversalTranscoder_UASTC_RGBA_SRGB
* UniversalTranscoder_UASTC_R8_UNORM
* UniversalTranscoder_UASTC_RG8_UNORM
* MSCTranscoder
*/
get bypassTranscoders() {
return this._bypassTranscoders;
}
set bypassTranscoders(value) {
if (this._bypassTranscoders === value) {
return;
}
this._bypassTranscoders = value;
this._isDirty = true;
}
/** @internal */
_getKTX2DecoderOptions() {
if (!this._isDirty) {
return this._ktx2DecoderOptions;
}
this._isDirty = false;
const options = {};
if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC !== void 0) {
options.useRGBAIfASTCBC7NotAvailableWhenUASTC = this._useRGBAIfASTCBC7NotAvailableWhenUASTC;
}
if (this._forceRGBA !== void 0) {
options.forceRGBA = this._forceRGBA;
}
if (this._forceR8 !== void 0) {
options.forceR8 = this._forceR8;
}
if (this._forceRG8 !== void 0) {
options.forceRG8 = this._forceRG8;
}
if (this._bypassTranscoders !== void 0) {
options.bypassTranscoders = this._bypassTranscoders;
}
if (this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC) {
options.transcodeFormatDecisionTree = {
UASTC: {
transcodeFormat: [TranscodeTarget.BC1_RGB, TranscodeTarget.BC3_RGBA],
yes: {
transcodeFormat: TranscodeTarget.RGBA32,
engineFormat: 32856,
roundToMultiple4: false
}
}
};
}
this._ktx2DecoderOptions = options;
return options;
}
};
KhronosTextureContainer2 = class _KhronosTextureContainer2 {
static {
__name(this, "KhronosTextureContainer2");
}
static GetDefaultNumWorkers() {
if (typeof navigator !== "object" || !navigator.hardwareConcurrency) {
return 1;
}
return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);
}
static _Initialize(numWorkers) {
if (_KhronosTextureContainer2._WorkerPoolPromise || _KhronosTextureContainer2._DecoderModulePromise) {
return;
}
const urls = {
wasmBaseUrl: Tools.ScriptBaseUrl,
jsDecoderModule: Tools.GetBabylonScriptURL(this.URLConfig.jsDecoderModule, true),
wasmUASTCToASTC: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC, true),
wasmUASTCToBC7: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7, true),
wasmUASTCToRGBA_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM, true),
wasmUASTCToRGBA_SRGB: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB, true),
wasmUASTCToR8_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM, true),
wasmUASTCToRG8_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM, true),
jsMSCTranscoder: Tools.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder, true),
wasmMSCTranscoder: Tools.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder, true),
wasmZSTDDecoder: Tools.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder, true)
};
if (numWorkers && typeof Worker === "function" && typeof URL !== "undefined") {
_KhronosTextureContainer2._WorkerPoolPromise = new Promise((resolve) => {
const workerContent = `${applyConfig}(${workerFunction2})()`;
const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" }));
resolve(new AutoReleaseWorkerPool(numWorkers, async () => await initializeWebWorker2(new Worker(workerBlobUrl), void 0, urls)));
});
} else {
if (typeof _KhronosTextureContainer2._KTX2DecoderModule === "undefined") {
_KhronosTextureContainer2._DecoderModulePromise = Tools.LoadBabylonScriptAsync(urls.jsDecoderModule).then(() => {
_KhronosTextureContainer2._KTX2DecoderModule = KTX2DECODER;
_KhronosTextureContainer2._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread = false;
_KhronosTextureContainer2._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread = true;
applyConfig(urls, _KhronosTextureContainer2._KTX2DecoderModule);
return new _KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder();
});
} else {
_KhronosTextureContainer2._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread = false;
_KhronosTextureContainer2._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread = true;
_KhronosTextureContainer2._DecoderModulePromise = Promise.resolve(new _KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder());
}
}
}
/**
* Constructor
* @param engine The engine to use
* @param numWorkersOrOptions The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.
*/
constructor(engine, numWorkersOrOptions = _KhronosTextureContainer2.DefaultNumWorkers) {
this._engine = engine;
const workerPoolOption = typeof numWorkersOrOptions === "object" && numWorkersOrOptions.workerPool || _KhronosTextureContainer2.WorkerPool;
if (workerPoolOption) {
_KhronosTextureContainer2._WorkerPoolPromise = Promise.resolve(workerPoolOption);
} else {
if (typeof numWorkersOrOptions === "object") {
_KhronosTextureContainer2._KTX2DecoderModule = numWorkersOrOptions?.binariesAndModulesContainer?.jsDecoderModule;
} else if (typeof KTX2DECODER !== "undefined") {
_KhronosTextureContainer2._KTX2DecoderModule = KTX2DECODER;
}
const numberOfWorkers = typeof numWorkersOrOptions === "number" ? numWorkersOrOptions : numWorkersOrOptions.numWorkers ?? _KhronosTextureContainer2.DefaultNumWorkers;
_KhronosTextureContainer2._Initialize(numberOfWorkers);
}
}
/**
* @internal
*/
async _uploadAsync(data, internalTexture, options) {
const caps = this._engine.getCaps();
const compressedTexturesCaps = {
astc: !!caps.astc,
bptc: !!caps.bptc,
s3tc: !!caps.s3tc,
pvrtc: !!caps.pvrtc,
etc2: !!caps.etc2,
etc1: !!caps.etc1
};
if (_KhronosTextureContainer2._WorkerPoolPromise) {
const workerPool = await _KhronosTextureContainer2._WorkerPoolPromise;
return await new Promise((resolve, reject) => {
workerPool.push((worker, onComplete) => {
const onError = /* @__PURE__ */ __name((error) => {
worker.removeEventListener("error", onError);
worker.removeEventListener("message", onMessage);
reject(error);
onComplete();
}, "onError");
const onMessage = /* @__PURE__ */ __name((message) => {
if (message.data.action === "decoded") {
worker.removeEventListener("error", onError);
worker.removeEventListener("message", onMessage);
if (!message.data.success) {
reject({ message: message.data.msg });
} else {
try {
this._createTexture(message.data.decodedData, internalTexture, options);
resolve();
} catch (err) {
reject({ message: err });
}
}
onComplete();
}
}, "onMessage");
worker.addEventListener("error", onError);
worker.addEventListener("message", onMessage);
worker.postMessage({ action: "setDefaultDecoderOptions", options: _KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions() });
const dataCopy = new Uint8Array(data.byteLength);
dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
worker.postMessage({ action: "decode", data: dataCopy, caps: compressedTexturesCaps, options }, [dataCopy.buffer]);
});
});
} else if (_KhronosTextureContainer2._DecoderModulePromise) {
const decoder = await _KhronosTextureContainer2._DecoderModulePromise;
if (_KhronosTextureContainer2.DefaultDecoderOptions.isDirty) {
_KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions = _KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions();
}
return await new Promise((resolve, reject) => {
decoder.decode(data, caps).then((data2) => {
this._createTexture(data2, internalTexture);
resolve();
}).catch((reason) => {
reject({ message: reason });
});
});
}
throw new Error("KTX2 decoder module is not available");
}
_createTexture(data, internalTexture, options) {
const oglTexture2D = 3553;
this._engine._bindTextureDirectly(oglTexture2D, internalTexture);
if (options) {
options.transcodedFormat = data.transcodedFormat;
options.isInGammaSpace = data.isInGammaSpace;
options.hasAlpha = data.hasAlpha;
options.transcoderName = data.transcoderName;
}
let isUncompressedFormat = true;
switch (data.transcodedFormat) {
case 32856:
internalTexture.type = 0;
internalTexture.format = 5;
break;
case 33321:
internalTexture.type = 0;
internalTexture.format = 6;
break;
case 33323:
internalTexture.type = 0;
internalTexture.format = 7;
break;
default:
internalTexture.format = data.transcodedFormat;
isUncompressedFormat = false;
break;
}
internalTexture._gammaSpace = data.isInGammaSpace;
internalTexture.generateMipMaps = data.mipmaps.length > 1;
internalTexture.width = data.mipmaps[0].width;
internalTexture.height = data.mipmaps[0].height;
if (data.errors) {
throw new Error("KTX2 container - could not transcode the data. " + data.errors);
}
for (let t = 0; t < data.mipmaps.length; ++t) {
const mipmap = data.mipmaps[t];
if (!mipmap || !mipmap.data) {
throw new Error("KTX2 container - could not transcode one of the image");
}
if (isUncompressedFormat) {
internalTexture.width = mipmap.width;
internalTexture.height = mipmap.height;
this._engine._uploadDataToTextureDirectly(internalTexture, mipmap.data, 0, t, void 0, true);
} else {
this._engine._uploadCompressedDataToTextureDirectly(internalTexture, data.transcodedFormat, mipmap.width, mipmap.height, mipmap.data, 0, t);
}
}
internalTexture._extension = ".ktx2";
internalTexture.isReady = true;
this._engine._bindTextureDirectly(oglTexture2D, null);
}
/**
* Checks if the given data starts with a KTX2 file identifier.
* @param data the data to check
* @returns true if the data is a KTX2 file or false otherwise
*/
static IsValid(data) {
if (data.byteLength >= 12) {
const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);
if (identifier[0] === 171 && identifier[1] === 75 && identifier[2] === 84 && identifier[3] === 88 && identifier[4] === 32 && identifier[5] === 50 && identifier[6] === 48 && identifier[7] === 187 && identifier[8] === 13 && identifier[9] === 10 && identifier[10] === 26 && identifier[11] === 10) {
return true;
}
}
return false;
}
};
KhronosTextureContainer2.URLConfig = {
jsDecoderModule: "https://cdn.babylonjs.com/babylon.ktx2Decoder.js",
wasmUASTCToASTC: null,
wasmUASTCToBC7: null,
wasmUASTCToRGBA_UNORM: null,
wasmUASTCToRGBA_SRGB: null,
wasmUASTCToR8_UNORM: null,
wasmUASTCToRG8_UNORM: null,
jsMSCTranscoder: null,
wasmMSCTranscoder: null,
wasmZSTDDecoder: null
};
KhronosTextureContainer2.DefaultNumWorkers = KhronosTextureContainer2.GetDefaultNumWorkers();
KhronosTextureContainer2.DefaultDecoderOptions = new DefaultKTX2DecoderOptions();
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader.js
var ktxTextureLoader_exports = {};
__export(ktxTextureLoader_exports, {
_KTXTextureLoader: () => _KTXTextureLoader
});
function MapSRGBToLinear(format) {
switch (format) {
case 35916:
return 33776;
case 35918:
return 33778;
case 35919:
return 33779;
case 37493:
return 37492;
case 37497:
return 37496;
case 37495:
return 37494;
case 37840:
return 37808;
case 36493:
return 36492;
}
return null;
}
var _KTXTextureLoader;
var init_ktxTextureLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader.js"() {
init_khronosTextureContainer();
init_khronosTextureContainer2();
init_logger();
__name(MapSRGBToLinear, "MapSRGBToLinear");
_KTXTextureLoader = class {
static {
__name(this, "_KTXTextureLoader");
}
constructor() {
this.supportCascades = false;
}
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
*/
loadCubeData(data, texture, createPolynomials, onLoad) {
if (Array.isArray(data)) {
return;
}
texture._invertVScale = !texture.invertY;
const engine = texture.getEngine();
const ktx = new KhronosTextureContainer(data, 6);
const loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
engine._unpackFlipY(true);
ktx.uploadLevels(texture, texture.generateMipMaps);
texture.width = ktx.pixelWidth;
texture.height = ktx.pixelHeight;
engine._setCubeMapTextureParams(texture, loadMipmap, ktx.numberOfMipmapLevels - 1);
texture.isReady = true;
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
}
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
* @param options
*/
loadData(data, texture, callback, options) {
if (KhronosTextureContainer.IsValid(data)) {
texture._invertVScale = !texture.invertY;
const ktx = new KhronosTextureContainer(data, 1);
const mappedFormat = MapSRGBToLinear(ktx.glInternalFormat);
if (mappedFormat) {
texture.format = mappedFormat;
texture._useSRGBBuffer = texture.getEngine()._getUseSRGBBuffer(true, texture.generateMipMaps);
texture._gammaSpace = true;
} else {
texture.format = ktx.glInternalFormat;
}
callback(ktx.pixelWidth, ktx.pixelHeight, texture.generateMipMaps, true, () => {
ktx.uploadLevels(texture, texture.generateMipMaps);
}, ktx.isInvalid);
} else if (KhronosTextureContainer2.IsValid(data)) {
const ktx2 = new KhronosTextureContainer2(texture.getEngine());
ktx2._uploadAsync(data, texture, options).then(() => {
callback(texture.width, texture.height, texture.generateMipMaps, true, () => {
}, false);
}, (error) => {
Logger.Warn(`Failed to load KTX2 texture data: ${error.message}`);
callback(0, 0, false, false, () => {
}, true);
});
} else {
Logger.Error("texture missing KTX identifier");
callback(0, 0, false, false, () => {
}, true);
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tga.js
function GetTGAHeader(data) {
let offset = 0;
const header = {
id_length: data[offset++],
colormap_type: data[offset++],
image_type: data[offset++],
colormap_index: data[offset++] | data[offset++] << 8,
colormap_length: data[offset++] | data[offset++] << 8,
colormap_size: data[offset++],
origin: [data[offset++] | data[offset++] << 8, data[offset++] | data[offset++] << 8],
width: data[offset++] | data[offset++] << 8,
height: data[offset++] | data[offset++] << 8,
pixel_size: data[offset++],
flags: data[offset++]
};
return header;
}
function UploadContent(texture, data) {
if (data.length < 19) {
Logger.Error("Unable to load TGA file - Not enough data to contain header");
return;
}
let offset = 18;
const header = GetTGAHeader(data);
if (header.id_length + offset > data.length) {
Logger.Error("Unable to load TGA file - Not enough data");
return;
}
offset += header.id_length;
let use_rle = false;
let use_pal = false;
let use_grey = false;
switch (header.image_type) {
case _TYPE_RLE_INDEXED:
use_rle = true;
// eslint-disable-next-line no-fallthrough
case _TYPE_INDEXED:
use_pal = true;
break;
case _TYPE_RLE_RGB:
use_rle = true;
// eslint-disable-next-line no-fallthrough
case _TYPE_RGB:
break;
case _TYPE_RLE_GREY:
use_rle = true;
// eslint-disable-next-line no-fallthrough
case _TYPE_GREY:
use_grey = true;
break;
}
let pixel_data;
const pixel_size = header.pixel_size >> 3;
const pixel_total = header.width * header.height * pixel_size;
let palettes;
if (use_pal) {
palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
}
if (use_rle) {
pixel_data = new Uint8Array(pixel_total);
let c, count, i;
let localOffset = 0;
const pixels = new Uint8Array(pixel_size);
while (offset < pixel_total && localOffset < pixel_total) {
c = data[offset++];
count = (c & 127) + 1;
if (c & 128) {
for (i = 0; i < pixel_size; ++i) {
pixels[i] = data[offset++];
}
for (i = 0; i < count; ++i) {
pixel_data.set(pixels, localOffset + i * pixel_size);
}
localOffset += pixel_size * count;
} else {
count *= pixel_size;
for (i = 0; i < count; ++i) {
pixel_data[localOffset + i] = data[offset++];
}
localOffset += count;
}
}
} else {
pixel_data = data.subarray(offset, offset += use_pal ? header.width * header.height : pixel_total);
}
let x_start, y_start, x_step, y_step, y_end, x_end;
switch ((header.flags & _ORIGIN_MASK) >> _ORIGIN_SHIFT) {
default:
case _ORIGIN_UL:
x_start = 0;
x_step = 1;
x_end = header.width;
y_start = 0;
y_step = 1;
y_end = header.height;
break;
case _ORIGIN_BL:
x_start = 0;
x_step = 1;
x_end = header.width;
y_start = header.height - 1;
y_step = -1;
y_end = -1;
break;
case _ORIGIN_UR:
x_start = header.width - 1;
x_step = -1;
x_end = -1;
y_start = 0;
y_step = 1;
y_end = header.height;
break;
case _ORIGIN_BR:
x_start = header.width - 1;
x_step = -1;
x_end = -1;
y_start = header.height - 1;
y_step = -1;
y_end = -1;
break;
}
const func = "_getImageData" + (use_grey ? "Grey" : "") + header.pixel_size + "bits";
const imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
const engine = texture.getEngine();
engine._uploadDataToTextureDirectly(texture, imageData);
}
function GetImageData8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
const image = pixel_data, colormap = palettes;
const width = header.width, height = header.height;
let color, i = 0, x, y;
const imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i++) {
color = image[i];
imageData[(x + width * y) * 4 + 3] = 255;
imageData[(x + width * y) * 4 + 2] = colormap[color * 3 + 0];
imageData[(x + width * y) * 4 + 1] = colormap[color * 3 + 1];
imageData[(x + width * y) * 4 + 0] = colormap[color * 3 + 2];
}
}
return imageData;
}
function GetImageData16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
const image = pixel_data;
const width = header.width, height = header.height;
let color, i = 0, x, y;
const imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i += 2) {
color = image[i + 0] + (image[i + 1] << 8);
const r = ((color & 31744) >> 10) * 255 / 31 | 0;
const g = ((color & 992) >> 5) * 255 / 31 | 0;
const b = (color & 31) * 255 / 31 | 0;
imageData[(x + width * y) * 4 + 0] = r;
imageData[(x + width * y) * 4 + 1] = g;
imageData[(x + width * y) * 4 + 2] = b;
imageData[(x + width * y) * 4 + 3] = color & 32768 ? 0 : 255;
}
}
return imageData;
}
function GetImageData24bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
const image = pixel_data;
const width = header.width, height = header.height;
let i = 0, x, y;
const imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i += 3) {
imageData[(x + width * y) * 4 + 3] = 255;
imageData[(x + width * y) * 4 + 2] = image[i + 0];
imageData[(x + width * y) * 4 + 1] = image[i + 1];
imageData[(x + width * y) * 4 + 0] = image[i + 2];
}
}
return imageData;
}
function GetImageData32bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
const image = pixel_data;
const width = header.width, height = header.height;
let i = 0, x, y;
const imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i += 4) {
imageData[(x + width * y) * 4 + 2] = image[i + 0];
imageData[(x + width * y) * 4 + 1] = image[i + 1];
imageData[(x + width * y) * 4 + 0] = image[i + 2];
imageData[(x + width * y) * 4 + 3] = image[i + 3];
}
}
return imageData;
}
function GetImageDataGrey8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
const image = pixel_data;
const width = header.width, height = header.height;
let color, i = 0, x, y;
const imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i++) {
color = image[i];
imageData[(x + width * y) * 4 + 0] = color;
imageData[(x + width * y) * 4 + 1] = color;
imageData[(x + width * y) * 4 + 2] = color;
imageData[(x + width * y) * 4 + 3] = 255;
}
}
return imageData;
}
function GetImageDataGrey16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
const image = pixel_data;
const width = header.width, height = header.height;
let i = 0, x, y;
const imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i += 2) {
imageData[(x + width * y) * 4 + 0] = image[i + 0];
imageData[(x + width * y) * 4 + 1] = image[i + 0];
imageData[(x + width * y) * 4 + 2] = image[i + 0];
imageData[(x + width * y) * 4 + 3] = image[i + 1];
}
}
return imageData;
}
var _TYPE_INDEXED, _TYPE_RGB, _TYPE_GREY, _TYPE_RLE_INDEXED, _TYPE_RLE_RGB, _TYPE_RLE_GREY, _ORIGIN_MASK, _ORIGIN_SHIFT, _ORIGIN_BL, _ORIGIN_BR, _ORIGIN_UL, _ORIGIN_UR, TGATools;
var init_tga = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tga.js"() {
init_logger();
_TYPE_INDEXED = 1;
_TYPE_RGB = 2;
_TYPE_GREY = 3;
_TYPE_RLE_INDEXED = 9;
_TYPE_RLE_RGB = 10;
_TYPE_RLE_GREY = 11;
_ORIGIN_MASK = 48;
_ORIGIN_SHIFT = 4;
_ORIGIN_BL = 0;
_ORIGIN_BR = 1;
_ORIGIN_UL = 2;
_ORIGIN_UR = 3;
__name(GetTGAHeader, "GetTGAHeader");
__name(UploadContent, "UploadContent");
__name(GetImageData8bits, "GetImageData8bits");
__name(GetImageData16bits, "GetImageData16bits");
__name(GetImageData24bits, "GetImageData24bits");
__name(GetImageData32bits, "GetImageData32bits");
__name(GetImageDataGrey8bits, "GetImageDataGrey8bits");
__name(GetImageDataGrey16bits, "GetImageDataGrey16bits");
TGATools = {
/**
* Gets the header of a TGA file
* @param data defines the TGA data
* @returns the header
*/
GetTGAHeader,
/**
* Uploads TGA content to a Babylon Texture
* @internal
*/
UploadContent,
/** @internal */
_getImageData8bits: GetImageData8bits,
/** @internal */
_getImageData16bits: GetImageData16bits,
/** @internal */
_getImageData24bits: GetImageData24bits,
/** @internal */
_getImageData32bits: GetImageData32bits,
/** @internal */
_getImageDataGrey8bits: GetImageDataGrey8bits,
/** @internal */
_getImageDataGrey16bits: GetImageDataGrey16bits
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/tgaTextureLoader.js
var tgaTextureLoader_exports = {};
__export(tgaTextureLoader_exports, {
_TGATextureLoader: () => _TGATextureLoader
});
var _TGATextureLoader;
var init_tgaTextureLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/tgaTextureLoader.js"() {
init_tga();
_TGATextureLoader = class {
static {
__name(this, "_TGATextureLoader");
}
constructor() {
this.supportCascades = false;
}
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
*/
loadCubeData() {
throw ".env not supported in Cube.";
}
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
loadData(data, texture, callback) {
const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
const header = GetTGAHeader(bytes);
callback(header.width, header.height, texture.generateMipMaps, false, () => {
UploadContent(texture, bytes);
});
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.interfaces.js
var INT32_SIZE, FLOAT32_SIZE, INT8_SIZE, INT16_SIZE, ULONG_SIZE, USHORT_RANGE, BITMAP_SIZE, HUF_ENCBITS, HUF_DECBITS, HUF_ENCSIZE, HUF_DECSIZE, HUF_DECMASK, SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN;
var init_exrLoader_interfaces = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.interfaces.js"() {
INT32_SIZE = 4;
FLOAT32_SIZE = 4;
INT8_SIZE = 1;
INT16_SIZE = 2;
ULONG_SIZE = 8;
USHORT_RANGE = 1 << 16;
BITMAP_SIZE = USHORT_RANGE >> 3;
HUF_ENCBITS = 16;
HUF_DECBITS = 14;
HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1;
HUF_DECSIZE = 1 << HUF_DECBITS;
HUF_DECMASK = HUF_DECSIZE - 1;
SHORT_ZEROCODE_RUN = 59;
LONG_ZEROCODE_RUN = 63;
SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.core.js
function GenerateTables() {
const buffer = new ArrayBuffer(4);
const floatView2 = new Float32Array(buffer);
const uint32View = new Uint32Array(buffer);
const baseTable = new Uint32Array(512);
const shiftTable = new Uint32Array(512);
for (let i = 0; i < 256; ++i) {
const e = i - 127;
if (e < -27) {
baseTable[i] = 0;
baseTable[i | 256] = 32768;
shiftTable[i] = 24;
shiftTable[i | 256] = 24;
} else if (e < -14) {
baseTable[i] = 1024 >> -e - 14;
baseTable[i | 256] = 1024 >> -e - 14 | 32768;
shiftTable[i] = -e - 1;
shiftTable[i | 256] = -e - 1;
} else if (e <= 15) {
baseTable[i] = e + 15 << 10;
baseTable[i | 256] = e + 15 << 10 | 32768;
shiftTable[i] = 13;
shiftTable[i | 256] = 13;
} else if (e < 128) {
baseTable[i] = 31744;
baseTable[i | 256] = 64512;
shiftTable[i] = 24;
shiftTable[i | 256] = 24;
} else {
baseTable[i] = 31744;
baseTable[i | 256] = 64512;
shiftTable[i] = 13;
shiftTable[i | 256] = 13;
}
}
const mantissaTable = new Uint32Array(2048);
const exponentTable = new Uint32Array(64);
const offsetTable = new Uint32Array(64);
for (let i = 1; i < 1024; ++i) {
let m = i << 13;
let e = 0;
while ((m & 8388608) === 0) {
m <<= 1;
e -= 8388608;
}
m &= ~8388608;
e += 947912704;
mantissaTable[i] = m | e;
}
for (let i = 1024; i < 2048; ++i) {
mantissaTable[i] = 939524096 + (i - 1024 << 13);
}
for (let i = 1; i < 31; ++i) {
exponentTable[i] = i << 23;
}
exponentTable[31] = 1199570944;
exponentTable[32] = 2147483648;
for (let i = 33; i < 63; ++i) {
exponentTable[i] = 2147483648 + (i - 32 << 23);
}
exponentTable[63] = 3347054592;
for (let i = 1; i < 64; ++i) {
if (i !== 32) {
offsetTable[i] = 1024;
}
}
return {
floatView: floatView2,
uint32View,
baseTable,
shiftTable,
mantissaTable,
exponentTable,
offsetTable
};
}
function ParseNullTerminatedString(buffer, offset) {
const uintBuffer = new Uint8Array(buffer);
let endOffset = 0;
while (uintBuffer[offset.value + endOffset] != 0) {
endOffset += 1;
}
const stringValue = new TextDecoder().decode(uintBuffer.slice(offset.value, offset.value + endOffset));
offset.value = offset.value + endOffset + 1;
return stringValue;
}
function ParseInt32(dataView, offset) {
const value = dataView.getInt32(offset.value, true);
offset.value += INT32_SIZE;
return value;
}
function ParseUint32(dataView, offset) {
const value = dataView.getUint32(offset.value, true);
offset.value += INT32_SIZE;
return value;
}
function ParseUint8(dataView, offset) {
const value = dataView.getUint8(offset.value);
offset.value += INT8_SIZE;
return value;
}
function ParseUint16(dataView, offset) {
const value = dataView.getUint16(offset.value, true);
offset.value += INT16_SIZE;
return value;
}
function ParseUint8Array(array, offset) {
const value = array[offset.value];
offset.value += INT8_SIZE;
return value;
}
function ParseInt64(dataView, offset) {
let int;
if ("getBigInt64" in DataView.prototype) {
int = Number(dataView.getBigInt64(offset.value, true));
} else {
int = dataView.getUint32(offset.value + 4, true) + Number(dataView.getUint32(offset.value, true) << 32);
}
offset.value += ULONG_SIZE;
return int;
}
function ParseFloat32(dataView, offset) {
const value = dataView.getFloat32(offset.value, true);
offset.value += FLOAT32_SIZE;
return value;
}
function ParseFloat16(dataView, offset) {
return DecodeFloat16(ParseUint16(dataView, offset));
}
function DecodeFloat16(binary) {
const exponent = (binary & 31744) >> 10;
const fraction = binary & 1023;
return (binary >> 15 ? -1 : 1) * (exponent ? exponent === 31 ? fraction ? NaN : Infinity : Math.pow(2, exponent - 15) * (1 + fraction / 1024) : 6103515625e-14 * (fraction / 1024));
}
function ToHalfFloat2(value) {
if (Math.abs(value) > 65504) {
throw new Error("Value out of range.Consider using float instead of half-float.");
}
value = Clamp(value, -65504, 65504);
Tables.floatView[0] = value;
const f = Tables.uint32View[0];
const e = f >> 23 & 511;
return Tables.baseTable[e] + ((f & 8388607) >> Tables.shiftTable[e]);
}
function DecodeFloat32(dataView, offset) {
return ToHalfFloat2(ParseFloat32(dataView, offset));
}
function ParseFixedLengthString(buffer, offset, size) {
const stringValue = new TextDecoder().decode(new Uint8Array(buffer).slice(offset.value, offset.value + size));
offset.value = offset.value + size;
return stringValue;
}
function ParseRational(dataView, offset) {
const x = ParseInt32(dataView, offset);
const y = ParseUint32(dataView, offset);
return [x, y];
}
function ParseTimecode(dataView, offset) {
const x = ParseUint32(dataView, offset);
const y = ParseUint32(dataView, offset);
return [x, y];
}
function ParseV2f(dataView, offset) {
const x = ParseFloat32(dataView, offset);
const y = ParseFloat32(dataView, offset);
return [x, y];
}
function ParseV3f(dataView, offset) {
const x = ParseFloat32(dataView, offset);
const y = ParseFloat32(dataView, offset);
const z = ParseFloat32(dataView, offset);
return [x, y, z];
}
function ParseChlist(dataView, offset, size) {
const startOffset = offset.value;
const channels = [];
while (offset.value < startOffset + size - 1) {
const name260 = ParseNullTerminatedString(dataView.buffer, offset);
const pixelType = ParseInt32(dataView, offset);
const pLinear = ParseUint8(dataView, offset);
offset.value += 3;
const xSampling = ParseInt32(dataView, offset);
const ySampling = ParseInt32(dataView, offset);
channels.push({
name: name260,
pixelType,
pLinear,
xSampling,
ySampling
});
}
offset.value += 1;
return channels;
}
function ParseChromaticities(dataView, offset) {
const redX = ParseFloat32(dataView, offset);
const redY = ParseFloat32(dataView, offset);
const greenX = ParseFloat32(dataView, offset);
const greenY = ParseFloat32(dataView, offset);
const blueX = ParseFloat32(dataView, offset);
const blueY = ParseFloat32(dataView, offset);
const whiteX = ParseFloat32(dataView, offset);
const whiteY = ParseFloat32(dataView, offset);
return { redX, redY, greenX, greenY, blueX, blueY, whiteX, whiteY };
}
function ParseCompression(dataView, offset) {
return ParseUint8(dataView, offset);
}
function ParseBox2i(dataView, offset) {
const xMin = ParseInt32(dataView, offset);
const yMin = ParseInt32(dataView, offset);
const xMax = ParseInt32(dataView, offset);
const yMax = ParseInt32(dataView, offset);
return { xMin, yMin, xMax, yMax };
}
function ParseLineOrder(dataView, offset) {
const lineOrder = ParseUint8(dataView, offset);
return LineOrders[lineOrder];
}
function ParseValue(dataView, offset, type, size) {
switch (type) {
case "string":
case "stringvector":
case "iccProfile":
return ParseFixedLengthString(dataView.buffer, offset, size);
case "chlist":
return ParseChlist(dataView, offset, size);
case "chromaticities":
return ParseChromaticities(dataView, offset);
case "compression":
return ParseCompression(dataView, offset);
case "box2i":
return ParseBox2i(dataView, offset);
case "lineOrder":
return ParseLineOrder(dataView, offset);
case "float":
return ParseFloat32(dataView, offset);
case "v2f":
return ParseV2f(dataView, offset);
case "v3f":
return ParseV3f(dataView, offset);
case "int":
return ParseInt32(dataView, offset);
case "rational":
return ParseRational(dataView, offset);
case "timecode":
return ParseTimecode(dataView, offset);
case "preview":
offset.value += size;
return "skipped";
default:
offset.value += size;
return void 0;
}
}
function Predictor(source) {
for (let t = 1; t < source.length; t++) {
const d = source[t - 1] + source[t] - 128;
source[t] = d;
}
}
function InterleaveScalar(source, out) {
let t1 = 0;
let t2 = Math.floor((source.length + 1) / 2);
let s = 0;
const stop = source.length - 1;
while (true) {
if (s > stop) {
break;
}
out[s++] = source[t1++];
if (s > stop) {
break;
}
out[s++] = source[t2++];
}
}
var CompressionCodes, LineOrders, Tables;
var init_exrLoader_core = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.core.js"() {
init_math_scalar_functions();
init_exrLoader_interfaces();
(function(CompressionCodes2) {
CompressionCodes2[CompressionCodes2["NO_COMPRESSION"] = 0] = "NO_COMPRESSION";
CompressionCodes2[CompressionCodes2["RLE_COMPRESSION"] = 1] = "RLE_COMPRESSION";
CompressionCodes2[CompressionCodes2["ZIPS_COMPRESSION"] = 2] = "ZIPS_COMPRESSION";
CompressionCodes2[CompressionCodes2["ZIP_COMPRESSION"] = 3] = "ZIP_COMPRESSION";
CompressionCodes2[CompressionCodes2["PIZ_COMPRESSION"] = 4] = "PIZ_COMPRESSION";
CompressionCodes2[CompressionCodes2["PXR24_COMPRESSION"] = 5] = "PXR24_COMPRESSION";
})(CompressionCodes || (CompressionCodes = {}));
(function(LineOrders2) {
LineOrders2[LineOrders2["INCREASING_Y"] = 0] = "INCREASING_Y";
LineOrders2[LineOrders2["DECREASING_Y"] = 1] = "DECREASING_Y";
})(LineOrders || (LineOrders = {}));
Tables = GenerateTables();
__name(GenerateTables, "GenerateTables");
__name(ParseNullTerminatedString, "ParseNullTerminatedString");
__name(ParseInt32, "ParseInt32");
__name(ParseUint32, "ParseUint32");
__name(ParseUint8, "ParseUint8");
__name(ParseUint16, "ParseUint16");
__name(ParseUint8Array, "ParseUint8Array");
__name(ParseInt64, "ParseInt64");
__name(ParseFloat32, "ParseFloat32");
__name(ParseFloat16, "ParseFloat16");
__name(DecodeFloat16, "DecodeFloat16");
__name(ToHalfFloat2, "ToHalfFloat");
__name(DecodeFloat32, "DecodeFloat32");
__name(ParseFixedLengthString, "ParseFixedLengthString");
__name(ParseRational, "ParseRational");
__name(ParseTimecode, "ParseTimecode");
__name(ParseV2f, "ParseV2f");
__name(ParseV3f, "ParseV3f");
__name(ParseChlist, "ParseChlist");
__name(ParseChromaticities, "ParseChromaticities");
__name(ParseCompression, "ParseCompression");
__name(ParseBox2i, "ParseBox2i");
__name(ParseLineOrder, "ParseLineOrder");
__name(ParseValue, "ParseValue");
__name(Predictor, "Predictor");
__name(InterleaveScalar, "InterleaveScalar");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.header.js
function GetExrHeader(dataView, offset) {
if (dataView.getUint32(0, true) != EXR_MAGIC) {
throw new Error("Incorrect OpenEXR format");
}
const version = dataView.getUint8(4);
const specData = dataView.getUint8(5);
const spec = {
singleTile: !!(specData & 2),
longName: !!(specData & 4),
deepFormat: !!(specData & 8),
multiPart: !!(specData & 16)
};
offset.value = 8;
const headerData = {};
let keepReading = true;
while (keepReading) {
const attributeName = ParseNullTerminatedString(dataView.buffer, offset);
if (!attributeName) {
keepReading = false;
} else {
const attributeType = ParseNullTerminatedString(dataView.buffer, offset);
const attributeSize = ParseUint32(dataView, offset);
const attributeValue = ParseValue(dataView, offset, attributeType, attributeSize);
if (attributeValue === void 0) {
Logger.Warn(`Unknown header attribute type ${attributeType}'.`);
} else {
headerData[attributeName] = attributeValue;
}
}
}
if ((specData & ~4) != 0) {
throw new Error("Unsupported file format");
}
return { version, spec, ...headerData };
}
var EXR_MAGIC;
var init_exrLoader_header = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.header.js"() {
init_logger();
init_exrLoader_core();
EXR_MAGIC = 20000630;
__name(GetExrHeader, "GetExrHeader");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.huf.js
function ReverseLutFromBitmap(bitmap, lut) {
let k = 0;
for (let i = 0; i < USHORT_RANGE; ++i) {
if (i == 0 || bitmap[i >> 3] & 1 << (i & 7)) {
lut[k++] = i;
}
}
const n = k - 1;
while (k < USHORT_RANGE) {
lut[k++] = 0;
}
return n;
}
function HufClearDecTable(hdec) {
for (let i = 0; i < HUF_DECSIZE; i++) {
hdec[i] = {};
hdec[i].len = 0;
hdec[i].lit = 0;
hdec[i].p = null;
}
}
function GetBits(nBits, c, lc, array, offset) {
while (lc < nBits) {
c = c << 8 | ParseUint8Array(array, offset);
lc += 8;
}
lc -= nBits;
return {
l: c >> lc & (1 << nBits) - 1,
c,
lc
};
}
function GetChar(c, lc, array, offset) {
c = c << 8 | ParseUint8Array(array, offset);
lc += 8;
return {
c,
lc
};
}
function GetCode(po, rlc, c, lc, array, offset, outBuffer, outBufferOffset, outBufferEndOffset) {
if (po == rlc) {
if (lc < 8) {
const gc = GetChar(c, lc, array, offset);
c = gc.c;
lc = gc.lc;
}
lc -= 8;
let cs = c >> lc;
cs = new Uint8Array([cs])[0];
if (outBufferOffset.value + cs > outBufferEndOffset) {
return null;
}
const s = outBuffer[outBufferOffset.value - 1];
while (cs-- > 0) {
outBuffer[outBufferOffset.value++] = s;
}
} else if (outBufferOffset.value < outBufferEndOffset) {
outBuffer[outBufferOffset.value++] = po;
} else {
return null;
}
return { c, lc };
}
function HufCanonicalCodeTable(hcode) {
for (let i = 0; i <= 58; ++i) {
HufTableBuffer[i] = 0;
}
for (let i = 0; i < HUF_ENCSIZE; ++i) {
HufTableBuffer[hcode[i]] += 1;
}
let c = 0;
for (let i = 58; i > 0; --i) {
const nc = c + HufTableBuffer[i] >> 1;
HufTableBuffer[i] = c;
c = nc;
}
for (let i = 0; i < HUF_ENCSIZE; ++i) {
const l = hcode[i];
if (l > 0) {
hcode[i] = l | HufTableBuffer[l]++ << 6;
}
}
}
function HufUnpackEncTable(array, offset, ni, im, iM, hcode) {
const p = offset;
let c = 0;
let lc = 0;
for (; im <= iM; im++) {
if (p.value - offset.value > ni) {
return;
}
let gb = GetBits(6, c, lc, array, p);
const l = gb.l;
c = gb.c;
lc = gb.lc;
hcode[im] = l;
if (l == LONG_ZEROCODE_RUN) {
if (p.value - offset.value > ni) {
throw new Error("Error in HufUnpackEncTable");
}
gb = GetBits(8, c, lc, array, p);
let zerun = gb.l + SHORTEST_LONG_RUN;
c = gb.c;
lc = gb.lc;
if (im + zerun > iM + 1) {
throw new Error("Error in HufUnpackEncTable");
}
while (zerun--) {
hcode[im++] = 0;
}
im--;
} else if (l >= SHORT_ZEROCODE_RUN) {
let zerun = l - SHORT_ZEROCODE_RUN + 2;
if (im + zerun > iM + 1) {
throw new Error("Error in HufUnpackEncTable");
}
while (zerun--) {
hcode[im++] = 0;
}
im--;
}
}
HufCanonicalCodeTable(hcode);
}
function HufLength(code) {
return code & 63;
}
function HufCode(code) {
return code >> 6;
}
function HufBuildDecTable(hcode, im, iM, hdecod) {
for (; im <= iM; im++) {
const c = HufCode(hcode[im]);
const l = HufLength(hcode[im]);
if (c >> l) {
throw new Error("Invalid table entry");
}
if (l > HUF_DECBITS) {
const pl = hdecod[c >> l - HUF_DECBITS];
if (pl.len) {
throw new Error("Invalid table entry");
}
pl.lit++;
if (pl.p) {
const p = pl.p;
pl.p = new Array(pl.lit);
for (let i = 0; i < pl.lit - 1; ++i) {
pl.p[i] = p[i];
}
} else {
pl.p = new Array(1);
}
pl.p[pl.lit - 1] = im;
} else if (l) {
let plOffset = 0;
for (let i = 1 << HUF_DECBITS - l; i > 0; i--) {
const pl = hdecod[(c << HUF_DECBITS - l) + plOffset];
if (pl.len || pl.p) {
throw new Error("Invalid table entry");
}
pl.len = l;
pl.lit = im;
plOffset++;
}
}
}
return true;
}
function HufDecode(encodingTable, decodingTable, array, offset, ni, rlc, no, outBuffer, outOffset) {
let c = 0;
let lc = 0;
const outBufferEndOffset = no;
const inOffsetEnd = Math.trunc(offset.value + (ni + 7) / 8);
while (offset.value < inOffsetEnd) {
let gc = GetChar(c, lc, array, offset);
c = gc.c;
lc = gc.lc;
while (lc >= HUF_DECBITS) {
const index = c >> lc - HUF_DECBITS & HUF_DECMASK;
const pl = decodingTable[index];
if (pl.len) {
lc -= pl.len;
const gCode = GetCode(pl.lit, rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset);
if (gCode) {
c = gCode.c;
lc = gCode.lc;
}
} else {
if (!pl.p) {
throw new Error("hufDecode issues");
}
let j;
for (j = 0; j < pl.lit; j++) {
const l = HufLength(encodingTable[pl.p[j]]);
while (lc < l && offset.value < inOffsetEnd) {
gc = GetChar(c, lc, array, offset);
c = gc.c;
lc = gc.lc;
}
if (lc >= l) {
if (HufCode(encodingTable[pl.p[j]]) == (c >> lc - l & (1 << l) - 1)) {
lc -= l;
const gCode = GetCode(pl.p[j], rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset);
if (gCode) {
c = gCode.c;
lc = gCode.lc;
}
break;
}
}
}
if (j == pl.lit) {
throw new Error("HufDecode issues");
}
}
}
}
const i = 8 - ni & 7;
c >>= i;
lc -= i;
while (lc > 0) {
const pl = decodingTable[c << HUF_DECBITS - lc & HUF_DECMASK];
if (pl.len) {
lc -= pl.len;
const gCode = GetCode(pl.lit, rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset);
if (gCode) {
c = gCode.c;
lc = gCode.lc;
}
} else {
throw new Error("HufDecode issues");
}
}
return true;
}
function HufUncompress(array, dataView, offset, nCompressed, outBuffer, nRaw) {
const outOffset = { value: 0 };
const initialInOffset = offset.value;
const im = ParseUint32(dataView, offset);
const iM = ParseUint32(dataView, offset);
offset.value += 4;
const nBits = ParseUint32(dataView, offset);
offset.value += 4;
if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) {
throw new Error("Wrong HUF_ENCSIZE");
}
const freq = new Array(HUF_ENCSIZE);
const hdec = new Array(HUF_DECSIZE);
HufClearDecTable(hdec);
const ni = nCompressed - (offset.value - initialInOffset);
HufUnpackEncTable(array, offset, ni, im, iM, freq);
if (nBits > 8 * (nCompressed - (offset.value - initialInOffset))) {
throw new Error("Wrong hufUncompress");
}
HufBuildDecTable(freq, im, iM, hdec);
HufDecode(freq, hdec, array, offset, nBits, iM, nRaw, outBuffer, outOffset);
}
function UInt16(value) {
return value & 65535;
}
function Int16(value) {
const ref = UInt16(value);
return ref > 32767 ? ref - 65536 : ref;
}
function Wdec14(l, h) {
const ls = Int16(l);
const hs = Int16(h);
const hi = hs;
const ai = ls + (hi & 1) + (hi >> 1);
const as = ai;
const bs = ai - hi;
return { a: as, b: bs };
}
function Wdec16(l, h) {
const m = UInt16(l);
const d = UInt16(h);
const bb = m - (d >> 1) & MOD_MASK;
const aa = d + bb - A_OFFSET & MOD_MASK;
return { a: aa, b: bb };
}
function Wav2Decode(buffer, j, nx, ox, ny, oy, mx) {
const w14 = mx < 1 << 14;
const n = nx > ny ? ny : nx;
let p = 1;
let p2;
let py;
while (p <= n) {
p <<= 1;
}
p >>= 1;
p2 = p;
p >>= 1;
while (p >= 1) {
py = 0;
const ey = py + oy * (ny - p2);
const oy1 = oy * p;
const oy2 = oy * p2;
const ox1 = ox * p;
const ox2 = ox * p2;
let i00, i01, i10, i11;
for (; py <= ey; py += oy2) {
let px = py;
const ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
const p01 = px + ox1;
const p10 = px + oy1;
const p11 = p10 + ox1;
if (w14) {
let result = Wdec14(buffer[px + j], buffer[p10 + j]);
i00 = result.a;
i10 = result.b;
result = Wdec14(buffer[p01 + j], buffer[p11 + j]);
i01 = result.a;
i11 = result.b;
result = Wdec14(i00, i01);
buffer[px + j] = result.a;
buffer[p01 + j] = result.b;
result = Wdec14(i10, i11);
buffer[p10 + j] = result.a;
buffer[p11 + j] = result.b;
} else {
let result = Wdec16(buffer[px + j], buffer[p10 + j]);
i00 = result.a;
i10 = result.b;
result = Wdec16(buffer[p01 + j], buffer[p11 + j]);
i01 = result.a;
i11 = result.b;
result = Wdec16(i00, i01);
buffer[px + j] = result.a;
buffer[p01 + j] = result.b;
result = Wdec16(i10, i11);
buffer[p10 + j] = result.a;
buffer[p11 + j] = result.b;
}
}
if (nx & p) {
const p10 = px + oy1;
let result;
if (w14) {
result = Wdec14(buffer[px + j], buffer[p10 + j]);
} else {
result = Wdec16(buffer[px + j], buffer[p10 + j]);
}
i00 = result.a;
buffer[p10 + j] = result.b;
buffer[px + j] = i00;
}
}
if (ny & p) {
let px = py;
const ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
const p01 = px + ox1;
let result;
if (w14) {
result = Wdec14(buffer[px + j], buffer[p01 + j]);
} else {
result = Wdec16(buffer[px + j], buffer[p01 + j]);
}
i00 = result.a;
buffer[p01 + j] = result.b;
buffer[px + j] = i00;
}
}
p2 = p;
p >>= 1;
}
return py;
}
function ApplyLut(lut, data, nData) {
for (let i = 0; i < nData; ++i) {
data[i] = lut[data[i]];
}
}
var NBITS, A_OFFSET, MOD_MASK, HufTableBuffer;
var init_exrLoader_compression_huf = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.huf.js"() {
init_exrLoader_core();
init_exrLoader_interfaces();
NBITS = 16;
A_OFFSET = 1 << NBITS - 1;
MOD_MASK = (1 << NBITS) - 1;
__name(ReverseLutFromBitmap, "ReverseLutFromBitmap");
__name(HufClearDecTable, "HufClearDecTable");
__name(GetBits, "GetBits");
__name(GetChar, "GetChar");
__name(GetCode, "GetCode");
HufTableBuffer = new Array(59);
__name(HufCanonicalCodeTable, "HufCanonicalCodeTable");
__name(HufUnpackEncTable, "HufUnpackEncTable");
__name(HufLength, "HufLength");
__name(HufCode, "HufCode");
__name(HufBuildDecTable, "HufBuildDecTable");
__name(HufDecode, "HufDecode");
__name(HufUncompress, "HufUncompress");
__name(UInt16, "UInt16");
__name(Int16, "Int16");
__name(Wdec14, "Wdec14");
__name(Wdec16, "Wdec16");
__name(Wav2Decode, "Wav2Decode");
__name(ApplyLut, "ApplyLut");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.rle.js
function DecodeRunLength(source) {
let size = source.byteLength;
const out = [];
let p = 0;
const reader = new DataView(source);
while (size > 0) {
const l = reader.getInt8(p++);
if (l < 0) {
const count = -l;
size -= count + 1;
for (let i = 0; i < count; i++) {
out.push(reader.getUint8(p++));
}
} else {
const count = l;
size -= 2;
const value = reader.getUint8(p++);
for (let i = 0; i < count + 1; i++) {
out.push(value);
}
}
}
return out;
}
var init_exrLoader_compression_rle = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.rle.js"() {
__name(DecodeRunLength, "DecodeRunLength");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.js
function UncompressRAW(decoder) {
return new DataView(decoder.array.buffer, decoder.offset.value, decoder.size);
}
function UncompressRLE(decoder) {
const compressed = decoder.viewer.buffer.slice(decoder.offset.value, decoder.offset.value + decoder.size);
const rawBuffer = new Uint8Array(DecodeRunLength(compressed));
const tmpBuffer = new Uint8Array(rawBuffer.length);
Predictor(rawBuffer);
InterleaveScalar(rawBuffer, tmpBuffer);
return new DataView(tmpBuffer.buffer);
}
function UncompressZIP(decoder) {
const compressed = decoder.array.slice(decoder.offset.value, decoder.offset.value + decoder.size);
const rawBuffer = fflate.unzlibSync(compressed);
const tmpBuffer = new Uint8Array(rawBuffer.length);
Predictor(rawBuffer);
InterleaveScalar(rawBuffer, tmpBuffer);
return new DataView(tmpBuffer.buffer);
}
function UncompressPXR(decoder) {
const compressed = decoder.array.slice(decoder.offset.value, decoder.offset.value + decoder.size);
const rawBuffer = fflate.unzlibSync(compressed);
const sz = decoder.lines * decoder.channels * decoder.width;
const tmpBuffer = decoder.type == 1 ? new Uint16Array(sz) : new Uint32Array(sz);
let tmpBufferEnd = 0;
let writePtr = 0;
const ptr = new Array(4);
for (let y = 0; y < decoder.lines; y++) {
for (let c = 0; c < decoder.channels; c++) {
let pixel = 0;
switch (decoder.type) {
case 1:
ptr[0] = tmpBufferEnd;
ptr[1] = ptr[0] + decoder.width;
tmpBufferEnd = ptr[1] + decoder.width;
for (let j = 0; j < decoder.width; ++j) {
const diff = rawBuffer[ptr[0]++] << 8 | rawBuffer[ptr[1]++];
pixel += diff;
tmpBuffer[writePtr] = pixel;
writePtr++;
}
break;
case 2:
ptr[0] = tmpBufferEnd;
ptr[1] = ptr[0] + decoder.width;
ptr[2] = ptr[1] + decoder.width;
tmpBufferEnd = ptr[2] + decoder.width;
for (let j = 0; j < decoder.width; ++j) {
const diff = rawBuffer[ptr[0]++] << 24 | rawBuffer[ptr[1]++] << 16 | rawBuffer[ptr[2]++] << 8;
pixel += diff;
tmpBuffer[writePtr] = pixel;
writePtr++;
}
break;
}
}
}
return new DataView(tmpBuffer.buffer);
}
function UncompressPIZ(decoder) {
const inDataView = decoder.viewer;
const inOffset = { value: decoder.offset.value };
const outBuffer = new Uint16Array(decoder.width * decoder.scanlineBlockSize * (decoder.channels * decoder.type));
const bitmap = new Uint8Array(BITMAP_SIZE);
let outBufferEnd = 0;
const pizChannelData = new Array(decoder.channels);
for (let i = 0; i < decoder.channels; i++) {
pizChannelData[i] = {};
pizChannelData[i]["start"] = outBufferEnd;
pizChannelData[i]["end"] = pizChannelData[i]["start"];
pizChannelData[i]["nx"] = decoder.width;
pizChannelData[i]["ny"] = decoder.lines;
pizChannelData[i]["size"] = decoder.type;
outBufferEnd += pizChannelData[i].nx * pizChannelData[i].ny * pizChannelData[i].size;
}
const minNonZero = ParseUint16(inDataView, inOffset);
const maxNonZero = ParseUint16(inDataView, inOffset);
if (maxNonZero >= BITMAP_SIZE) {
throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE");
}
if (minNonZero <= maxNonZero) {
for (let i = 0; i < maxNonZero - minNonZero + 1; i++) {
bitmap[i + minNonZero] = ParseUint8(inDataView, inOffset);
}
}
const lut = new Uint16Array(USHORT_RANGE);
const maxValue = ReverseLutFromBitmap(bitmap, lut);
const length = ParseUint32(inDataView, inOffset);
HufUncompress(decoder.array, inDataView, inOffset, length, outBuffer, outBufferEnd);
for (let i = 0; i < decoder.channels; ++i) {
const cd = pizChannelData[i];
for (let j = 0; j < pizChannelData[i].size; ++j) {
Wav2Decode(outBuffer, cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue);
}
}
ApplyLut(lut, outBuffer, outBufferEnd);
let tmpOffset = 0;
const tmpBuffer = new Uint8Array(outBuffer.buffer.byteLength);
for (let y = 0; y < decoder.lines; y++) {
for (let c = 0; c < decoder.channels; c++) {
const cd = pizChannelData[c];
const n = cd.nx * cd.size;
const cp = new Uint8Array(outBuffer.buffer, cd.end * INT16_SIZE, n * INT16_SIZE);
tmpBuffer.set(cp, tmpOffset);
tmpOffset += n * INT16_SIZE;
cd.end += n;
}
}
return new DataView(tmpBuffer.buffer);
}
var init_exrLoader_compression = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.js"() {
init_exrLoader_compression_huf();
init_exrLoader_compression_rle();
init_exrLoader_core();
init_exrLoader_interfaces();
__name(UncompressRAW, "UncompressRAW");
__name(UncompressRLE, "UncompressRLE");
__name(UncompressZIP, "UncompressZIP");
__name(UncompressPXR, "UncompressPXR");
__name(UncompressPIZ, "UncompressPIZ");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.configuration.js
var EXROutputType, ExrLoaderGlobalConfiguration;
var init_exrLoader_configuration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.configuration.js"() {
(function(EXROutputType2) {
EXROutputType2[EXROutputType2["Float"] = 0] = "Float";
EXROutputType2[EXROutputType2["HalfFloat"] = 1] = "HalfFloat";
})(EXROutputType || (EXROutputType = {}));
ExrLoaderGlobalConfiguration = class {
static {
__name(this, "ExrLoaderGlobalConfiguration");
}
};
ExrLoaderGlobalConfiguration.DefaultOutputType = EXROutputType.HalfFloat;
ExrLoaderGlobalConfiguration.FFLATEUrl = "https://unpkg.com/fflate@0.8.2";
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.decoder.js
async function CreateDecoderAsync(header, dataView, offset, outputType) {
const decoder = {
size: 0,
viewer: dataView,
array: new Uint8Array(dataView.buffer),
offset,
width: header.dataWindow.xMax - header.dataWindow.xMin + 1,
height: header.dataWindow.yMax - header.dataWindow.yMin + 1,
channels: header.channels.length,
channelLineOffsets: {},
scanOrder: /* @__PURE__ */ __name(() => 0, "scanOrder"),
bytesPerLine: 0,
outLineWidth: 0,
lines: 0,
scanlineBlockSize: 0,
inputSize: null,
type: 0,
uncompress: null,
getter: /* @__PURE__ */ __name(() => 0, "getter"),
format: 5,
outputChannels: 0,
decodeChannels: {},
blockCount: null,
byteArray: null,
linearSpace: false,
textureType: 0
};
switch (header.compression) {
case CompressionCodes.NO_COMPRESSION:
decoder.lines = 1;
decoder.uncompress = UncompressRAW;
break;
case CompressionCodes.RLE_COMPRESSION:
decoder.lines = 1;
decoder.uncompress = UncompressRLE;
break;
case CompressionCodes.ZIPS_COMPRESSION:
decoder.lines = 1;
decoder.uncompress = UncompressZIP;
await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl);
break;
case CompressionCodes.ZIP_COMPRESSION:
decoder.lines = 16;
decoder.uncompress = UncompressZIP;
await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl);
break;
case CompressionCodes.PIZ_COMPRESSION:
decoder.lines = 32;
decoder.uncompress = UncompressPIZ;
break;
case CompressionCodes.PXR24_COMPRESSION:
decoder.lines = 16;
decoder.uncompress = UncompressPXR;
await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl);
break;
default:
throw new Error(CompressionCodes[header.compression] + " is unsupported");
}
decoder.scanlineBlockSize = decoder.lines;
const channels = {};
for (const channel of header.channels) {
switch (channel.name) {
case "R":
case "G":
case "B":
case "A":
channels[channel.name] = true;
decoder.type = channel.pixelType;
break;
case "Y":
channels[channel.name] = true;
decoder.type = channel.pixelType;
break;
default:
break;
}
}
let fillAlpha = false;
if (channels.R && channels.G && channels.B && channels.A) {
decoder.outputChannels = 4;
decoder.decodeChannels = { R: 0, G: 1, B: 2, A: 3 };
} else if (channels.R && channels.G && channels.B) {
fillAlpha = true;
decoder.outputChannels = 4;
decoder.decodeChannels = { R: 0, G: 1, B: 2, A: 3 };
} else if (channels.R && channels.G) {
decoder.outputChannels = 2;
decoder.decodeChannels = { R: 0, G: 1 };
} else if (channels.R) {
decoder.outputChannels = 1;
decoder.decodeChannels = { R: 0 };
} else if (channels.Y) {
decoder.outputChannels = 1;
decoder.decodeChannels = { Y: 0 };
} else {
throw new Error("EXRLoader.parse: file contains unsupported data channels.");
}
if (decoder.type === 1) {
switch (outputType) {
case EXROutputType.Float:
decoder.getter = ParseFloat16;
decoder.inputSize = INT16_SIZE;
break;
case EXROutputType.HalfFloat:
decoder.getter = ParseUint16;
decoder.inputSize = INT16_SIZE;
break;
}
} else if (decoder.type === 2) {
switch (outputType) {
case EXROutputType.Float:
decoder.getter = ParseFloat32;
decoder.inputSize = FLOAT32_SIZE;
break;
case EXROutputType.HalfFloat:
decoder.getter = DecodeFloat32;
decoder.inputSize = FLOAT32_SIZE;
}
} else {
throw new Error("Unsupported pixelType " + decoder.type + " for " + header.compression);
}
decoder.blockCount = decoder.height / decoder.scanlineBlockSize;
for (let i = 0; i < decoder.blockCount; i++) {
ParseInt64(dataView, offset);
}
const size = decoder.width * decoder.height * decoder.outputChannels;
switch (outputType) {
case EXROutputType.Float:
decoder.byteArray = new Float32Array(size);
decoder.textureType = 1;
if (fillAlpha) {
decoder.byteArray.fill(1, 0, size);
}
break;
case EXROutputType.HalfFloat:
decoder.byteArray = new Uint16Array(size);
decoder.textureType = 2;
if (fillAlpha) {
decoder.byteArray.fill(15360, 0, size);
}
break;
default:
throw new Error("Unsupported type: " + outputType);
}
let byteOffset = 0;
for (const channel of header.channels) {
if (decoder.decodeChannels[channel.name] !== void 0) {
decoder.channelLineOffsets[channel.name] = byteOffset * decoder.width;
}
byteOffset += channel.pixelType * 2;
}
decoder.bytesPerLine = decoder.width * byteOffset;
decoder.outLineWidth = decoder.width * decoder.outputChannels;
if (header.lineOrder === "INCREASING_Y") {
decoder.scanOrder = (y) => y;
} else {
decoder.scanOrder = (y) => decoder.height - 1 - y;
}
if (decoder.outputChannels == 4) {
decoder.format = 5;
decoder.linearSpace = true;
} else {
decoder.format = 6;
decoder.linearSpace = false;
}
return decoder;
}
function ScanData(decoder, header, dataView, offset) {
const tmpOffset = { value: 0 };
for (let scanlineBlockIdx = 0; scanlineBlockIdx < decoder.height / decoder.scanlineBlockSize; scanlineBlockIdx++) {
const line = ParseInt32(dataView, offset) - header.dataWindow.yMin;
decoder.size = ParseUint32(dataView, offset);
decoder.lines = line + decoder.scanlineBlockSize > decoder.height ? decoder.height - line : decoder.scanlineBlockSize;
const isCompressed = decoder.size < decoder.lines * decoder.bytesPerLine;
const viewer = isCompressed && decoder.uncompress ? decoder.uncompress(decoder) : UncompressRAW(decoder);
offset.value += decoder.size;
for (let lineY = 0; lineY < decoder.scanlineBlockSize; lineY++) {
const scanY = scanlineBlockIdx * decoder.scanlineBlockSize;
const trueY = lineY + decoder.scanOrder(scanY);
if (trueY >= decoder.height) {
continue;
}
const lineOffset = lineY * decoder.bytesPerLine;
const outLineOffset = (decoder.height - 1 - trueY) * decoder.outLineWidth;
for (let channelID = 0; channelID < decoder.channels; channelID++) {
const name260 = header.channels[channelID].name;
const lOff = decoder.channelLineOffsets[name260];
const cOff = decoder.decodeChannels[name260];
if (cOff === void 0) {
continue;
}
tmpOffset.value = lineOffset + lOff;
for (let x = 0; x < decoder.width; x++) {
const outIndex = outLineOffset + x * decoder.outputChannels + cOff;
if (decoder.byteArray) {
decoder.byteArray[outIndex] = decoder.getter(viewer, tmpOffset);
}
}
}
}
}
}
var init_exrLoader_decoder = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.decoder.js"() {
init_exrLoader_core();
init_exrLoader_compression();
init_exrLoader_interfaces();
init_tools();
init_exrLoader_configuration();
__name(CreateDecoderAsync, "CreateDecoderAsync");
__name(ScanData, "ScanData");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/exrTextureLoader.js
var exrTextureLoader_exports = {};
__export(exrTextureLoader_exports, {
ReadExrDataAsync: () => ReadExrDataAsync,
_ExrTextureLoader: () => _ExrTextureLoader
});
async function ReadExrDataAsync(data) {
const dataView = new DataView(data);
const offset = { value: 0 };
const header = GetExrHeader(dataView, offset);
try {
const decoder = await CreateDecoderAsync(header, dataView, offset, EXROutputType.Float);
ScanData(decoder, header, dataView, offset);
if (!decoder.byteArray) {
Logger.Error("Failed to decode EXR data: No byte array available.");
return { width: 0, height: 0, data: null };
}
return {
width: header.dataWindow.xMax - header.dataWindow.xMin + 1,
height: header.dataWindow.yMax - header.dataWindow.yMin + 1,
data: new Float32Array(decoder.byteArray)
};
} catch (error) {
Logger.Error("Failed to load EXR data: ", error);
}
return { width: 0, height: 0, data: null };
}
var _ExrTextureLoader;
var init_exrTextureLoader = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/exrTextureLoader.js"() {
init_exrLoader_header();
init_exrLoader_decoder();
init_exrLoader_configuration();
init_logger();
_ExrTextureLoader = class {
static {
__name(this, "_ExrTextureLoader");
}
constructor() {
this.supportCascades = false;
}
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param _data contains the texture data
* @param _texture defines the BabylonJS internal texture
* @param _createPolynomials will be true if polynomials have been requested
* @param _onLoad defines the callback to trigger once the texture is ready
* @param _onError defines the callback to trigger in case of error
* Cube texture are not supported by .exr files
*/
loadCubeData(_data, _texture, _createPolynomials, _onLoad, _onError) {
throw ".exr not supported in Cube.";
}
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
loadData(data, texture, callback) {
const dataView = new DataView(data.buffer);
const offset = { value: 0 };
const header = GetExrHeader(dataView, offset);
CreateDecoderAsync(header, dataView, offset, ExrLoaderGlobalConfiguration.DefaultOutputType).then((decoder) => {
ScanData(decoder, header, dataView, offset);
const width = header.dataWindow.xMax - header.dataWindow.xMin + 1;
const height = header.dataWindow.yMax - header.dataWindow.yMin + 1;
callback(width, height, texture.generateMipMaps, false, () => {
const engine = texture.getEngine();
texture.format = header.format;
texture.type = decoder.textureType;
texture.invertY = false;
texture._gammaSpace = !header.linearSpace;
if (decoder.byteArray) {
engine._uploadDataToTextureDirectly(texture, decoder.byteArray, 0, 0, void 0, true);
}
});
}).catch((error) => {
Logger.Error("Failed to load EXR texture: ", error);
});
}
};
__name(ReadExrDataAsync, "ReadExrDataAsync");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/textureLoaderManager.js
function registerTextureLoader(extension, loaderFactory) {
if (unregisterTextureLoader(extension)) {
Logger.Warn(`Extension with the name '${extension}' already exists`);
}
RegisteredTextureLoaders.set(extension, loaderFactory);
}
function unregisterTextureLoader(extension) {
return RegisteredTextureLoaders.delete(extension);
}
function _GetCompatibleTextureLoader(extension, mimeType) {
if (mimeType === "image/ktx" || mimeType === "image/ktx2") {
extension = ".ktx";
}
if (!RegisteredTextureLoaders.has(extension)) {
if (extension.endsWith(".ies")) {
registerTextureLoader(".ies", async () => await Promise.resolve().then(() => (init_iesTextureLoader(), iesTextureLoader_exports)).then((module2) => new module2._IESTextureLoader()));
}
if (extension.endsWith(".dds")) {
registerTextureLoader(".dds", async () => await Promise.resolve().then(() => (init_ddsTextureLoader(), ddsTextureLoader_exports)).then((module2) => new module2._DDSTextureLoader()));
}
if (extension.endsWith(".basis")) {
registerTextureLoader(".basis", async () => await Promise.resolve().then(() => (init_basisTextureLoader(), basisTextureLoader_exports)).then((module2) => new module2._BasisTextureLoader()));
}
if (extension.endsWith(".env")) {
registerTextureLoader(".env", async () => await Promise.resolve().then(() => (init_envTextureLoader(), envTextureLoader_exports)).then((module2) => new module2._ENVTextureLoader()));
}
if (extension.endsWith(".hdr")) {
registerTextureLoader(".hdr", async () => await Promise.resolve().then(() => (init_hdrTextureLoader(), hdrTextureLoader_exports)).then((module2) => new module2._HDRTextureLoader()));
}
if (extension.endsWith(".ktx") || extension.endsWith(".ktx2")) {
registerTextureLoader(".ktx", async () => await Promise.resolve().then(() => (init_ktxTextureLoader(), ktxTextureLoader_exports)).then((module2) => new module2._KTXTextureLoader()));
registerTextureLoader(".ktx2", async () => await Promise.resolve().then(() => (init_ktxTextureLoader(), ktxTextureLoader_exports)).then((module2) => new module2._KTXTextureLoader()));
}
if (extension.endsWith(".tga")) {
registerTextureLoader(".tga", async () => await Promise.resolve().then(() => (init_tgaTextureLoader(), tgaTextureLoader_exports)).then((module2) => new module2._TGATextureLoader()));
}
if (extension.endsWith(".exr")) {
registerTextureLoader(".exr", async () => await Promise.resolve().then(() => (init_exrTextureLoader(), exrTextureLoader_exports)).then((module2) => new module2._ExrTextureLoader()));
}
}
const registered6 = RegisteredTextureLoaders.get(extension);
return registered6 ? Promise.resolve(registered6(mimeType)) : null;
}
var RegisteredTextureLoaders;
var init_textureLoaderManager = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/textureLoaderManager.js"() {
init_logger();
RegisteredTextureLoaders = /* @__PURE__ */ new Map();
__name(registerTextureLoader, "registerTextureLoader");
__name(unregisterTextureLoader, "unregisterTextureLoader");
__name(_GetCompatibleTextureLoader, "_GetCompatibleTextureLoader");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/abstractEngine.js
function QueueNewFrame(func, requester) {
if (!IsWindowObjectExist()) {
if (typeof requestAnimationFrame === "function") {
return requestAnimationFrame(func);
}
} else {
const { requestAnimationFrame: requestAnimationFrame2 } = requester || window;
if (typeof requestAnimationFrame2 === "function") {
return requestAnimationFrame2(func);
}
}
return setTimeout(func, 16);
}
var AbstractEngine;
var init_abstractEngine = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/abstractEngine.js"() {
init_engineStore();
init_logger();
init_effect();
init_performanceConfigurator();
init_precisionDate();
init_depthCullingState();
init_stencilStateComposer();
init_stencilState();
init_alphaCullingState();
init_devTools();
init_internalTexture();
init_domManagement();
init_observable();
init_abstractEngine_functions();
init_textureLoaderManager();
__name(QueueNewFrame, "QueueNewFrame");
AbstractEngine = class _AbstractEngine {
static {
__name(this, "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;
}
/**
* @internal
*/
_resetAlphaMode() {
this._alphaMode.fill(-1);
this._alphaEquation.fill(-1);
}
/**
* 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();
for (const internalTexture of currentState) {
internalTexture._rebuild();
}
}
_rebuildRenderTargetWrappers() {
const currentState = this._renderTargetWrapperCache.slice();
for (const renderTargetWrapper of currentState) {
renderTargetWrapper._rebuild();
}
}
_rebuildEffects() {
for (const key in this._compiledEffects) {
const effect = this._compiledEffects[key];
effect._pipelineContext = null;
effect._prepareEffect();
}
Effect.ResetCache();
}
_rebuildGraphicsResources() {
this.wipeCaches(true);
this._rebuildEffects();
this._rebuildComputeEffects?.();
this._rebuildBuffers();
this._rebuildInternalTextures();
this._rebuildTextures();
this._rebuildRenderTargetWrappers();
this.wipeCaches(true);
}
_flagContextRestored() {
Logger.Warn(this.name + " context successfully restored.");
this.onContextRestoredObservable.notifyObservers(this);
this._contextWasLost = false;
}
_restoreEngineAfterContextLost(initEngine) {
setTimeout(() => {
this._clearEmptyResources();
const depthTest = this._depthCullingState.depthTest;
const depthFunc = this._depthCullingState.depthFunc;
const depthMask = this._depthCullingState.depthMask;
const stencilTest = this._stencilState.stencilTest;
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) {
}
/**
* 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: cancelAnimationFrame2 } = this.getHostWindow() || window;
if (typeof cancelAnimationFrame2 === "function") {
return cancelAnimationFrame2(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 === void 0) {
return;
}
if (value <= 0) {
this._minFrameTime = Number.MAX_VALUE;
return;
}
this._minFrameTime = 1e3 / value;
}
_isOverFrameTime(timestamp) {
if (!timestamp || this._maxFPS === void 0) {
return false;
}
const elapsedTime = timestamp - this._lastFrameTime;
this._lastFrameTime = timestamp;
this._renderAccumulator += elapsedTime;
if (this._renderAccumulator < this._minFrameTime) {
return true;
}
this._renderAccumulator -= this._minFrameTime;
if (this._renderAccumulator > this._minFrameTime) {
this._renderAccumulator = this._minFrameTime;
}
return false;
}
_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) {
this.beginFrame();
if (!this.skipFrameRender && !this._renderViews()) {
this._renderFrame();
}
this.endFrame();
}
}
}
/** @internal */
_renderLoop(timestamp) {
this._processFrame(timestamp);
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);
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) {
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.substring(0, 5) === "data:";
const fromBlob = url.substring(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);
}
const originalUrl = url;
if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
url = this._transformTextureUrl(url);
}
if (originalUrl !== url) {
texture._originalUrl = originalUrl;
}
const lastDot = url.lastIndexOf(".");
let extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : "";
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) {
texture._buffer = buffer;
}
let onLoadObserver = null;
if (onLoad && !fallback) {
onLoadObserver = texture.onLoadedObservable.add(onLoad);
}
if (!fallback) {
this._internalTexturesCache.push(texture);
}
const onInternalError = /* @__PURE__ */ __name((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 {
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);
}
}, "onInternalError");
if (loaderPromise) {
const callbackAsync = /* @__PURE__ */ __name(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);
}, "callbackAsync");
if (!buffer) {
this._loadFile(url, (data) => {
callbackAsync(new Uint8Array(data));
}, void 0, scene ? scene.offlineProvider : void 0, true, (request, exception) => {
onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
});
} else {
if (buffer instanceof ArrayBuffer) {
callbackAsync(new Uint8Array(buffer));
} else if (ArrayBuffer.isView(buffer)) {
callbackAsync(buffer);
} else {
if (onError) {
onError("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null);
}
}
}
} else {
const onload = /* @__PURE__ */ __name((img) => {
if (fromBlob && !this._doNotHandleContextLost) {
texture._buffer = img;
}
prepareTexture(texture, extension, scene, img, texture.invertY, noMipmap, false, prepareTextureProcess, samplingMode);
}, "onload");
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" } : void 0, 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" } : void 0, this);
} else if (buffer) {
onload(buffer);
}
}
return texture;
}
_rebuildBuffers() {
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@8.33.2";
}
/**
* Returns the current version of the framework
*/
static get Version() {
return "8.33.2";
}
/**
* 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
* NOTE that modifying the object after engine creation will have no effect
* @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) {
this._colorWrite = true;
this._colorWriteChanged = true;
this._depthCullingState = new DepthCullingState();
this._stencilStateComposer = new StencilStateComposer();
this._stencilState = new StencilState();
this._alphaState = new AlphaState(false);
this._alphaMode = Array(8).fill(-1);
this._alphaEquation = Array(8).fill(-1);
this._activeRequests = [];
this._badOS = false;
this._badDesktopOS = false;
this._compatibilityMode = true;
this._internalTexturesCache = new Array();
this._currentRenderTarget = null;
this._boundTexturesCache = {};
this._activeChannel = 0;
this._currentTextureChannel = -1;
this._viewportCached = { x: 0, y: 0, z: 0, w: 0 };
this._isWebGPU = false;
this.onCanvasBlurObservable = new Observable();
this.onCanvasFocusObservable = new Observable();
this.onNewSceneAddedObservable = new Observable();
this.onResizeObservable = new Observable();
this.onCanvasPointerOutObservable = new Observable();
this.onEffectErrorObservable = new Observable();
this.disablePerformanceMonitorInBackground = false;
this.disableVertexArrayObjects = false;
this._frameId = 0;
this.hostInformation = {
isMobile: false
};
this.isFullscreen = false;
this.enableOfflineSupport = false;
this.disableManifestCheck = false;
this.disableContextMenu = true;
this.currentRenderPassId = 0;
this.isPointerLock = false;
this.postProcesses = [];
this.canvasTabIndex = 1;
this._contextWasLost = false;
this._useReverseDepthBuffer = false;
this.isNDCHalfZRange = false;
this.hasOriginBottomLeft = true;
this._renderTargetWrapperCache = new Array();
this._compiledEffects = {};
this._isDisposed = false;
this.scenes = [];
this._virtualScenes = new Array();
this.onBeforeTextureInitObservable = new Observable();
this.renderEvenInBackground = true;
this.preventCacheWipeBetweenFrames = false;
this._frameHandler = 0;
this._activeRenderLoops = new Array();
this._windowIsBackground = false;
this._boundRenderFunction = (timestamp) => this._renderLoop(timestamp);
this._lastFrameTime = 0;
this._renderAccumulator = 0;
this.skipFrameRender = false;
this.onBeforeShaderCompilationObservable = new Observable();
this.onAfterShaderCompilationObservable = new Observable();
this.onBeginFrameObservable = new Observable();
this.onEndFrameObservable = new Observable();
this._transformTextureUrl = null;
this._uniformBuffers = new Array();
this._storageBuffers = new Array();
this._highPrecisionShadersAllowed = true;
this.onContextLostObservable = new Observable();
this.onContextRestoredObservable = new Observable();
this._name = "";
this.premultipliedAlpha = true;
this.adaptToDeviceRatio = false;
this._lastDevicePixelRatio = 1;
this._doNotHandleContextLost = false;
this.cullBackFaces = null;
this._renderPassNames = ["main"];
this._fps = 60;
this._deltaTime = 0;
this._deterministicLockstep = false;
this._lockstepMaxSteps = 4;
this._timeStep = 1 / 60;
this.onDisposeObservable = new Observable();
this.onReleaseEffectsObservable = new Observable();
EngineStore.Instances.push(this);
this.startTime = PrecisionDate.Now;
this._stencilStateComposer.stencilGlobal = this._stencilState;
PerformanceConfigurator.SetMatrixPrecision(!!options.useLargeWorldRendering || !!options.useHighPrecisionMatrix);
if (IsNavigatorAvailable() && navigator.userAgent) {
this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
}
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 : 1;
const limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
adaptToDeviceRatio = adaptToDeviceRatio || options.adaptToDeviceRatio || false;
this._hardwareScalingLevel = adaptToDeviceRatio ? 1 / Math.min(limitDeviceRatio, devicePixelRatio) : 1;
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;
if (this.adaptToDeviceRatio) {
const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1 : 1;
const changeRatio = this._lastDevicePixelRatio / devicePixelRatio;
this._lastDevicePixelRatio = devicePixelRatio;
this._hardwareScalingLevel *= changeRatio;
}
if (IsWindowObjectExist() && IsDocumentAvailable()) {
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;
}
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;
};
this._checkForMobile();
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 * 1e3;
}
/**
* 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.
*/
// eslint-disable-next-line @typescript-eslint/promise-function-async
_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
*/
// eslint-disable-next-line @typescript-eslint/promise-function-async
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();
if (this._emptyTexture) {
this._releaseTexture(this._emptyTexture);
this._emptyTexture = null;
}
if (this._emptyCubeTexture) {
this._releaseTexture(this._emptyCubeTexture);
this._emptyCubeTexture = null;
}
this._renderingCanvas = null;
if (this.onBeforeTextureInitObservable) {
this.onBeforeTextureInitObservable.clear();
}
while (this.postProcesses.length) {
this.postProcesses[0].dispose();
}
while (this.scenes.length) {
this.scenes[0].dispose();
}
while (this._virtualScenes.length) {
this._virtualScenes[0].dispose();
}
this.releaseComputeEffects?.();
Effect.ResetCache();
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);
}
const index = EngineStore.Instances.indexOf(this);
if (index >= 0) {
EngineStore.Instances.splice(index, 1);
}
if (!EngineStore.Instances.length) {
EngineStore.OnEnginesDisposedObservable.notifyObservers(this);
EngineStore.OnEnginesDisposedObservable.clear();
}
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);
}
}
}
};
AbstractEngine._RenderPassIdCounter = 0;
AbstractEngine._RescalePostProcessFactory = null;
AbstractEngine.CollisionsEpsilon = 1e-3;
AbstractEngine.QueueNewFrame = QueueNewFrame;
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/fileTools.js
function DecodeBase64UrlToBinary(uri) {
return DecodeBase64ToBinary(uri.split(",")[1]);
}
var Base64DataUrlRegEx, LoadFileError, RequestFileError, ReadFileError, CleanUrl, FileToolsOptions, SetCorsBehavior, LoadImageConfiguration, LoadImage, ReadFile, LoadFile, RequestFile, GetMimeType, IsFileURL, IsBase64DataUrl, TestBase64DataUrl, DecodeBase64UrlToString, initSideEffects, FileTools, _injectLTSFileTools;
var init_fileTools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/fileTools.js"() {
init_webRequest();
init_domManagement();
init_observable();
init_filesInputStore();
init_retryStrategy();
init_error();
init_stringTools();
init_shaderProcessor();
init_engineStore();
init_logger();
init_timingTools();
init_abstractEngine_functions();
init_abstractEngine();
Base64DataUrlRegEx = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);
LoadFileError = class _LoadFileError extends RuntimeError {
static {
__name(this, "LoadFileError");
}
/**
* 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;
}
}
};
RequestFileError = class _RequestFileError extends RuntimeError {
static {
__name(this, "RequestFileError");
}
/**
* 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);
}
};
ReadFileError = class _ReadFileError extends RuntimeError {
static {
__name(this, "ReadFileError");
}
/**
* 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);
}
};
CleanUrl = /* @__PURE__ */ __name((url) => {
url = url.replace(/#/gm, "%23");
return url;
}, "CleanUrl");
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: /* @__PURE__ */ __name((url) => url, "PreprocessUrl"),
/**
* 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: /* @__PURE__ */ __name((url) => url, "ScriptPreprocessUrl"),
/**
* 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
};
SetCorsBehavior = /* @__PURE__ */ __name((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;
}
}
}
}, "SetCorsBehavior");
LoadImageConfiguration = {
getRequiredSize: null
};
LoadImage = /* @__PURE__ */ __name((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 = /* @__PURE__ */ __name((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);
}
}, "onErrorHandler");
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);
}
});
}, void 0, offlineProvider || void 0, true, (request, exception) => {
onErrorHandler(exception);
});
return null;
}
const img = new Image();
if (LoadImageConfiguration.getRequiredSize) {
const size = LoadImageConfiguration.getRequiredSize(input);
if (size.width) {
img.width = size.width;
}
if (size.height) {
img.height = size.height;
}
}
SetCorsBehavior(url, img);
const handlersList = [];
const loadHandlersList = /* @__PURE__ */ __name(() => {
for (const handler of handlersList) {
handler.target.addEventListener(handler.name, handler.handler);
}
}, "loadHandlersList");
const unloadHandlersList = /* @__PURE__ */ __name(() => {
for (const handler of handlersList) {
handler.target.removeEventListener(handler.name, handler.handler);
}
handlersList.length = 0;
}, "unloadHandlersList");
const loadHandler = /* @__PURE__ */ __name(() => {
unloadHandlersList();
onLoad(img);
if (usingObjectURL && img.src) {
URL.revokeObjectURL(img.src);
}
}, "loadHandler");
const errorHandler = /* @__PURE__ */ __name((err) => {
unloadHandlersList();
onErrorHandler(err);
if (usingObjectURL && img.src) {
URL.revokeObjectURL(img.src);
}
}, "errorHandler");
const cspHandler = /* @__PURE__ */ __name((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 = "";
}, "cspHandler");
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 = /* @__PURE__ */ __name(() => {
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 url2 = URL.createObjectURL(blob);
usingObjectURL = true;
img.src = url2;
}, void 0, offlineProvider || void 0, true, (_request, exception) => {
onErrorHandler(exception);
});
}
}, "noOfflineSupport");
const loadFromOfflineSupport = /* @__PURE__ */ __name(() => {
if (offlineProvider) {
offlineProvider.loadImage(url, img);
}
}, "loadFromOfflineSupport");
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) {
blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);
}
img.src = blobURL;
usingObjectURL = true;
} catch (e) {
img.src = "";
}
return img;
}
}
noOfflineSupport();
}
return img;
}, "LoadImage");
ReadFile = /* @__PURE__ */ __name((file, onSuccess, onProgress, useArrayBuffer, onError) => {
const reader = new FileReader();
const fileRequest = {
onCompleteObservable: new Observable(),
abort: /* @__PURE__ */ __name(() => reader.abort(), "abort")
};
reader.onloadend = () => fileRequest.onCompleteObservable.notifyObservers(fileRequest);
if (onError) {
reader.onerror = () => {
onError(new ReadFileError(`Unable to read ${file.name}`, file));
};
}
reader.onload = (e) => {
onSuccess(e.target["result"]);
};
if (onProgress) {
reader.onprogress = onProgress;
}
if (!useArrayBuffer) {
reader.readAsText(file);
} else {
reader.readAsArrayBuffer(file);
}
return fileRequest;
}, "ReadFile");
LoadFile = /* @__PURE__ */ __name((fileOrUrl, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => {
if (fileOrUrl.name) {
return ReadFile(fileOrUrl, onSuccess, onProgress, useArrayBuffer, onError ? (error) => {
onError(void 0, error);
} : void 0);
}
const url = fileOrUrl;
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(void 0, new LoadFileError(error.message, error.file)) : void 0);
}
}
const { match, type } = TestBase64DataUrl(url);
if (match) {
const fileRequest = {
onCompleteObservable: new Observable(),
abort: /* @__PURE__ */ __name(() => () => {
}, "abort")
};
try {
const data = useArrayBuffer ? DecodeBase64UrlToBinary(url) : DecodeBase64UrlToString(url);
onSuccess(data, void 0, type);
} catch (error) {
if (onError) {
onError(void 0, 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));
} : void 0, onOpened);
}, "LoadFile");
RequestFile = /* @__PURE__ */ __name((url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => {
if (offlineProvider !== null) {
offlineProvider ?? (offlineProvider = EngineStore.LastCreatedScene?.offlineProvider);
}
url = FileToolsOptions.CleanUrl(url);
url = FileToolsOptions.PreprocessUrl(url);
const loadUrl = FileToolsOptions.BaseUrl + url;
let aborted = false;
const fileRequest = {
onCompleteObservable: new Observable(),
abort: /* @__PURE__ */ __name(() => aborted = true, "abort")
};
const requestFile = /* @__PURE__ */ __name(() => {
let request = new WebRequest();
let retryHandle = null;
let onReadyStateChange;
const unbindEvents = /* @__PURE__ */ __name(() => {
if (!request) {
return;
}
if (onProgress) {
request.removeEventListener("progress", onProgress);
}
if (onReadyStateChange) {
request.removeEventListener("readystatechange", onReadyStateChange);
}
request.removeEventListener("loadend", onLoadEnd);
}, "unbindEvents");
let onLoadEnd = /* @__PURE__ */ __name(() => {
unbindEvents();
fileRequest.onCompleteObservable.notifyObservers(fileRequest);
fileRequest.onCompleteObservable.clear();
onProgress = void 0;
onReadyStateChange = null;
onLoadEnd = null;
onError = void 0;
onOpened = void 0;
onSuccess = void 0;
}, "onLoadEnd");
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 = /* @__PURE__ */ __name((error) => {
const message = error.message || "Unknown error";
if (onError && request) {
onError(new RequestFileError(message, request));
} else {
Logger.Error(message);
}
}, "handleError");
const retryLoop = /* @__PURE__ */ __name((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 = /* @__PURE__ */ __name(() => {
if (aborted || !request) {
return;
}
if (request.readyState === (XMLHttpRequest.DONE || 4)) {
if (onReadyStateChange) {
request.removeEventListener("readystatechange", onReadyStateChange);
}
if (request.status >= 200 && request.status < 300 || request.status === 0 && (!IsWindowObjectExist() || IsFileURL())) {
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) {
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);
}
}
}, "onReadyStateChange");
request.addEventListener("readystatechange", onReadyStateChange);
request.send();
}, "retryLoop");
retryLoop(0);
}, "requestFile");
if (offlineProvider && offlineProvider.enableSceneOffline && !url.startsWith("blob:")) {
const noOfflineSupport = /* @__PURE__ */ __name((request) => {
if (request && request.status > 400) {
if (onError) {
onError(request);
}
} else {
requestFile();
}
}, "noOfflineSupport");
const loadFromOfflineSupport = /* @__PURE__ */ __name(() => {
if (offlineProvider) {
offlineProvider.loadFile(FileToolsOptions.BaseUrl + url, (data) => {
if (!aborted && onSuccess) {
onSuccess(data);
}
fileRequest.onCompleteObservable.notifyObservers(fileRequest);
}, onProgress ? (event) => {
if (!aborted && onProgress) {
onProgress(event);
}
} : void 0, noOfflineSupport, useArrayBuffer);
}
}, "loadFromOfflineSupport");
offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
} else {
requestFile();
}
return fileRequest;
}, "RequestFile");
GetMimeType = /* @__PURE__ */ __name((url) => {
const { match, type } = TestBase64DataUrl(url);
if (match) {
return type || void 0;
}
const lastDot = url.lastIndexOf(".");
const extension = url.substring(lastDot + 1).toLowerCase();
switch (extension) {
case "glb":
return "model/gltf-binary";
case "bin":
return "application/octet-stream";
case "gltf":
return "model/gltf+json";
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "webp":
return "image/webp";
case "ktx":
return "image/ktx";
case "ktx2":
return "image/ktx2";
case "avif":
return "image/avif";
default:
return void 0;
}
}, "GetMimeType");
IsFileURL = /* @__PURE__ */ __name(() => {
return typeof location !== "undefined" && location.protocol === "file:";
}, "IsFileURL");
IsBase64DataUrl = /* @__PURE__ */ __name((uri) => {
return Base64DataUrlRegEx.test(uri);
}, "IsBase64DataUrl");
TestBase64DataUrl = /* @__PURE__ */ __name((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 };
}
}, "TestBase64DataUrl");
__name(DecodeBase64UrlToBinary, "DecodeBase64UrlToBinary");
DecodeBase64UrlToString = /* @__PURE__ */ __name((uri) => {
return DecodeBase64ToString(uri.split(",")[1]);
}, "DecodeBase64UrlToString");
initSideEffects = /* @__PURE__ */ __name(() => {
AbstractEngine._FileToolsLoadImage = LoadImage;
EngineFunctionContext.loadFile = LoadFile;
_FunctionContainer.loadFile = LoadFile;
}, "initSideEffects");
initSideEffects();
_injectLTSFileTools = /* @__PURE__ */ __name((DecodeBase64UrlToBinary2, DecodeBase64UrlToString2, FileToolsOptions2, IsBase64DataUrl2, IsFileURL2, LoadFile2, LoadImage2, ReadFile2, RequestFile2, SetCorsBehavior2) => {
FileTools = {
DecodeBase64UrlToBinary: DecodeBase64UrlToBinary2,
DecodeBase64UrlToString: DecodeBase64UrlToString2,
DefaultRetryStrategy: FileToolsOptions2.DefaultRetryStrategy,
BaseUrl: FileToolsOptions2.BaseUrl,
CorsBehavior: FileToolsOptions2.CorsBehavior,
PreprocessUrl: FileToolsOptions2.PreprocessUrl,
IsBase64DataUrl: IsBase64DataUrl2,
IsFileURL: IsFileURL2,
LoadFile: LoadFile2,
LoadImage: LoadImage2,
ReadFile: ReadFile2,
RequestFile: RequestFile2,
SetCorsBehavior: SetCorsBehavior2
};
Object.defineProperty(FileTools, "DefaultRetryStrategy", {
get: /* @__PURE__ */ __name(function() {
return FileToolsOptions2.DefaultRetryStrategy;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
FileToolsOptions2.DefaultRetryStrategy = value;
}, "set")
});
Object.defineProperty(FileTools, "BaseUrl", {
get: /* @__PURE__ */ __name(function() {
return FileToolsOptions2.BaseUrl;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
FileToolsOptions2.BaseUrl = value;
}, "set")
});
Object.defineProperty(FileTools, "PreprocessUrl", {
get: /* @__PURE__ */ __name(function() {
return FileToolsOptions2.PreprocessUrl;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
FileToolsOptions2.PreprocessUrl = value;
}, "set")
});
Object.defineProperty(FileTools, "CorsBehavior", {
get: /* @__PURE__ */ __name(function() {
return FileToolsOptions2.CorsBehavior;
}, "get"),
set: /* @__PURE__ */ __name(function(value) {
FileToolsOptions2.CorsBehavior = value;
}, "set")
});
}, "_injectLTSFileTools");
_injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior);
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tools.js
function className(name260, module2) {
return (target) => {
target["__bjsclassName__"] = name260;
target["__bjsmoduleName__"] = module2 != null ? module2 : null;
};
}
var Tools, AsyncLoop;
var init_tools = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tools.js"() {
init_observable();
init_domManagement();
init_logger();
init_deepCopier();
init_precisionDate();
init_devTools();
init_webRequest();
init_engineStore();
init_fileTools();
init_timingTools();
init_instantiationTools();
init_guid();
init_tools_functions();
Tools = class _Tools {
static {
__name(this, "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) {
if (url.indexOf("//") === 0) {
return true;
}
if (url.indexOf("://") === -1) {
return false;
}
if (url.indexOf(".") === -1) {
return false;
}
if (url.indexOf("/") === -1) {
return false;
}
if (url.indexOf(":") > url.indexOf("/")) {
return false;
}
if (url.indexOf("://") < url.indexOf(".")) {
return true;
}
if (url.indexOf("data:") === 0 || url.indexOf("blob:") === 0) {
return true;
}
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!
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
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(className2) {
return InstantiationTools.Instantiate(className2);
}
/**
* 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 === void 0 || 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 async LoadFileAsync(url, useArrayBuffer = true) {
return await new Promise((resolve, reject) => {
LoadFile(url, (data) => {
resolve(data);
}, void 0, void 0, 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)) {
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 (_Tools.ScriptBaseUrl && scriptUrl.startsWith(_Tools._DefaultCdnUrl)) {
const baseUrl = _Tools.ScriptBaseUrl[_Tools.ScriptBaseUrl.length - 1] === "/" ? _Tools.ScriptBaseUrl.substring(0, _Tools.ScriptBaseUrl.length - 1) : _Tools.ScriptBaseUrl;
scriptUrl = scriptUrl.replace(_Tools._DefaultCdnUrl, baseUrl);
}
scriptUrl = _Tools.ScriptPreprocessUrl(scriptUrl);
if (forceAbsoluteUrl && !_Tools.IsAbsoluteUrl(scriptUrl)) {
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 async LoadBabylonScriptAsync(scriptUrl) {
scriptUrl = _Tools.GetBabylonScriptURL(scriptUrl);
return await _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 async LoadScriptAsync(scriptUrl, scriptId) {
return await 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: /* @__PURE__ */ __name(() => reader.abort(), "abort")
};
reader.onloadend = () => {
request.onCompleteObservable.notifyObservers(request);
};
reader.onload = (e) => {
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) {
}
}
}
/**
* 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) {
}
}
}
/**
* 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
*/
// Should end with Async but this is a breaking change
// eslint-disable-next-line no-restricted-syntax, @typescript-eslint/require-await, @typescript-eslint/naming-convention
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
*/
// eslint-disable-next-line no-restricted-syntax, @typescript-eslint/require-await
static async DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) {
throw _WarnImport("DumpTools");
}
static _IsOffScreenCanvas(canvas) {
return canvas.convertToBlob !== void 0;
}
/**
* 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) {
if (!_Tools._IsOffScreenCanvas(canvas) && !canvas.toBlob) {
canvas.toBlob = function(callback, type, quality2) {
setTimeout(() => {
const binStr = atob(this.toDataURL(type, quality2).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) {
if ("download" in document.createElement("a")) {
if (!fileName) {
const date = /* @__PURE__ */ 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() {
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) {
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, no-restricted-syntax, @typescript-eslint/require-await
static async 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, no-restricted-syntax, @typescript-eslint/require-await
static async 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 name260 = null;
if (!isType && object.getClassName) {
name260 = object.getClassName();
} else {
if (object instanceof Object) {
const classObj = isType ? object : Object.getPrototypeOf(object);
name260 = classObj.constructor["__bjsclassName__"];
}
if (!name260) {
name260 = typeof object;
}
}
return name260;
}
/**
* 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 className2 = null;
let moduleName = null;
if (!isType && object.getClassName) {
className2 = object.getClassName();
} else {
if (object instanceof Object) {
const classObj = isType ? object : Object.getPrototypeOf(object);
className2 = classObj.constructor["__bjsclassName__"];
moduleName = classObj.constructor["__bjsmoduleName__"];
}
if (!className2) {
className2 = typeof object;
}
}
if (!className2) {
return null;
}
return (moduleName != null ? moduleName + "." : "") + className2;
}
/**
* 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 async DelayAsync(delay) {
await 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);
}
};
Tools.AssetBaseUrl = "";
Tools.UseCustomRequestHeaders = false;
Tools.CustomRequestHeaders = WebRequest.CustomRequestHeaders;
Tools.GetDOMTextContent = GetDOMTextContent;
Tools._DefaultCdnUrl = "https://cdn.babylonjs.com";
Tools._DefaultAssetsUrl = "https://assets.babylonjs.com/core";
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.");
};
Tools.NoneLogLevel = Logger.NoneLogLevel;
Tools.MessageLogLevel = Logger.MessageLogLevel;
Tools.WarningLogLevel = Logger.WarningLogLevel;
Tools.ErrorLogLevel = Logger.ErrorLogLevel;
Tools.AllLogLevel = Logger.AllLogLevel;
Tools.IsWindowObjectExist = IsWindowObjectExist;
Tools.PerformanceNoneLogLevel = 0;
Tools.PerformanceUserMarkLogLevel = 1;
Tools.PerformanceConsoleLogLevel = 2;
Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
__name(className, "className");
AsyncLoop = class _AsyncLoop {
static {
__name(this, "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(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;
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";
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/bitArray.js
function GetByteIndex(bitIndex) {
return Math.floor(bitIndex / 8);
}
function GetBitMask(bitIndex) {
return 1 << bitIndex % 8;
}
var BitArray;
var init_bitArray = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/bitArray.js"() {
__name(GetByteIndex, "GetByteIndex");
__name(GetBitMask, "GetBitMask");
BitArray = class {
static {
__name(this, "BitArray");
}
/**
* Creates a new bit array with a fixed size.
* @param size The number of bits to store.
*/
constructor(size) {
this.size = size;
this._byteArray = new Uint8Array(Math.ceil(this.size / 8));
}
/**
* Gets the current value at the specified index.
* @param bitIndex The index to get the value from.
* @returns The value at the specified index.
*/
get(bitIndex) {
if (bitIndex >= this.size) {
throw new RangeError("Bit index out of range");
}
const byteIndex = GetByteIndex(bitIndex);
const bitMask = GetBitMask(bitIndex);
return (this._byteArray[byteIndex] & bitMask) !== 0;
}
/**
* Sets the value at the specified index.
* @param bitIndex The index to set the value at.
* @param value The value to set.
*/
set(bitIndex, value) {
if (bitIndex >= this.size) {
throw new RangeError("Bit index out of range");
}
const byteIndex = GetByteIndex(bitIndex);
const bitMask = GetBitMask(bitIndex);
if (value) {
this._byteArray[byteIndex] |= bitMask;
} else {
this._byteArray[byteIndex] &= ~bitMask;
}
}
};
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/mesh.vertexData.functions.js
var mesh_vertexData_functions_exports = {};
__export(mesh_vertexData_functions_exports, {
OptimizeIndices: () => OptimizeIndices
});
function OptimizeIndices(indices) {
const faces = [];
const faceCount = indices.length / 3;
for (let i = 0; i < faceCount; i++) {
faces.push([indices[i * 3], indices[i * 3 + 1], indices[i * 3 + 2]]);
}
const vertexToFaceMap = /* @__PURE__ */ new Map();
for (let faceIndex = 0; faceIndex < faces.length; faceIndex++) {
const face = faces[faceIndex];
for (const vertex of face) {
let face2 = vertexToFaceMap.get(vertex);
if (!face2) {
vertexToFaceMap.set(vertex, face2 = []);
}
face2.push(faceIndex);
}
}
const visited = new BitArray(faceCount);
const sortedFaces = [];
const deepFirstSearchStack = /* @__PURE__ */ __name((startFaceIndex) => {
const stack = [startFaceIndex];
while (stack.length > 0) {
const currentFaceIndex = stack.pop();
if (visited.get(currentFaceIndex)) {
continue;
}
visited.set(currentFaceIndex, true);
sortedFaces.push(faces[currentFaceIndex]);
for (const vertex of faces[currentFaceIndex]) {
const neighbors = vertexToFaceMap.get(vertex);
if (!neighbors) {
return;
}
for (const neighborFaceIndex of neighbors) {
if (!visited.get(neighborFaceIndex)) {
stack.push(neighborFaceIndex);
}
}
}
}
}, "deepFirstSearchStack");
for (let i = 0; i < faceCount; i++) {
if (!visited.get(i)) {
deepFirstSearchStack(i);
}
}
let index = 0;
for (const face of sortedFaces) {
indices[index++] = face[0];
indices[index++] = face[1];
indices[index++] = face[2];
}
}
var init_mesh_vertexData_functions = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/mesh.vertexData.functions.js"() {
init_bitArray();
__name(OptimizeIndices, "OptimizeIndices");
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/defaultUboDeclaration.js
var name95, shader95, defaultUboDeclarationWGSL;
var init_defaultUboDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/defaultUboDeclaration.js"() {
init_shaderStore();
init_sceneUboDeclaration();
init_meshUboDeclaration();
name95 = "defaultUboDeclaration";
shader95 = `uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f;uniform cameraInfo: vec4f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;
#define ADDITIONAL_UBO_DECLARATION
#include
#include
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name95]) {
ShaderStore.IncludesShadersStoreWGSL[name95] = shader95;
}
defaultUboDeclarationWGSL = { name: name95, shader: shader95 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvAttributeDeclaration.js
var name96, shader96, uvAttributeDeclarationWGSL;
var init_uvAttributeDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvAttributeDeclaration.js"() {
init_shaderStore();
name96 = "uvAttributeDeclaration";
shader96 = `#ifdef UV{X}
attribute uv{X}: vec2f;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name96]) {
ShaderStore.IncludesShadersStoreWGSL[name96] = shader96;
}
uvAttributeDeclarationWGSL = { name: name96, shader: shader96 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertexDeclaration.js
var name97, shader97, prePassVertexDeclarationWGSL;
var init_prePassVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertexDeclaration.js"() {
init_shaderStore();
name97 = "prePassVertexDeclaration";
shader97 = `#ifdef PREPASS
#ifdef PREPASS_LOCAL_POSITION
varying vPosition : vec3f;
#endif
#ifdef PREPASS_DEPTH
varying vViewPos: vec3f;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
varying vNormViewDepth: f32;
#endif
#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)
uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name97]) {
ShaderStore.IncludesShadersStoreWGSL[name97] = shader97;
}
prePassVertexDeclarationWGSL = { name: name97, shader: shader97 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/mainUVVaryingDeclaration.js
var name98, shader98, mainUVVaryingDeclarationWGSL;
var init_mainUVVaryingDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/mainUVVaryingDeclaration.js"() {
init_shaderStore();
name98 = "mainUVVaryingDeclaration";
shader98 = `#ifdef MAINUV{X}
varying vMainUV{X}: vec2f;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name98]) {
ShaderStore.IncludesShadersStoreWGSL[name98] = shader98;
}
mainUVVaryingDeclarationWGSL = { name: name98, shader: shader98 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexDeclaration.js
var name99, shader99, samplerVertexDeclarationWGSL;
var init_samplerVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexDeclaration.js"() {
init_shaderStore();
name99 = "samplerVertexDeclaration";
shader99 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
varying v_VARYINGNAME_UV: vec2f;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name99]) {
ShaderStore.IncludesShadersStoreWGSL[name99] = shader99;
}
samplerVertexDeclarationWGSL = { name: name99, shader: shader99 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertexDeclaration.js
var name100, shader100, bumpVertexDeclarationWGSL;
var init_bumpVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertexDeclaration.js"() {
init_shaderStore();
name100 = "bumpVertexDeclaration";
shader100 = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name100]) {
ShaderStore.IncludesShadersStoreWGSL[name100] = shader100;
}
bumpVertexDeclarationWGSL = { name: name100, shader: shader100 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertexDeclaration.js
var name101, shader101, fogVertexDeclarationWGSL;
var init_fogVertexDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertexDeclaration.js"() {
init_shaderStore();
name101 = "fogVertexDeclaration";
shader101 = `#ifdef FOG
varying vFogDistance: vec3f;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name101]) {
ShaderStore.IncludesShadersStoreWGSL[name101] = shader101;
}
fogVertexDeclarationWGSL = { name: name101, shader: shader101 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxFragmentDeclaration.js
var name102, shader102, lightVxFragmentDeclarationWGSL;
var init_lightVxFragmentDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxFragmentDeclaration.js"() {
init_shaderStore();
name102 = "lightVxFragmentDeclaration";
shader102 = `#ifdef LIGHT{X}
uniform vLightData{X}: vec4f;uniform vLightDiffuse{X}: vec4f;
#ifdef SPECULARTERM
uniform vLightSpecular{X}: vec4f;
#else
var vLightSpecular{X}: vec4f= vec4f(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform lightMatrix{X}: mat4x4f[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromLight{X}: vec4f[SHADOWCSMNUM_CASCADES{X}];varying var vDepthMetric{X}: f32[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromCamera{X}: vec4f;
#elif defined(SHADOWCUBE{X})
#else
varying var vPositionFromLight{X}: vec4f;varying var vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;
#endif
uniform shadowsInfo{X}: vec4f;uniform depthValues{X}: vec2f;
#endif
#ifdef SPOTLIGHT{X}
uniform vLightDirection{X}: vec4f;uniform vLightFalloff{X}: vec4f;
#elif defined(POINTLIGHT{X})
uniform vLightFalloff{X}: vec4f;
#elif defined(HEMILIGHT{X})
uniform vLightGround{X}: vec3f;
#endif
#if defined(AREALIGHT{X})
uniform vLightWidth{X}: vec4f;uniform vLightHeight{X}: vec4f;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name102]) {
ShaderStore.IncludesShadersStoreWGSL[name102] = shader102;
}
lightVxFragmentDeclarationWGSL = { name: name102, shader: shader102 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxUboDeclaration.js
var name103, shader103, lightVxUboDeclarationWGSL;
var init_lightVxUboDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxUboDeclaration.js"() {
init_shaderStore();
name103 = "lightVxUboDeclaration";
shader103 = `#ifdef LIGHT{X}
struct Light{X}
{vLightData: vec4f,
vLightDiffuse: vec4f,
vLightSpecular: vec4f,
#ifdef SPOTLIGHT{X}
vLightDirection: vec4f,
vLightFalloff: vec4f,
#elif defined(POINTLIGHT{X})
vLightFalloff: vec4f,
#elif defined(HEMILIGHT{X})
vLightGround: vec3f,
#elif defined(CLUSTLIGHT{X})
vSliceData: vec2f,
vSliceRanges: array,
#endif
#if defined(AREALIGHT{X})
vLightWidth: vec4f,
vLightHeight: vec4f,
#endif
shadowsInfo: vec4f,
depthValues: vec2f} ;var light{X} : Light{X};
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;
#elif defined(SHADOWCUBE{X})
#else
varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;
#endif
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name103]) {
ShaderStore.IncludesShadersStoreWGSL[name103] = shader103;
}
lightVxUboDeclarationWGSL = { name: name103, shader: shader103 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthDeclaration.js
var name104, shader104, logDepthDeclarationWGSL;
var init_logDepthDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthDeclaration.js"() {
init_shaderStore();
name104 = "logDepthDeclaration";
shader104 = `#ifdef LOGARITHMICDEPTH
uniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name104]) {
ShaderStore.IncludesShadersStoreWGSL[name104] = shader104;
}
logDepthDeclarationWGSL = { name: name104, shader: shader104 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertex.js
var name105, shader105, prePassVertexWGSL;
var init_prePassVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertex.js"() {
init_shaderStore();
name105 = "prePassVertex";
shader105 = `#ifdef PREPASS_DEPTH
vertexOutputs.vViewPos=(scene.view*worldPos).rgb;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
vertexOutputs.vNormViewDepth=((scene.view*worldPos).z-uniforms.cameraInfo.x)/(uniforms.cameraInfo.y-uniforms.cameraInfo.x);
#endif
#ifdef PREPASS_LOCAL_POSITION
vertexOutputs.vPosition=positionUpdated.xyz;
#endif
#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)
vertexOutputs.vCurrentPosition=scene.viewProjection*worldPos;
#if NUM_BONE_INFLUENCERS>0
var previousInfluence: mat4x4f;previousInfluence=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];
#endif
vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0);
#else
vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name105]) {
ShaderStore.IncludesShadersStoreWGSL[name105] = shader105;
}
prePassVertexWGSL = { name: name105, shader: shader105 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvVariableDeclaration.js
var name106, shader106, uvVariableDeclarationWGSL;
var init_uvVariableDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvVariableDeclaration.js"() {
init_shaderStore();
name106 = "uvVariableDeclaration";
shader106 = `#ifdef MAINUV{X}
#if !defined(UV{X})
var uv{X}: vec2f=vec2f(0.,0.);
#else
var uv{X}: vec2f=vertexInputs.uv{X};
#endif
vertexOutputs.vMainUV{X}=uv{X};
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name106]) {
ShaderStore.IncludesShadersStoreWGSL[name106] = shader106;
}
uvVariableDeclarationWGSL = { name: name106, shader: shader106 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexImplementation.js
var name107, shader107, samplerVertexImplementationWGSL;
var init_samplerVertexImplementation = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexImplementation.js"() {
init_shaderStore();
name107 = "samplerVertexImplementation";
shader107 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
if (uniforms.v_INFONAME_==0.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uvUpdated,1.0,0.0)).xy;}
#ifdef UV2
else if (uniforms.v_INFONAME_==1.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uv2Updated,1.0,0.0)).xy;}
#endif
#ifdef UV3
else if (uniforms.v_INFONAME_==2.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv3,1.0,0.0)).xy;}
#endif
#ifdef UV4
else if (uniforms.v_INFONAME_==3.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv4,1.0,0.0)).xy;}
#endif
#ifdef UV5
else if (uniforms.v_INFONAME_==4.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv5,1.0,0.0)).xy;}
#endif
#ifdef UV6
else if (uniforms.v_INFONAME_==5.)
{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv6,1.0,0.0)).xy;}
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name107]) {
ShaderStore.IncludesShadersStoreWGSL[name107] = shader107;
}
samplerVertexImplementationWGSL = { name: name107, shader: shader107 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertex.js
var name108, shader108, bumpVertexWGSL;
var init_bumpVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertex.js"() {
init_shaderStore();
name108 = "bumpVertex";
shader108 = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
var tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2];
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name108]) {
ShaderStore.IncludesShadersStoreWGSL[name108] = shader108;
}
bumpVertexWGSL = { name: name108, shader: shader108 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertex.js
var name109, shader109, fogVertexWGSL;
var init_fogVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertex.js"() {
init_shaderStore();
name109 = "fogVertex";
shader109 = `#ifdef FOG
#ifdef SCENE_UBO
vertexOutputs.vFogDistance=(scene.view*worldPos).xyz;
#else
vertexOutputs.vFogDistance=(uniforms.view*worldPos).xyz;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name109]) {
ShaderStore.IncludesShadersStoreWGSL[name109] = shader109;
}
fogVertexWGSL = { name: name109, shader: shader109 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowsVertex.js
var name110, shader110, shadowsVertexWGSL;
var init_shadowsVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowsVertex.js"() {
init_shaderStore();
name110 = "shadowsVertex";
shader110 = `#ifdef SHADOWS
#if defined(SHADOWCSM{X})
vertexOutputs.vPositionFromCamera{X}=scene.view*worldPos;
#if SHADOWCSMNUM_CASCADES{X}>0
vertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#if SHADOWCSMNUM_CASCADES{X}>1
vertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#if SHADOWCSMNUM_CASCADES{X}>2
vertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#if SHADOWCSMNUM_CASCADES{X}>3
vertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})
vertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name110]) {
ShaderStore.IncludesShadersStoreWGSL[name110] = shader110;
}
shadowsVertexWGSL = { name: name110, shader: shader110 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/vertexColorMixing.js
var name111, shader111, vertexColorMixingWGSL;
var init_vertexColorMixing = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/vertexColorMixing.js"() {
init_shaderStore();
name111 = "vertexColorMixing";
shader111 = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
vertexOutputs.vColor=vec4f(1.0);
#ifdef VERTEXCOLOR
#ifdef VERTEXALPHA
vertexOutputs.vColor*=vertexInputs.color;
#else
vertexOutputs.vColor=vec4f(vertexOutputs.vColor.rgb*vertexInputs.color.rgb,vertexOutputs.vColor.a);
#endif
#endif
#ifdef INSTANCESCOLOR
vertexOutputs.vColor*=vertexInputs.instanceColor;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name111]) {
ShaderStore.IncludesShadersStoreWGSL[name111] = shader111;
}
vertexColorMixingWGSL = { name: name111, shader: shader111 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthVertex.js
var name112, shader112, logDepthVertexWGSL;
var init_logDepthVertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthVertex.js"() {
init_shaderStore();
name112 = "logDepthVertex";
shader112 = `#ifdef LOGARITHMICDEPTH
vertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name112]) {
ShaderStore.IncludesShadersStoreWGSL[name112] = shader112;
}
logDepthVertexWGSL = { name: name112, shader: shader112 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/default.vertex.js
var default_vertex_exports = {};
__export(default_vertex_exports, {
defaultVertexShaderWGSL: () => defaultVertexShaderWGSL
});
var name113, shader113, defaultVertexShaderWGSL;
var init_default_vertex = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/default.vertex.js"() {
init_shaderStore();
init_defaultUboDeclaration();
init_uvAttributeDeclaration();
init_helperFunctions();
init_bonesDeclaration();
init_bakedVertexAnimationDeclaration();
init_instancesDeclaration();
init_prePassVertexDeclaration();
init_mainUVVaryingDeclaration();
init_samplerVertexDeclaration();
init_bumpVertexDeclaration();
init_clipPlaneVertexDeclaration();
init_fogVertexDeclaration();
init_lightVxFragmentDeclaration();
init_lightVxUboDeclaration();
init_morphTargetsVertexGlobalDeclaration();
init_morphTargetsVertexDeclaration();
init_logDepthDeclaration();
init_morphTargetsVertexGlobal();
init_morphTargetsVertex();
init_instancesVertex();
init_bonesVertex();
init_bakedVertexAnimation();
init_prePassVertex();
init_uvVariableDeclaration();
init_samplerVertexImplementation();
init_bumpVertex();
init_clipPlaneVertex();
init_fogVertex();
init_shadowsVertex();
init_vertexColorMixing();
init_logDepthVertex();
name113 = "defaultVertexShader";
shader113 = `#include
#define CUSTOM_VERTEX_BEGIN
attribute position: vec3f;
#ifdef NORMAL
attribute normal: vec3f;
#endif
#ifdef TANGENT
attribute tangent: vec4f;
#endif
#ifdef UV1
attribute uv: vec2f;
#endif
#include[2..7]
#ifdef VERTEXCOLOR
attribute color: vec4f;
#endif
#include
#include
#include
#include
#include
#include[1..7]
#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)
#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#if defined(SPECULARTERM)
#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)
#endif
#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
varying vPositionW: vec3f;
#ifdef NORMAL
varying vNormalW: vec3f;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#include
#include
#include
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include
#include[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
varying vViewDepth: f32;
#endif
#include
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
var positionUpdated: vec3f=vertexInputs.position;
#ifdef NORMAL
var normalUpdated: vec3f=vertexInputs.normal;
#endif
#ifdef TANGENT
var tangentUpdated: vec4f=vertexInputs.tangent;
#endif
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vertexInputs.color;
#endif
#include
#include[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vertexOutputs.vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0);
#endif
#include
#include
var worldPos: vec4f=finalWorld*vec4f(positionUpdated,1.0);
#ifdef NORMAL
var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}
#else
vertexOutputs.position=scene.viewProjection*worldPos;
#endif
vertexOutputs.vPositionW= worldPos.xyz;
#ifdef PREPASS
#include
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vertexOutputs.vDirectionW=normalize((finalWorld* vec4f(positionUpdated,0.0)).xyz);
#endif
#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0
vertexOutputs.vViewDepth=(scene.view*worldPos).z;
#endif
#ifndef UV1
var uvUpdated: vec2f=vec2f(0.,0.);
#endif
#ifdef MAINUV1
vertexOutputs.vMainUV1=uvUpdated;
#endif
#ifndef UV2
var uv2Updated: vec2f=vec2f(0.,0.);
#endif
#ifdef MAINUV2
vertexOutputs.vMainUV2=uv2Updated;
#endif
#include[3..7]
#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)
#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#if defined(SPECULARTERM)
#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)
#endif
#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#include
#include
#include
#include[0..maxSimultaneousLights]
#include
#include
#define CUSTOM_VERTEX_MAIN_END
}
`;
if (!ShaderStore.ShadersStoreWGSL[name113]) {
ShaderStore.ShadersStoreWGSL[name113] = shader113;
}
defaultVertexShaderWGSL = { name: name113, shader: shader113 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassDeclaration.js
var name114, shader114, prePassDeclarationWGSL;
var init_prePassDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassDeclaration.js"() {
init_shaderStore();
name114 = "prePassDeclaration";
shader114 = `#ifdef PREPASS
#ifdef PREPASS_LOCAL_POSITION
varying vPosition : vec3f;
#endif
#ifdef PREPASS_DEPTH
varying vViewPos: vec3f;
#endif
#ifdef PREPASS_NORMALIZED_VIEW_DEPTH
varying vNormViewDepth: f32;
#endif
#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)
varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;
#endif
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name114]) {
ShaderStore.IncludesShadersStoreWGSL[name114] = shader114;
}
prePassDeclarationWGSL = { name: name114, shader: shader114 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/oitDeclaration.js
var name115, shader115, oitDeclarationWGSL;
var init_oitDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/oitDeclaration.js"() {
init_shaderStore();
name115 = "oitDeclaration";
shader115 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY
#define MAX_DEPTH 99999.0
var oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d;
#endif
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name115]) {
ShaderStore.IncludesShadersStoreWGSL[name115] = shader115;
}
oitDeclarationWGSL = { name: name115, shader: shader115 };
}
});
// Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightUboDeclaration.js
var name116, shader116, lightUboDeclarationWGSL;
var init_lightUboDeclaration = __esm({
"Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightUboDeclaration.js"() {
init_shaderStore();
name116 = "lightUboDeclaration";
shader116 = `#ifdef LIGHT{X}
struct Light{X}
{vLightData: vec4f,
vLightDiffuse: vec4f,
vLightSpecular: vec4f,
#ifdef SPOTLIGHT{X}
vLightDirection: vec4f,
vLightFalloff: vec4f,
#elif defined(POINTLIGHT{X})
vLightFalloff: vec4f,
#elif defined(HEMILIGHT{X})
vLightGround: vec3f,
#elif defined(CLUSTLIGHT{X})
vSliceData: vec2f,
vSliceRanges: array,
#endif
#if defined(AREALIGHT{X})
vLightWidth: vec4f,
vLightHeight: vec4f,
#endif
shadowsInfo: vec4f,
depthValues: vec2f} ;var